blob: c694ea8118b4df0ec38af573b7832c1f8793b4ea [file] [log] [blame]
Mingyao Yangf384f882014-10-22 16:08:18 -07001/*
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 "bounds_check_elimination.h"
Aart Bikaab5b752015-09-23 11:18:57 -070018
19#include <limits>
20
21#include "base/arena_containers.h"
Aart Bik22af3be2015-09-10 12:50:58 -070022#include "induction_var_range.h"
Aart Bik4a342772015-11-30 10:17:46 -080023#include "side_effects_analysis.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070024#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070025
26namespace art {
27
28class MonotonicValueRange;
29
30/**
31 * A value bound is represented as a pair of value and constant,
32 * e.g. array.length - 1.
33 */
34class ValueBound : public ValueObject {
35 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080036 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080037 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080038 // Normalize ValueBound with constant instruction.
39 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080040 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080041 instruction_ = nullptr;
42 constant_ = instr_const + constant;
43 return;
44 }
Mingyao Yangf384f882014-10-22 16:08:18 -070045 }
Mingyao Yang64197522014-12-05 15:56:23 -080046 instruction_ = instruction;
47 constant_ = constant;
48 }
49
Mingyao Yang8c8bad82015-02-09 18:13:26 -080050 // Return whether (left + right) overflows or underflows.
51 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
52 if (right == 0) {
53 return false;
54 }
Aart Bikaab5b752015-09-23 11:18:57 -070055 if ((right > 0) && (left <= (std::numeric_limits<int32_t>::max() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080056 // No overflow.
57 return false;
58 }
Aart Bikaab5b752015-09-23 11:18:57 -070059 if ((right < 0) && (left >= (std::numeric_limits<int32_t>::min() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080060 // No underflow.
61 return false;
62 }
63 return true;
64 }
65
Aart Bik1d239822016-02-09 14:26:34 -080066 // Return true if instruction can be expressed as "left_instruction + right_constant".
Mingyao Yang0304e182015-01-30 16:41:29 -080067 static bool IsAddOrSubAConstant(HInstruction* instruction,
Aart Bik1d239822016-02-09 14:26:34 -080068 /* out */ HInstruction** left_instruction,
69 /* out */ int32_t* right_constant) {
Mingyao Yang0304e182015-01-30 16:41:29 -080070 if (instruction->IsAdd() || instruction->IsSub()) {
71 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
72 HInstruction* left = bin_op->GetLeft();
73 HInstruction* right = bin_op->GetRight();
74 if (right->IsIntConstant()) {
75 *left_instruction = left;
76 int32_t c = right->AsIntConstant()->GetValue();
77 *right_constant = instruction->IsAdd() ? c : -c;
78 return true;
79 }
80 }
81 *left_instruction = nullptr;
82 *right_constant = 0;
83 return false;
84 }
85
Aart Bik1d239822016-02-09 14:26:34 -080086 // Expresses any instruction as a value bound.
87 static ValueBound AsValueBound(HInstruction* instruction) {
88 if (instruction->IsIntConstant()) {
89 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
90 }
91 HInstruction *left;
92 int32_t right;
93 if (IsAddOrSubAConstant(instruction, &left, &right)) {
94 return ValueBound(left, right);
95 }
96 return ValueBound(instruction, 0);
97 }
98
Mingyao Yang64197522014-12-05 15:56:23 -080099 // Try to detect useful value bound format from an instruction, e.g.
100 // a constant or array length related value.
Aart Bik1d239822016-02-09 14:26:34 -0800101 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, /* out */ bool* found) {
Mingyao Yang64197522014-12-05 15:56:23 -0800102 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -0700103 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800104 *found = true;
105 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -0700106 }
Mingyao Yang64197522014-12-05 15:56:23 -0800107
108 if (instruction->IsArrayLength()) {
109 *found = true;
110 return ValueBound(instruction, 0);
111 }
112 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -0800113 HInstruction *left;
114 int32_t right;
115 if (IsAddOrSubAConstant(instruction, &left, &right)) {
116 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800117 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -0800118 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800119 }
120 }
121
122 // No useful bound detected.
123 *found = false;
124 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700125 }
126
127 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800128 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700129
Mingyao Yang0304e182015-01-30 16:41:29 -0800130 bool IsRelatedToArrayLength() const {
131 // Some bounds are created with HNewArray* as the instruction instead
132 // of HArrayLength*. They are treated the same.
133 return (instruction_ != nullptr) &&
134 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700135 }
136
137 bool IsConstant() const {
138 return instruction_ == nullptr;
139 }
140
Aart Bikaab5b752015-09-23 11:18:57 -0700141 static ValueBound Min() { return ValueBound(nullptr, std::numeric_limits<int32_t>::min()); }
142 static ValueBound Max() { return ValueBound(nullptr, std::numeric_limits<int32_t>::max()); }
Mingyao Yangf384f882014-10-22 16:08:18 -0700143
144 bool Equals(ValueBound bound) const {
145 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
146 }
147
Aart Bik22af3be2015-09-10 12:50:58 -0700148 /*
149 * Hunt "under the hood" of array lengths (leading to array references),
150 * null checks (also leading to array references), and new arrays
151 * (leading to the actual length). This makes it more likely related
152 * instructions become actually comparable.
153 */
154 static HInstruction* HuntForDeclaration(HInstruction* instruction) {
155 while (instruction->IsArrayLength() ||
156 instruction->IsNullCheck() ||
157 instruction->IsNewArray()) {
158 instruction = instruction->InputAt(0);
Mingyao Yang0304e182015-01-30 16:41:29 -0800159 }
160 return instruction;
161 }
162
163 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
164 if (instruction1 == instruction2) {
165 return true;
166 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800167 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700168 return false;
169 }
Aart Bik22af3be2015-09-10 12:50:58 -0700170 instruction1 = HuntForDeclaration(instruction1);
171 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800172 return instruction1 == instruction2;
173 }
174
175 // Returns if it's certain this->bound >= `bound`.
176 bool GreaterThanOrEqualTo(ValueBound bound) const {
177 if (Equal(instruction_, bound.instruction_)) {
178 return constant_ >= bound.constant_;
179 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700180 // Not comparable. Just return false.
181 return false;
182 }
183
Mingyao Yang0304e182015-01-30 16:41:29 -0800184 // Returns if it's certain this->bound <= `bound`.
185 bool LessThanOrEqualTo(ValueBound bound) const {
186 if (Equal(instruction_, bound.instruction_)) {
187 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700188 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700189 // Not comparable. Just return false.
190 return false;
191 }
192
Aart Bik4a342772015-11-30 10:17:46 -0800193 // Returns if it's certain this->bound > `bound`.
194 bool GreaterThan(ValueBound bound) const {
195 if (Equal(instruction_, bound.instruction_)) {
196 return constant_ > bound.constant_;
197 }
198 // Not comparable. Just return false.
199 return false;
200 }
201
202 // Returns if it's certain this->bound < `bound`.
203 bool LessThan(ValueBound bound) const {
204 if (Equal(instruction_, bound.instruction_)) {
205 return constant_ < bound.constant_;
206 }
207 // Not comparable. Just return false.
208 return false;
209 }
210
Mingyao Yangf384f882014-10-22 16:08:18 -0700211 // Try to narrow lower bound. Returns the greatest of the two if possible.
212 // Pick one if they are not comparable.
213 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800214 if (bound1.GreaterThanOrEqualTo(bound2)) {
215 return bound1;
216 }
217 if (bound2.GreaterThanOrEqualTo(bound1)) {
218 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700219 }
220
221 // Not comparable. Just pick one. We may lose some info, but that's ok.
222 // Favor constant as lower bound.
223 return bound1.IsConstant() ? bound1 : bound2;
224 }
225
226 // Try to narrow upper bound. Returns the lowest of the two if possible.
227 // Pick one if they are not comparable.
228 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800229 if (bound1.LessThanOrEqualTo(bound2)) {
230 return bound1;
231 }
232 if (bound2.LessThanOrEqualTo(bound1)) {
233 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700234 }
235
236 // Not comparable. Just pick one. We may lose some info, but that's ok.
237 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800238 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700239 }
240
Mingyao Yang0304e182015-01-30 16:41:29 -0800241 // Add a constant to a ValueBound.
242 // `overflow` or `underflow` will return whether the resulting bound may
243 // overflow or underflow an int.
Aart Bik1d239822016-02-09 14:26:34 -0800244 ValueBound Add(int32_t c, /* out */ bool* overflow, /* out */ bool* underflow) const {
Mingyao Yang0304e182015-01-30 16:41:29 -0800245 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700246 if (c == 0) {
247 return *this;
248 }
249
Mingyao Yang0304e182015-01-30 16:41:29 -0800250 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700251 if (c > 0) {
Aart Bikaab5b752015-09-23 11:18:57 -0700252 if (constant_ > (std::numeric_limits<int32_t>::max() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800253 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800254 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700255 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800256
257 new_constant = constant_ + c;
258 // (array.length + non-positive-constant) won't overflow an int.
259 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
260 return ValueBound(instruction_, new_constant);
261 }
262 // Be conservative.
263 *overflow = true;
264 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700265 } else {
Aart Bikaab5b752015-09-23 11:18:57 -0700266 if (constant_ < (std::numeric_limits<int32_t>::min() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800267 *underflow = true;
268 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700269 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800270
271 new_constant = constant_ + c;
272 // Regardless of the value new_constant, (array.length+new_constant) will
273 // never underflow since array.length is no less than 0.
274 if (IsConstant() || IsRelatedToArrayLength()) {
275 return ValueBound(instruction_, new_constant);
276 }
277 // Be conservative.
278 *underflow = true;
279 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700280 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700281 }
282
283 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700284 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800285 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700286};
287
288/**
289 * Represent a range of lower bound and upper bound, both being inclusive.
290 * Currently a ValueRange may be generated as a result of the following:
291 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800292 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700293 * incrementing/decrementing array index (MonotonicValueRange).
294 */
Vladimir Marko5233f932015-09-29 19:01:15 +0100295class ValueRange : public ArenaObject<kArenaAllocBoundsCheckElimination> {
Mingyao Yangf384f882014-10-22 16:08:18 -0700296 public:
297 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
298 : allocator_(allocator), lower_(lower), upper_(upper) {}
299
300 virtual ~ValueRange() {}
301
Mingyao Yang57e04752015-02-09 18:13:26 -0800302 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
303 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700304 return AsMonotonicValueRange() != nullptr;
305 }
306
307 ArenaAllocator* GetAllocator() const { return allocator_; }
308 ValueBound GetLower() const { return lower_; }
309 ValueBound GetUpper() const { return upper_; }
310
Mingyao Yang3584bce2015-05-19 16:01:59 -0700311 bool IsConstantValueRange() { return lower_.IsConstant() && upper_.IsConstant(); }
312
Mingyao Yangf384f882014-10-22 16:08:18 -0700313 // If it's certain that this value range fits in other_range.
314 virtual bool FitsIn(ValueRange* other_range) const {
315 if (other_range == nullptr) {
316 return true;
317 }
318 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800319 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
320 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700321 }
322
323 // Returns the intersection of this and range.
324 // If it's not possible to do intersection because some
325 // bounds are not comparable, it's ok to pick either bound.
326 virtual ValueRange* Narrow(ValueRange* range) {
327 if (range == nullptr) {
328 return this;
329 }
330
331 if (range->IsMonotonicValueRange()) {
332 return this;
333 }
334
335 return new (allocator_) ValueRange(
336 allocator_,
337 ValueBound::NarrowLowerBound(lower_, range->lower_),
338 ValueBound::NarrowUpperBound(upper_, range->upper_));
339 }
340
Mingyao Yang0304e182015-01-30 16:41:29 -0800341 // Shift a range by a constant.
342 ValueRange* Add(int32_t constant) const {
343 bool overflow, underflow;
344 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
345 if (underflow) {
346 // Lower bound underflow will wrap around to positive values
347 // and invalidate the upper bound.
348 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700349 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800350 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
351 if (overflow) {
352 // Upper bound overflow will wrap around to negative values
353 // and invalidate the lower bound.
354 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700355 }
356 return new (allocator_) ValueRange(allocator_, lower, upper);
357 }
358
Mingyao Yangf384f882014-10-22 16:08:18 -0700359 private:
360 ArenaAllocator* const allocator_;
361 const ValueBound lower_; // inclusive
362 const ValueBound upper_; // inclusive
363
364 DISALLOW_COPY_AND_ASSIGN(ValueRange);
365};
366
367/**
368 * A monotonically incrementing/decrementing value range, e.g.
369 * the variable i in "for (int i=0; i<array.length; i++)".
370 * Special care needs to be taken to account for overflow/underflow
371 * of such value ranges.
372 */
373class MonotonicValueRange : public ValueRange {
374 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800375 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700376 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800377 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800378 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800379 ValueBound bound)
Aart Bikaab5b752015-09-23 11:18:57 -0700380 // To be conservative, give it full range [Min(), Max()] in case it's
Mingyao Yang64197522014-12-05 15:56:23 -0800381 // used as a regular value range, due to possible overflow/underflow.
382 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700383 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800384 initial_(initial),
385 increment_(increment),
386 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700387
388 virtual ~MonotonicValueRange() {}
389
Mingyao Yang57e04752015-02-09 18:13:26 -0800390 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800391 ValueBound GetBound() const { return bound_; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700392 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700393 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
394 return induction_variable_->GetBlock();
395 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800396
397 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700398
399 // If it's certain that this value range fits in other_range.
400 bool FitsIn(ValueRange* other_range) const OVERRIDE {
401 if (other_range == nullptr) {
402 return true;
403 }
404 DCHECK(!other_range->IsMonotonicValueRange());
405 return false;
406 }
407
408 // Try to narrow this MonotonicValueRange given another range.
409 // Ideally it will return a normal ValueRange. But due to
410 // possible overflow/underflow, that may not be possible.
411 ValueRange* Narrow(ValueRange* range) OVERRIDE {
412 if (range == nullptr) {
413 return this;
414 }
415 DCHECK(!range->IsMonotonicValueRange());
416
417 if (increment_ > 0) {
418 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800419 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Aart Bikaab5b752015-09-23 11:18:57 -0700420 if (!lower.IsConstant() || lower.GetConstant() == std::numeric_limits<int32_t>::min()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700421 // Lower bound isn't useful. Leave it to deoptimization.
422 return this;
423 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700424
Aart Bikaab5b752015-09-23 11:18:57 -0700425 // We currently conservatively assume max array length is Max().
426 // If we can make assumptions about the max array length, e.g. due to the max heap size,
Mingyao Yangf384f882014-10-22 16:08:18 -0700427 // divided by the element size (such as 4 bytes for each integer array), we can
428 // lower this number and rule out some possible overflows.
Aart Bikaab5b752015-09-23 11:18:57 -0700429 int32_t max_array_len = std::numeric_limits<int32_t>::max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700430
Mingyao Yang0304e182015-01-30 16:41:29 -0800431 // max possible integer value of range's upper value.
Aart Bikaab5b752015-09-23 11:18:57 -0700432 int32_t upper = std::numeric_limits<int32_t>::max();
Mingyao Yang0304e182015-01-30 16:41:29 -0800433 // Try to lower upper.
434 ValueBound upper_bound = range->GetUpper();
435 if (upper_bound.IsConstant()) {
436 upper = upper_bound.GetConstant();
437 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
438 // Normal case. e.g. <= array.length - 1.
439 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700440 }
441
442 // If we can prove for the last number in sequence of initial_,
443 // initial_ + increment_, initial_ + 2 x increment_, ...
444 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
445 // then this MonoticValueRange is narrowed to a normal value range.
446
447 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800448 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700449 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800450 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700451 if (upper <= initial_constant) {
452 last_num_in_sequence = upper;
453 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800454 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700455 last_num_in_sequence = initial_constant +
456 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
457 }
458 }
Aart Bikaab5b752015-09-23 11:18:57 -0700459 if (last_num_in_sequence <= (std::numeric_limits<int32_t>::max() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700460 // No overflow. The sequence will be stopped by the upper bound test as expected.
461 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
462 }
463
464 // There might be overflow. Give up narrowing.
465 return this;
466 } else {
467 DCHECK_NE(increment_, 0);
468 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800469 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Aart Bikaab5b752015-09-23 11:18:57 -0700470 if ((!upper.IsConstant() || upper.GetConstant() == std::numeric_limits<int32_t>::max()) &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700471 !upper.IsRelatedToArrayLength()) {
472 // Upper bound isn't useful. Leave it to deoptimization.
473 return this;
474 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700475
476 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800477 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700478 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800479 int32_t constant = range->GetLower().GetConstant();
Aart Bikaab5b752015-09-23 11:18:57 -0700480 if (constant >= (std::numeric_limits<int32_t>::min() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700481 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
482 }
483 }
484
Mingyao Yang0304e182015-01-30 16:41:29 -0800485 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700486 return this;
487 }
488 }
489
490 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700491 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
492 HInstruction* const initial_; // Initial value.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700493 const int32_t increment_; // Increment for each loop iteration.
494 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700495
496 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
497};
498
499class BCEVisitor : public HGraphVisitor {
500 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700501 // The least number of bounds checks that should be eliminated by triggering
502 // the deoptimization technique.
503 static constexpr size_t kThresholdForAddingDeoptimize = 2;
504
Aart Bik1d239822016-02-09 14:26:34 -0800505 // Very large lengths are considered an anomaly. This is a threshold beyond which we don't
506 // bother to apply the deoptimization technique since it's likely, or sometimes certain,
507 // an AIOOBE will be thrown.
508 static constexpr uint32_t kMaxLengthForAddingDeoptimize =
Aart Bikaab5b752015-09-23 11:18:57 -0700509 std::numeric_limits<int32_t>::max() - 1024 * 1024;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700510
Mingyao Yang3584bce2015-05-19 16:01:59 -0700511 // Added blocks for loop body entry test.
512 bool IsAddedBlock(HBasicBlock* block) const {
513 return block->GetBlockId() >= initial_block_size_;
514 }
515
Aart Bik4a342772015-11-30 10:17:46 -0800516 BCEVisitor(HGraph* graph,
517 const SideEffectsAnalysis& side_effects,
518 HInductionVarAnalysis* induction_analysis)
Aart Bik22af3be2015-09-10 12:50:58 -0700519 : HGraphVisitor(graph),
Vladimir Marko5233f932015-09-29 19:01:15 +0100520 maps_(graph->GetBlocks().size(),
521 ArenaSafeMap<int, ValueRange*>(
522 std::less<int>(),
523 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
524 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800525 first_index_bounds_check_map_(
Vladimir Marko5233f932015-09-29 19:01:15 +0100526 std::less<int>(),
527 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik4a342772015-11-30 10:17:46 -0800528 early_exit_loop_(
529 std::less<uint32_t>(),
530 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
531 taken_test_loop_(
532 std::less<uint32_t>(),
533 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
534 finite_loop_(graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800535 has_dom_based_dynamic_bce_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100536 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800537 side_effects_(side_effects),
Aart Bik22af3be2015-09-10 12:50:58 -0700538 induction_range_(induction_analysis) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700539
540 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700541 DCHECK(!IsAddedBlock(block));
Aart Bik1d239822016-02-09 14:26:34 -0800542 first_index_bounds_check_map_.clear();
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700543 HGraphVisitor::VisitBasicBlock(block);
Aart Bik1d239822016-02-09 14:26:34 -0800544 AddComparesWithDeoptimization(block);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700545 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700546
Aart Bik4a342772015-11-30 10:17:46 -0800547 void Finish() {
548 // Preserve SSA structure which may have been broken by adding one or more
549 // new taken-test structures (see TransformLoopForDeoptimizationIfNeeded()).
550 InsertPhiNodes();
551
552 // Clear the loop data structures.
553 early_exit_loop_.clear();
554 taken_test_loop_.clear();
555 finite_loop_.clear();
556 }
557
Mingyao Yangf384f882014-10-22 16:08:18 -0700558 private:
559 // Return the map of proven value ranges at the beginning of a basic block.
560 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700561 if (IsAddedBlock(basic_block)) {
562 // Added blocks don't keep value ranges.
563 return nullptr;
564 }
Aart Bik1d239822016-02-09 14:26:34 -0800565 return &maps_[basic_block->GetBlockId()];
Mingyao Yangf384f882014-10-22 16:08:18 -0700566 }
567
568 // Traverse up the dominator tree to look for value range info.
569 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
570 while (basic_block != nullptr) {
571 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700572 if (map != nullptr) {
573 if (map->find(instruction->GetId()) != map->end()) {
574 return map->Get(instruction->GetId());
575 }
576 } else {
577 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -0700578 }
579 basic_block = basic_block->GetDominator();
580 }
581 // Didn't find any.
582 return nullptr;
583 }
584
Aart Bik1d239822016-02-09 14:26:34 -0800585 // Helper method to assign a new range to an instruction in given basic block.
586 void AssignRange(HBasicBlock* basic_block, HInstruction* instruction, ValueRange* range) {
587 GetValueRangeMap(basic_block)->Overwrite(instruction->GetId(), range);
588 }
589
Mingyao Yang0304e182015-01-30 16:41:29 -0800590 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
591 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700592 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800593 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700594 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800595 if (existing_range == nullptr) {
596 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800597 AssignRange(successor, instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800598 }
599 return;
600 }
601 if (existing_range->IsMonotonicValueRange()) {
602 DCHECK(instruction->IsLoopHeaderPhi());
603 // Make sure the comparison is in the loop header so each increment is
604 // checked with a comparison.
605 if (instruction->GetBlock() != basic_block) {
606 return;
607 }
608 }
Aart Bik1d239822016-02-09 14:26:34 -0800609 AssignRange(successor, instruction, existing_range->Narrow(range));
Mingyao Yangf384f882014-10-22 16:08:18 -0700610 }
611
Mingyao Yang57e04752015-02-09 18:13:26 -0800612 // Special case that we may simultaneously narrow two MonotonicValueRange's to
613 // regular value ranges.
614 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
615 HInstruction* left,
616 HInstruction* right,
617 IfCondition cond,
618 MonotonicValueRange* left_range,
619 MonotonicValueRange* right_range) {
620 DCHECK(left->IsLoopHeaderPhi());
621 DCHECK(right->IsLoopHeaderPhi());
622 if (instruction->GetBlock() != left->GetBlock()) {
623 // Comparison needs to be in loop header to make sure it's done after each
624 // increment/decrement.
625 return;
626 }
627
628 // Handle common cases which also don't have overflow/underflow concerns.
629 if (left_range->GetIncrement() == 1 &&
630 left_range->GetBound().IsConstant() &&
631 right_range->GetIncrement() == -1 &&
632 right_range->GetBound().IsRelatedToArrayLength() &&
633 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800634 HBasicBlock* successor = nullptr;
635 int32_t left_compensation = 0;
636 int32_t right_compensation = 0;
637 if (cond == kCondLT) {
638 left_compensation = -1;
639 right_compensation = 1;
640 successor = instruction->IfTrueSuccessor();
641 } else if (cond == kCondLE) {
642 successor = instruction->IfTrueSuccessor();
643 } else if (cond == kCondGT) {
644 successor = instruction->IfFalseSuccessor();
645 } else if (cond == kCondGE) {
646 left_compensation = -1;
647 right_compensation = 1;
648 successor = instruction->IfFalseSuccessor();
649 } else {
650 // We don't handle '=='/'!=' test in case left and right can cross and
651 // miss each other.
652 return;
653 }
654
655 if (successor != nullptr) {
656 bool overflow;
657 bool underflow;
658 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
659 GetGraph()->GetArena(),
660 left_range->GetBound(),
661 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
662 if (!overflow && !underflow) {
663 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
664 new_left_range);
665 }
666
667 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
668 GetGraph()->GetArena(),
669 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
670 right_range->GetBound());
671 if (!overflow && !underflow) {
672 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
673 new_right_range);
674 }
675 }
676 }
677 }
678
Mingyao Yangf384f882014-10-22 16:08:18 -0700679 // Handle "if (left cmp_cond right)".
680 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
681 HBasicBlock* block = instruction->GetBlock();
682
683 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
684 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000685 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700686
687 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
688 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000689 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700690
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700691 ValueRange* left_range = LookupValueRange(left, block);
692 MonotonicValueRange* left_monotonic_range = nullptr;
693 if (left_range != nullptr) {
694 left_monotonic_range = left_range->AsMonotonicValueRange();
695 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700696 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700697 if (instruction->GetBlock() != loop_head) {
698 // For monotonic value range, don't handle `instruction`
699 // if it's not defined in the loop header.
700 return;
701 }
702 }
703 }
704
Mingyao Yang64197522014-12-05 15:56:23 -0800705 bool found;
706 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800707 // Each comparison can establish a lower bound and an upper bound
708 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700709 ValueBound lower = bound;
710 ValueBound upper = bound;
711 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800712 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700713 // For i<j, we can still use j's upper bound as i's upper bound. Same for lower.
Mingyao Yang57e04752015-02-09 18:13:26 -0800714 ValueRange* right_range = LookupValueRange(right, block);
715 if (right_range != nullptr) {
716 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800717 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
718 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
719 left_range->AsMonotonicValueRange(),
720 right_range->AsMonotonicValueRange());
721 return;
722 }
723 }
724 lower = right_range->GetLower();
725 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700726 } else {
727 lower = ValueBound::Min();
728 upper = ValueBound::Max();
729 }
730 }
731
Mingyao Yang0304e182015-01-30 16:41:29 -0800732 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700733 if (cond == kCondLT || cond == kCondLE) {
734 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800735 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
736 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
737 if (overflow || underflow) {
738 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800739 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700740 ValueRange* new_range = new (GetGraph()->GetArena())
741 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
742 ApplyRangeFromComparison(left, block, true_successor, new_range);
743 }
744
745 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800746 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
747 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
748 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
749 if (overflow || underflow) {
750 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800751 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700752 ValueRange* new_range = new (GetGraph()->GetArena())
753 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
754 ApplyRangeFromComparison(left, block, false_successor, new_range);
755 }
756 } else if (cond == kCondGT || cond == kCondGE) {
757 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800758 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
759 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
760 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
761 if (overflow || underflow) {
762 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800763 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700764 ValueRange* new_range = new (GetGraph()->GetArena())
765 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
766 ApplyRangeFromComparison(left, block, true_successor, new_range);
767 }
768
769 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800770 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
771 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
772 if (overflow || underflow) {
773 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800774 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700775 ValueRange* new_range = new (GetGraph()->GetArena())
776 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
777 ApplyRangeFromComparison(left, block, false_successor, new_range);
778 }
779 }
780 }
781
Aart Bik4a342772015-11-30 10:17:46 -0800782 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700783 HBasicBlock* block = bounds_check->GetBlock();
784 HInstruction* index = bounds_check->InputAt(0);
785 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700786 DCHECK(array_length->IsIntConstant() ||
787 array_length->IsArrayLength() ||
788 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800789 bool try_dynamic_bce = true;
Mingyao Yangf384f882014-10-22 16:08:18 -0700790
Aart Bik1d239822016-02-09 14:26:34 -0800791 // Analyze index range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800792 if (!index->IsIntConstant()) {
Aart Bik1d239822016-02-09 14:26:34 -0800793 // Non-constant index.
Aart Bik22af3be2015-09-10 12:50:58 -0700794 ValueBound lower = ValueBound(nullptr, 0); // constant 0
795 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
796 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800797 // Try index range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800798 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700799 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800800 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700801 return;
802 }
Aart Bik1d239822016-02-09 14:26:34 -0800803 // Try index range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800804 // Disables dynamic bce if OOB is certain.
805 if (InductionRangeFitsIn(&array_range, bounds_check, index, &try_dynamic_bce)) {
806 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700807 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700808 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800809 } else {
Aart Bik1d239822016-02-09 14:26:34 -0800810 // Constant index.
Mingyao Yang0304e182015-01-30 16:41:29 -0800811 int32_t constant = index->AsIntConstant()->GetValue();
812 if (constant < 0) {
813 // Will always throw exception.
814 return;
Aart Bik1d239822016-02-09 14:26:34 -0800815 } else if (array_length->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800816 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800817 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800818 }
819 return;
820 }
Aart Bik1d239822016-02-09 14:26:34 -0800821 // Analyze array length range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800822 DCHECK(array_length->IsArrayLength());
823 ValueRange* existing_range = LookupValueRange(array_length, block);
824 if (existing_range != nullptr) {
825 ValueBound lower = existing_range->GetLower();
826 DCHECK(lower.IsConstant());
827 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800828 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800829 return;
830 } else {
831 // Existing range isn't strong enough to eliminate the bounds check.
832 // Fall through to update the array_length range with info from this
833 // bounds check.
834 }
835 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700836 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800837 // We currently don't do it for non-constant index since a valid array[i] can't prove
838 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700839 if (constant == std::numeric_limits<int32_t>::max()) {
840 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700841 return;
Aart Bik1d239822016-02-09 14:26:34 -0800842 } else {
843 ValueBound lower = ValueBound(nullptr, constant + 1);
844 ValueBound upper = ValueBound::Max();
845 ValueRange* range = new (GetGraph()->GetArena())
846 ValueRange(GetGraph()->GetArena(), lower, upper);
847 AssignRange(block, array_length, range);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700848 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700849 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700850
Aart Bik4a342772015-11-30 10:17:46 -0800851 // If static analysis fails, and OOB is not certain, try dynamic elimination.
852 if (try_dynamic_bce) {
Aart Bik1d239822016-02-09 14:26:34 -0800853 // Try loop-based dynamic elimination.
854 if (TryDynamicBCE(bounds_check)) {
855 return;
856 }
857 // Prepare dominator-based dynamic elimination.
858 if (first_index_bounds_check_map_.find(array_length->GetId()) ==
859 first_index_bounds_check_map_.end()) {
860 // Remember the first bounds check against each array_length. That bounds check
861 // instruction has an associated HEnvironment where we may add an HDeoptimize
862 // to eliminate subsequent bounds checks against the same array_length.
863 first_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
864 }
Aart Bik4a342772015-11-30 10:17:46 -0800865 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700866 }
867
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100868 static bool HasSameInputAtBackEdges(HPhi* phi) {
869 DCHECK(phi->IsLoopHeaderPhi());
870 // Start with input 1. Input 0 is from the incoming block.
871 HInstruction* input1 = phi->InputAt(1);
872 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100873 *phi->GetBlock()->GetPredecessors()[1]));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100874 for (size_t i = 2, e = phi->InputCount(); i < e; ++i) {
875 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100876 *phi->GetBlock()->GetPredecessors()[i]));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100877 if (input1 != phi->InputAt(i)) {
878 return false;
879 }
880 }
881 return true;
882 }
883
Aart Bik4a342772015-11-30 10:17:46 -0800884 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100885 if (phi->IsLoopHeaderPhi()
886 && (phi->GetType() == Primitive::kPrimInt)
887 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700888 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800889 HInstruction *left;
890 int32_t increment;
891 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
892 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700893 HInstruction* initial_value = phi->InputAt(0);
894 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800895 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700896 // Add constant 0. It's really a fixed value.
897 range = new (GetGraph()->GetArena()) ValueRange(
898 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800899 ValueBound(initial_value, 0),
900 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700901 } else {
902 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800903 bool found;
904 ValueBound bound = ValueBound::DetectValueBoundFromValue(
905 initial_value, &found);
906 if (!found) {
907 // No constant or array.length+c bound found.
908 // For i=j, we can still use j's upper bound as i's upper bound.
909 // Same for lower.
910 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
911 if (initial_range != nullptr) {
912 bound = increment > 0 ? initial_range->GetLower() :
913 initial_range->GetUpper();
914 } else {
915 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
916 }
917 }
918 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700919 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700920 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700921 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800922 increment,
923 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700924 }
Aart Bik1d239822016-02-09 14:26:34 -0800925 AssignRange(phi->GetBlock(), phi, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700926 }
927 }
928 }
929 }
930
Aart Bik4a342772015-11-30 10:17:46 -0800931 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700932 if (instruction->InputAt(0)->IsCondition()) {
933 HCondition* cond = instruction->InputAt(0)->AsCondition();
934 IfCondition cmp = cond->GetCondition();
935 if (cmp == kCondGT || cmp == kCondGE ||
936 cmp == kCondLT || cmp == kCondLE) {
937 HInstruction* left = cond->GetLeft();
938 HInstruction* right = cond->GetRight();
939 HandleIf(instruction, left, right, cmp);
940 }
941 }
942 }
943
Aart Bik4a342772015-11-30 10:17:46 -0800944 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700945 HInstruction* right = add->GetRight();
946 if (right->IsIntConstant()) {
947 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
948 if (left_range == nullptr) {
949 return;
950 }
951 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
952 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800953 AssignRange(add->GetBlock(), add, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700954 }
955 }
956 }
957
Aart Bik4a342772015-11-30 10:17:46 -0800958 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700959 HInstruction* left = sub->GetLeft();
960 HInstruction* right = sub->GetRight();
961 if (right->IsIntConstant()) {
962 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
963 if (left_range == nullptr) {
964 return;
965 }
966 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
967 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800968 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700969 return;
970 }
971 }
972
973 // Here we are interested in the typical triangular case of nested loops,
974 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
975 // is the index for outer loop. In this case, we know j is bounded by array.length-1.
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800976
977 // Try to handle (array.length - i) or (array.length + c - i) format.
978 HInstruction* left_of_left; // left input of left.
979 int32_t right_const = 0;
980 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
981 left = left_of_left;
982 }
983 // The value of left input of the sub equals (left + right_const).
984
Mingyao Yangf384f882014-10-22 16:08:18 -0700985 if (left->IsArrayLength()) {
986 HInstruction* array_length = left->AsArrayLength();
987 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
988 if (right_range != nullptr) {
989 ValueBound lower = right_range->GetLower();
990 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -0800991 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700992 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -0800993 // Make sure it's the same array.
994 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800995 int32_t c0 = right_const;
996 int32_t c1 = lower.GetConstant();
997 int32_t c2 = upper.GetConstant();
998 // (array.length + c0 - v) where v is in [c1, array.length + c2]
999 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1000 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1001 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1002 if ((c0 - c1) <= 0) {
1003 // array.length + (c0 - c1) won't overflow/underflow.
1004 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1005 GetGraph()->GetArena(),
1006 ValueBound(nullptr, right_const - upper.GetConstant()),
1007 ValueBound(array_length, right_const - lower.GetConstant()));
Aart Bik1d239822016-02-09 14:26:34 -08001008 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001009 }
1010 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001011 }
1012 }
1013 }
1014 }
1015 }
1016
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001017 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1018 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1019 HInstruction* right = instruction->GetRight();
1020 int32_t right_const;
1021 if (right->IsIntConstant()) {
1022 right_const = right->AsIntConstant()->GetValue();
1023 // Detect division by two or more.
1024 if ((instruction->IsDiv() && right_const <= 1) ||
1025 (instruction->IsShr() && right_const < 1) ||
1026 (instruction->IsUShr() && right_const < 1)) {
1027 return;
1028 }
1029 } else {
1030 return;
1031 }
1032
1033 // Try to handle array.length/2 or (array.length-1)/2 format.
1034 HInstruction* left = instruction->GetLeft();
1035 HInstruction* left_of_left; // left input of left.
1036 int32_t c = 0;
1037 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1038 left = left_of_left;
1039 }
1040 // The value of left input of instruction equals (left + c).
1041
1042 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001043 // always generate a value in [Min(), array_length].
1044 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001045 if (left->IsArrayLength() && c <= 1) {
1046 if (instruction->IsUShr() && c < 0) {
1047 // Make sure for unsigned shift, left side is not negative.
1048 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1049 // than array_length.
1050 return;
1051 }
1052 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1053 GetGraph()->GetArena(),
Aart Bikaab5b752015-09-23 11:18:57 -07001054 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001055 ValueBound(left, 0));
Aart Bik1d239822016-02-09 14:26:34 -08001056 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001057 }
1058 }
1059
Aart Bik4a342772015-11-30 10:17:46 -08001060 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001061 FindAndHandlePartialArrayLength(div);
1062 }
1063
Aart Bik4a342772015-11-30 10:17:46 -08001064 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001065 FindAndHandlePartialArrayLength(shr);
1066 }
1067
Aart Bik4a342772015-11-30 10:17:46 -08001068 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001069 FindAndHandlePartialArrayLength(ushr);
1070 }
1071
Aart Bik4a342772015-11-30 10:17:46 -08001072 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001073 if (instruction->GetRight()->IsIntConstant()) {
1074 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1075 if (constant > 0) {
1076 // constant serves as a mask so any number masked with it
1077 // gets a [0, constant] value range.
1078 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1079 GetGraph()->GetArena(),
1080 ValueBound(nullptr, 0),
1081 ValueBound(nullptr, constant));
Aart Bik1d239822016-02-09 14:26:34 -08001082 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang4559f002015-02-27 14:43:53 -08001083 }
1084 }
1085 }
1086
Aart Bik4a342772015-11-30 10:17:46 -08001087 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Mingyao Yang0304e182015-01-30 16:41:29 -08001088 HInstruction* len = new_array->InputAt(0);
1089 if (!len->IsIntConstant()) {
1090 HInstruction *left;
1091 int32_t right_const;
1092 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1093 // (left + right_const) is used as size to new the array.
1094 // We record "-right_const <= left <= new_array - right_const";
1095 ValueBound lower = ValueBound(nullptr, -right_const);
1096 // We use new_array for the bound instead of new_array.length,
1097 // which isn't available as an instruction yet. new_array will
1098 // be treated the same as new_array.length when it's used in a ValueBound.
1099 ValueBound upper = ValueBound(new_array, -right_const);
1100 ValueRange* range = new (GetGraph()->GetArena())
1101 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001102 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1103 if (existing_range != nullptr) {
1104 range = existing_range->Narrow(range);
1105 }
Aart Bik1d239822016-02-09 14:26:34 -08001106 AssignRange(new_array->GetBlock(), left, range);
Mingyao Yang0304e182015-01-30 16:41:29 -08001107 }
1108 }
1109 }
1110
Aart Bik4a342772015-11-30 10:17:46 -08001111 /**
1112 * After null/bounds checks are eliminated, some invariant array references
1113 * may be exposed underneath which can be hoisted out of the loop to the
1114 * preheader or, in combination with dynamic bce, the deoptimization block.
1115 *
1116 * for (int i = 0; i < n; i++) {
1117 * <-------+
1118 * for (int j = 0; j < n; j++) |
1119 * a[i][j] = 0; --a[i]--+
1120 * }
1121 *
Aart Bik1d239822016-02-09 14:26:34 -08001122 * Note: this optimization is no longer applied after dominator-based dynamic deoptimization
1123 * has occurred (see AddCompareWithDeoptimization()), since in those cases it would be
1124 * unsafe to hoist array references across their deoptimization instruction inside a loop.
Aart Bik4a342772015-11-30 10:17:46 -08001125 */
1126 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
Aart Bik1d239822016-02-09 14:26:34 -08001127 if (!has_dom_based_dynamic_bce_ && array_get->IsInLoop()) {
Aart Bik4a342772015-11-30 10:17:46 -08001128 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001129 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1130 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001131 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1132 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001133 HoistToPreHeaderOrDeoptBlock(loop, array_get);
Aart Bik4a342772015-11-30 10:17:46 -08001134 }
1135 }
1136 }
1137 }
1138
Aart Bik1d239822016-02-09 14:26:34 -08001139 // Perform dominator-based dynamic elimination on suitable set of bounds checks.
1140 void AddCompareWithDeoptimization(HBasicBlock* block,
1141 HInstruction* array_length,
1142 HInstruction* base,
1143 int32_t min_c, int32_t max_c) {
1144 HBoundsCheck* bounds_check =
1145 first_index_bounds_check_map_.Get(array_length->GetId())->AsBoundsCheck();
1146 // Construct deoptimization on single or double bounds on range [base-min_c,base+max_c],
1147 // for example either for a[0]..a[3] just 3 or for a[base-1]..a[base+3] both base-1
1148 // and base+3, since we made the assumption any in between value may occur too.
1149 static_assert(kMaxLengthForAddingDeoptimize < std::numeric_limits<int32_t>::max(),
1150 "Incorrect max length may be subject to arithmetic wrap-around");
1151 HInstruction* upper = GetGraph()->GetIntConstant(max_c);
1152 if (base == nullptr) {
1153 DCHECK_GE(min_c, 0);
1154 } else {
1155 HInstruction* lower = new (GetGraph()->GetArena())
1156 HAdd(Primitive::kPrimInt, base, GetGraph()->GetIntConstant(min_c));
1157 upper = new (GetGraph()->GetArena()) HAdd(Primitive::kPrimInt, base, upper);
1158 block->InsertInstructionBefore(lower, bounds_check);
1159 block->InsertInstructionBefore(upper, bounds_check);
1160 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAbove(lower, upper));
1161 }
1162 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAboveOrEqual(upper, array_length));
1163 // Flag that this kind of deoptimization has occurred.
1164 has_dom_based_dynamic_bce_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001165 }
1166
Aart Bik1d239822016-02-09 14:26:34 -08001167 // Attempt dominator-based dynamic elimination on remaining candidates.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001168 void AddComparesWithDeoptimization(HBasicBlock* block) {
Aart Bik1d239822016-02-09 14:26:34 -08001169 for (const auto& it : first_index_bounds_check_map_) {
1170 HBoundsCheck* bounds_check = it.second;
1171 HInstruction* index = bounds_check->InputAt(0);
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001172 HInstruction* array_length = bounds_check->InputAt(1);
1173 if (!array_length->IsArrayLength()) {
Aart Bik1d239822016-02-09 14:26:34 -08001174 continue; // disregard phis and constants
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001175 }
Aart Bik1d239822016-02-09 14:26:34 -08001176 // Collect all bounds checks are still there and that are related as "a[base + constant]"
1177 // for a base instruction (possibly absent) and various constants. Note that no attempt
1178 // is made to partition the set into matching subsets (viz. a[0], a[1] and a[base+1] and
1179 // a[base+2] are considered as one set).
1180 // TODO: would such a partitioning be worthwhile?
1181 ValueBound value = ValueBound::AsValueBound(index);
1182 HInstruction* base = value.GetInstruction();
1183 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1184 int32_t max_c = value.GetConstant();
1185 ArenaVector<HBoundsCheck*> candidates(
1186 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1187 ArenaVector<HBoundsCheck*> standby(
1188 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1189 for (HUseIterator<HInstruction*> it2(array_length->GetUses()); !it2.Done(); it2.Advance()) {
1190 // Another bounds check in same or dominated block?
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001191 HInstruction* user = it2.Current()->GetUser();
Aart Bik1d239822016-02-09 14:26:34 -08001192 HBasicBlock* other_block = user->GetBlock();
1193 if (user->IsBoundsCheck() && block->Dominates(other_block)) {
1194 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1195 HInstruction* other_index = other_bounds_check->InputAt(0);
1196 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1197 ValueBound other_value = ValueBound::AsValueBound(other_index);
1198 if (array_length == other_array_length && base == other_value.GetInstruction()) {
1199 int32_t other_c = other_value.GetConstant();
1200 // Since a subsequent dominated block could be under a conditional, only accept
1201 // the other bounds check if it is in same block or both blocks dominate the exit.
1202 // TODO: we could improve this by testing proper post-dominance, or even if this
1203 // constant is seen along *all* conditional paths that follow.
1204 HBasicBlock* exit = GetGraph()->GetExitBlock();
1205 if (block == user->GetBlock() ||
1206 (block->Dominates(exit) && other_block->Dominates(exit))) {
1207 min_c = std::min(min_c, other_c);
1208 max_c = std::max(max_c, other_c);
1209 candidates.push_back(other_bounds_check);
1210 } else {
1211 // Add this candidate later only if it falls into the range.
1212 standby.push_back(other_bounds_check);
1213 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001214 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001215 }
1216 }
Aart Bik1d239822016-02-09 14:26:34 -08001217 // Add standby candidates that fall in selected range.
1218 for (size_t i = 0; i < standby.size(); ++i) {
1219 HBoundsCheck* other_bounds_check = standby[i]->AsBoundsCheck();
1220 HInstruction* other_index = other_bounds_check->InputAt(0);
1221 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1222 if (min_c <= other_c && other_c <= max_c) {
1223 candidates.push_back(other_bounds_check);
1224 }
1225 }
1226 // Perform dominator-based deoptimization if it seems profitable. Note that we reject cases
1227 // where the distance min_c:max_c range gets close to the maximum possible array length,
1228 // since those cases are likely to always deopt (such situations do not necessarily go
1229 // OOB, though, since the programmer could rely on wrap-around from max to min).
1230 size_t threshold = kThresholdForAddingDeoptimize + (base == nullptr ? 0 : 1); // extra test?
1231 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1232 if (candidates.size() >= threshold &&
1233 (base != nullptr || min_c >= 0) && // reject certain OOB
1234 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1235 AddCompareWithDeoptimization(block, array_length, base, min_c, max_c);
1236 for (size_t i = 0; i < candidates.size(); ++i) {
1237 HInstruction* other_bounds_check = candidates[i];
1238 ReplaceInstruction(other_bounds_check, other_bounds_check->InputAt(0));
1239 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001240 }
1241 }
1242 }
1243
Aart Bik4a342772015-11-30 10:17:46 -08001244 /**
1245 * Returns true if static range analysis based on induction variables can determine the bounds
1246 * check on the given array range is always satisfied with the computed index range. The output
1247 * parameter try_dynamic_bce is set to false if OOB is certain.
1248 */
1249 bool InductionRangeFitsIn(ValueRange* array_range,
1250 HInstruction* context,
1251 HInstruction* index,
1252 bool* try_dynamic_bce) {
1253 InductionVarRange::Value v1;
1254 InductionVarRange::Value v2;
1255 bool needs_finite_test = false;
Aart Bik1fc3afb2016-02-02 13:26:16 -08001256 if (induction_range_.GetInductionRange(context, index, &v1, &v2, &needs_finite_test)) {
1257 do {
1258 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1259 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1260 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1261 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1262 ValueRange index_range(GetGraph()->GetArena(),
1263 ValueBound(v1.instruction, v1.b_constant),
1264 ValueBound(v2.instruction, v2.b_constant));
1265 // If analysis reveals a certain OOB, disable dynamic BCE.
1266 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1267 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1268 *try_dynamic_bce = false;
1269 return false;
1270 }
1271 // Use analysis for static bce only if loop is finite.
1272 if (!needs_finite_test && index_range.FitsIn(array_range)) {
1273 return true;
1274 }
Aart Bikb738d4f2015-12-03 11:23:35 -08001275 }
Aart Bik1fc3afb2016-02-02 13:26:16 -08001276 } while (induction_range_.RefineOuter(&v1, &v2));
1277 }
Aart Bik4a342772015-11-30 10:17:46 -08001278 return false;
1279 }
1280
1281 /**
1282 * When the compiler fails to remove a bounds check statically, we try to remove the bounds
1283 * check dynamically by adding runtime tests that trigger a deoptimization in case bounds
1284 * will go out of range (we want to be rather certain of that given the slowdown of
1285 * deoptimization). If no deoptimization occurs, the loop is executed with all corresponding
1286 * bounds checks and related null checks removed.
1287 */
Aart Bik1d239822016-02-09 14:26:34 -08001288 bool TryDynamicBCE(HBoundsCheck* instruction) {
Aart Bik4a342772015-11-30 10:17:46 -08001289 HLoopInformation* loop = instruction->GetBlock()->GetLoopInformation();
1290 HInstruction* index = instruction->InputAt(0);
1291 HInstruction* length = instruction->InputAt(1);
1292 // If dynamic bounds check elimination seems profitable and is possible, then proceed.
1293 bool needs_finite_test = false;
1294 bool needs_taken_test = false;
1295 if (DynamicBCESeemsProfitable(loop, instruction->GetBlock()) &&
1296 induction_range_.CanGenerateCode(
1297 instruction, index, &needs_finite_test, &needs_taken_test) &&
1298 CanHandleInfiniteLoop(loop, index, needs_finite_test) &&
1299 CanHandleLength(loop, length, needs_taken_test)) { // do this test last (may code gen)
1300 HInstruction* lower = nullptr;
1301 HInstruction* upper = nullptr;
1302 // Generate the following unsigned comparisons
1303 // if (lower > upper) deoptimize;
1304 // if (upper >= length) deoptimize;
1305 // or, for a non-induction index, just the unsigned comparison on its 'upper' value
1306 // if (upper >= length) deoptimize;
1307 // as runtime test. By restricting dynamic bce to unit strides (with a maximum of 32-bit
1308 // iterations) and by not combining access (e.g. a[i], a[i-3], a[i+5] etc.), these tests
1309 // correctly guard against any possible OOB (including arithmetic wrap-around cases).
Aart Bik55b14df2016-01-12 14:12:47 -08001310 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1311 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001312 induction_range_.GenerateRangeCode(instruction, index, GetGraph(), block, &lower, &upper);
1313 if (lower != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001314 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(lower, upper));
Aart Bik4a342772015-11-30 10:17:46 -08001315 }
Aart Bik1d239822016-02-09 14:26:34 -08001316 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAboveOrEqual(upper, length));
Aart Bik4a342772015-11-30 10:17:46 -08001317 ReplaceInstruction(instruction, index);
Aart Bik1d239822016-02-09 14:26:34 -08001318 return true;
Aart Bik4a342772015-11-30 10:17:46 -08001319 }
Aart Bik1d239822016-02-09 14:26:34 -08001320 return false;
Aart Bik4a342772015-11-30 10:17:46 -08001321 }
1322
1323 /**
1324 * Returns true if heuristics indicate that dynamic bce may be profitable.
1325 */
1326 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1327 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001328 // The loop preheader of an irreducible loop does not dominate all the blocks in
1329 // the loop. We would need to find the common dominator of all blocks in the loop.
1330 if (loop->IsIrreducible()) {
1331 return false;
1332 }
Aart Bik4a342772015-11-30 10:17:46 -08001333 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001334 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001335 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1336 return false;
1337 }
1338 // Does loop have early-exits? If so, the full range may not be covered by the loop
1339 // at runtime and testing the range may apply deoptimization unnecessarily.
1340 if (IsEarlyExitLoop(loop)) {
1341 return false;
1342 }
1343 // Does the current basic block dominate all back edges? If not,
1344 // don't apply dynamic bce to something that may not be executed.
1345 for (HBasicBlock* back_edge : loop->GetBackEdges()) {
1346 if (!block->Dominates(back_edge)) {
1347 return false;
1348 }
1349 }
1350 // Success!
1351 return true;
1352 }
1353 return false;
1354 }
1355
1356 /**
1357 * Returns true if the loop has early exits, which implies it may not cover
1358 * the full range computed by range analysis based on induction variables.
1359 */
1360 bool IsEarlyExitLoop(HLoopInformation* loop) {
1361 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1362 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1363 auto it = early_exit_loop_.find(loop_id);
1364 if (it != early_exit_loop_.end()) {
1365 return it->second;
1366 }
1367 // First time early-exit analysis for this loop. Since analysis requires scanning
1368 // the full loop-body, results of the analysis is stored for subsequent queries.
1369 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1370 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1371 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1372 if (!loop->Contains(*successor)) {
1373 early_exit_loop_.Put(loop_id, true);
1374 return true;
1375 }
1376 }
1377 }
1378 early_exit_loop_.Put(loop_id, false);
1379 return false;
1380 }
1381
1382 /**
1383 * Returns true if the array length is already loop invariant, or can be made so
1384 * by handling the null check under the hood of the array length operation.
1385 */
1386 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001387 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001388 return true;
1389 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1390 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001391 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001392 return true;
1393 }
1394 }
1395 return false;
1396 }
1397
1398 /**
1399 * Returns true if the null check is already loop invariant, or can be made so
1400 * by generating a deoptimization test.
1401 */
1402 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001403 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001404 return true;
1405 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1406 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001407 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001408 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001409 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1410 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001411 HInstruction* cond =
1412 new (GetGraph()->GetArena()) HEqual(array, GetGraph()->GetNullConstant());
Aart Bik1d239822016-02-09 14:26:34 -08001413 InsertDeoptInLoop(loop, block, cond);
Aart Bik4a342772015-11-30 10:17:46 -08001414 ReplaceInstruction(check, array);
1415 return true;
1416 }
1417 }
1418 return false;
1419 }
1420
1421 /**
1422 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1423 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1424 * the range analysis evaluation code by "overshooting" the computed range.
1425 * Since deoptimization would be a bad choice, and there is no other version
1426 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1427 * ensure the loop is finite.
1428 */
1429 bool CanHandleInfiniteLoop(
1430 HLoopInformation* loop, HInstruction* index, bool needs_infinite_test) {
1431 if (needs_infinite_test) {
1432 // If we already forced the loop to be finite, allow directly.
1433 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1434 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1435 return true;
1436 }
1437 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1438 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1439 // ensure upper bound cannot cause an infinite loop.
1440 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1441 if (control->IsIf()) {
1442 HInstruction* if_expr = control->AsIf()->InputAt(0);
1443 if (if_expr->IsCondition()) {
1444 HCondition* condition = if_expr->AsCondition();
1445 if (index == condition->InputAt(0) ||
1446 index == condition->InputAt(1)) {
1447 finite_loop_.insert(loop_id);
1448 return true;
1449 }
1450 }
1451 }
1452 return false;
1453 }
1454 return true;
1455 }
1456
Aart Bik55b14df2016-01-12 14:12:47 -08001457 /**
1458 * Returns appropriate preheader for the loop, depending on whether the
1459 * instruction appears in the loop header or proper loop-body.
1460 */
1461 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1462 // Use preheader unless there is an earlier generated deoptimization block since
1463 // hoisted expressions may depend on and/or used by the deoptimization tests.
1464 HBasicBlock* header = loop->GetHeader();
1465 const uint32_t loop_id = header->GetBlockId();
1466 auto it = taken_test_loop_.find(loop_id);
1467 if (it != taken_test_loop_.end()) {
1468 HBasicBlock* block = it->second;
1469 // If always taken, keep it that way by returning the original preheader,
1470 // which can be found by following the predecessor of the true-block twice.
1471 if (instruction->GetBlock() == header) {
1472 return block->GetSinglePredecessor()->GetSinglePredecessor();
1473 }
1474 return block;
1475 }
1476 return loop->GetPreHeader();
1477 }
1478
Aart Bik1d239822016-02-09 14:26:34 -08001479 /** Inserts a deoptimization test in a loop preheader. */
1480 void InsertDeoptInLoop(HLoopInformation* loop, HBasicBlock* block, HInstruction* condition) {
Aart Bik4a342772015-11-30 10:17:46 -08001481 HInstruction* suspend = loop->GetSuspendCheck();
1482 block->InsertInstructionBefore(condition, block->GetLastInstruction());
1483 HDeoptimize* deoptimize =
1484 new (GetGraph()->GetArena()) HDeoptimize(condition, suspend->GetDexPc());
1485 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1486 if (suspend->HasEnvironment()) {
1487 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1488 suspend->GetEnvironment(), loop->GetHeader());
1489 }
1490 }
1491
Aart Bik1d239822016-02-09 14:26:34 -08001492 /** Inserts a deoptimization test right before a bounds check. */
1493 void InsertDeoptInBlock(HBoundsCheck* bounds_check, HInstruction* condition) {
1494 HBasicBlock* block = bounds_check->GetBlock();
1495 block->InsertInstructionBefore(condition, bounds_check);
1496 HDeoptimize* deoptimize =
1497 new (GetGraph()->GetArena()) HDeoptimize(condition, bounds_check->GetDexPc());
1498 block->InsertInstructionBefore(deoptimize, bounds_check);
1499 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
1500 }
1501
Aart Bik4a342772015-11-30 10:17:46 -08001502 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001503 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1504 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001505 DCHECK(!instruction->HasEnvironment());
1506 instruction->MoveBefore(block->GetLastInstruction());
1507 }
1508
1509 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001510 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001511 * The taken-test protects range analysis evaluation code to avoid any
1512 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1513 *
Aart Bik4a342772015-11-30 10:17:46 -08001514 * old_preheader
1515 * |
1516 * if_block <- taken-test protects deoptimization block
1517 * / \
1518 * true_block false_block <- deoptimizations/invariants are placed in true_block
1519 * \ /
1520 * new_preheader <- may require phi nodes to preserve SSA structure
1521 * |
1522 * header
1523 *
1524 * For example, this loop:
1525 *
1526 * for (int i = lower; i < upper; i++) {
1527 * array[i] = 0;
1528 * }
1529 *
1530 * will be transformed to:
1531 *
1532 * if (lower < upper) {
1533 * if (array == null) deoptimize;
1534 * array_length = array.length;
1535 * if (lower > upper) deoptimize; // unsigned
1536 * if (upper >= array_length) deoptimize; // unsigned
1537 * } else {
1538 * array_length = 0;
1539 * }
1540 * for (int i = lower; i < upper; i++) {
1541 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1542 * array[i] = 0;
1543 * }
1544 */
Aart Bik55b14df2016-01-12 14:12:47 -08001545 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1546 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001547 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001548 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1549 return;
Aart Bik4a342772015-11-30 10:17:46 -08001550 }
1551
1552 // Generate top test structure.
1553 HBasicBlock* header = loop->GetHeader();
1554 GetGraph()->TransformLoopHeaderForBCE(header);
1555 HBasicBlock* new_preheader = loop->GetPreHeader();
1556 HBasicBlock* if_block = new_preheader->GetDominator();
1557 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1558 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1559
1560 // Goto instructions.
1561 true_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1562 false_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1563 new_preheader->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1564
1565 // Insert the taken-test to see if the loop body is entered. If the
1566 // loop isn't entered at all, it jumps around the deoptimization block.
1567 if_block->AddInstruction(new (GetGraph()->GetArena()) HGoto()); // placeholder
1568 HInstruction* condition = nullptr;
1569 induction_range_.GenerateTakenTest(header->GetLastInstruction(),
1570 GetGraph(),
1571 if_block,
1572 &condition);
1573 DCHECK(condition != nullptr);
1574 if_block->RemoveInstruction(if_block->GetLastInstruction());
1575 if_block->AddInstruction(new (GetGraph()->GetArena()) HIf(condition));
1576
1577 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001578 }
1579
1580 /**
1581 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1582 * All uses of instructions in the deoptimization block that reach the loop need
1583 * a phi node in the new loop preheader to fix the dominance relation.
1584 *
1585 * Example:
1586 * if_block
1587 * / \
1588 * x_0 = .. false_block
1589 * \ /
1590 * x_1 = phi(x_0, null) <- synthetic phi
1591 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001592 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001593 */
1594 void InsertPhiNodes() {
1595 // Scan all new deoptimization blocks.
1596 for (auto it1 = taken_test_loop_.begin(); it1 != taken_test_loop_.end(); ++it1) {
1597 HBasicBlock* true_block = it1->second;
1598 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1599 // Scan all instructions in a new deoptimization block.
1600 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1601 HInstruction* instruction = it.Current();
1602 Primitive::Type type = instruction->GetType();
1603 HPhi* phi = nullptr;
1604 // Scan all uses of an instruction and replace each later use with a phi node.
1605 for (HUseIterator<HInstruction*> it2(instruction->GetUses());
1606 !it2.Done();
1607 it2.Advance()) {
1608 HInstruction* user = it2.Current()->GetUser();
1609 if (user->GetBlock() != true_block) {
1610 if (phi == nullptr) {
1611 phi = NewPhi(new_preheader, instruction, type);
1612 }
1613 user->ReplaceInput(phi, it2.Current()->GetIndex());
1614 }
1615 }
1616 // Scan all environment uses of an instruction and replace each later use with a phi node.
1617 for (HUseIterator<HEnvironment*> it2(instruction->GetEnvUses());
1618 !it2.Done();
1619 it2.Advance()) {
1620 HEnvironment* user = it2.Current()->GetUser();
1621 if (user->GetHolder()->GetBlock() != true_block) {
1622 if (phi == nullptr) {
1623 phi = NewPhi(new_preheader, instruction, type);
1624 }
1625 user->RemoveAsUserOfInput(it2.Current()->GetIndex());
1626 user->SetRawEnvAt(it2.Current()->GetIndex(), phi);
1627 phi->AddEnvUseAt(user, it2.Current()->GetIndex());
1628 }
1629 }
1630 }
1631 }
1632 }
1633
1634 /**
1635 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1636 * These are synthetic phi nodes without a virtual register.
1637 */
1638 HPhi* NewPhi(HBasicBlock* new_preheader,
1639 HInstruction* instruction,
1640 Primitive::Type type) {
1641 HGraph* graph = GetGraph();
1642 HInstruction* zero;
1643 switch (type) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001644 case Primitive::kPrimNot: zero = graph->GetNullConstant(); break;
1645 case Primitive::kPrimFloat: zero = graph->GetFloatConstant(0); break;
1646 case Primitive::kPrimDouble: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001647 default: zero = graph->GetConstant(type, 0); break;
1648 }
1649 HPhi* phi = new (graph->GetArena())
1650 HPhi(graph->GetArena(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
1651 phi->SetRawInputAt(0, instruction);
1652 phi->SetRawInputAt(1, zero);
David Brazdil4833f5a2015-12-16 10:37:39 +00001653 if (type == Primitive::kPrimNot) {
1654 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1655 }
Aart Bik4a342772015-11-30 10:17:46 -08001656 new_preheader->AddPhi(phi);
1657 return phi;
1658 }
1659
1660 /** Helper method to replace an instruction with another instruction. */
1661 static void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1662 instruction->ReplaceWith(replacement);
1663 instruction->GetBlock()->RemoveInstruction(instruction);
1664 }
1665
1666 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko5233f932015-09-29 19:01:15 +01001667 ArenaVector<ArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001668
Aart Bik1d239822016-02-09 14:26:34 -08001669 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction
1670 // in a block that checks an index against that HArrayLength.
1671 ArenaSafeMap<int, HBoundsCheck*> first_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001672
Aart Bik4a342772015-11-30 10:17:46 -08001673 // Early-exit loop bookkeeping.
1674 ArenaSafeMap<uint32_t, bool> early_exit_loop_;
1675
1676 // Taken-test loop bookkeeping.
1677 ArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
1678
1679 // Finite loop bookkeeping.
1680 ArenaSet<uint32_t> finite_loop_;
1681
Aart Bik1d239822016-02-09 14:26:34 -08001682 // Flag that denotes whether dominator-based dynamic elimination has occurred.
1683 bool has_dom_based_dynamic_bce_;
Aart Bik4a342772015-11-30 10:17:46 -08001684
Mingyao Yang3584bce2015-05-19 16:01:59 -07001685 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001686 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001687
Aart Bik4a342772015-11-30 10:17:46 -08001688 // Side effects.
1689 const SideEffectsAnalysis& side_effects_;
1690
Aart Bik22af3be2015-09-10 12:50:58 -07001691 // Range analysis based on induction variables.
1692 InductionVarRange induction_range_;
1693
Mingyao Yangf384f882014-10-22 16:08:18 -07001694 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1695};
1696
1697void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001698 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001699 return;
1700 }
1701
Mingyao Yangf384f882014-10-22 16:08:18 -07001702 // Reverse post order guarantees a node's dominators are visited first.
1703 // We want to visit in the dominator-based order since if a value is known to
1704 // be bounded by a range at one instruction, it must be true that all uses of
1705 // that value dominated by that instruction fits in that range. Range of that
1706 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001707 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001708 HBasicBlock* last_visited_block = nullptr;
1709 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1710 HBasicBlock* current = it.Current();
1711 if (current == last_visited_block) {
1712 // We may insert blocks into the reverse post order list when processing
1713 // a loop header. Don't process it again.
1714 DCHECK(current->IsLoopHeader());
1715 continue;
1716 }
1717 if (visitor.IsAddedBlock(current)) {
1718 // Skip added blocks. Their effects are already taken care of.
1719 continue;
1720 }
1721 visitor.VisitBasicBlock(current);
1722 last_visited_block = current;
1723 }
Aart Bik4a342772015-11-30 10:17:46 -08001724
1725 // Perform cleanup.
1726 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001727}
1728
1729} // namespace art