blob: 839cf446323da72db133a779877fe24c76fdf992 [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
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010019#include "intrinsics.h"
Calin Juravleacf735c2015-02-12 15:25:22 +000020#include "mirror/class-inl.h"
21#include "scoped_thread_state_change.h"
22
Nicolas Geoffray3c049742014-09-24 18:10:46 +010023namespace art {
24
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010025class InstructionSimplifierVisitor : public HGraphDelegateVisitor {
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000026 public:
Calin Juravleacf735c2015-02-12 15:25:22 +000027 InstructionSimplifierVisitor(HGraph* graph, OptimizingCompilerStats* stats)
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010028 : HGraphDelegateVisitor(graph),
Alexandre Rames188d4312015-04-09 18:30:21 +010029 stats_(stats) {}
30
31 void Run();
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000032
33 private:
Alexandre Rames188d4312015-04-09 18:30:21 +010034 void RecordSimplification() {
35 simplification_occurred_ = true;
36 simplifications_at_current_position_++;
37 if (stats_) {
38 stats_->RecordStat(kInstructionSimplifications);
39 }
40 }
41
42 bool TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000043 void VisitShift(HBinaryOperation* shift);
44
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000045 void VisitSuspendCheck(HSuspendCheck* check) OVERRIDE;
46 void VisitEqual(HEqual* equal) OVERRIDE;
David Brazdil0d13fee2015-04-17 14:52:19 +010047 void VisitNotEqual(HNotEqual* equal) OVERRIDE;
48 void VisitBooleanNot(HBooleanNot* bool_not) OVERRIDE;
Nicolas Geoffray07276db2015-05-18 14:22:09 +010049 void VisitInstanceFieldSet(HInstanceFieldSet* equal) OVERRIDE;
50 void VisitStaticFieldSet(HStaticFieldSet* equal) OVERRIDE;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000051 void VisitArraySet(HArraySet* equal) OVERRIDE;
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +000052 void VisitTypeConversion(HTypeConversion* instruction) OVERRIDE;
Calin Juravle10e244f2015-01-26 18:54:32 +000053 void VisitNullCheck(HNullCheck* instruction) OVERRIDE;
Mingyao Yang0304e182015-01-30 16:41:29 -080054 void VisitArrayLength(HArrayLength* instruction) OVERRIDE;
Calin Juravleacf735c2015-02-12 15:25:22 +000055 void VisitCheckCast(HCheckCast* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000056 void VisitAdd(HAdd* instruction) OVERRIDE;
57 void VisitAnd(HAnd* instruction) OVERRIDE;
Mark Mendellc4701932015-04-10 13:18:51 -040058 void VisitCondition(HCondition* instruction) OVERRIDE;
59 void VisitGreaterThan(HGreaterThan* condition) OVERRIDE;
60 void VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) OVERRIDE;
61 void VisitLessThan(HLessThan* condition) OVERRIDE;
62 void VisitLessThanOrEqual(HLessThanOrEqual* condition) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000063 void VisitDiv(HDiv* instruction) OVERRIDE;
64 void VisitMul(HMul* instruction) OVERRIDE;
Alexandre Rames188d4312015-04-09 18:30:21 +010065 void VisitNeg(HNeg* instruction) OVERRIDE;
66 void VisitNot(HNot* instruction) OVERRIDE;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +000067 void VisitOr(HOr* instruction) OVERRIDE;
68 void VisitShl(HShl* instruction) OVERRIDE;
69 void VisitShr(HShr* instruction) OVERRIDE;
70 void VisitSub(HSub* instruction) OVERRIDE;
71 void VisitUShr(HUShr* instruction) OVERRIDE;
72 void VisitXor(HXor* instruction) OVERRIDE;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +010073 void VisitInstanceOf(HInstanceOf* instruction) OVERRIDE;
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +010074 void VisitFakeString(HFakeString* fake_string) OVERRIDE;
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +010075 void VisitInvoke(HInvoke* invoke) OVERRIDE;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +010076
77 bool CanEnsureNotNullAt(HInstruction* instr, HInstruction* at) const;
Calin Juravleacf735c2015-02-12 15:25:22 +000078
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +010079 void SimplifySystemArrayCopy(HInvoke* invoke);
80 void SimplifyStringEquals(HInvoke* invoke);
81
Calin Juravleacf735c2015-02-12 15:25:22 +000082 OptimizingCompilerStats* stats_;
Alexandre Rames188d4312015-04-09 18:30:21 +010083 bool simplification_occurred_ = false;
84 int simplifications_at_current_position_ = 0;
85 // We ensure we do not loop infinitely. The value is a finger in the air guess
86 // that should allow enough simplification.
87 static constexpr int kMaxSamePositionSimplifications = 10;
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +000088};
89
Nicolas Geoffray3c049742014-09-24 18:10:46 +010090void InstructionSimplifier::Run() {
Calin Juravleacf735c2015-02-12 15:25:22 +000091 InstructionSimplifierVisitor visitor(graph_, stats_);
Alexandre Rames188d4312015-04-09 18:30:21 +010092 visitor.Run();
93}
94
95void InstructionSimplifierVisitor::Run() {
Nicolas Geoffray07276db2015-05-18 14:22:09 +010096 // Iterate in reverse post order to open up more simplifications to users
97 // of instructions that got simplified.
Alexandre Rames188d4312015-04-09 18:30:21 +010098 for (HReversePostOrderIterator it(*GetGraph()); !it.Done();) {
99 // The simplification of an instruction to another instruction may yield
100 // possibilities for other simplifications. So although we perform a reverse
101 // post order visit, we sometimes need to revisit an instruction index.
102 simplification_occurred_ = false;
103 VisitBasicBlock(it.Current());
104 if (simplification_occurred_ &&
105 (simplifications_at_current_position_ < kMaxSamePositionSimplifications)) {
106 // New simplifications may be applicable to the instruction at the
107 // current index, so don't advance the iterator.
108 continue;
109 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100110 simplifications_at_current_position_ = 0;
111 it.Advance();
112 }
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100113}
114
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000115namespace {
116
117bool AreAllBitsSet(HConstant* constant) {
118 return Int64FromConstant(constant) == -1;
119}
120
121} // namespace
122
Alexandre Rames188d4312015-04-09 18:30:21 +0100123// Returns true if the code was simplified to use only one negation operation
124// after the binary operation instead of one on each of the inputs.
125bool InstructionSimplifierVisitor::TryMoveNegOnInputsAfterBinop(HBinaryOperation* binop) {
126 DCHECK(binop->IsAdd() || binop->IsSub());
127 DCHECK(binop->GetLeft()->IsNeg() && binop->GetRight()->IsNeg());
128 HNeg* left_neg = binop->GetLeft()->AsNeg();
129 HNeg* right_neg = binop->GetRight()->AsNeg();
130 if (!left_neg->HasOnlyOneNonEnvironmentUse() ||
131 !right_neg->HasOnlyOneNonEnvironmentUse()) {
132 return false;
133 }
134 // Replace code looking like
135 // NEG tmp1, a
136 // NEG tmp2, b
137 // ADD dst, tmp1, tmp2
138 // with
139 // ADD tmp, a, b
140 // NEG dst, tmp
Serdjuk, Nikolay Yaae9e662015-08-21 13:26:34 +0600141 // Note that we cannot optimize `(-a) + (-b)` to `-(a + b)` for floating-point.
142 // When `a` is `-0.0` and `b` is `0.0`, the former expression yields `0.0`,
143 // while the later yields `-0.0`.
144 if (!Primitive::IsIntegralType(binop->GetType())) {
145 return false;
146 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100147 binop->ReplaceInput(left_neg->GetInput(), 0);
148 binop->ReplaceInput(right_neg->GetInput(), 1);
149 left_neg->GetBlock()->RemoveInstruction(left_neg);
150 right_neg->GetBlock()->RemoveInstruction(right_neg);
151 HNeg* neg = new (GetGraph()->GetArena()) HNeg(binop->GetType(), binop);
152 binop->GetBlock()->InsertInstructionBefore(neg, binop->GetNext());
153 binop->ReplaceWithExceptInReplacementAtIndex(neg, 0);
154 RecordSimplification();
155 return true;
156}
157
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000158void InstructionSimplifierVisitor::VisitShift(HBinaryOperation* instruction) {
159 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
160 HConstant* input_cst = instruction->GetConstantRight();
161 HInstruction* input_other = instruction->GetLeastConstantLeft();
162
Mark Mendellba56d062015-05-05 21:34:03 -0400163 if (input_cst != nullptr) {
164 if (input_cst->IsZero()) {
165 // Replace code looking like
166 // SHL dst, src, 0
167 // with
168 // src
169 instruction->ReplaceWith(input_other);
170 instruction->GetBlock()->RemoveInstruction(instruction);
171 } else if (instruction->IsShl() && input_cst->IsOne()) {
172 // Replace Shl looking like
173 // SHL dst, src, 1
174 // with
175 // ADD dst, src, src
176 HAdd *add = new(GetGraph()->GetArena()) HAdd(instruction->GetType(),
177 input_other,
178 input_other);
179 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
180 RecordSimplification();
181 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000182 }
183}
184
Calin Juravle10e244f2015-01-26 18:54:32 +0000185void InstructionSimplifierVisitor::VisitNullCheck(HNullCheck* null_check) {
186 HInstruction* obj = null_check->InputAt(0);
187 if (!obj->CanBeNull()) {
188 null_check->ReplaceWith(obj);
189 null_check->GetBlock()->RemoveInstruction(null_check);
Calin Juravleacf735c2015-02-12 15:25:22 +0000190 if (stats_ != nullptr) {
191 stats_->RecordStat(MethodCompilationStat::kRemovedNullCheck);
192 }
193 }
194}
195
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100196bool InstructionSimplifierVisitor::CanEnsureNotNullAt(HInstruction* input, HInstruction* at) const {
197 if (!input->CanBeNull()) {
198 return true;
199 }
200
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100201 for (HUseIterator<HInstruction*> it(input->GetUses()); !it.Done(); it.Advance()) {
202 HInstruction* use = it.Current()->GetUser();
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100203 if (use->IsNullCheck() && use->StrictlyDominates(at)) {
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100204 return true;
205 }
206 }
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100207
Guillaume "Vermeille" Sanchez8909baf2015-04-23 21:35:11 +0100208 return false;
209}
210
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100211// Returns whether doing a type test between the class of `object` against `klass` has
212// a statically known outcome. The result of the test is stored in `outcome`.
213static bool TypeCheckHasKnownOutcome(HLoadClass* klass, HInstruction* object, bool* outcome) {
Calin Juravle2e768302015-07-28 14:41:11 +0000214 DCHECK(!object->IsNullConstant()) << "Null constants should be special cased";
215 ReferenceTypeInfo obj_rti = object->GetReferenceTypeInfo();
216 ScopedObjectAccess soa(Thread::Current());
217 if (!obj_rti.IsValid()) {
218 // We run the simplifier before the reference type propagation so type info might not be
219 // available.
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100220 return false;
Calin Juravleacf735c2015-02-12 15:25:22 +0000221 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100222
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100223 ReferenceTypeInfo class_rti = klass->GetLoadedClassRTI();
Calin Juravle98893e12015-10-02 21:05:03 +0100224 if (!class_rti.IsValid()) {
225 // Happens when the loaded class is unresolved.
226 return false;
227 }
228 DCHECK(class_rti.IsExact());
Calin Juravleacf735c2015-02-12 15:25:22 +0000229 if (class_rti.IsSupertypeOf(obj_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100230 *outcome = true;
231 return true;
232 } else if (obj_rti.IsExact()) {
233 // The test failed at compile time so will also fail at runtime.
234 *outcome = false;
235 return true;
Nicolas Geoffray7cb499b2015-06-17 11:35:11 +0100236 } else if (!class_rti.IsInterface()
237 && !obj_rti.IsInterface()
238 && !obj_rti.IsSupertypeOf(class_rti)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100239 // Different type hierarchy. The test will fail.
240 *outcome = false;
241 return true;
242 }
243 return false;
244}
245
246void InstructionSimplifierVisitor::VisitCheckCast(HCheckCast* check_cast) {
247 HInstruction* object = check_cast->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100248 HLoadClass* load_class = check_cast->InputAt(1)->AsLoadClass();
249 if (load_class->NeedsAccessCheck()) {
250 // If we need to perform an access check we cannot remove the instruction.
251 return;
252 }
253
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100254 if (CanEnsureNotNullAt(object, check_cast)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100255 check_cast->ClearMustDoNullCheck();
256 }
257
258 if (object->IsNullConstant()) {
Calin Juravleacf735c2015-02-12 15:25:22 +0000259 check_cast->GetBlock()->RemoveInstruction(check_cast);
260 if (stats_ != nullptr) {
261 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
262 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100263 return;
264 }
265
266 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700267 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100268 if (outcome) {
269 check_cast->GetBlock()->RemoveInstruction(check_cast);
270 if (stats_ != nullptr) {
271 stats_->RecordStat(MethodCompilationStat::kRemovedCheckedCast);
272 }
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700273 if (!load_class->HasUses()) {
274 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
275 // However, here we know that it cannot because the checkcast was successfull, hence
276 // the class was already loaded.
277 load_class->GetBlock()->RemoveInstruction(load_class);
278 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100279 } else {
280 // Don't do anything for exceptional cases for now. Ideally we should remove
281 // all instructions and blocks this instruction dominates.
282 }
Calin Juravle10e244f2015-01-26 18:54:32 +0000283 }
284}
285
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100286void InstructionSimplifierVisitor::VisitInstanceOf(HInstanceOf* instruction) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100287 HInstruction* object = instruction->InputAt(0);
Calin Juravlee53fb552015-10-07 17:51:52 +0100288 HLoadClass* load_class = instruction->InputAt(1)->AsLoadClass();
289 if (load_class->NeedsAccessCheck()) {
290 // If we need to perform an access check we cannot remove the instruction.
291 return;
292 }
293
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100294 bool can_be_null = true;
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100295 if (CanEnsureNotNullAt(object, instruction)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100296 can_be_null = false;
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100297 instruction->ClearMustDoNullCheck();
298 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100299
300 HGraph* graph = GetGraph();
301 if (object->IsNullConstant()) {
302 instruction->ReplaceWith(graph->GetIntConstant(0));
303 instruction->GetBlock()->RemoveInstruction(instruction);
304 RecordSimplification();
305 return;
306 }
307
308 bool outcome;
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700309 if (TypeCheckHasKnownOutcome(load_class, object, &outcome)) {
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100310 if (outcome && can_be_null) {
311 // Type test will succeed, we just need a null test.
312 HNotEqual* test = new (graph->GetArena()) HNotEqual(graph->GetNullConstant(), object);
313 instruction->GetBlock()->InsertInstructionBefore(test, instruction);
314 instruction->ReplaceWith(test);
315 } else {
316 // We've statically determined the result of the instanceof.
317 instruction->ReplaceWith(graph->GetIntConstant(outcome));
318 }
319 RecordSimplification();
320 instruction->GetBlock()->RemoveInstruction(instruction);
Nicolas Geoffrayefa84682015-08-12 18:28:14 -0700321 if (outcome && !load_class->HasUses()) {
322 // We cannot rely on DCE to remove the class because the `HLoadClass` thinks it can throw.
323 // However, here we know that it cannot because the instanceof check was successfull, hence
324 // the class was already loaded.
325 load_class->GetBlock()->RemoveInstruction(load_class);
326 }
Guillaume Sanchez222862c2015-06-09 18:33:02 +0100327 }
Guillaume "Vermeille" Sanchezaf888352015-04-20 14:41:30 +0100328}
329
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100330void InstructionSimplifierVisitor::VisitInstanceFieldSet(HInstanceFieldSet* instruction) {
331 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100332 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100333 instruction->ClearValueCanBeNull();
334 }
335}
336
337void InstructionSimplifierVisitor::VisitStaticFieldSet(HStaticFieldSet* instruction) {
338 if ((instruction->GetValue()->GetType() == Primitive::kPrimNot)
Nicolas Geoffray6e7455e2015-09-28 16:25:37 +0100339 && CanEnsureNotNullAt(instruction->GetValue(), instruction)) {
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100340 instruction->ClearValueCanBeNull();
341 }
342}
343
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000344void InstructionSimplifierVisitor::VisitSuspendCheck(HSuspendCheck* check) {
Nicolas Geoffray3c049742014-09-24 18:10:46 +0100345 HBasicBlock* block = check->GetBlock();
346 // Currently always keep the suspend check at entry.
347 if (block->IsEntryBlock()) return;
348
349 // Currently always keep suspend checks at loop entry.
350 if (block->IsLoopHeader() && block->GetFirstInstruction() == check) {
351 DCHECK(block->GetLoopInformation()->GetSuspendCheck() == check);
352 return;
353 }
354
355 // Remove the suspend check that was added at build time for the baseline
356 // compiler.
357 block->RemoveInstruction(check);
358}
359
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000360void InstructionSimplifierVisitor::VisitEqual(HEqual* equal) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100361 HInstruction* input_const = equal->GetConstantRight();
362 if (input_const != nullptr) {
363 HInstruction* input_value = equal->GetLeastConstantLeft();
364 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
365 HBasicBlock* block = equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100366 // We are comparing the boolean to a constant which is of type int and can
367 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100368 if (input_const->AsIntConstant()->IsOne()) {
369 // Replace (bool_value == true) with bool_value
370 equal->ReplaceWith(input_value);
371 block->RemoveInstruction(equal);
372 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100373 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100374 // Replace (bool_value == false) with !bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100375 block->ReplaceAndRemoveInstructionWith(
376 equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
377 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100378 } else {
379 // Replace (bool_value == integer_not_zero_nor_one_constant) with false
380 equal->ReplaceWith(GetGraph()->GetIntConstant(0));
381 block->RemoveInstruction(equal);
382 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100383 }
Mark Mendellc4701932015-04-10 13:18:51 -0400384 } else {
385 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100386 }
Mark Mendellc4701932015-04-10 13:18:51 -0400387 } else {
388 VisitCondition(equal);
Nicolas Geoffray01ef3452014-10-01 11:32:17 +0100389 }
390}
391
David Brazdil0d13fee2015-04-17 14:52:19 +0100392void InstructionSimplifierVisitor::VisitNotEqual(HNotEqual* not_equal) {
393 HInstruction* input_const = not_equal->GetConstantRight();
394 if (input_const != nullptr) {
395 HInstruction* input_value = not_equal->GetLeastConstantLeft();
396 if (input_value->GetType() == Primitive::kPrimBoolean && input_const->IsIntConstant()) {
397 HBasicBlock* block = not_equal->GetBlock();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100398 // We are comparing the boolean to a constant which is of type int and can
399 // be any constant.
David Brazdil0d13fee2015-04-17 14:52:19 +0100400 if (input_const->AsIntConstant()->IsOne()) {
401 // Replace (bool_value != true) with !bool_value
402 block->ReplaceAndRemoveInstructionWith(
403 not_equal, new (block->GetGraph()->GetArena()) HBooleanNot(input_value));
404 RecordSimplification();
Nicolas Geoffray3c4ab802015-06-19 11:42:07 +0100405 } else if (input_const->AsIntConstant()->IsZero()) {
David Brazdil0d13fee2015-04-17 14:52:19 +0100406 // Replace (bool_value != false) with bool_value
David Brazdil0d13fee2015-04-17 14:52:19 +0100407 not_equal->ReplaceWith(input_value);
408 block->RemoveInstruction(not_equal);
409 RecordSimplification();
David Brazdil1e9ec052015-06-22 10:26:45 +0100410 } else {
411 // Replace (bool_value != integer_not_zero_nor_one_constant) with true
412 not_equal->ReplaceWith(GetGraph()->GetIntConstant(1));
413 block->RemoveInstruction(not_equal);
414 RecordSimplification();
David Brazdil0d13fee2015-04-17 14:52:19 +0100415 }
Mark Mendellc4701932015-04-10 13:18:51 -0400416 } else {
417 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100418 }
Mark Mendellc4701932015-04-10 13:18:51 -0400419 } else {
420 VisitCondition(not_equal);
David Brazdil0d13fee2015-04-17 14:52:19 +0100421 }
422}
423
424void InstructionSimplifierVisitor::VisitBooleanNot(HBooleanNot* bool_not) {
425 HInstruction* parent = bool_not->InputAt(0);
426 if (parent->IsBooleanNot()) {
427 HInstruction* value = parent->InputAt(0);
428 // Replace (!(!bool_value)) with bool_value
429 bool_not->ReplaceWith(value);
430 bool_not->GetBlock()->RemoveInstruction(bool_not);
431 // It is possible that `parent` is dead at this point but we leave
432 // its removal to DCE for simplicity.
433 RecordSimplification();
434 }
435}
436
Mingyao Yang0304e182015-01-30 16:41:29 -0800437void InstructionSimplifierVisitor::VisitArrayLength(HArrayLength* instruction) {
438 HInstruction* input = instruction->InputAt(0);
439 // If the array is a NewArray with constant size, replace the array length
440 // with the constant instruction. This helps the bounds check elimination phase.
441 if (input->IsNewArray()) {
442 input = input->InputAt(0);
443 if (input->IsIntConstant()) {
444 instruction->ReplaceWith(input);
445 }
446 }
447}
448
Nicolas Geoffray5e6916c2014-11-18 16:53:35 +0000449void InstructionSimplifierVisitor::VisitArraySet(HArraySet* instruction) {
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000450 HInstruction* value = instruction->GetValue();
451 if (value->GetType() != Primitive::kPrimNot) return;
452
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100453 if (CanEnsureNotNullAt(value, instruction)) {
454 instruction->ClearValueCanBeNull();
455 }
456
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000457 if (value->IsArrayGet()) {
458 if (value->AsArrayGet()->GetArray() == instruction->GetArray()) {
459 // If the code is just swapping elements in the array, no need for a type check.
460 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100461 return;
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000462 }
463 }
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100464
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100465 if (value->IsNullConstant()) {
466 instruction->ClearNeedsTypeCheck();
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100467 return;
Nicolas Geoffray9fdb31e2015-07-01 12:56:46 +0100468 }
469
Nicolas Geoffraye0395dd2015-09-25 11:04:45 +0100470 ScopedObjectAccess soa(Thread::Current());
471 ReferenceTypeInfo array_rti = instruction->GetArray()->GetReferenceTypeInfo();
472 ReferenceTypeInfo value_rti = value->GetReferenceTypeInfo();
473 if (!array_rti.IsValid()) {
474 return;
475 }
476
477 if (value_rti.IsValid() && array_rti.CanArrayHold(value_rti)) {
478 instruction->ClearNeedsTypeCheck();
479 return;
480 }
481
482 if (array_rti.IsObjectArray()) {
483 if (array_rti.IsExact()) {
484 instruction->ClearNeedsTypeCheck();
485 return;
486 }
487 instruction->SetStaticTypeOfArrayIsObjectArray();
Nicolas Geoffray07276db2015-05-18 14:22:09 +0100488 }
Nicolas Geoffrayaf07bc12014-11-12 18:08:09 +0000489}
490
Nicolas Geoffray01fcc9e2014-12-01 14:16:20 +0000491void InstructionSimplifierVisitor::VisitTypeConversion(HTypeConversion* instruction) {
492 if (instruction->GetResultType() == instruction->GetInputType()) {
493 // Remove the instruction if it's converting to the same type.
494 instruction->ReplaceWith(instruction->GetInput());
495 instruction->GetBlock()->RemoveInstruction(instruction);
496 }
497}
498
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000499void InstructionSimplifierVisitor::VisitAdd(HAdd* instruction) {
500 HConstant* input_cst = instruction->GetConstantRight();
501 HInstruction* input_other = instruction->GetLeastConstantLeft();
502 if ((input_cst != nullptr) && input_cst->IsZero()) {
503 // Replace code looking like
504 // ADD dst, src, 0
505 // with
506 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600507 // Note that we cannot optimize `x + 0.0` to `x` for floating-point. When
508 // `x` is `-0.0`, the former expression yields `0.0`, while the later
509 // yields `-0.0`.
510 if (Primitive::IsIntegralType(instruction->GetType())) {
511 instruction->ReplaceWith(input_other);
512 instruction->GetBlock()->RemoveInstruction(instruction);
513 return;
514 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100515 }
516
517 HInstruction* left = instruction->GetLeft();
518 HInstruction* right = instruction->GetRight();
519 bool left_is_neg = left->IsNeg();
520 bool right_is_neg = right->IsNeg();
521
522 if (left_is_neg && right_is_neg) {
523 if (TryMoveNegOnInputsAfterBinop(instruction)) {
524 return;
525 }
526 }
527
528 HNeg* neg = left_is_neg ? left->AsNeg() : right->AsNeg();
529 if ((left_is_neg ^ right_is_neg) && neg->HasOnlyOneNonEnvironmentUse()) {
530 // Replace code looking like
531 // NEG tmp, b
532 // ADD dst, a, tmp
533 // with
534 // SUB dst, a, b
535 // We do not perform the optimization if the input negation has environment
536 // uses or multiple non-environment uses as it could lead to worse code. In
537 // particular, we do not want the live range of `b` to be extended if we are
538 // not sure the initial 'NEG' instruction can be removed.
539 HInstruction* other = left_is_neg ? right : left;
540 HSub* sub = new(GetGraph()->GetArena()) HSub(instruction->GetType(), other, neg->GetInput());
541 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, sub);
542 RecordSimplification();
543 neg->GetBlock()->RemoveInstruction(neg);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000544 }
545}
546
547void InstructionSimplifierVisitor::VisitAnd(HAnd* instruction) {
548 HConstant* input_cst = instruction->GetConstantRight();
549 HInstruction* input_other = instruction->GetLeastConstantLeft();
550
Vladimir Marko452c1b62015-09-25 14:44:17 +0100551 if (input_cst != nullptr) {
552 int64_t value = Int64FromConstant(input_cst);
553 if (value == -1) {
554 // Replace code looking like
555 // AND dst, src, 0xFFF...FF
556 // with
557 // src
558 instruction->ReplaceWith(input_other);
559 instruction->GetBlock()->RemoveInstruction(instruction);
560 RecordSimplification();
561 return;
562 }
563 // Eliminate And from UShr+And if the And-mask contains all the bits that
564 // can be non-zero after UShr. Transform Shr+And to UShr if the And-mask
565 // precisely clears the shifted-in sign bits.
566 if ((input_other->IsUShr() || input_other->IsShr()) && input_other->InputAt(1)->IsConstant()) {
567 size_t reg_bits = (instruction->GetResultType() == Primitive::kPrimLong) ? 64 : 32;
568 size_t shift = Int64FromConstant(input_other->InputAt(1)->AsConstant()) & (reg_bits - 1);
569 size_t num_tail_bits_set = CTZ(value + 1);
570 if ((num_tail_bits_set >= reg_bits - shift) && input_other->IsUShr()) {
571 // This AND clears only bits known to be clear, for example "(x >>> 24) & 0xff".
572 instruction->ReplaceWith(input_other);
573 instruction->GetBlock()->RemoveInstruction(instruction);
574 RecordSimplification();
575 return;
576 } else if ((num_tail_bits_set == reg_bits - shift) && IsPowerOfTwo(value + 1) &&
577 input_other->HasOnlyOneNonEnvironmentUse()) {
578 DCHECK(input_other->IsShr()); // For UShr, we would have taken the branch above.
579 // Replace SHR+AND with USHR, for example "(x >> 24) & 0xff" -> "x >>> 24".
580 HUShr* ushr = new (GetGraph()->GetArena()) HUShr(instruction->GetType(),
581 input_other->InputAt(0),
582 input_other->InputAt(1),
583 input_other->GetDexPc());
584 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, ushr);
585 input_other->GetBlock()->RemoveInstruction(input_other);
586 RecordSimplification();
587 return;
588 }
589 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000590 }
591
592 // We assume that GVN has run before, so we only perform a pointer comparison.
593 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100594 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000595 if (instruction->GetLeft() == instruction->GetRight()) {
596 // Replace code looking like
597 // AND dst, src, src
598 // with
599 // src
600 instruction->ReplaceWith(instruction->GetLeft());
601 instruction->GetBlock()->RemoveInstruction(instruction);
602 }
603}
604
Mark Mendellc4701932015-04-10 13:18:51 -0400605void InstructionSimplifierVisitor::VisitGreaterThan(HGreaterThan* condition) {
606 VisitCondition(condition);
607}
608
609void InstructionSimplifierVisitor::VisitGreaterThanOrEqual(HGreaterThanOrEqual* condition) {
610 VisitCondition(condition);
611}
612
613void InstructionSimplifierVisitor::VisitLessThan(HLessThan* condition) {
614 VisitCondition(condition);
615}
616
617void InstructionSimplifierVisitor::VisitLessThanOrEqual(HLessThanOrEqual* condition) {
618 VisitCondition(condition);
619}
620
621void InstructionSimplifierVisitor::VisitCondition(HCondition* condition) {
622 // Try to fold an HCompare into this HCondition.
623
Roland Levillain7f63c522015-07-13 15:54:55 +0000624 // This simplification is currently supported on x86, x86_64, ARM and ARM64.
625 // TODO: Implement it for MIPS64.
Mark Mendellc4701932015-04-10 13:18:51 -0400626 InstructionSet instruction_set = GetGraph()->GetInstructionSet();
Roland Levillain7f63c522015-07-13 15:54:55 +0000627 if (instruction_set == kMips64) {
Mark Mendellc4701932015-04-10 13:18:51 -0400628 return;
629 }
630
631 HInstruction* left = condition->GetLeft();
632 HInstruction* right = condition->GetRight();
633 // We can only replace an HCondition which compares a Compare to 0.
634 // Both 'dx' and 'jack' generate a compare to 0 when compiling a
635 // condition with a long, float or double comparison as input.
636 if (!left->IsCompare() || !right->IsConstant() || right->AsIntConstant()->GetValue() != 0) {
637 // Conversion is not possible.
638 return;
639 }
640
641 // Is the Compare only used for this purpose?
642 if (!left->GetUses().HasOnlyOneUse()) {
643 // Someone else also wants the result of the compare.
644 return;
645 }
646
647 if (!left->GetEnvUses().IsEmpty()) {
648 // There is a reference to the compare result in an environment. Do we really need it?
649 if (GetGraph()->IsDebuggable()) {
650 return;
651 }
652
653 // We have to ensure that there are no deopt points in the sequence.
654 if (left->HasAnyEnvironmentUseBefore(condition)) {
655 return;
656 }
657 }
658
659 // Clean up any environment uses from the HCompare, if any.
660 left->RemoveEnvironmentUsers();
661
662 // We have decided to fold the HCompare into the HCondition. Transfer the information.
663 condition->SetBias(left->AsCompare()->GetBias());
664
665 // Replace the operands of the HCondition.
666 condition->ReplaceInput(left->InputAt(0), 0);
667 condition->ReplaceInput(left->InputAt(1), 1);
668
669 // Remove the HCompare.
670 left->GetBlock()->RemoveInstruction(left);
671
672 RecordSimplification();
673}
674
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000675void InstructionSimplifierVisitor::VisitDiv(HDiv* instruction) {
676 HConstant* input_cst = instruction->GetConstantRight();
677 HInstruction* input_other = instruction->GetLeastConstantLeft();
678 Primitive::Type type = instruction->GetType();
679
680 if ((input_cst != nullptr) && input_cst->IsOne()) {
681 // Replace code looking like
682 // DIV dst, src, 1
683 // with
684 // src
685 instruction->ReplaceWith(input_other);
686 instruction->GetBlock()->RemoveInstruction(instruction);
687 return;
688 }
689
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000690 if ((input_cst != nullptr) && input_cst->IsMinusOne()) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000691 // Replace code looking like
692 // DIV dst, src, -1
693 // with
694 // NEG dst, src
695 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000696 instruction, new (GetGraph()->GetArena()) HNeg(type, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100697 RecordSimplification();
Nicolas Geoffray0d221842015-04-27 08:53:46 +0000698 return;
699 }
700
701 if ((input_cst != nullptr) && Primitive::IsFloatingPointType(type)) {
702 // Try replacing code looking like
703 // DIV dst, src, constant
704 // with
705 // MUL dst, src, 1 / constant
706 HConstant* reciprocal = nullptr;
707 if (type == Primitive::Primitive::kPrimDouble) {
708 double value = input_cst->AsDoubleConstant()->GetValue();
709 if (CanDivideByReciprocalMultiplyDouble(bit_cast<int64_t, double>(value))) {
710 reciprocal = GetGraph()->GetDoubleConstant(1.0 / value);
711 }
712 } else {
713 DCHECK_EQ(type, Primitive::kPrimFloat);
714 float value = input_cst->AsFloatConstant()->GetValue();
715 if (CanDivideByReciprocalMultiplyFloat(bit_cast<int32_t, float>(value))) {
716 reciprocal = GetGraph()->GetFloatConstant(1.0f / value);
717 }
718 }
719
720 if (reciprocal != nullptr) {
721 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(
722 instruction, new (GetGraph()->GetArena()) HMul(type, input_other, reciprocal));
723 RecordSimplification();
724 return;
725 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000726 }
727}
728
729void InstructionSimplifierVisitor::VisitMul(HMul* instruction) {
730 HConstant* input_cst = instruction->GetConstantRight();
731 HInstruction* input_other = instruction->GetLeastConstantLeft();
732 Primitive::Type type = instruction->GetType();
733 HBasicBlock* block = instruction->GetBlock();
734 ArenaAllocator* allocator = GetGraph()->GetArena();
735
736 if (input_cst == nullptr) {
737 return;
738 }
739
740 if (input_cst->IsOne()) {
741 // Replace code looking like
742 // MUL dst, src, 1
743 // with
744 // src
745 instruction->ReplaceWith(input_other);
746 instruction->GetBlock()->RemoveInstruction(instruction);
747 return;
748 }
749
750 if (input_cst->IsMinusOne() &&
751 (Primitive::IsFloatingPointType(type) || Primitive::IsIntOrLongType(type))) {
752 // Replace code looking like
753 // MUL dst, src, -1
754 // with
755 // NEG dst, src
756 HNeg* neg = new (allocator) HNeg(type, input_other);
757 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100758 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000759 return;
760 }
761
762 if (Primitive::IsFloatingPointType(type) &&
763 ((input_cst->IsFloatConstant() && input_cst->AsFloatConstant()->GetValue() == 2.0f) ||
764 (input_cst->IsDoubleConstant() && input_cst->AsDoubleConstant()->GetValue() == 2.0))) {
765 // Replace code looking like
766 // FP_MUL dst, src, 2.0
767 // with
768 // FP_ADD dst, src, src
769 // The 'int' and 'long' cases are handled below.
770 block->ReplaceAndRemoveInstructionWith(instruction,
771 new (allocator) HAdd(type, input_other, input_other));
Alexandre Rames188d4312015-04-09 18:30:21 +0100772 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000773 return;
774 }
775
776 if (Primitive::IsIntOrLongType(type)) {
777 int64_t factor = Int64FromConstant(input_cst);
Serguei Katkov53849192015-04-20 14:22:27 +0600778 // Even though constant propagation also takes care of the zero case, other
779 // optimizations can lead to having a zero multiplication.
780 if (factor == 0) {
781 // Replace code looking like
782 // MUL dst, src, 0
783 // with
784 // 0
785 instruction->ReplaceWith(input_cst);
786 instruction->GetBlock()->RemoveInstruction(instruction);
787 } else if (IsPowerOfTwo(factor)) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000788 // Replace code looking like
789 // MUL dst, src, pow_of_2
790 // with
791 // SHL dst, src, log2(pow_of_2)
David Brazdil8d5b8b22015-03-24 10:51:52 +0000792 HIntConstant* shift = GetGraph()->GetIntConstant(WhichPowerOf2(factor));
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000793 HShl* shl = new(allocator) HShl(type, input_other, shift);
794 block->ReplaceAndRemoveInstructionWith(instruction, shl);
Alexandre Rames188d4312015-04-09 18:30:21 +0100795 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000796 }
797 }
798}
799
Alexandre Rames188d4312015-04-09 18:30:21 +0100800void InstructionSimplifierVisitor::VisitNeg(HNeg* instruction) {
801 HInstruction* input = instruction->GetInput();
802 if (input->IsNeg()) {
803 // Replace code looking like
804 // NEG tmp, src
805 // NEG dst, tmp
806 // with
807 // src
808 HNeg* previous_neg = input->AsNeg();
809 instruction->ReplaceWith(previous_neg->GetInput());
810 instruction->GetBlock()->RemoveInstruction(instruction);
811 // We perform the optimization even if the input negation has environment
812 // uses since it allows removing the current instruction. But we only delete
813 // the input negation only if it is does not have any uses left.
814 if (!previous_neg->HasUses()) {
815 previous_neg->GetBlock()->RemoveInstruction(previous_neg);
816 }
817 RecordSimplification();
818 return;
819 }
820
Serguei Katkov339dfc22015-04-20 12:29:32 +0600821 if (input->IsSub() && input->HasOnlyOneNonEnvironmentUse() &&
822 !Primitive::IsFloatingPointType(input->GetType())) {
Alexandre Rames188d4312015-04-09 18:30:21 +0100823 // Replace code looking like
824 // SUB tmp, a, b
825 // NEG dst, tmp
826 // with
827 // SUB dst, b, a
828 // We do not perform the optimization if the input subtraction has
829 // environment uses or multiple non-environment uses as it could lead to
830 // worse code. In particular, we do not want the live ranges of `a` and `b`
831 // to be extended if we are not sure the initial 'SUB' instruction can be
832 // removed.
Serguei Katkov339dfc22015-04-20 12:29:32 +0600833 // We do not perform optimization for fp because we could lose the sign of zero.
Alexandre Rames188d4312015-04-09 18:30:21 +0100834 HSub* sub = input->AsSub();
835 HSub* new_sub =
836 new (GetGraph()->GetArena()) HSub(instruction->GetType(), sub->GetRight(), sub->GetLeft());
837 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, new_sub);
838 if (!sub->HasUses()) {
839 sub->GetBlock()->RemoveInstruction(sub);
840 }
841 RecordSimplification();
842 }
843}
844
845void InstructionSimplifierVisitor::VisitNot(HNot* instruction) {
846 HInstruction* input = instruction->GetInput();
847 if (input->IsNot()) {
848 // Replace code looking like
849 // NOT tmp, src
850 // NOT dst, tmp
851 // with
852 // src
853 // We perform the optimization even if the input negation has environment
854 // uses since it allows removing the current instruction. But we only delete
855 // the input negation only if it is does not have any uses left.
856 HNot* previous_not = input->AsNot();
857 instruction->ReplaceWith(previous_not->GetInput());
858 instruction->GetBlock()->RemoveInstruction(instruction);
859 if (!previous_not->HasUses()) {
860 previous_not->GetBlock()->RemoveInstruction(previous_not);
861 }
862 RecordSimplification();
863 }
864}
865
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000866void InstructionSimplifierVisitor::VisitOr(HOr* instruction) {
867 HConstant* input_cst = instruction->GetConstantRight();
868 HInstruction* input_other = instruction->GetLeastConstantLeft();
869
870 if ((input_cst != nullptr) && input_cst->IsZero()) {
871 // Replace code looking like
872 // OR dst, src, 0
873 // with
874 // src
875 instruction->ReplaceWith(input_other);
876 instruction->GetBlock()->RemoveInstruction(instruction);
877 return;
878 }
879
880 // We assume that GVN has run before, so we only perform a pointer comparison.
881 // If for some reason the values are equal but the pointers are different, we
Alexandre Rames188d4312015-04-09 18:30:21 +0100882 // are still correct and only miss an optimization opportunity.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000883 if (instruction->GetLeft() == instruction->GetRight()) {
884 // Replace code looking like
885 // OR dst, src, src
886 // with
887 // src
888 instruction->ReplaceWith(instruction->GetLeft());
889 instruction->GetBlock()->RemoveInstruction(instruction);
890 }
891}
892
893void InstructionSimplifierVisitor::VisitShl(HShl* instruction) {
894 VisitShift(instruction);
895}
896
897void InstructionSimplifierVisitor::VisitShr(HShr* instruction) {
898 VisitShift(instruction);
899}
900
901void InstructionSimplifierVisitor::VisitSub(HSub* instruction) {
902 HConstant* input_cst = instruction->GetConstantRight();
903 HInstruction* input_other = instruction->GetLeastConstantLeft();
904
Serguei Katkov115b53f2015-08-05 17:03:30 +0600905 Primitive::Type type = instruction->GetType();
906 if (Primitive::IsFloatingPointType(type)) {
907 return;
908 }
909
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000910 if ((input_cst != nullptr) && input_cst->IsZero()) {
911 // Replace code looking like
912 // SUB dst, src, 0
913 // with
914 // src
Serguei Katkov115b53f2015-08-05 17:03:30 +0600915 // Note that we cannot optimize `x - 0.0` to `x` for floating-point. When
916 // `x` is `-0.0`, the former expression yields `0.0`, while the later
917 // yields `-0.0`.
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000918 instruction->ReplaceWith(input_other);
919 instruction->GetBlock()->RemoveInstruction(instruction);
920 return;
921 }
922
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000923 HBasicBlock* block = instruction->GetBlock();
924 ArenaAllocator* allocator = GetGraph()->GetArena();
925
Alexandre Rames188d4312015-04-09 18:30:21 +0100926 HInstruction* left = instruction->GetLeft();
927 HInstruction* right = instruction->GetRight();
928 if (left->IsConstant()) {
929 if (Int64FromConstant(left->AsConstant()) == 0) {
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000930 // Replace code looking like
931 // SUB dst, 0, src
932 // with
933 // NEG dst, src
Alexandre Rames188d4312015-04-09 18:30:21 +0100934 // Note that we cannot optimize `0.0 - x` to `-x` for floating-point. When
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000935 // `x` is `0.0`, the former expression yields `0.0`, while the later
936 // yields `-0.0`.
Alexandre Rames188d4312015-04-09 18:30:21 +0100937 HNeg* neg = new (allocator) HNeg(type, right);
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000938 block->ReplaceAndRemoveInstructionWith(instruction, neg);
Alexandre Rames188d4312015-04-09 18:30:21 +0100939 RecordSimplification();
940 return;
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000941 }
942 }
Alexandre Rames188d4312015-04-09 18:30:21 +0100943
944 if (left->IsNeg() && right->IsNeg()) {
945 if (TryMoveNegOnInputsAfterBinop(instruction)) {
946 return;
947 }
948 }
949
950 if (right->IsNeg() && right->HasOnlyOneNonEnvironmentUse()) {
951 // Replace code looking like
952 // NEG tmp, b
953 // SUB dst, a, tmp
954 // with
955 // ADD dst, a, b
956 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left, right->AsNeg()->GetInput());
957 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, add);
958 RecordSimplification();
959 right->GetBlock()->RemoveInstruction(right);
960 return;
961 }
962
963 if (left->IsNeg() && left->HasOnlyOneNonEnvironmentUse()) {
964 // Replace code looking like
965 // NEG tmp, a
966 // SUB dst, tmp, b
967 // with
968 // ADD tmp, a, b
969 // NEG dst, tmp
970 // The second version is not intrinsically better, but enables more
971 // transformations.
972 HAdd* add = new(GetGraph()->GetArena()) HAdd(type, left->AsNeg()->GetInput(), right);
973 instruction->GetBlock()->InsertInstructionBefore(add, instruction);
974 HNeg* neg = new (GetGraph()->GetArena()) HNeg(instruction->GetType(), add);
975 instruction->GetBlock()->InsertInstructionBefore(neg, instruction);
976 instruction->ReplaceWith(neg);
977 instruction->GetBlock()->RemoveInstruction(instruction);
978 RecordSimplification();
979 left->GetBlock()->RemoveInstruction(left);
980 }
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +0000981}
982
983void InstructionSimplifierVisitor::VisitUShr(HUShr* instruction) {
984 VisitShift(instruction);
985}
986
987void InstructionSimplifierVisitor::VisitXor(HXor* instruction) {
988 HConstant* input_cst = instruction->GetConstantRight();
989 HInstruction* input_other = instruction->GetLeastConstantLeft();
990
991 if ((input_cst != nullptr) && input_cst->IsZero()) {
992 // Replace code looking like
993 // XOR dst, src, 0
994 // with
995 // src
996 instruction->ReplaceWith(input_other);
997 instruction->GetBlock()->RemoveInstruction(instruction);
998 return;
999 }
1000
1001 if ((input_cst != nullptr) && AreAllBitsSet(input_cst)) {
1002 // Replace code looking like
1003 // XOR dst, src, 0xFFF...FF
1004 // with
1005 // NOT dst, src
1006 HNot* bitwise_not = new (GetGraph()->GetArena()) HNot(instruction->GetType(), input_other);
1007 instruction->GetBlock()->ReplaceAndRemoveInstructionWith(instruction, bitwise_not);
Alexandre Rames188d4312015-04-09 18:30:21 +01001008 RecordSimplification();
Alexandre Ramesb2fd7bc2015-03-11 16:48:16 +00001009 return;
1010 }
1011}
1012
Nicolas Geoffray2e7cd752015-07-10 11:38:52 +01001013void InstructionSimplifierVisitor::VisitFakeString(HFakeString* instruction) {
1014 HInstruction* actual_string = nullptr;
1015
1016 // Find the string we need to replace this instruction with. The actual string is
1017 // the return value of a StringFactory call.
1018 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1019 HInstruction* use = it.Current()->GetUser();
1020 if (use->IsInvokeStaticOrDirect()
1021 && use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction)) {
1022 use->AsInvokeStaticOrDirect()->RemoveFakeStringArgumentAsLastInput();
1023 actual_string = use;
1024 break;
1025 }
1026 }
1027
1028 // Check that there is no other instruction that thinks it is the factory for that string.
1029 if (kIsDebugBuild) {
1030 CHECK(actual_string != nullptr);
1031 for (HUseIterator<HInstruction*> it(instruction->GetUses()); !it.Done(); it.Advance()) {
1032 HInstruction* use = it.Current()->GetUser();
1033 if (use->IsInvokeStaticOrDirect()) {
1034 CHECK(!use->AsInvokeStaticOrDirect()->IsStringFactoryFor(instruction));
1035 }
1036 }
1037 }
1038
1039 // We need to remove any environment uses of the fake string that are not dominated by
1040 // `actual_string` to null.
1041 for (HUseIterator<HEnvironment*> it(instruction->GetEnvUses()); !it.Done(); it.Advance()) {
1042 HEnvironment* environment = it.Current()->GetUser();
1043 if (!actual_string->StrictlyDominates(environment->GetHolder())) {
1044 environment->RemoveAsUserOfInput(it.Current()->GetIndex());
1045 environment->SetRawEnvAt(it.Current()->GetIndex(), nullptr);
1046 }
1047 }
1048
1049 // Only uses dominated by `actual_string` must remain. We can safely replace and remove
1050 // `instruction`.
1051 instruction->ReplaceWith(actual_string);
1052 instruction->GetBlock()->RemoveInstruction(instruction);
1053}
1054
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001055void InstructionSimplifierVisitor::SimplifyStringEquals(HInvoke* instruction) {
1056 HInstruction* argument = instruction->InputAt(1);
1057 HInstruction* receiver = instruction->InputAt(0);
1058 if (receiver == argument) {
1059 // Because String.equals is an instance call, the receiver is
1060 // a null check if we don't know it's null. The argument however, will
1061 // be the actual object. So we cannot end up in a situation where both
1062 // are equal but could be null.
1063 DCHECK(CanEnsureNotNullAt(argument, instruction));
1064 instruction->ReplaceWith(GetGraph()->GetIntConstant(1));
1065 instruction->GetBlock()->RemoveInstruction(instruction);
1066 } else {
1067 StringEqualsOptimizations optimizations(instruction);
1068 if (CanEnsureNotNullAt(argument, instruction)) {
1069 optimizations.SetArgumentNotNull();
1070 }
1071 ScopedObjectAccess soa(Thread::Current());
1072 ReferenceTypeInfo argument_rti = argument->GetReferenceTypeInfo();
1073 if (argument_rti.IsValid() && argument_rti.IsStringClass()) {
1074 optimizations.SetArgumentIsString();
1075 }
1076 }
1077}
1078
1079static bool IsArrayLengthOf(HInstruction* potential_length, HInstruction* potential_array) {
1080 if (potential_length->IsArrayLength()) {
1081 return potential_length->InputAt(0) == potential_array;
1082 }
1083
1084 if (potential_array->IsNewArray()) {
1085 return potential_array->InputAt(0) == potential_length;
1086 }
1087
1088 return false;
1089}
1090
1091void InstructionSimplifierVisitor::SimplifySystemArrayCopy(HInvoke* instruction) {
1092 HInstruction* source = instruction->InputAt(0);
1093 HInstruction* destination = instruction->InputAt(2);
1094 HInstruction* count = instruction->InputAt(4);
1095 SystemArrayCopyOptimizations optimizations(instruction);
1096 if (CanEnsureNotNullAt(source, instruction)) {
1097 optimizations.SetSourceIsNotNull();
1098 }
1099 if (CanEnsureNotNullAt(destination, instruction)) {
1100 optimizations.SetDestinationIsNotNull();
1101 }
1102 if (destination == source) {
1103 optimizations.SetDestinationIsSource();
1104 }
1105
1106 if (IsArrayLengthOf(count, source)) {
1107 optimizations.SetCountIsSourceLength();
1108 }
1109
1110 if (IsArrayLengthOf(count, destination)) {
1111 optimizations.SetCountIsDestinationLength();
1112 }
1113
1114 {
1115 ScopedObjectAccess soa(Thread::Current());
1116 ReferenceTypeInfo destination_rti = destination->GetReferenceTypeInfo();
1117 if (destination_rti.IsValid()) {
1118 if (destination_rti.IsObjectArray()) {
1119 if (destination_rti.IsExact()) {
1120 optimizations.SetDoesNotNeedTypeCheck();
1121 }
1122 optimizations.SetDestinationIsTypedObjectArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001123 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001124 if (destination_rti.IsPrimitiveArrayClass()) {
1125 optimizations.SetDestinationIsPrimitiveArray();
1126 } else if (destination_rti.IsNonPrimitiveArrayClass()) {
1127 optimizations.SetDestinationIsNonPrimitiveArray();
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001128 }
1129 }
Nicolas Geoffrayee3cf072015-10-06 11:45:02 +01001130 ReferenceTypeInfo source_rti = source->GetReferenceTypeInfo();
1131 if (source_rti.IsValid()) {
1132 if (destination_rti.IsValid() && destination_rti.CanArrayHoldValuesOf(source_rti)) {
1133 optimizations.SetDoesNotNeedTypeCheck();
1134 }
1135 if (source_rti.IsPrimitiveArrayClass()) {
1136 optimizations.SetSourceIsPrimitiveArray();
1137 } else if (source_rti.IsNonPrimitiveArrayClass()) {
1138 optimizations.SetSourceIsNonPrimitiveArray();
1139 }
1140 }
1141 }
1142}
1143
1144void InstructionSimplifierVisitor::VisitInvoke(HInvoke* instruction) {
1145 if (instruction->GetIntrinsic() == Intrinsics::kStringEquals) {
1146 SimplifyStringEquals(instruction);
1147 } else if (instruction->GetIntrinsic() == Intrinsics::kSystemArrayCopy) {
1148 SimplifySystemArrayCopy(instruction);
Nicolas Geoffraya83a54d2015-10-02 17:30:26 +01001149 }
1150}
1151
Nicolas Geoffray3c049742014-09-24 18:10:46 +01001152} // namespace art