blob: a7f7bce07ad3815ef80f26f0da6d272bf8835aa6 [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"
Mingyao Yangf384f882014-10-22 16:08:18 -070023#include "nodes.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024#include "side_effects_analysis.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) {
Aart Bikbf3f1cf2016-02-22 16:22:33 -080070 HInstruction* left_so_far = nullptr;
71 int32_t right_so_far = 0;
72 while (instruction->IsAdd() || instruction->IsSub()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080073 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
74 HInstruction* left = bin_op->GetLeft();
75 HInstruction* right = bin_op->GetRight();
76 if (right->IsIntConstant()) {
Aart Bikbf3f1cf2016-02-22 16:22:33 -080077 int32_t v = right->AsIntConstant()->GetValue();
78 int32_t c = instruction->IsAdd() ? v : -v;
79 if (!WouldAddOverflowOrUnderflow(right_so_far, c)) {
80 instruction = left;
81 left_so_far = left;
82 right_so_far += c;
83 continue;
84 }
Mingyao Yang0304e182015-01-30 16:41:29 -080085 }
Aart Bikbf3f1cf2016-02-22 16:22:33 -080086 break;
Mingyao Yang0304e182015-01-30 16:41:29 -080087 }
Aart Bikbf3f1cf2016-02-22 16:22:33 -080088 // Return result: either false and "null+0" or true and "instr+constant".
89 *left_instruction = left_so_far;
90 *right_constant = right_so_far;
91 return left_so_far != nullptr;
Mingyao Yang0304e182015-01-30 16:41:29 -080092 }
93
Aart Bik1d239822016-02-09 14:26:34 -080094 // Expresses any instruction as a value bound.
95 static ValueBound AsValueBound(HInstruction* instruction) {
96 if (instruction->IsIntConstant()) {
97 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
98 }
99 HInstruction *left;
100 int32_t right;
101 if (IsAddOrSubAConstant(instruction, &left, &right)) {
102 return ValueBound(left, right);
103 }
104 return ValueBound(instruction, 0);
105 }
106
Mingyao Yang64197522014-12-05 15:56:23 -0800107 // Try to detect useful value bound format from an instruction, e.g.
108 // a constant or array length related value.
Aart Bik1d239822016-02-09 14:26:34 -0800109 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, /* out */ bool* found) {
Mingyao Yang64197522014-12-05 15:56:23 -0800110 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -0700111 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800112 *found = true;
113 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -0700114 }
Mingyao Yang64197522014-12-05 15:56:23 -0800115
116 if (instruction->IsArrayLength()) {
117 *found = true;
118 return ValueBound(instruction, 0);
119 }
120 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -0800121 HInstruction *left;
122 int32_t right;
123 if (IsAddOrSubAConstant(instruction, &left, &right)) {
124 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -0800125 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -0800126 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800127 }
128 }
129
130 // No useful bound detected.
131 *found = false;
132 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700133 }
134
135 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800136 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700137
Mingyao Yang0304e182015-01-30 16:41:29 -0800138 bool IsRelatedToArrayLength() const {
139 // Some bounds are created with HNewArray* as the instruction instead
140 // of HArrayLength*. They are treated the same.
141 return (instruction_ != nullptr) &&
142 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700143 }
144
145 bool IsConstant() const {
146 return instruction_ == nullptr;
147 }
148
Aart Bikaab5b752015-09-23 11:18:57 -0700149 static ValueBound Min() { return ValueBound(nullptr, std::numeric_limits<int32_t>::min()); }
150 static ValueBound Max() { return ValueBound(nullptr, std::numeric_limits<int32_t>::max()); }
Mingyao Yangf384f882014-10-22 16:08:18 -0700151
152 bool Equals(ValueBound bound) const {
153 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
154 }
155
Mingyao Yang0304e182015-01-30 16:41:29 -0800156 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
157 if (instruction1 == instruction2) {
158 return true;
159 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800160 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700161 return false;
162 }
Aart Bik22af3be2015-09-10 12:50:58 -0700163 instruction1 = HuntForDeclaration(instruction1);
164 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800165 return instruction1 == instruction2;
166 }
167
168 // Returns if it's certain this->bound >= `bound`.
169 bool GreaterThanOrEqualTo(ValueBound bound) const {
170 if (Equal(instruction_, bound.instruction_)) {
171 return constant_ >= bound.constant_;
172 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700173 // Not comparable. Just return false.
174 return false;
175 }
176
Mingyao Yang0304e182015-01-30 16:41:29 -0800177 // Returns if it's certain this->bound <= `bound`.
178 bool LessThanOrEqualTo(ValueBound bound) const {
179 if (Equal(instruction_, bound.instruction_)) {
180 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700181 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700182 // Not comparable. Just return false.
183 return false;
184 }
185
Aart Bik4a342772015-11-30 10:17:46 -0800186 // Returns if it's certain this->bound > `bound`.
187 bool GreaterThan(ValueBound bound) const {
188 if (Equal(instruction_, bound.instruction_)) {
189 return constant_ > bound.constant_;
190 }
191 // Not comparable. Just return false.
192 return false;
193 }
194
195 // Returns if it's certain this->bound < `bound`.
196 bool LessThan(ValueBound bound) const {
197 if (Equal(instruction_, bound.instruction_)) {
198 return constant_ < bound.constant_;
199 }
200 // Not comparable. Just return false.
201 return false;
202 }
203
Mingyao Yangf384f882014-10-22 16:08:18 -0700204 // Try to narrow lower bound. Returns the greatest of the two if possible.
205 // Pick one if they are not comparable.
206 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800207 if (bound1.GreaterThanOrEqualTo(bound2)) {
208 return bound1;
209 }
210 if (bound2.GreaterThanOrEqualTo(bound1)) {
211 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700212 }
213
214 // Not comparable. Just pick one. We may lose some info, but that's ok.
215 // Favor constant as lower bound.
216 return bound1.IsConstant() ? bound1 : bound2;
217 }
218
219 // Try to narrow upper bound. Returns the lowest of the two if possible.
220 // Pick one if they are not comparable.
221 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800222 if (bound1.LessThanOrEqualTo(bound2)) {
223 return bound1;
224 }
225 if (bound2.LessThanOrEqualTo(bound1)) {
226 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700227 }
228
229 // Not comparable. Just pick one. We may lose some info, but that's ok.
230 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800231 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700232 }
233
Mingyao Yang0304e182015-01-30 16:41:29 -0800234 // Add a constant to a ValueBound.
235 // `overflow` or `underflow` will return whether the resulting bound may
236 // overflow or underflow an int.
Aart Bik1d239822016-02-09 14:26:34 -0800237 ValueBound Add(int32_t c, /* out */ bool* overflow, /* out */ bool* underflow) const {
Mingyao Yang0304e182015-01-30 16:41:29 -0800238 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700239 if (c == 0) {
240 return *this;
241 }
242
Mingyao Yang0304e182015-01-30 16:41:29 -0800243 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700244 if (c > 0) {
Aart Bikaab5b752015-09-23 11:18:57 -0700245 if (constant_ > (std::numeric_limits<int32_t>::max() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800246 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800247 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700248 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800249
250 new_constant = constant_ + c;
251 // (array.length + non-positive-constant) won't overflow an int.
252 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
253 return ValueBound(instruction_, new_constant);
254 }
255 // Be conservative.
256 *overflow = true;
257 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700258 } else {
Aart Bikaab5b752015-09-23 11:18:57 -0700259 if (constant_ < (std::numeric_limits<int32_t>::min() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800260 *underflow = true;
261 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700262 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800263
264 new_constant = constant_ + c;
265 // Regardless of the value new_constant, (array.length+new_constant) will
266 // never underflow since array.length is no less than 0.
267 if (IsConstant() || IsRelatedToArrayLength()) {
268 return ValueBound(instruction_, new_constant);
269 }
270 // Be conservative.
271 *underflow = true;
272 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700273 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700274 }
275
276 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700277 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800278 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700279};
280
281/**
282 * Represent a range of lower bound and upper bound, both being inclusive.
283 * Currently a ValueRange may be generated as a result of the following:
284 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800285 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700286 * incrementing/decrementing array index (MonotonicValueRange).
287 */
Vladimir Marko5233f932015-09-29 19:01:15 +0100288class ValueRange : public ArenaObject<kArenaAllocBoundsCheckElimination> {
Mingyao Yangf384f882014-10-22 16:08:18 -0700289 public:
290 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
291 : allocator_(allocator), lower_(lower), upper_(upper) {}
292
293 virtual ~ValueRange() {}
294
Mingyao Yang57e04752015-02-09 18:13:26 -0800295 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
296 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700297 return AsMonotonicValueRange() != nullptr;
298 }
299
300 ArenaAllocator* GetAllocator() const { return allocator_; }
301 ValueBound GetLower() const { return lower_; }
302 ValueBound GetUpper() const { return upper_; }
303
Mingyao Yang3584bce2015-05-19 16:01:59 -0700304 bool IsConstantValueRange() { return lower_.IsConstant() && upper_.IsConstant(); }
305
Mingyao Yangf384f882014-10-22 16:08:18 -0700306 // If it's certain that this value range fits in other_range.
307 virtual bool FitsIn(ValueRange* other_range) const {
308 if (other_range == nullptr) {
309 return true;
310 }
311 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800312 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
313 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700314 }
315
316 // Returns the intersection of this and range.
317 // If it's not possible to do intersection because some
318 // bounds are not comparable, it's ok to pick either bound.
319 virtual ValueRange* Narrow(ValueRange* range) {
320 if (range == nullptr) {
321 return this;
322 }
323
324 if (range->IsMonotonicValueRange()) {
325 return this;
326 }
327
328 return new (allocator_) ValueRange(
329 allocator_,
330 ValueBound::NarrowLowerBound(lower_, range->lower_),
331 ValueBound::NarrowUpperBound(upper_, range->upper_));
332 }
333
Mingyao Yang0304e182015-01-30 16:41:29 -0800334 // Shift a range by a constant.
335 ValueRange* Add(int32_t constant) const {
336 bool overflow, underflow;
337 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
338 if (underflow) {
339 // Lower bound underflow will wrap around to positive values
340 // and invalidate the upper bound.
341 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700342 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800343 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
344 if (overflow) {
345 // Upper bound overflow will wrap around to negative values
346 // and invalidate the lower bound.
347 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700348 }
349 return new (allocator_) ValueRange(allocator_, lower, upper);
350 }
351
Mingyao Yangf384f882014-10-22 16:08:18 -0700352 private:
353 ArenaAllocator* const allocator_;
354 const ValueBound lower_; // inclusive
355 const ValueBound upper_; // inclusive
356
357 DISALLOW_COPY_AND_ASSIGN(ValueRange);
358};
359
360/**
361 * A monotonically incrementing/decrementing value range, e.g.
362 * the variable i in "for (int i=0; i<array.length; i++)".
363 * Special care needs to be taken to account for overflow/underflow
364 * of such value ranges.
365 */
366class MonotonicValueRange : public ValueRange {
367 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800368 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700369 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800370 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800371 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800372 ValueBound bound)
Aart Bikaab5b752015-09-23 11:18:57 -0700373 // To be conservative, give it full range [Min(), Max()] in case it's
Mingyao Yang64197522014-12-05 15:56:23 -0800374 // used as a regular value range, due to possible overflow/underflow.
375 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700376 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800377 initial_(initial),
378 increment_(increment),
379 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700380
381 virtual ~MonotonicValueRange() {}
382
Mingyao Yang57e04752015-02-09 18:13:26 -0800383 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800384 ValueBound GetBound() const { return bound_; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700385 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700386 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
387 return induction_variable_->GetBlock();
388 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800389
390 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700391
392 // If it's certain that this value range fits in other_range.
393 bool FitsIn(ValueRange* other_range) const OVERRIDE {
394 if (other_range == nullptr) {
395 return true;
396 }
397 DCHECK(!other_range->IsMonotonicValueRange());
398 return false;
399 }
400
401 // Try to narrow this MonotonicValueRange given another range.
402 // Ideally it will return a normal ValueRange. But due to
403 // possible overflow/underflow, that may not be possible.
404 ValueRange* Narrow(ValueRange* range) OVERRIDE {
405 if (range == nullptr) {
406 return this;
407 }
408 DCHECK(!range->IsMonotonicValueRange());
409
410 if (increment_ > 0) {
411 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800412 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Aart Bikaab5b752015-09-23 11:18:57 -0700413 if (!lower.IsConstant() || lower.GetConstant() == std::numeric_limits<int32_t>::min()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700414 // Lower bound isn't useful. Leave it to deoptimization.
415 return this;
416 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700417
Aart Bikaab5b752015-09-23 11:18:57 -0700418 // We currently conservatively assume max array length is Max().
419 // 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 -0700420 // divided by the element size (such as 4 bytes for each integer array), we can
421 // lower this number and rule out some possible overflows.
Aart Bikaab5b752015-09-23 11:18:57 -0700422 int32_t max_array_len = std::numeric_limits<int32_t>::max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700423
Mingyao Yang0304e182015-01-30 16:41:29 -0800424 // max possible integer value of range's upper value.
Aart Bikaab5b752015-09-23 11:18:57 -0700425 int32_t upper = std::numeric_limits<int32_t>::max();
Mingyao Yang0304e182015-01-30 16:41:29 -0800426 // Try to lower upper.
427 ValueBound upper_bound = range->GetUpper();
428 if (upper_bound.IsConstant()) {
429 upper = upper_bound.GetConstant();
430 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
431 // Normal case. e.g. <= array.length - 1.
432 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700433 }
434
435 // If we can prove for the last number in sequence of initial_,
436 // initial_ + increment_, initial_ + 2 x increment_, ...
437 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
438 // then this MonoticValueRange is narrowed to a normal value range.
439
440 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800441 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700442 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800443 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700444 if (upper <= initial_constant) {
445 last_num_in_sequence = upper;
446 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800447 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700448 last_num_in_sequence = initial_constant +
449 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
450 }
451 }
Aart Bikaab5b752015-09-23 11:18:57 -0700452 if (last_num_in_sequence <= (std::numeric_limits<int32_t>::max() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700453 // No overflow. The sequence will be stopped by the upper bound test as expected.
454 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
455 }
456
457 // There might be overflow. Give up narrowing.
458 return this;
459 } else {
460 DCHECK_NE(increment_, 0);
461 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800462 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Aart Bikaab5b752015-09-23 11:18:57 -0700463 if ((!upper.IsConstant() || upper.GetConstant() == std::numeric_limits<int32_t>::max()) &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700464 !upper.IsRelatedToArrayLength()) {
465 // Upper bound isn't useful. Leave it to deoptimization.
466 return this;
467 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700468
469 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800470 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700471 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800472 int32_t constant = range->GetLower().GetConstant();
Aart Bikaab5b752015-09-23 11:18:57 -0700473 if (constant >= (std::numeric_limits<int32_t>::min() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700474 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
475 }
476 }
477
Mingyao Yang0304e182015-01-30 16:41:29 -0800478 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700479 return this;
480 }
481 }
482
483 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700484 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
485 HInstruction* const initial_; // Initial value.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700486 const int32_t increment_; // Increment for each loop iteration.
487 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700488
489 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
490};
491
492class BCEVisitor : public HGraphVisitor {
493 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700494 // The least number of bounds checks that should be eliminated by triggering
495 // the deoptimization technique.
496 static constexpr size_t kThresholdForAddingDeoptimize = 2;
497
Aart Bik1d239822016-02-09 14:26:34 -0800498 // Very large lengths are considered an anomaly. This is a threshold beyond which we don't
499 // bother to apply the deoptimization technique since it's likely, or sometimes certain,
500 // an AIOOBE will be thrown.
501 static constexpr uint32_t kMaxLengthForAddingDeoptimize =
Aart Bikaab5b752015-09-23 11:18:57 -0700502 std::numeric_limits<int32_t>::max() - 1024 * 1024;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700503
Mingyao Yang3584bce2015-05-19 16:01:59 -0700504 // Added blocks for loop body entry test.
505 bool IsAddedBlock(HBasicBlock* block) const {
506 return block->GetBlockId() >= initial_block_size_;
507 }
508
Aart Bik4a342772015-11-30 10:17:46 -0800509 BCEVisitor(HGraph* graph,
510 const SideEffectsAnalysis& side_effects,
511 HInductionVarAnalysis* induction_analysis)
Aart Bik22af3be2015-09-10 12:50:58 -0700512 : HGraphVisitor(graph),
Vladimir Marko5233f932015-09-29 19:01:15 +0100513 maps_(graph->GetBlocks().size(),
514 ArenaSafeMap<int, ValueRange*>(
515 std::less<int>(),
516 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
517 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800518 first_index_bounds_check_map_(
Vladimir Marko5233f932015-09-29 19:01:15 +0100519 std::less<int>(),
520 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik4a342772015-11-30 10:17:46 -0800521 early_exit_loop_(
522 std::less<uint32_t>(),
523 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
524 taken_test_loop_(
525 std::less<uint32_t>(),
526 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
527 finite_loop_(graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800528 has_dom_based_dynamic_bce_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100529 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800530 side_effects_(side_effects),
Andreas Gamped9911ee2017-03-27 13:27:24 -0700531 induction_range_(induction_analysis),
532 next_(nullptr) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700533
534 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700535 DCHECK(!IsAddedBlock(block));
Aart Bik1d239822016-02-09 14:26:34 -0800536 first_index_bounds_check_map_.clear();
Aart Bik1e677482016-11-01 14:23:58 -0700537 // Visit phis and instructions using a safe iterator. The iteration protects
538 // against deleting the current instruction during iteration. However, it
539 // must advance next_ if that instruction is deleted during iteration.
540 for (HInstruction* instruction = block->GetFirstPhi(); instruction != nullptr;) {
541 DCHECK(instruction->IsInBlock());
542 next_ = instruction->GetNext();
543 instruction->Accept(this);
544 instruction = next_;
545 }
546 for (HInstruction* instruction = block->GetFirstInstruction(); instruction != nullptr;) {
547 DCHECK(instruction->IsInBlock());
548 next_ = instruction->GetNext();
549 instruction->Accept(this);
550 instruction = next_;
551 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100552 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
553 // code dominated by the deoptimization.
554 if (!GetGraph()->IsCompilingOsr()) {
555 AddComparesWithDeoptimization(block);
556 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700557 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700558
Aart Bik4a342772015-11-30 10:17:46 -0800559 void Finish() {
560 // Preserve SSA structure which may have been broken by adding one or more
561 // new taken-test structures (see TransformLoopForDeoptimizationIfNeeded()).
562 InsertPhiNodes();
563
564 // Clear the loop data structures.
565 early_exit_loop_.clear();
566 taken_test_loop_.clear();
567 finite_loop_.clear();
568 }
569
Mingyao Yangf384f882014-10-22 16:08:18 -0700570 private:
571 // Return the map of proven value ranges at the beginning of a basic block.
572 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700573 if (IsAddedBlock(basic_block)) {
574 // Added blocks don't keep value ranges.
575 return nullptr;
576 }
Aart Bik1d239822016-02-09 14:26:34 -0800577 return &maps_[basic_block->GetBlockId()];
Mingyao Yangf384f882014-10-22 16:08:18 -0700578 }
579
580 // Traverse up the dominator tree to look for value range info.
581 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
582 while (basic_block != nullptr) {
583 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700584 if (map != nullptr) {
585 if (map->find(instruction->GetId()) != map->end()) {
586 return map->Get(instruction->GetId());
587 }
588 } else {
589 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -0700590 }
591 basic_block = basic_block->GetDominator();
592 }
593 // Didn't find any.
594 return nullptr;
595 }
596
Aart Bik1d239822016-02-09 14:26:34 -0800597 // Helper method to assign a new range to an instruction in given basic block.
598 void AssignRange(HBasicBlock* basic_block, HInstruction* instruction, ValueRange* range) {
Mingyao Yang73b326e2017-09-12 14:42:29 -0700599 DCHECK(!range->IsMonotonicValueRange() || instruction->IsLoopHeaderPhi());
Aart Bik1d239822016-02-09 14:26:34 -0800600 GetValueRangeMap(basic_block)->Overwrite(instruction->GetId(), range);
601 }
602
Mingyao Yang0304e182015-01-30 16:41:29 -0800603 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
604 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700605 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800606 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700607 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800608 if (existing_range == nullptr) {
609 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800610 AssignRange(successor, instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800611 }
612 return;
613 }
614 if (existing_range->IsMonotonicValueRange()) {
615 DCHECK(instruction->IsLoopHeaderPhi());
616 // Make sure the comparison is in the loop header so each increment is
617 // checked with a comparison.
618 if (instruction->GetBlock() != basic_block) {
619 return;
620 }
621 }
Aart Bik1d239822016-02-09 14:26:34 -0800622 AssignRange(successor, instruction, existing_range->Narrow(range));
Mingyao Yangf384f882014-10-22 16:08:18 -0700623 }
624
Mingyao Yang57e04752015-02-09 18:13:26 -0800625 // Special case that we may simultaneously narrow two MonotonicValueRange's to
626 // regular value ranges.
627 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
628 HInstruction* left,
629 HInstruction* right,
630 IfCondition cond,
631 MonotonicValueRange* left_range,
632 MonotonicValueRange* right_range) {
633 DCHECK(left->IsLoopHeaderPhi());
634 DCHECK(right->IsLoopHeaderPhi());
635 if (instruction->GetBlock() != left->GetBlock()) {
636 // Comparison needs to be in loop header to make sure it's done after each
637 // increment/decrement.
638 return;
639 }
640
641 // Handle common cases which also don't have overflow/underflow concerns.
642 if (left_range->GetIncrement() == 1 &&
643 left_range->GetBound().IsConstant() &&
644 right_range->GetIncrement() == -1 &&
645 right_range->GetBound().IsRelatedToArrayLength() &&
646 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800647 HBasicBlock* successor = nullptr;
648 int32_t left_compensation = 0;
649 int32_t right_compensation = 0;
650 if (cond == kCondLT) {
651 left_compensation = -1;
652 right_compensation = 1;
653 successor = instruction->IfTrueSuccessor();
654 } else if (cond == kCondLE) {
655 successor = instruction->IfTrueSuccessor();
656 } else if (cond == kCondGT) {
657 successor = instruction->IfFalseSuccessor();
658 } else if (cond == kCondGE) {
659 left_compensation = -1;
660 right_compensation = 1;
661 successor = instruction->IfFalseSuccessor();
662 } else {
663 // We don't handle '=='/'!=' test in case left and right can cross and
664 // miss each other.
665 return;
666 }
667
668 if (successor != nullptr) {
669 bool overflow;
670 bool underflow;
671 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
672 GetGraph()->GetArena(),
673 left_range->GetBound(),
674 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
675 if (!overflow && !underflow) {
676 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
677 new_left_range);
678 }
679
680 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
681 GetGraph()->GetArena(),
682 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
683 right_range->GetBound());
684 if (!overflow && !underflow) {
685 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
686 new_right_range);
687 }
688 }
689 }
690 }
691
Mingyao Yangf384f882014-10-22 16:08:18 -0700692 // Handle "if (left cmp_cond right)".
693 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
694 HBasicBlock* block = instruction->GetBlock();
695
696 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
697 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000698 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700699
700 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
701 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000702 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700703
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700704 ValueRange* left_range = LookupValueRange(left, block);
705 MonotonicValueRange* left_monotonic_range = nullptr;
706 if (left_range != nullptr) {
707 left_monotonic_range = left_range->AsMonotonicValueRange();
708 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700709 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700710 if (instruction->GetBlock() != loop_head) {
711 // For monotonic value range, don't handle `instruction`
712 // if it's not defined in the loop header.
713 return;
714 }
715 }
716 }
717
Mingyao Yang64197522014-12-05 15:56:23 -0800718 bool found;
719 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800720 // Each comparison can establish a lower bound and an upper bound
721 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700722 ValueBound lower = bound;
723 ValueBound upper = bound;
724 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800725 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700726 // 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 -0800727 ValueRange* right_range = LookupValueRange(right, block);
728 if (right_range != nullptr) {
729 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800730 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
731 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
732 left_range->AsMonotonicValueRange(),
733 right_range->AsMonotonicValueRange());
734 return;
735 }
736 }
737 lower = right_range->GetLower();
738 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700739 } else {
740 lower = ValueBound::Min();
741 upper = ValueBound::Max();
742 }
743 }
744
Mingyao Yang0304e182015-01-30 16:41:29 -0800745 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700746 if (cond == kCondLT || cond == kCondLE) {
747 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800748 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
749 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
750 if (overflow || underflow) {
751 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800752 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700753 ValueRange* new_range = new (GetGraph()->GetArena())
754 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
755 ApplyRangeFromComparison(left, block, true_successor, new_range);
756 }
757
758 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800759 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
760 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
761 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
762 if (overflow || underflow) {
763 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800764 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700765 ValueRange* new_range = new (GetGraph()->GetArena())
766 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
767 ApplyRangeFromComparison(left, block, false_successor, new_range);
768 }
769 } else if (cond == kCondGT || cond == kCondGE) {
770 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800771 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
772 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
773 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
774 if (overflow || underflow) {
775 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800776 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700777 ValueRange* new_range = new (GetGraph()->GetArena())
778 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
779 ApplyRangeFromComparison(left, block, true_successor, new_range);
780 }
781
782 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800783 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
784 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
785 if (overflow || underflow) {
786 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800787 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700788 ValueRange* new_range = new (GetGraph()->GetArena())
789 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
790 ApplyRangeFromComparison(left, block, false_successor, new_range);
791 }
Aart Bika2106892016-05-04 14:00:55 -0700792 } else if (cond == kCondNE || cond == kCondEQ) {
793 if (left->IsArrayLength() && lower.IsConstant() && upper.IsConstant()) {
794 // Special case:
795 // length == [c,d] yields [c, d] along true
796 // length != [c,d] yields [c, d] along false
797 if (!lower.Equals(ValueBound::Min()) || !upper.Equals(ValueBound::Max())) {
798 ValueRange* new_range = new (GetGraph()->GetArena())
799 ValueRange(GetGraph()->GetArena(), lower, upper);
800 ApplyRangeFromComparison(
801 left, block, cond == kCondEQ ? true_successor : false_successor, new_range);
802 }
803 // In addition:
804 // length == 0 yields [1, max] along false
805 // length != 0 yields [1, max] along true
806 if (lower.GetConstant() == 0 && upper.GetConstant() == 0) {
807 ValueRange* new_range = new (GetGraph()->GetArena())
808 ValueRange(GetGraph()->GetArena(), ValueBound(nullptr, 1), ValueBound::Max());
809 ApplyRangeFromComparison(
810 left, block, cond == kCondEQ ? false_successor : true_successor, new_range);
811 }
812 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700813 }
814 }
815
Aart Bik4a342772015-11-30 10:17:46 -0800816 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700817 HBasicBlock* block = bounds_check->GetBlock();
818 HInstruction* index = bounds_check->InputAt(0);
819 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700820 DCHECK(array_length->IsIntConstant() ||
821 array_length->IsArrayLength() ||
822 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800823 bool try_dynamic_bce = true;
Aart Bik1d239822016-02-09 14:26:34 -0800824 // Analyze index range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800825 if (!index->IsIntConstant()) {
Aart Bik1d239822016-02-09 14:26:34 -0800826 // Non-constant index.
Aart Bik22af3be2015-09-10 12:50:58 -0700827 ValueBound lower = ValueBound(nullptr, 0); // constant 0
828 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
829 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800830 // Try index range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800831 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700832 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800833 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700834 return;
835 }
Aart Bik1d239822016-02-09 14:26:34 -0800836 // Try index range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800837 // Disables dynamic bce if OOB is certain.
Aart Bik52be7e72016-06-23 11:20:41 -0700838 if (InductionRangeFitsIn(&array_range, bounds_check, &try_dynamic_bce)) {
Aart Bik4a342772015-11-30 10:17:46 -0800839 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700840 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700841 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800842 } else {
Aart Bik1d239822016-02-09 14:26:34 -0800843 // Constant index.
Mingyao Yang0304e182015-01-30 16:41:29 -0800844 int32_t constant = index->AsIntConstant()->GetValue();
845 if (constant < 0) {
846 // Will always throw exception.
847 return;
Aart Bik1d239822016-02-09 14:26:34 -0800848 } else if (array_length->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800849 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800850 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800851 }
852 return;
853 }
Aart Bik1d239822016-02-09 14:26:34 -0800854 // Analyze array length range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800855 DCHECK(array_length->IsArrayLength());
856 ValueRange* existing_range = LookupValueRange(array_length, block);
857 if (existing_range != nullptr) {
858 ValueBound lower = existing_range->GetLower();
859 DCHECK(lower.IsConstant());
860 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800861 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800862 return;
863 } else {
864 // Existing range isn't strong enough to eliminate the bounds check.
865 // Fall through to update the array_length range with info from this
866 // bounds check.
867 }
868 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700869 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800870 // We currently don't do it for non-constant index since a valid array[i] can't prove
871 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700872 if (constant == std::numeric_limits<int32_t>::max()) {
873 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700874 return;
Aart Bik1d239822016-02-09 14:26:34 -0800875 } else {
876 ValueBound lower = ValueBound(nullptr, constant + 1);
877 ValueBound upper = ValueBound::Max();
878 ValueRange* range = new (GetGraph()->GetArena())
879 ValueRange(GetGraph()->GetArena(), lower, upper);
880 AssignRange(block, array_length, range);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700881 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700882 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700883
Aart Bik4a342772015-11-30 10:17:46 -0800884 // If static analysis fails, and OOB is not certain, try dynamic elimination.
885 if (try_dynamic_bce) {
Aart Bik1d239822016-02-09 14:26:34 -0800886 // Try loop-based dynamic elimination.
Aart Bik67def592016-07-14 17:19:43 -0700887 HLoopInformation* loop = bounds_check->GetBlock()->GetLoopInformation();
888 bool needs_finite_test = false;
889 bool needs_taken_test = false;
890 if (DynamicBCESeemsProfitable(loop, bounds_check->GetBlock()) &&
Aart Bik16d3a652016-09-09 10:33:50 -0700891 induction_range_.CanGenerateRange(
Aart Bik67def592016-07-14 17:19:43 -0700892 bounds_check, index, &needs_finite_test, &needs_taken_test) &&
893 CanHandleInfiniteLoop(loop, index, needs_finite_test) &&
894 // Do this test last, since it may generate code.
895 CanHandleLength(loop, array_length, needs_taken_test)) {
896 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
897 TransformLoopForDynamicBCE(loop, bounds_check);
Aart Bik1d239822016-02-09 14:26:34 -0800898 return;
899 }
Aart Bik67def592016-07-14 17:19:43 -0700900 // Otherwise, prepare dominator-based dynamic elimination.
Aart Bik1d239822016-02-09 14:26:34 -0800901 if (first_index_bounds_check_map_.find(array_length->GetId()) ==
902 first_index_bounds_check_map_.end()) {
903 // Remember the first bounds check against each array_length. That bounds check
904 // instruction has an associated HEnvironment where we may add an HDeoptimize
905 // to eliminate subsequent bounds checks against the same array_length.
906 first_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
907 }
Aart Bik4a342772015-11-30 10:17:46 -0800908 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700909 }
910
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100911 static bool HasSameInputAtBackEdges(HPhi* phi) {
912 DCHECK(phi->IsLoopHeaderPhi());
Vladimir Markoe9004912016-06-16 16:50:52 +0100913 HConstInputsRef inputs = phi->GetInputs();
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100914 // Start with input 1. Input 0 is from the incoming block.
Vladimir Markoe9004912016-06-16 16:50:52 +0100915 const HInstruction* input1 = inputs[1];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100916 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100917 *phi->GetBlock()->GetPredecessors()[1]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100918 for (size_t i = 2; i < inputs.size(); ++i) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100919 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100920 *phi->GetBlock()->GetPredecessors()[i]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100921 if (input1 != inputs[i]) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100922 return false;
923 }
924 }
925 return true;
926 }
927
Aart Bik4a342772015-11-30 10:17:46 -0800928 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100929 if (phi->IsLoopHeaderPhi()
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100930 && (phi->GetType() == DataType::Type::kInt32)
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100931 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700932 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800933 HInstruction *left;
934 int32_t increment;
935 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
936 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700937 HInstruction* initial_value = phi->InputAt(0);
938 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800939 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700940 // Add constant 0. It's really a fixed value.
941 range = new (GetGraph()->GetArena()) ValueRange(
942 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800943 ValueBound(initial_value, 0),
944 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700945 } else {
946 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800947 bool found;
948 ValueBound bound = ValueBound::DetectValueBoundFromValue(
949 initial_value, &found);
950 if (!found) {
951 // No constant or array.length+c bound found.
952 // For i=j, we can still use j's upper bound as i's upper bound.
953 // Same for lower.
954 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
955 if (initial_range != nullptr) {
956 bound = increment > 0 ? initial_range->GetLower() :
957 initial_range->GetUpper();
958 } else {
959 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
960 }
961 }
962 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700963 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700964 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700965 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800966 increment,
967 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700968 }
Aart Bik1d239822016-02-09 14:26:34 -0800969 AssignRange(phi->GetBlock(), phi, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700970 }
971 }
972 }
973 }
974
Aart Bik4a342772015-11-30 10:17:46 -0800975 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700976 if (instruction->InputAt(0)->IsCondition()) {
977 HCondition* cond = instruction->InputAt(0)->AsCondition();
Aart Bika2106892016-05-04 14:00:55 -0700978 HandleIf(instruction, cond->GetLeft(), cond->GetRight(), cond->GetCondition());
Mingyao Yangf384f882014-10-22 16:08:18 -0700979 }
980 }
981
Aart Bik4a342772015-11-30 10:17:46 -0800982 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700983 HInstruction* right = add->GetRight();
984 if (right->IsIntConstant()) {
985 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
986 if (left_range == nullptr) {
987 return;
988 }
989 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
990 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800991 AssignRange(add->GetBlock(), add, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700992 }
993 }
994 }
995
Aart Bik4a342772015-11-30 10:17:46 -0800996 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700997 HInstruction* left = sub->GetLeft();
998 HInstruction* right = sub->GetRight();
999 if (right->IsIntConstant()) {
1000 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1001 if (left_range == nullptr) {
1002 return;
1003 }
1004 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1005 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001006 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001007 return;
1008 }
1009 }
1010
1011 // Here we are interested in the typical triangular case of nested loops,
1012 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1013 // 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 -08001014
1015 // Try to handle (array.length - i) or (array.length + c - i) format.
1016 HInstruction* left_of_left; // left input of left.
1017 int32_t right_const = 0;
1018 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1019 left = left_of_left;
1020 }
1021 // The value of left input of the sub equals (left + right_const).
1022
Mingyao Yangf384f882014-10-22 16:08:18 -07001023 if (left->IsArrayLength()) {
1024 HInstruction* array_length = left->AsArrayLength();
1025 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1026 if (right_range != nullptr) {
1027 ValueBound lower = right_range->GetLower();
1028 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001029 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001030 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001031 // Make sure it's the same array.
1032 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001033 int32_t c0 = right_const;
1034 int32_t c1 = lower.GetConstant();
1035 int32_t c2 = upper.GetConstant();
1036 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1037 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1038 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1039 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1040 if ((c0 - c1) <= 0) {
1041 // array.length + (c0 - c1) won't overflow/underflow.
1042 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1043 GetGraph()->GetArena(),
1044 ValueBound(nullptr, right_const - upper.GetConstant()),
1045 ValueBound(array_length, right_const - lower.GetConstant()));
Aart Bik1d239822016-02-09 14:26:34 -08001046 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001047 }
1048 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001049 }
1050 }
1051 }
1052 }
1053 }
1054
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001055 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1056 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1057 HInstruction* right = instruction->GetRight();
1058 int32_t right_const;
1059 if (right->IsIntConstant()) {
1060 right_const = right->AsIntConstant()->GetValue();
1061 // Detect division by two or more.
1062 if ((instruction->IsDiv() && right_const <= 1) ||
1063 (instruction->IsShr() && right_const < 1) ||
1064 (instruction->IsUShr() && right_const < 1)) {
1065 return;
1066 }
1067 } else {
1068 return;
1069 }
1070
1071 // Try to handle array.length/2 or (array.length-1)/2 format.
1072 HInstruction* left = instruction->GetLeft();
1073 HInstruction* left_of_left; // left input of left.
1074 int32_t c = 0;
1075 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1076 left = left_of_left;
1077 }
1078 // The value of left input of instruction equals (left + c).
1079
1080 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001081 // always generate a value in [Min(), array_length].
1082 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001083 if (left->IsArrayLength() && c <= 1) {
1084 if (instruction->IsUShr() && c < 0) {
1085 // Make sure for unsigned shift, left side is not negative.
1086 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1087 // than array_length.
1088 return;
1089 }
1090 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1091 GetGraph()->GetArena(),
Aart Bikaab5b752015-09-23 11:18:57 -07001092 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001093 ValueBound(left, 0));
Aart Bik1d239822016-02-09 14:26:34 -08001094 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001095 }
1096 }
1097
Aart Bik4a342772015-11-30 10:17:46 -08001098 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001099 FindAndHandlePartialArrayLength(div);
1100 }
1101
Aart Bik4a342772015-11-30 10:17:46 -08001102 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001103 FindAndHandlePartialArrayLength(shr);
1104 }
1105
Aart Bik4a342772015-11-30 10:17:46 -08001106 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001107 FindAndHandlePartialArrayLength(ushr);
1108 }
1109
Aart Bik4a342772015-11-30 10:17:46 -08001110 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001111 if (instruction->GetRight()->IsIntConstant()) {
1112 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1113 if (constant > 0) {
1114 // constant serves as a mask so any number masked with it
1115 // gets a [0, constant] value range.
1116 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1117 GetGraph()->GetArena(),
1118 ValueBound(nullptr, 0),
1119 ValueBound(nullptr, constant));
Aart Bik1d239822016-02-09 14:26:34 -08001120 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang4559f002015-02-27 14:43:53 -08001121 }
1122 }
1123 }
1124
xueliang.zhonga22cae72017-06-26 17:49:48 +01001125 void VisitRem(HRem* instruction) OVERRIDE {
1126 HInstruction* left = instruction->GetLeft();
1127 HInstruction* right = instruction->GetRight();
1128
1129 // Handle 'i % CONST' format expression in array index, e.g:
1130 // array[i % 20];
1131 if (right->IsIntConstant()) {
1132 int32_t right_const = std::abs(right->AsIntConstant()->GetValue());
1133 if (right_const == 0) {
1134 return;
1135 }
1136 // The sign of divisor CONST doesn't affect the sign final value range.
1137 // For example:
1138 // if (i > 0) {
1139 // array[i % 10]; // index value range [0, 9]
1140 // array[i % -10]; // index value range [0, 9]
1141 // }
1142 ValueRange* right_range = new (GetGraph()->GetArena()) ValueRange(
1143 GetGraph()->GetArena(),
1144 ValueBound(nullptr, 1 - right_const),
1145 ValueBound(nullptr, right_const - 1));
1146
Aart Bikbae9c9a2017-09-11 14:51:54 -07001147 ValueRange* left_range = LookupValueRange(left, instruction->GetBlock());
xueliang.zhonga22cae72017-06-26 17:49:48 +01001148 if (left_range != nullptr) {
Aart Bikbae9c9a2017-09-11 14:51:54 -07001149 right_range = right_range->Narrow(left_range);
xueliang.zhonga22cae72017-06-26 17:49:48 +01001150 }
1151 AssignRange(instruction->GetBlock(), instruction, right_range);
1152 return;
1153 }
1154
1155 // Handle following pattern:
1156 // i0 NullCheck
1157 // i1 ArrayLength[i0]
1158 // i2 DivByZeroCheck [i1] <-- right
1159 // i3 Rem [i5, i2] <-- we are here.
1160 // i4 BoundsCheck [i3,i1]
1161 if (right->IsDivZeroCheck()) {
1162 // if array_length can pass div-by-zero check,
1163 // array_length must be > 0.
1164 right = right->AsDivZeroCheck()->InputAt(0);
1165 }
1166
1167 // Handle 'i % array.length' format expression in array index, e.g:
1168 // array[(i+7) % array.length];
1169 if (right->IsArrayLength()) {
1170 ValueBound lower = ValueBound::Min(); // ideally, lower should be '1-array_length'.
1171 ValueBound upper = ValueBound(right, -1); // array_length - 1
1172 ValueRange* right_range = new (GetGraph()->GetArena()) ValueRange(
1173 GetGraph()->GetArena(),
1174 lower,
1175 upper);
Aart Bikbae9c9a2017-09-11 14:51:54 -07001176 ValueRange* left_range = LookupValueRange(left, instruction->GetBlock());
xueliang.zhonga22cae72017-06-26 17:49:48 +01001177 if (left_range != nullptr) {
Aart Bikbae9c9a2017-09-11 14:51:54 -07001178 right_range = right_range->Narrow(left_range);
xueliang.zhonga22cae72017-06-26 17:49:48 +01001179 }
1180 AssignRange(instruction->GetBlock(), instruction, right_range);
1181 return;
1182 }
1183 }
1184
Aart Bik4a342772015-11-30 10:17:46 -08001185 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001186 HInstruction* len = new_array->GetLength();
Mingyao Yang0304e182015-01-30 16:41:29 -08001187 if (!len->IsIntConstant()) {
1188 HInstruction *left;
1189 int32_t right_const;
1190 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1191 // (left + right_const) is used as size to new the array.
1192 // We record "-right_const <= left <= new_array - right_const";
1193 ValueBound lower = ValueBound(nullptr, -right_const);
1194 // We use new_array for the bound instead of new_array.length,
1195 // which isn't available as an instruction yet. new_array will
1196 // be treated the same as new_array.length when it's used in a ValueBound.
1197 ValueBound upper = ValueBound(new_array, -right_const);
1198 ValueRange* range = new (GetGraph()->GetArena())
1199 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001200 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1201 if (existing_range != nullptr) {
1202 range = existing_range->Narrow(range);
1203 }
Aart Bik1d239822016-02-09 14:26:34 -08001204 AssignRange(new_array->GetBlock(), left, range);
Mingyao Yang0304e182015-01-30 16:41:29 -08001205 }
1206 }
1207 }
1208
Aart Bik4a342772015-11-30 10:17:46 -08001209 /**
1210 * After null/bounds checks are eliminated, some invariant array references
1211 * may be exposed underneath which can be hoisted out of the loop to the
1212 * preheader or, in combination with dynamic bce, the deoptimization block.
1213 *
1214 * for (int i = 0; i < n; i++) {
1215 * <-------+
1216 * for (int j = 0; j < n; j++) |
1217 * a[i][j] = 0; --a[i]--+
1218 * }
1219 *
Aart Bik1d239822016-02-09 14:26:34 -08001220 * Note: this optimization is no longer applied after dominator-based dynamic deoptimization
1221 * has occurred (see AddCompareWithDeoptimization()), since in those cases it would be
1222 * unsafe to hoist array references across their deoptimization instruction inside a loop.
Aart Bik4a342772015-11-30 10:17:46 -08001223 */
1224 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
Aart Bik1d239822016-02-09 14:26:34 -08001225 if (!has_dom_based_dynamic_bce_ && array_get->IsInLoop()) {
Aart Bik4a342772015-11-30 10:17:46 -08001226 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001227 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1228 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001229 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1230 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Anton Shaminf89381f2016-05-16 16:44:13 +06001231 // We can hoist ArrayGet only if its execution is guaranteed on every iteration.
1232 // In other words only if array_get_bb dominates all back branches.
1233 if (loop->DominatesAllBackEdges(array_get->GetBlock())) {
1234 HoistToPreHeaderOrDeoptBlock(loop, array_get);
1235 }
Aart Bik4a342772015-11-30 10:17:46 -08001236 }
1237 }
1238 }
1239 }
1240
Aart Bik67def592016-07-14 17:19:43 -07001241 /** Performs dominator-based dynamic elimination on suitable set of bounds checks. */
Aart Bik1d239822016-02-09 14:26:34 -08001242 void AddCompareWithDeoptimization(HBasicBlock* block,
1243 HInstruction* array_length,
1244 HInstruction* base,
1245 int32_t min_c, int32_t max_c) {
1246 HBoundsCheck* bounds_check =
1247 first_index_bounds_check_map_.Get(array_length->GetId())->AsBoundsCheck();
1248 // Construct deoptimization on single or double bounds on range [base-min_c,base+max_c],
1249 // for example either for a[0]..a[3] just 3 or for a[base-1]..a[base+3] both base-1
1250 // and base+3, since we made the assumption any in between value may occur too.
Aart Bik67def592016-07-14 17:19:43 -07001251 // In code, using unsigned comparisons:
1252 // (1) constants only
1253 // if (max_c >= a.length) deoptimize;
1254 // (2) general case
1255 // if (base-min_c > base+max_c) deoptimize;
1256 // if (base+max_c >= a.length ) deoptimize;
Aart Bik1d239822016-02-09 14:26:34 -08001257 static_assert(kMaxLengthForAddingDeoptimize < std::numeric_limits<int32_t>::max(),
1258 "Incorrect max length may be subject to arithmetic wrap-around");
1259 HInstruction* upper = GetGraph()->GetIntConstant(max_c);
1260 if (base == nullptr) {
1261 DCHECK_GE(min_c, 0);
1262 } else {
1263 HInstruction* lower = new (GetGraph()->GetArena())
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001264 HAdd(DataType::Type::kInt32, base, GetGraph()->GetIntConstant(min_c));
1265 upper = new (GetGraph()->GetArena()) HAdd(DataType::Type::kInt32, base, upper);
Aart Bik1d239822016-02-09 14:26:34 -08001266 block->InsertInstructionBefore(lower, bounds_check);
1267 block->InsertInstructionBefore(upper, bounds_check);
1268 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAbove(lower, upper));
1269 }
1270 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAboveOrEqual(upper, array_length));
1271 // Flag that this kind of deoptimization has occurred.
1272 has_dom_based_dynamic_bce_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001273 }
1274
Aart Bik67def592016-07-14 17:19:43 -07001275 /** Attempts dominator-based dynamic elimination on remaining candidates. */
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001276 void AddComparesWithDeoptimization(HBasicBlock* block) {
Vladimir Markoda571cb2016-02-15 17:54:56 +00001277 for (const auto& entry : first_index_bounds_check_map_) {
1278 HBoundsCheck* bounds_check = entry.second;
Aart Bik1d239822016-02-09 14:26:34 -08001279 HInstruction* index = bounds_check->InputAt(0);
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001280 HInstruction* array_length = bounds_check->InputAt(1);
1281 if (!array_length->IsArrayLength()) {
Aart Bik1d239822016-02-09 14:26:34 -08001282 continue; // disregard phis and constants
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001283 }
Aart Bik1ae88742016-03-14 14:11:26 -07001284 // Collect all bounds checks that are still there and that are related as "a[base + constant]"
Aart Bik1d239822016-02-09 14:26:34 -08001285 // for a base instruction (possibly absent) and various constants. Note that no attempt
1286 // is made to partition the set into matching subsets (viz. a[0], a[1] and a[base+1] and
1287 // a[base+2] are considered as one set).
1288 // TODO: would such a partitioning be worthwhile?
1289 ValueBound value = ValueBound::AsValueBound(index);
1290 HInstruction* base = value.GetInstruction();
1291 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1292 int32_t max_c = value.GetConstant();
1293 ArenaVector<HBoundsCheck*> candidates(
1294 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1295 ArenaVector<HBoundsCheck*> standby(
1296 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
Vladimir Marko46817b82016-03-29 12:21:58 +01001297 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
Aart Bik1d239822016-02-09 14:26:34 -08001298 // Another bounds check in same or dominated block?
Vladimir Marko46817b82016-03-29 12:21:58 +01001299 HInstruction* user = use.GetUser();
Aart Bik1d239822016-02-09 14:26:34 -08001300 HBasicBlock* other_block = user->GetBlock();
1301 if (user->IsBoundsCheck() && block->Dominates(other_block)) {
1302 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1303 HInstruction* other_index = other_bounds_check->InputAt(0);
1304 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1305 ValueBound other_value = ValueBound::AsValueBound(other_index);
1306 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik1ae88742016-03-14 14:11:26 -07001307 // Reject certain OOB if BoundsCheck(l, l) occurs on considered subset.
1308 if (array_length == other_index) {
1309 candidates.clear();
1310 standby.clear();
1311 break;
1312 }
Aart Bik1d239822016-02-09 14:26:34 -08001313 // Since a subsequent dominated block could be under a conditional, only accept
1314 // the other bounds check if it is in same block or both blocks dominate the exit.
1315 // TODO: we could improve this by testing proper post-dominance, or even if this
1316 // constant is seen along *all* conditional paths that follow.
1317 HBasicBlock* exit = GetGraph()->GetExitBlock();
1318 if (block == user->GetBlock() ||
1319 (block->Dominates(exit) && other_block->Dominates(exit))) {
Aart Bik1ae88742016-03-14 14:11:26 -07001320 int32_t other_c = other_value.GetConstant();
Aart Bik1d239822016-02-09 14:26:34 -08001321 min_c = std::min(min_c, other_c);
1322 max_c = std::max(max_c, other_c);
1323 candidates.push_back(other_bounds_check);
1324 } else {
1325 // Add this candidate later only if it falls into the range.
1326 standby.push_back(other_bounds_check);
1327 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001328 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001329 }
1330 }
Aart Bik1d239822016-02-09 14:26:34 -08001331 // Add standby candidates that fall in selected range.
Vladimir Markoda571cb2016-02-15 17:54:56 +00001332 for (HBoundsCheck* other_bounds_check : standby) {
Aart Bik1d239822016-02-09 14:26:34 -08001333 HInstruction* other_index = other_bounds_check->InputAt(0);
1334 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1335 if (min_c <= other_c && other_c <= max_c) {
1336 candidates.push_back(other_bounds_check);
1337 }
1338 }
Aart Bik67def592016-07-14 17:19:43 -07001339 // Perform dominator-based deoptimization if it seems profitable, where we eliminate
1340 // bounds checks and replace these with deopt checks that guard against any possible
1341 // OOB. Note that we reject cases where the distance min_c:max_c range gets close to
1342 // the maximum possible array length, since those cases are likely to always deopt
1343 // (such situations do not necessarily go OOB, though, since the array could be really
1344 // large, or the programmer could rely on arithmetic wrap-around from max to min).
Aart Bik1d239822016-02-09 14:26:34 -08001345 size_t threshold = kThresholdForAddingDeoptimize + (base == nullptr ? 0 : 1); // extra test?
1346 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1347 if (candidates.size() >= threshold &&
1348 (base != nullptr || min_c >= 0) && // reject certain OOB
1349 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1350 AddCompareWithDeoptimization(block, array_length, base, min_c, max_c);
Aart Bik67def592016-07-14 17:19:43 -07001351 for (HBoundsCheck* other_bounds_check : candidates) {
Aart Bik1ae88742016-03-14 14:11:26 -07001352 // Only replace if still in the graph. This avoids visiting the same
1353 // bounds check twice if it occurred multiple times in the use list.
1354 if (other_bounds_check->IsInBlock()) {
1355 ReplaceInstruction(other_bounds_check, other_bounds_check->InputAt(0));
1356 }
Aart Bik1d239822016-02-09 14:26:34 -08001357 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001358 }
1359 }
1360 }
1361
Aart Bik4a342772015-11-30 10:17:46 -08001362 /**
1363 * Returns true if static range analysis based on induction variables can determine the bounds
1364 * check on the given array range is always satisfied with the computed index range. The output
1365 * parameter try_dynamic_bce is set to false if OOB is certain.
1366 */
1367 bool InductionRangeFitsIn(ValueRange* array_range,
Aart Bik52be7e72016-06-23 11:20:41 -07001368 HBoundsCheck* context,
Aart Bik4a342772015-11-30 10:17:46 -08001369 bool* try_dynamic_bce) {
1370 InductionVarRange::Value v1;
1371 InductionVarRange::Value v2;
1372 bool needs_finite_test = false;
Aart Bik52be7e72016-06-23 11:20:41 -07001373 HInstruction* index = context->InputAt(0);
Nicolas Geoffraye761bcc2017-01-19 08:59:37 +00001374 HInstruction* hint = HuntForDeclaration(context->InputAt(1));
Aart Bik52be7e72016-06-23 11:20:41 -07001375 if (induction_range_.GetInductionRange(context, index, hint, &v1, &v2, &needs_finite_test)) {
1376 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1377 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1378 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1379 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1380 ValueRange index_range(GetGraph()->GetArena(),
1381 ValueBound(v1.instruction, v1.b_constant),
1382 ValueBound(v2.instruction, v2.b_constant));
1383 // If analysis reveals a certain OOB, disable dynamic BCE. Otherwise,
1384 // use analysis for static bce only if loop is finite.
1385 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1386 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1387 *try_dynamic_bce = false;
1388 } else if (!needs_finite_test && index_range.FitsIn(array_range)) {
1389 return true;
Aart Bikb738d4f2015-12-03 11:23:35 -08001390 }
Aart Bik52be7e72016-06-23 11:20:41 -07001391 }
Aart Bik1fc3afb2016-02-02 13:26:16 -08001392 }
Aart Bik4a342772015-11-30 10:17:46 -08001393 return false;
1394 }
1395
1396 /**
Aart Bik67def592016-07-14 17:19:43 -07001397 * Performs loop-based dynamic elimination on a bounds check. In order to minimize the
1398 * number of eventually generated tests, related bounds checks with tests that can be
1399 * combined with tests for the given bounds check are collected first.
Aart Bik4a342772015-11-30 10:17:46 -08001400 */
Aart Bik67def592016-07-14 17:19:43 -07001401 void TransformLoopForDynamicBCE(HLoopInformation* loop, HBoundsCheck* bounds_check) {
1402 HInstruction* index = bounds_check->InputAt(0);
1403 HInstruction* array_length = bounds_check->InputAt(1);
1404 DCHECK(loop->IsDefinedOutOfTheLoop(array_length)); // pre-checked
1405 DCHECK(loop->DominatesAllBackEdges(bounds_check->GetBlock()));
1406 // Collect all bounds checks in the same loop that are related as "a[base + constant]"
1407 // for a base instruction (possibly absent) and various constants.
1408 ValueBound value = ValueBound::AsValueBound(index);
1409 HInstruction* base = value.GetInstruction();
1410 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1411 int32_t max_c = value.GetConstant();
1412 ArenaVector<HBoundsCheck*> candidates(
1413 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1414 ArenaVector<HBoundsCheck*> standby(
1415 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1416 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
1417 HInstruction* user = use.GetUser();
1418 if (user->IsBoundsCheck() && loop == user->GetBlock()->GetLoopInformation()) {
1419 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1420 HInstruction* other_index = other_bounds_check->InputAt(0);
1421 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1422 ValueBound other_value = ValueBound::AsValueBound(other_index);
1423 int32_t other_c = other_value.GetConstant();
1424 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik12a10602016-10-18 11:35:22 -07001425 // Ensure every candidate could be picked for code generation.
1426 bool b1 = false, b2 = false;
1427 if (!induction_range_.CanGenerateRange(other_bounds_check, other_index, &b1, &b2)) {
1428 continue;
1429 }
Aart Bik67def592016-07-14 17:19:43 -07001430 // Does the current basic block dominate all back edges? If not,
1431 // add this candidate later only if it falls into the range.
1432 if (!loop->DominatesAllBackEdges(user->GetBlock())) {
1433 standby.push_back(other_bounds_check);
1434 continue;
1435 }
1436 min_c = std::min(min_c, other_c);
1437 max_c = std::max(max_c, other_c);
1438 candidates.push_back(other_bounds_check);
1439 }
Aart Bik4a342772015-11-30 10:17:46 -08001440 }
Aart Bik4a342772015-11-30 10:17:46 -08001441 }
Aart Bik67def592016-07-14 17:19:43 -07001442 // Add standby candidates that fall in selected range.
1443 for (HBoundsCheck* other_bounds_check : standby) {
1444 HInstruction* other_index = other_bounds_check->InputAt(0);
1445 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1446 if (min_c <= other_c && other_c <= max_c) {
1447 candidates.push_back(other_bounds_check);
1448 }
1449 }
1450 // Perform loop-based deoptimization if it seems profitable, where we eliminate bounds
1451 // checks and replace these with deopt checks that guard against any possible OOB.
1452 DCHECK_LT(0u, candidates.size());
1453 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1454 if ((base != nullptr || min_c >= 0) && // reject certain OOB
1455 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1456 HBasicBlock* block = GetPreHeader(loop, bounds_check);
1457 HInstruction* min_lower = nullptr;
1458 HInstruction* min_upper = nullptr;
1459 HInstruction* max_lower = nullptr;
1460 HInstruction* max_upper = nullptr;
1461 // Iterate over all bounds checks.
1462 for (HBoundsCheck* other_bounds_check : candidates) {
1463 // Only handle if still in the graph. This avoids visiting the same
1464 // bounds check twice if it occurred multiple times in the use list.
1465 if (other_bounds_check->IsInBlock()) {
1466 HInstruction* other_index = other_bounds_check->InputAt(0);
1467 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1468 // Generate code for either the maximum or minimum. Range analysis already was queried
1469 // whether code generation on the original and, thus, related bounds check was possible.
1470 // It handles either loop invariants (lower is not set) or unit strides.
1471 if (other_c == max_c) {
Aart Bik16d3a652016-09-09 10:33:50 -07001472 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001473 other_bounds_check, other_index, GetGraph(), block, &max_lower, &max_upper);
1474 } else if (other_c == min_c && base != nullptr) {
Aart Bik16d3a652016-09-09 10:33:50 -07001475 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001476 other_bounds_check, other_index, GetGraph(), block, &min_lower, &min_upper);
1477 }
1478 ReplaceInstruction(other_bounds_check, other_index);
1479 }
1480 }
1481 // In code, using unsigned comparisons:
1482 // (1) constants only
1483 // if (max_upper >= a.length ) deoptimize;
1484 // (2) two symbolic invariants
1485 // if (min_upper > max_upper) deoptimize; unless min_c == max_c
1486 // if (max_upper >= a.length ) deoptimize;
1487 // (3) general case, unit strides (where lower would exceed upper for arithmetic wrap-around)
1488 // if (min_lower > max_lower) deoptimize; unless min_c == max_c
1489 // if (max_lower > max_upper) deoptimize;
1490 // if (max_upper >= a.length ) deoptimize;
1491 if (base == nullptr) {
1492 // Constants only.
1493 DCHECK_GE(min_c, 0);
1494 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1495 max_lower == nullptr && max_upper != nullptr);
1496 } else if (max_lower == nullptr) {
1497 // Two symbolic invariants.
1498 if (min_c != max_c) {
1499 DCHECK(min_lower == nullptr && min_upper != nullptr &&
1500 max_lower == nullptr && max_upper != nullptr);
1501 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(min_upper, max_upper));
1502 } else {
1503 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1504 max_lower == nullptr && max_upper != nullptr);
1505 }
1506 } else {
1507 // General case, unit strides.
1508 if (min_c != max_c) {
1509 DCHECK(min_lower != nullptr && min_upper != nullptr &&
1510 max_lower != nullptr && max_upper != nullptr);
1511 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(min_lower, max_lower));
1512 } else {
1513 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1514 max_lower != nullptr && max_upper != nullptr);
1515 }
1516 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(max_lower, max_upper));
1517 }
1518 InsertDeoptInLoop(
1519 loop, block, new (GetGraph()->GetArena()) HAboveOrEqual(max_upper, array_length));
1520 } else {
1521 // TODO: if rejected, avoid doing this again for subsequent instructions in this set?
1522 }
Aart Bik4a342772015-11-30 10:17:46 -08001523 }
1524
1525 /**
1526 * Returns true if heuristics indicate that dynamic bce may be profitable.
1527 */
1528 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1529 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001530 // The loop preheader of an irreducible loop does not dominate all the blocks in
1531 // the loop. We would need to find the common dominator of all blocks in the loop.
1532 if (loop->IsIrreducible()) {
1533 return false;
1534 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001535 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
1536 // code dominated by the deoptimization.
1537 if (GetGraph()->IsCompilingOsr()) {
1538 return false;
1539 }
Aart Bik4a342772015-11-30 10:17:46 -08001540 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001541 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001542 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1543 return false;
1544 }
1545 // Does loop have early-exits? If so, the full range may not be covered by the loop
1546 // at runtime and testing the range may apply deoptimization unnecessarily.
1547 if (IsEarlyExitLoop(loop)) {
1548 return false;
1549 }
1550 // Does the current basic block dominate all back edges? If not,
1551 // don't apply dynamic bce to something that may not be executed.
Anton Shaminf89381f2016-05-16 16:44:13 +06001552 return loop->DominatesAllBackEdges(block);
Aart Bik4a342772015-11-30 10:17:46 -08001553 }
1554 return false;
1555 }
1556
1557 /**
1558 * Returns true if the loop has early exits, which implies it may not cover
1559 * the full range computed by range analysis based on induction variables.
1560 */
1561 bool IsEarlyExitLoop(HLoopInformation* loop) {
1562 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1563 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1564 auto it = early_exit_loop_.find(loop_id);
1565 if (it != early_exit_loop_.end()) {
1566 return it->second;
1567 }
1568 // First time early-exit analysis for this loop. Since analysis requires scanning
1569 // the full loop-body, results of the analysis is stored for subsequent queries.
1570 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1571 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1572 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1573 if (!loop->Contains(*successor)) {
1574 early_exit_loop_.Put(loop_id, true);
1575 return true;
1576 }
1577 }
1578 }
1579 early_exit_loop_.Put(loop_id, false);
1580 return false;
1581 }
1582
1583 /**
1584 * Returns true if the array length is already loop invariant, or can be made so
1585 * by handling the null check under the hood of the array length operation.
1586 */
1587 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001588 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001589 return true;
1590 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1591 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001592 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001593 return true;
1594 }
1595 }
1596 return false;
1597 }
1598
1599 /**
1600 * Returns true if the null check is already loop invariant, or can be made so
1601 * by generating a deoptimization test.
1602 */
1603 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001604 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001605 return true;
1606 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1607 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001608 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001609 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001610 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1611 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001612 HInstruction* cond =
1613 new (GetGraph()->GetArena()) HEqual(array, GetGraph()->GetNullConstant());
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001614 InsertDeoptInLoop(loop, block, cond, /* is_null_check */ true);
Aart Bik4a342772015-11-30 10:17:46 -08001615 ReplaceInstruction(check, array);
1616 return true;
1617 }
1618 }
1619 return false;
1620 }
1621
1622 /**
1623 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1624 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1625 * the range analysis evaluation code by "overshooting" the computed range.
1626 * Since deoptimization would be a bad choice, and there is no other version
1627 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1628 * ensure the loop is finite.
1629 */
Aart Bik67def592016-07-14 17:19:43 -07001630 bool CanHandleInfiniteLoop(HLoopInformation* loop, HInstruction* index, bool needs_infinite_test) {
Aart Bik4a342772015-11-30 10:17:46 -08001631 if (needs_infinite_test) {
1632 // If we already forced the loop to be finite, allow directly.
1633 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1634 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1635 return true;
1636 }
1637 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1638 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1639 // ensure upper bound cannot cause an infinite loop.
1640 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1641 if (control->IsIf()) {
1642 HInstruction* if_expr = control->AsIf()->InputAt(0);
1643 if (if_expr->IsCondition()) {
1644 HCondition* condition = if_expr->AsCondition();
1645 if (index == condition->InputAt(0) ||
1646 index == condition->InputAt(1)) {
1647 finite_loop_.insert(loop_id);
1648 return true;
1649 }
1650 }
1651 }
1652 return false;
1653 }
1654 return true;
1655 }
1656
Aart Bik55b14df2016-01-12 14:12:47 -08001657 /**
1658 * Returns appropriate preheader for the loop, depending on whether the
1659 * instruction appears in the loop header or proper loop-body.
1660 */
1661 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1662 // Use preheader unless there is an earlier generated deoptimization block since
1663 // hoisted expressions may depend on and/or used by the deoptimization tests.
1664 HBasicBlock* header = loop->GetHeader();
1665 const uint32_t loop_id = header->GetBlockId();
1666 auto it = taken_test_loop_.find(loop_id);
1667 if (it != taken_test_loop_.end()) {
1668 HBasicBlock* block = it->second;
1669 // If always taken, keep it that way by returning the original preheader,
1670 // which can be found by following the predecessor of the true-block twice.
1671 if (instruction->GetBlock() == header) {
1672 return block->GetSinglePredecessor()->GetSinglePredecessor();
1673 }
1674 return block;
1675 }
1676 return loop->GetPreHeader();
1677 }
1678
Aart Bik1d239822016-02-09 14:26:34 -08001679 /** Inserts a deoptimization test in a loop preheader. */
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001680 void InsertDeoptInLoop(HLoopInformation* loop,
1681 HBasicBlock* block,
1682 HInstruction* condition,
1683 bool is_null_check = false) {
Aart Bik4a342772015-11-30 10:17:46 -08001684 HInstruction* suspend = loop->GetSuspendCheck();
1685 block->InsertInstructionBefore(condition, block->GetLastInstruction());
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001686 DeoptimizationKind kind =
1687 is_null_check ? DeoptimizationKind::kLoopNullBCE : DeoptimizationKind::kLoopBoundsBCE;
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001688 HDeoptimize* deoptimize = new (GetGraph()->GetArena()) HDeoptimize(
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001689 GetGraph()->GetArena(), condition, kind, suspend->GetDexPc());
Aart Bik4a342772015-11-30 10:17:46 -08001690 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1691 if (suspend->HasEnvironment()) {
1692 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1693 suspend->GetEnvironment(), loop->GetHeader());
1694 }
1695 }
1696
Aart Bik1d239822016-02-09 14:26:34 -08001697 /** Inserts a deoptimization test right before a bounds check. */
1698 void InsertDeoptInBlock(HBoundsCheck* bounds_check, HInstruction* condition) {
1699 HBasicBlock* block = bounds_check->GetBlock();
1700 block->InsertInstructionBefore(condition, bounds_check);
Nicolas Geoffray6f8e2c92017-03-23 14:37:26 +00001701 HDeoptimize* deoptimize = new (GetGraph()->GetArena()) HDeoptimize(
Nicolas Geoffray4e92c3c2017-05-08 09:34:26 +01001702 GetGraph()->GetArena(), condition, DeoptimizationKind::kBlockBCE, bounds_check->GetDexPc());
Aart Bik1d239822016-02-09 14:26:34 -08001703 block->InsertInstructionBefore(deoptimize, bounds_check);
1704 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
1705 }
1706
Aart Bik4a342772015-11-30 10:17:46 -08001707 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001708 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1709 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001710 DCHECK(!instruction->HasEnvironment());
1711 instruction->MoveBefore(block->GetLastInstruction());
1712 }
1713
1714 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001715 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001716 * The taken-test protects range analysis evaluation code to avoid any
1717 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1718 *
Aart Bik4a342772015-11-30 10:17:46 -08001719 * old_preheader
1720 * |
1721 * if_block <- taken-test protects deoptimization block
1722 * / \
1723 * true_block false_block <- deoptimizations/invariants are placed in true_block
1724 * \ /
1725 * new_preheader <- may require phi nodes to preserve SSA structure
1726 * |
1727 * header
1728 *
1729 * For example, this loop:
1730 *
1731 * for (int i = lower; i < upper; i++) {
1732 * array[i] = 0;
1733 * }
1734 *
1735 * will be transformed to:
1736 *
1737 * if (lower < upper) {
1738 * if (array == null) deoptimize;
1739 * array_length = array.length;
1740 * if (lower > upper) deoptimize; // unsigned
1741 * if (upper >= array_length) deoptimize; // unsigned
1742 * } else {
1743 * array_length = 0;
1744 * }
1745 * for (int i = lower; i < upper; i++) {
1746 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1747 * array[i] = 0;
1748 * }
1749 */
Aart Bik55b14df2016-01-12 14:12:47 -08001750 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1751 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001752 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001753 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1754 return;
Aart Bik4a342772015-11-30 10:17:46 -08001755 }
1756
1757 // Generate top test structure.
1758 HBasicBlock* header = loop->GetHeader();
1759 GetGraph()->TransformLoopHeaderForBCE(header);
1760 HBasicBlock* new_preheader = loop->GetPreHeader();
1761 HBasicBlock* if_block = new_preheader->GetDominator();
1762 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1763 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1764
1765 // Goto instructions.
1766 true_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1767 false_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1768 new_preheader->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1769
1770 // Insert the taken-test to see if the loop body is entered. If the
1771 // loop isn't entered at all, it jumps around the deoptimization block.
1772 if_block->AddInstruction(new (GetGraph()->GetArena()) HGoto()); // placeholder
Aart Bik16d3a652016-09-09 10:33:50 -07001773 HInstruction* condition = induction_range_.GenerateTakenTest(
1774 header->GetLastInstruction(), GetGraph(), if_block);
Aart Bik4a342772015-11-30 10:17:46 -08001775 DCHECK(condition != nullptr);
1776 if_block->RemoveInstruction(if_block->GetLastInstruction());
1777 if_block->AddInstruction(new (GetGraph()->GetArena()) HIf(condition));
1778
1779 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001780 }
1781
1782 /**
1783 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1784 * All uses of instructions in the deoptimization block that reach the loop need
1785 * a phi node in the new loop preheader to fix the dominance relation.
1786 *
1787 * Example:
1788 * if_block
1789 * / \
1790 * x_0 = .. false_block
1791 * \ /
1792 * x_1 = phi(x_0, null) <- synthetic phi
1793 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001794 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001795 */
1796 void InsertPhiNodes() {
1797 // Scan all new deoptimization blocks.
Vladimir Marko7d157fc2017-05-10 16:29:23 +01001798 for (const auto& entry : taken_test_loop_) {
1799 HBasicBlock* true_block = entry.second;
Aart Bik4a342772015-11-30 10:17:46 -08001800 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1801 // Scan all instructions in a new deoptimization block.
1802 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1803 HInstruction* instruction = it.Current();
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001804 DataType::Type type = instruction->GetType();
Aart Bik4a342772015-11-30 10:17:46 -08001805 HPhi* phi = nullptr;
1806 // Scan all uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001807 const HUseList<HInstruction*>& uses = instruction->GetUses();
1808 for (auto it2 = uses.begin(), end2 = uses.end(); it2 != end2; /* ++it2 below */) {
1809 HInstruction* user = it2->GetUser();
1810 size_t index = it2->GetIndex();
1811 // Increment `it2` now because `*it2` may disappear thanks to user->ReplaceInput().
1812 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001813 if (user->GetBlock() != true_block) {
1814 if (phi == nullptr) {
1815 phi = NewPhi(new_preheader, instruction, type);
1816 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001817 user->ReplaceInput(phi, index); // Removes the use node from the list.
Aart Bike22445f2017-05-03 14:29:20 -07001818 induction_range_.Replace(user, instruction, phi); // update induction
Aart Bik4a342772015-11-30 10:17:46 -08001819 }
1820 }
1821 // Scan all environment uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001822 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1823 for (auto it2 = env_uses.begin(), end2 = env_uses.end(); it2 != end2; /* ++it2 below */) {
1824 HEnvironment* user = it2->GetUser();
1825 size_t index = it2->GetIndex();
1826 // Increment `it2` now because `*it2` may disappear thanks to user->RemoveAsUserOfInput().
1827 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001828 if (user->GetHolder()->GetBlock() != true_block) {
1829 if (phi == nullptr) {
1830 phi = NewPhi(new_preheader, instruction, type);
1831 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001832 user->RemoveAsUserOfInput(index);
1833 user->SetRawEnvAt(index, phi);
1834 phi->AddEnvUseAt(user, index);
Aart Bik4a342772015-11-30 10:17:46 -08001835 }
1836 }
1837 }
1838 }
1839 }
1840
1841 /**
1842 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1843 * These are synthetic phi nodes without a virtual register.
1844 */
1845 HPhi* NewPhi(HBasicBlock* new_preheader,
1846 HInstruction* instruction,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001847 DataType::Type type) {
Aart Bik4a342772015-11-30 10:17:46 -08001848 HGraph* graph = GetGraph();
1849 HInstruction* zero;
1850 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001851 case DataType::Type::kReference: zero = graph->GetNullConstant(); break;
1852 case DataType::Type::kFloat32: zero = graph->GetFloatConstant(0); break;
1853 case DataType::Type::kFloat64: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001854 default: zero = graph->GetConstant(type, 0); break;
1855 }
1856 HPhi* phi = new (graph->GetArena())
1857 HPhi(graph->GetArena(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
1858 phi->SetRawInputAt(0, instruction);
1859 phi->SetRawInputAt(1, zero);
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001860 if (type == DataType::Type::kReference) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001861 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1862 }
Aart Bik4a342772015-11-30 10:17:46 -08001863 new_preheader->AddPhi(phi);
1864 return phi;
1865 }
1866
1867 /** Helper method to replace an instruction with another instruction. */
Aart Bik1e677482016-11-01 14:23:58 -07001868 void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1869 // Safe iteration.
1870 if (instruction == next_) {
1871 next_ = next_->GetNext();
1872 }
1873 // Replace and remove.
Aart Bik4a342772015-11-30 10:17:46 -08001874 instruction->ReplaceWith(replacement);
1875 instruction->GetBlock()->RemoveInstruction(instruction);
1876 }
1877
1878 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko5233f932015-09-29 19:01:15 +01001879 ArenaVector<ArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001880
Aart Bik1d239822016-02-09 14:26:34 -08001881 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction
1882 // in a block that checks an index against that HArrayLength.
1883 ArenaSafeMap<int, HBoundsCheck*> first_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001884
Aart Bik4a342772015-11-30 10:17:46 -08001885 // Early-exit loop bookkeeping.
1886 ArenaSafeMap<uint32_t, bool> early_exit_loop_;
1887
1888 // Taken-test loop bookkeeping.
1889 ArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
1890
1891 // Finite loop bookkeeping.
1892 ArenaSet<uint32_t> finite_loop_;
1893
Aart Bik1d239822016-02-09 14:26:34 -08001894 // Flag that denotes whether dominator-based dynamic elimination has occurred.
1895 bool has_dom_based_dynamic_bce_;
Aart Bik4a342772015-11-30 10:17:46 -08001896
Mingyao Yang3584bce2015-05-19 16:01:59 -07001897 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001898 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001899
Aart Bik4a342772015-11-30 10:17:46 -08001900 // Side effects.
1901 const SideEffectsAnalysis& side_effects_;
1902
Aart Bik22af3be2015-09-10 12:50:58 -07001903 // Range analysis based on induction variables.
1904 InductionVarRange induction_range_;
1905
Aart Bik1e677482016-11-01 14:23:58 -07001906 // Safe iteration.
1907 HInstruction* next_;
1908
Mingyao Yangf384f882014-10-22 16:08:18 -07001909 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1910};
1911
1912void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001913 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001914 return;
1915 }
1916
Mingyao Yangf384f882014-10-22 16:08:18 -07001917 // Reverse post order guarantees a node's dominators are visited first.
1918 // We want to visit in the dominator-based order since if a value is known to
1919 // be bounded by a range at one instruction, it must be true that all uses of
1920 // that value dominated by that instruction fits in that range. Range of that
1921 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001922 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001923 for (size_t i = 0, size = graph_->GetReversePostOrder().size(); i != size; ++i) {
1924 HBasicBlock* current = graph_->GetReversePostOrder()[i];
Mingyao Yang3584bce2015-05-19 16:01:59 -07001925 if (visitor.IsAddedBlock(current)) {
1926 // Skip added blocks. Their effects are already taken care of.
1927 continue;
1928 }
1929 visitor.VisitBasicBlock(current);
Aart Bikb6347b72016-02-29 13:56:44 -08001930 // Skip forward to the current block in case new basic blocks were inserted
1931 // (which always appear earlier in reverse post order) to avoid visiting the
1932 // same basic block twice.
Vladimir Marko2c45bc92016-10-25 16:54:12 +01001933 size_t new_size = graph_->GetReversePostOrder().size();
1934 DCHECK_GE(new_size, size);
1935 i += new_size - size;
1936 DCHECK_EQ(current, graph_->GetReversePostOrder()[i]);
1937 size = new_size;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001938 }
Aart Bik4a342772015-11-30 10:17:46 -08001939
1940 // Perform cleanup.
1941 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001942}
1943
1944} // namespace art