blob: 994d394a2a3f87a9665983b789fd5d7ff46a14ac [file] [log] [blame]
Mingyao Yangf384f882014-10-22 16:08:18 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "bounds_check_elimination.h"
Aart Bikaab5b752015-09-23 11:18:57 -070018
19#include <limits>
20
21#include "base/arena_containers.h"
Aart Bik22af3be2015-09-10 12:50:58 -070022#include "induction_var_range.h"
Aart Bik4a342772015-11-30 10:17:46 -080023#include "side_effects_analysis.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070024#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070025
26namespace art {
27
28class MonotonicValueRange;
29
30/**
31 * A value bound is represented as a pair of value and constant,
32 * e.g. array.length - 1.
33 */
34class ValueBound : public ValueObject {
35 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080036 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080037 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080038 // Normalize ValueBound with constant instruction.
39 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080040 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080041 instruction_ = nullptr;
42 constant_ = instr_const + constant;
43 return;
44 }
Mingyao Yangf384f882014-10-22 16:08:18 -070045 }
Mingyao Yang64197522014-12-05 15:56:23 -080046 instruction_ = instruction;
47 constant_ = constant;
48 }
49
Mingyao Yang8c8bad82015-02-09 18:13:26 -080050 // Return whether (left + right) overflows or underflows.
51 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
52 if (right == 0) {
53 return false;
54 }
Aart Bikaab5b752015-09-23 11:18:57 -070055 if ((right > 0) && (left <= (std::numeric_limits<int32_t>::max() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080056 // No overflow.
57 return false;
58 }
Aart Bikaab5b752015-09-23 11:18:57 -070059 if ((right < 0) && (left >= (std::numeric_limits<int32_t>::min() - right))) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -080060 // No underflow.
61 return false;
62 }
63 return true;
64 }
65
Aart Bik1d239822016-02-09 14:26:34 -080066 // Return true if instruction can be expressed as "left_instruction + right_constant".
Mingyao Yang0304e182015-01-30 16:41:29 -080067 static bool IsAddOrSubAConstant(HInstruction* instruction,
Aart Bik1d239822016-02-09 14:26:34 -080068 /* out */ HInstruction** left_instruction,
69 /* out */ int32_t* right_constant) {
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
Aart Bik22af3be2015-09-10 12:50:58 -0700156 /*
157 * Hunt "under the hood" of array lengths (leading to array references),
158 * null checks (also leading to array references), and new arrays
159 * (leading to the actual length). This makes it more likely related
160 * instructions become actually comparable.
161 */
162 static HInstruction* HuntForDeclaration(HInstruction* instruction) {
163 while (instruction->IsArrayLength() ||
164 instruction->IsNullCheck() ||
165 instruction->IsNewArray()) {
166 instruction = instruction->InputAt(0);
Mingyao Yang0304e182015-01-30 16:41:29 -0800167 }
168 return instruction;
169 }
170
171 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
172 if (instruction1 == instruction2) {
173 return true;
174 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800175 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700176 return false;
177 }
Aart Bik22af3be2015-09-10 12:50:58 -0700178 instruction1 = HuntForDeclaration(instruction1);
179 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800180 return instruction1 == instruction2;
181 }
182
183 // Returns if it's certain this->bound >= `bound`.
184 bool GreaterThanOrEqualTo(ValueBound bound) const {
185 if (Equal(instruction_, bound.instruction_)) {
186 return constant_ >= bound.constant_;
187 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700188 // Not comparable. Just return false.
189 return false;
190 }
191
Mingyao Yang0304e182015-01-30 16:41:29 -0800192 // Returns if it's certain this->bound <= `bound`.
193 bool LessThanOrEqualTo(ValueBound bound) const {
194 if (Equal(instruction_, bound.instruction_)) {
195 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700196 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700197 // Not comparable. Just return false.
198 return false;
199 }
200
Aart Bik4a342772015-11-30 10:17:46 -0800201 // Returns if it's certain this->bound > `bound`.
202 bool GreaterThan(ValueBound bound) const {
203 if (Equal(instruction_, bound.instruction_)) {
204 return constant_ > bound.constant_;
205 }
206 // Not comparable. Just return false.
207 return false;
208 }
209
210 // Returns if it's certain this->bound < `bound`.
211 bool LessThan(ValueBound bound) const {
212 if (Equal(instruction_, bound.instruction_)) {
213 return constant_ < bound.constant_;
214 }
215 // Not comparable. Just return false.
216 return false;
217 }
218
Mingyao Yangf384f882014-10-22 16:08:18 -0700219 // Try to narrow lower bound. Returns the greatest of the two if possible.
220 // Pick one if they are not comparable.
221 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800222 if (bound1.GreaterThanOrEqualTo(bound2)) {
223 return bound1;
224 }
225 if (bound2.GreaterThanOrEqualTo(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 constant as lower bound.
231 return bound1.IsConstant() ? bound1 : bound2;
232 }
233
234 // Try to narrow upper bound. Returns the lowest of the two if possible.
235 // Pick one if they are not comparable.
236 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800237 if (bound1.LessThanOrEqualTo(bound2)) {
238 return bound1;
239 }
240 if (bound2.LessThanOrEqualTo(bound1)) {
241 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700242 }
243
244 // Not comparable. Just pick one. We may lose some info, but that's ok.
245 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800246 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700247 }
248
Mingyao Yang0304e182015-01-30 16:41:29 -0800249 // Add a constant to a ValueBound.
250 // `overflow` or `underflow` will return whether the resulting bound may
251 // overflow or underflow an int.
Aart Bik1d239822016-02-09 14:26:34 -0800252 ValueBound Add(int32_t c, /* out */ bool* overflow, /* out */ bool* underflow) const {
Mingyao Yang0304e182015-01-30 16:41:29 -0800253 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700254 if (c == 0) {
255 return *this;
256 }
257
Mingyao Yang0304e182015-01-30 16:41:29 -0800258 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700259 if (c > 0) {
Aart Bikaab5b752015-09-23 11:18:57 -0700260 if (constant_ > (std::numeric_limits<int32_t>::max() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800261 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800262 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700263 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800264
265 new_constant = constant_ + c;
266 // (array.length + non-positive-constant) won't overflow an int.
267 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
268 return ValueBound(instruction_, new_constant);
269 }
270 // Be conservative.
271 *overflow = true;
272 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700273 } else {
Aart Bikaab5b752015-09-23 11:18:57 -0700274 if (constant_ < (std::numeric_limits<int32_t>::min() - c)) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800275 *underflow = true;
276 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700277 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800278
279 new_constant = constant_ + c;
280 // Regardless of the value new_constant, (array.length+new_constant) will
281 // never underflow since array.length is no less than 0.
282 if (IsConstant() || IsRelatedToArrayLength()) {
283 return ValueBound(instruction_, new_constant);
284 }
285 // Be conservative.
286 *underflow = true;
287 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700288 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700289 }
290
291 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700292 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800293 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700294};
295
296/**
297 * Represent a range of lower bound and upper bound, both being inclusive.
298 * Currently a ValueRange may be generated as a result of the following:
299 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800300 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700301 * incrementing/decrementing array index (MonotonicValueRange).
302 */
Vladimir Marko5233f932015-09-29 19:01:15 +0100303class ValueRange : public ArenaObject<kArenaAllocBoundsCheckElimination> {
Mingyao Yangf384f882014-10-22 16:08:18 -0700304 public:
305 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
306 : allocator_(allocator), lower_(lower), upper_(upper) {}
307
308 virtual ~ValueRange() {}
309
Mingyao Yang57e04752015-02-09 18:13:26 -0800310 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
311 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700312 return AsMonotonicValueRange() != nullptr;
313 }
314
315 ArenaAllocator* GetAllocator() const { return allocator_; }
316 ValueBound GetLower() const { return lower_; }
317 ValueBound GetUpper() const { return upper_; }
318
Mingyao Yang3584bce2015-05-19 16:01:59 -0700319 bool IsConstantValueRange() { return lower_.IsConstant() && upper_.IsConstant(); }
320
Mingyao Yangf384f882014-10-22 16:08:18 -0700321 // If it's certain that this value range fits in other_range.
322 virtual bool FitsIn(ValueRange* other_range) const {
323 if (other_range == nullptr) {
324 return true;
325 }
326 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800327 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
328 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700329 }
330
331 // Returns the intersection of this and range.
332 // If it's not possible to do intersection because some
333 // bounds are not comparable, it's ok to pick either bound.
334 virtual ValueRange* Narrow(ValueRange* range) {
335 if (range == nullptr) {
336 return this;
337 }
338
339 if (range->IsMonotonicValueRange()) {
340 return this;
341 }
342
343 return new (allocator_) ValueRange(
344 allocator_,
345 ValueBound::NarrowLowerBound(lower_, range->lower_),
346 ValueBound::NarrowUpperBound(upper_, range->upper_));
347 }
348
Mingyao Yang0304e182015-01-30 16:41:29 -0800349 // Shift a range by a constant.
350 ValueRange* Add(int32_t constant) const {
351 bool overflow, underflow;
352 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
353 if (underflow) {
354 // Lower bound underflow will wrap around to positive values
355 // and invalidate the upper bound.
356 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700357 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800358 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
359 if (overflow) {
360 // Upper bound overflow will wrap around to negative values
361 // and invalidate the lower bound.
362 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700363 }
364 return new (allocator_) ValueRange(allocator_, lower, upper);
365 }
366
Mingyao Yangf384f882014-10-22 16:08:18 -0700367 private:
368 ArenaAllocator* const allocator_;
369 const ValueBound lower_; // inclusive
370 const ValueBound upper_; // inclusive
371
372 DISALLOW_COPY_AND_ASSIGN(ValueRange);
373};
374
375/**
376 * A monotonically incrementing/decrementing value range, e.g.
377 * the variable i in "for (int i=0; i<array.length; i++)".
378 * Special care needs to be taken to account for overflow/underflow
379 * of such value ranges.
380 */
381class MonotonicValueRange : public ValueRange {
382 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800383 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700384 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800385 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800386 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800387 ValueBound bound)
Aart Bikaab5b752015-09-23 11:18:57 -0700388 // To be conservative, give it full range [Min(), Max()] in case it's
Mingyao Yang64197522014-12-05 15:56:23 -0800389 // used as a regular value range, due to possible overflow/underflow.
390 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700391 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800392 initial_(initial),
393 increment_(increment),
394 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700395
396 virtual ~MonotonicValueRange() {}
397
Mingyao Yang57e04752015-02-09 18:13:26 -0800398 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800399 ValueBound GetBound() const { return bound_; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700400 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700401 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
402 return induction_variable_->GetBlock();
403 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800404
405 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700406
407 // If it's certain that this value range fits in other_range.
408 bool FitsIn(ValueRange* other_range) const OVERRIDE {
409 if (other_range == nullptr) {
410 return true;
411 }
412 DCHECK(!other_range->IsMonotonicValueRange());
413 return false;
414 }
415
416 // Try to narrow this MonotonicValueRange given another range.
417 // Ideally it will return a normal ValueRange. But due to
418 // possible overflow/underflow, that may not be possible.
419 ValueRange* Narrow(ValueRange* range) OVERRIDE {
420 if (range == nullptr) {
421 return this;
422 }
423 DCHECK(!range->IsMonotonicValueRange());
424
425 if (increment_ > 0) {
426 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800427 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Aart Bikaab5b752015-09-23 11:18:57 -0700428 if (!lower.IsConstant() || lower.GetConstant() == std::numeric_limits<int32_t>::min()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700429 // Lower bound isn't useful. Leave it to deoptimization.
430 return this;
431 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700432
Aart Bikaab5b752015-09-23 11:18:57 -0700433 // We currently conservatively assume max array length is Max().
434 // 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 -0700435 // divided by the element size (such as 4 bytes for each integer array), we can
436 // lower this number and rule out some possible overflows.
Aart Bikaab5b752015-09-23 11:18:57 -0700437 int32_t max_array_len = std::numeric_limits<int32_t>::max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700438
Mingyao Yang0304e182015-01-30 16:41:29 -0800439 // max possible integer value of range's upper value.
Aart Bikaab5b752015-09-23 11:18:57 -0700440 int32_t upper = std::numeric_limits<int32_t>::max();
Mingyao Yang0304e182015-01-30 16:41:29 -0800441 // Try to lower upper.
442 ValueBound upper_bound = range->GetUpper();
443 if (upper_bound.IsConstant()) {
444 upper = upper_bound.GetConstant();
445 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
446 // Normal case. e.g. <= array.length - 1.
447 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700448 }
449
450 // If we can prove for the last number in sequence of initial_,
451 // initial_ + increment_, initial_ + 2 x increment_, ...
452 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
453 // then this MonoticValueRange is narrowed to a normal value range.
454
455 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800456 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700457 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800458 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700459 if (upper <= initial_constant) {
460 last_num_in_sequence = upper;
461 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800462 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700463 last_num_in_sequence = initial_constant +
464 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
465 }
466 }
Aart Bikaab5b752015-09-23 11:18:57 -0700467 if (last_num_in_sequence <= (std::numeric_limits<int32_t>::max() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700468 // No overflow. The sequence will be stopped by the upper bound test as expected.
469 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
470 }
471
472 // There might be overflow. Give up narrowing.
473 return this;
474 } else {
475 DCHECK_NE(increment_, 0);
476 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800477 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Aart Bikaab5b752015-09-23 11:18:57 -0700478 if ((!upper.IsConstant() || upper.GetConstant() == std::numeric_limits<int32_t>::max()) &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700479 !upper.IsRelatedToArrayLength()) {
480 // Upper bound isn't useful. Leave it to deoptimization.
481 return this;
482 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700483
484 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800485 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700486 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800487 int32_t constant = range->GetLower().GetConstant();
Aart Bikaab5b752015-09-23 11:18:57 -0700488 if (constant >= (std::numeric_limits<int32_t>::min() - increment_)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700489 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
490 }
491 }
492
Mingyao Yang0304e182015-01-30 16:41:29 -0800493 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700494 return this;
495 }
496 }
497
498 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700499 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
500 HInstruction* const initial_; // Initial value.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700501 const int32_t increment_; // Increment for each loop iteration.
502 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700503
504 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
505};
506
507class BCEVisitor : public HGraphVisitor {
508 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700509 // The least number of bounds checks that should be eliminated by triggering
510 // the deoptimization technique.
511 static constexpr size_t kThresholdForAddingDeoptimize = 2;
512
Aart Bik1d239822016-02-09 14:26:34 -0800513 // Very large lengths are considered an anomaly. This is a threshold beyond which we don't
514 // bother to apply the deoptimization technique since it's likely, or sometimes certain,
515 // an AIOOBE will be thrown.
516 static constexpr uint32_t kMaxLengthForAddingDeoptimize =
Aart Bikaab5b752015-09-23 11:18:57 -0700517 std::numeric_limits<int32_t>::max() - 1024 * 1024;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700518
Mingyao Yang3584bce2015-05-19 16:01:59 -0700519 // Added blocks for loop body entry test.
520 bool IsAddedBlock(HBasicBlock* block) const {
521 return block->GetBlockId() >= initial_block_size_;
522 }
523
Aart Bik4a342772015-11-30 10:17:46 -0800524 BCEVisitor(HGraph* graph,
525 const SideEffectsAnalysis& side_effects,
526 HInductionVarAnalysis* induction_analysis)
Aart Bik22af3be2015-09-10 12:50:58 -0700527 : HGraphVisitor(graph),
Vladimir Marko5233f932015-09-29 19:01:15 +0100528 maps_(graph->GetBlocks().size(),
529 ArenaSafeMap<int, ValueRange*>(
530 std::less<int>(),
531 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
532 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800533 first_index_bounds_check_map_(
Vladimir Marko5233f932015-09-29 19:01:15 +0100534 std::less<int>(),
535 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik4a342772015-11-30 10:17:46 -0800536 early_exit_loop_(
537 std::less<uint32_t>(),
538 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
539 taken_test_loop_(
540 std::less<uint32_t>(),
541 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
542 finite_loop_(graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800543 has_dom_based_dynamic_bce_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100544 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800545 side_effects_(side_effects),
Aart Bik22af3be2015-09-10 12:50:58 -0700546 induction_range_(induction_analysis) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700547
548 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700549 DCHECK(!IsAddedBlock(block));
Aart Bik1d239822016-02-09 14:26:34 -0800550 first_index_bounds_check_map_.clear();
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700551 HGraphVisitor::VisitBasicBlock(block);
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) {
599 GetValueRangeMap(basic_block)->Overwrite(instruction->GetId(), range);
600 }
601
Mingyao Yang0304e182015-01-30 16:41:29 -0800602 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
603 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700604 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800605 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700606 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800607 if (existing_range == nullptr) {
608 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800609 AssignRange(successor, instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800610 }
611 return;
612 }
613 if (existing_range->IsMonotonicValueRange()) {
614 DCHECK(instruction->IsLoopHeaderPhi());
615 // Make sure the comparison is in the loop header so each increment is
616 // checked with a comparison.
617 if (instruction->GetBlock() != basic_block) {
618 return;
619 }
620 }
Aart Bik1d239822016-02-09 14:26:34 -0800621 AssignRange(successor, instruction, existing_range->Narrow(range));
Mingyao Yangf384f882014-10-22 16:08:18 -0700622 }
623
Mingyao Yang57e04752015-02-09 18:13:26 -0800624 // Special case that we may simultaneously narrow two MonotonicValueRange's to
625 // regular value ranges.
626 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
627 HInstruction* left,
628 HInstruction* right,
629 IfCondition cond,
630 MonotonicValueRange* left_range,
631 MonotonicValueRange* right_range) {
632 DCHECK(left->IsLoopHeaderPhi());
633 DCHECK(right->IsLoopHeaderPhi());
634 if (instruction->GetBlock() != left->GetBlock()) {
635 // Comparison needs to be in loop header to make sure it's done after each
636 // increment/decrement.
637 return;
638 }
639
640 // Handle common cases which also don't have overflow/underflow concerns.
641 if (left_range->GetIncrement() == 1 &&
642 left_range->GetBound().IsConstant() &&
643 right_range->GetIncrement() == -1 &&
644 right_range->GetBound().IsRelatedToArrayLength() &&
645 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800646 HBasicBlock* successor = nullptr;
647 int32_t left_compensation = 0;
648 int32_t right_compensation = 0;
649 if (cond == kCondLT) {
650 left_compensation = -1;
651 right_compensation = 1;
652 successor = instruction->IfTrueSuccessor();
653 } else if (cond == kCondLE) {
654 successor = instruction->IfTrueSuccessor();
655 } else if (cond == kCondGT) {
656 successor = instruction->IfFalseSuccessor();
657 } else if (cond == kCondGE) {
658 left_compensation = -1;
659 right_compensation = 1;
660 successor = instruction->IfFalseSuccessor();
661 } else {
662 // We don't handle '=='/'!=' test in case left and right can cross and
663 // miss each other.
664 return;
665 }
666
667 if (successor != nullptr) {
668 bool overflow;
669 bool underflow;
670 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
671 GetGraph()->GetArena(),
672 left_range->GetBound(),
673 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
674 if (!overflow && !underflow) {
675 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
676 new_left_range);
677 }
678
679 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
680 GetGraph()->GetArena(),
681 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
682 right_range->GetBound());
683 if (!overflow && !underflow) {
684 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
685 new_right_range);
686 }
687 }
688 }
689 }
690
Mingyao Yangf384f882014-10-22 16:08:18 -0700691 // Handle "if (left cmp_cond right)".
692 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
693 HBasicBlock* block = instruction->GetBlock();
694
695 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
696 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000697 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700698
699 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
700 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000701 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700702
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700703 ValueRange* left_range = LookupValueRange(left, block);
704 MonotonicValueRange* left_monotonic_range = nullptr;
705 if (left_range != nullptr) {
706 left_monotonic_range = left_range->AsMonotonicValueRange();
707 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700708 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700709 if (instruction->GetBlock() != loop_head) {
710 // For monotonic value range, don't handle `instruction`
711 // if it's not defined in the loop header.
712 return;
713 }
714 }
715 }
716
Mingyao Yang64197522014-12-05 15:56:23 -0800717 bool found;
718 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800719 // Each comparison can establish a lower bound and an upper bound
720 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700721 ValueBound lower = bound;
722 ValueBound upper = bound;
723 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800724 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700725 // 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 -0800726 ValueRange* right_range = LookupValueRange(right, block);
727 if (right_range != nullptr) {
728 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800729 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
730 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
731 left_range->AsMonotonicValueRange(),
732 right_range->AsMonotonicValueRange());
733 return;
734 }
735 }
736 lower = right_range->GetLower();
737 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700738 } else {
739 lower = ValueBound::Min();
740 upper = ValueBound::Max();
741 }
742 }
743
Mingyao Yang0304e182015-01-30 16:41:29 -0800744 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700745 if (cond == kCondLT || cond == kCondLE) {
746 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800747 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
748 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
749 if (overflow || underflow) {
750 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800751 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700752 ValueRange* new_range = new (GetGraph()->GetArena())
753 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
754 ApplyRangeFromComparison(left, block, true_successor, new_range);
755 }
756
757 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800758 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
759 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
760 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
761 if (overflow || underflow) {
762 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800763 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700764 ValueRange* new_range = new (GetGraph()->GetArena())
765 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
766 ApplyRangeFromComparison(left, block, false_successor, new_range);
767 }
768 } else if (cond == kCondGT || cond == kCondGE) {
769 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800770 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
771 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
772 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
773 if (overflow || underflow) {
774 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800775 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700776 ValueRange* new_range = new (GetGraph()->GetArena())
777 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
778 ApplyRangeFromComparison(left, block, true_successor, new_range);
779 }
780
781 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800782 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
783 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
784 if (overflow || underflow) {
785 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800786 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700787 ValueRange* new_range = new (GetGraph()->GetArena())
788 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
789 ApplyRangeFromComparison(left, block, false_successor, new_range);
790 }
Aart Bika2106892016-05-04 14:00:55 -0700791 } else if (cond == kCondNE || cond == kCondEQ) {
792 if (left->IsArrayLength() && lower.IsConstant() && upper.IsConstant()) {
793 // Special case:
794 // length == [c,d] yields [c, d] along true
795 // length != [c,d] yields [c, d] along false
796 if (!lower.Equals(ValueBound::Min()) || !upper.Equals(ValueBound::Max())) {
797 ValueRange* new_range = new (GetGraph()->GetArena())
798 ValueRange(GetGraph()->GetArena(), lower, upper);
799 ApplyRangeFromComparison(
800 left, block, cond == kCondEQ ? true_successor : false_successor, new_range);
801 }
802 // In addition:
803 // length == 0 yields [1, max] along false
804 // length != 0 yields [1, max] along true
805 if (lower.GetConstant() == 0 && upper.GetConstant() == 0) {
806 ValueRange* new_range = new (GetGraph()->GetArena())
807 ValueRange(GetGraph()->GetArena(), ValueBound(nullptr, 1), ValueBound::Max());
808 ApplyRangeFromComparison(
809 left, block, cond == kCondEQ ? false_successor : true_successor, new_range);
810 }
811 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700812 }
813 }
814
Aart Bik4a342772015-11-30 10:17:46 -0800815 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700816 HBasicBlock* block = bounds_check->GetBlock();
817 HInstruction* index = bounds_check->InputAt(0);
818 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700819 DCHECK(array_length->IsIntConstant() ||
820 array_length->IsArrayLength() ||
821 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800822 bool try_dynamic_bce = true;
Aart Bik1d239822016-02-09 14:26:34 -0800823 // Analyze index range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800824 if (!index->IsIntConstant()) {
Aart Bik1d239822016-02-09 14:26:34 -0800825 // Non-constant index.
Aart Bik22af3be2015-09-10 12:50:58 -0700826 ValueBound lower = ValueBound(nullptr, 0); // constant 0
827 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
828 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800829 // Try index range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800830 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700831 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800832 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700833 return;
834 }
Aart Bik1d239822016-02-09 14:26:34 -0800835 // Try index range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800836 // Disables dynamic bce if OOB is certain.
Aart Bik52be7e72016-06-23 11:20:41 -0700837 if (InductionRangeFitsIn(&array_range, bounds_check, &try_dynamic_bce)) {
Aart Bik4a342772015-11-30 10:17:46 -0800838 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700839 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700840 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800841 } else {
Aart Bik1d239822016-02-09 14:26:34 -0800842 // Constant index.
Mingyao Yang0304e182015-01-30 16:41:29 -0800843 int32_t constant = index->AsIntConstant()->GetValue();
844 if (constant < 0) {
845 // Will always throw exception.
846 return;
Aart Bik1d239822016-02-09 14:26:34 -0800847 } else if (array_length->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800848 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800849 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800850 }
851 return;
852 }
Aart Bik1d239822016-02-09 14:26:34 -0800853 // Analyze array length range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800854 DCHECK(array_length->IsArrayLength());
855 ValueRange* existing_range = LookupValueRange(array_length, block);
856 if (existing_range != nullptr) {
857 ValueBound lower = existing_range->GetLower();
858 DCHECK(lower.IsConstant());
859 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800860 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800861 return;
862 } else {
863 // Existing range isn't strong enough to eliminate the bounds check.
864 // Fall through to update the array_length range with info from this
865 // bounds check.
866 }
867 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700868 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800869 // We currently don't do it for non-constant index since a valid array[i] can't prove
870 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700871 if (constant == std::numeric_limits<int32_t>::max()) {
872 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700873 return;
Aart Bik1d239822016-02-09 14:26:34 -0800874 } else {
875 ValueBound lower = ValueBound(nullptr, constant + 1);
876 ValueBound upper = ValueBound::Max();
877 ValueRange* range = new (GetGraph()->GetArena())
878 ValueRange(GetGraph()->GetArena(), lower, upper);
879 AssignRange(block, array_length, range);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700880 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700881 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700882
Aart Bik4a342772015-11-30 10:17:46 -0800883 // If static analysis fails, and OOB is not certain, try dynamic elimination.
884 if (try_dynamic_bce) {
Aart Bik1d239822016-02-09 14:26:34 -0800885 // Try loop-based dynamic elimination.
Aart Bik67def592016-07-14 17:19:43 -0700886 HLoopInformation* loop = bounds_check->GetBlock()->GetLoopInformation();
887 bool needs_finite_test = false;
888 bool needs_taken_test = false;
889 if (DynamicBCESeemsProfitable(loop, bounds_check->GetBlock()) &&
Aart Bik16d3a652016-09-09 10:33:50 -0700890 induction_range_.CanGenerateRange(
Aart Bik67def592016-07-14 17:19:43 -0700891 bounds_check, index, &needs_finite_test, &needs_taken_test) &&
892 CanHandleInfiniteLoop(loop, index, needs_finite_test) &&
893 // Do this test last, since it may generate code.
894 CanHandleLength(loop, array_length, needs_taken_test)) {
895 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
896 TransformLoopForDynamicBCE(loop, bounds_check);
Aart Bik1d239822016-02-09 14:26:34 -0800897 return;
898 }
Aart Bik67def592016-07-14 17:19:43 -0700899 // Otherwise, prepare dominator-based dynamic elimination.
Aart Bik1d239822016-02-09 14:26:34 -0800900 if (first_index_bounds_check_map_.find(array_length->GetId()) ==
901 first_index_bounds_check_map_.end()) {
902 // Remember the first bounds check against each array_length. That bounds check
903 // instruction has an associated HEnvironment where we may add an HDeoptimize
904 // to eliminate subsequent bounds checks against the same array_length.
905 first_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
906 }
Aart Bik4a342772015-11-30 10:17:46 -0800907 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700908 }
909
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100910 static bool HasSameInputAtBackEdges(HPhi* phi) {
911 DCHECK(phi->IsLoopHeaderPhi());
Vladimir Markoe9004912016-06-16 16:50:52 +0100912 HConstInputsRef inputs = phi->GetInputs();
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100913 // Start with input 1. Input 0 is from the incoming block.
Vladimir Markoe9004912016-06-16 16:50:52 +0100914 const HInstruction* input1 = inputs[1];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100915 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100916 *phi->GetBlock()->GetPredecessors()[1]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100917 for (size_t i = 2; i < inputs.size(); ++i) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100918 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100919 *phi->GetBlock()->GetPredecessors()[i]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100920 if (input1 != inputs[i]) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100921 return false;
922 }
923 }
924 return true;
925 }
926
Aart Bik4a342772015-11-30 10:17:46 -0800927 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100928 if (phi->IsLoopHeaderPhi()
929 && (phi->GetType() == Primitive::kPrimInt)
930 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700931 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800932 HInstruction *left;
933 int32_t increment;
934 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
935 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700936 HInstruction* initial_value = phi->InputAt(0);
937 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800938 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700939 // Add constant 0. It's really a fixed value.
940 range = new (GetGraph()->GetArena()) ValueRange(
941 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800942 ValueBound(initial_value, 0),
943 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700944 } else {
945 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800946 bool found;
947 ValueBound bound = ValueBound::DetectValueBoundFromValue(
948 initial_value, &found);
949 if (!found) {
950 // No constant or array.length+c bound found.
951 // For i=j, we can still use j's upper bound as i's upper bound.
952 // Same for lower.
953 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
954 if (initial_range != nullptr) {
955 bound = increment > 0 ? initial_range->GetLower() :
956 initial_range->GetUpper();
957 } else {
958 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
959 }
960 }
961 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700962 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700963 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700964 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800965 increment,
966 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700967 }
Aart Bik1d239822016-02-09 14:26:34 -0800968 AssignRange(phi->GetBlock(), phi, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700969 }
970 }
971 }
972 }
973
Aart Bik4a342772015-11-30 10:17:46 -0800974 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700975 if (instruction->InputAt(0)->IsCondition()) {
976 HCondition* cond = instruction->InputAt(0)->AsCondition();
Aart Bika2106892016-05-04 14:00:55 -0700977 HandleIf(instruction, cond->GetLeft(), cond->GetRight(), cond->GetCondition());
Mingyao Yangf384f882014-10-22 16:08:18 -0700978 }
979 }
980
Aart Bik4a342772015-11-30 10:17:46 -0800981 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700982 HInstruction* right = add->GetRight();
983 if (right->IsIntConstant()) {
984 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
985 if (left_range == nullptr) {
986 return;
987 }
988 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
989 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800990 AssignRange(add->GetBlock(), add, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700991 }
992 }
993 }
994
Aart Bik4a342772015-11-30 10:17:46 -0800995 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700996 HInstruction* left = sub->GetLeft();
997 HInstruction* right = sub->GetRight();
998 if (right->IsIntConstant()) {
999 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1000 if (left_range == nullptr) {
1001 return;
1002 }
1003 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1004 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001005 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001006 return;
1007 }
1008 }
1009
1010 // Here we are interested in the typical triangular case of nested loops,
1011 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1012 // 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 -08001013
1014 // Try to handle (array.length - i) or (array.length + c - i) format.
1015 HInstruction* left_of_left; // left input of left.
1016 int32_t right_const = 0;
1017 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1018 left = left_of_left;
1019 }
1020 // The value of left input of the sub equals (left + right_const).
1021
Mingyao Yangf384f882014-10-22 16:08:18 -07001022 if (left->IsArrayLength()) {
1023 HInstruction* array_length = left->AsArrayLength();
1024 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1025 if (right_range != nullptr) {
1026 ValueBound lower = right_range->GetLower();
1027 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001028 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001029 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001030 // Make sure it's the same array.
1031 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001032 int32_t c0 = right_const;
1033 int32_t c1 = lower.GetConstant();
1034 int32_t c2 = upper.GetConstant();
1035 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1036 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1037 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1038 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1039 if ((c0 - c1) <= 0) {
1040 // array.length + (c0 - c1) won't overflow/underflow.
1041 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1042 GetGraph()->GetArena(),
1043 ValueBound(nullptr, right_const - upper.GetConstant()),
1044 ValueBound(array_length, right_const - lower.GetConstant()));
Aart Bik1d239822016-02-09 14:26:34 -08001045 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001046 }
1047 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001048 }
1049 }
1050 }
1051 }
1052 }
1053
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001054 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1055 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1056 HInstruction* right = instruction->GetRight();
1057 int32_t right_const;
1058 if (right->IsIntConstant()) {
1059 right_const = right->AsIntConstant()->GetValue();
1060 // Detect division by two or more.
1061 if ((instruction->IsDiv() && right_const <= 1) ||
1062 (instruction->IsShr() && right_const < 1) ||
1063 (instruction->IsUShr() && right_const < 1)) {
1064 return;
1065 }
1066 } else {
1067 return;
1068 }
1069
1070 // Try to handle array.length/2 or (array.length-1)/2 format.
1071 HInstruction* left = instruction->GetLeft();
1072 HInstruction* left_of_left; // left input of left.
1073 int32_t c = 0;
1074 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1075 left = left_of_left;
1076 }
1077 // The value of left input of instruction equals (left + c).
1078
1079 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001080 // always generate a value in [Min(), array_length].
1081 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001082 if (left->IsArrayLength() && c <= 1) {
1083 if (instruction->IsUShr() && c < 0) {
1084 // Make sure for unsigned shift, left side is not negative.
1085 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1086 // than array_length.
1087 return;
1088 }
1089 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1090 GetGraph()->GetArena(),
Aart Bikaab5b752015-09-23 11:18:57 -07001091 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001092 ValueBound(left, 0));
Aart Bik1d239822016-02-09 14:26:34 -08001093 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001094 }
1095 }
1096
Aart Bik4a342772015-11-30 10:17:46 -08001097 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001098 FindAndHandlePartialArrayLength(div);
1099 }
1100
Aart Bik4a342772015-11-30 10:17:46 -08001101 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001102 FindAndHandlePartialArrayLength(shr);
1103 }
1104
Aart Bik4a342772015-11-30 10:17:46 -08001105 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001106 FindAndHandlePartialArrayLength(ushr);
1107 }
1108
Aart Bik4a342772015-11-30 10:17:46 -08001109 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001110 if (instruction->GetRight()->IsIntConstant()) {
1111 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1112 if (constant > 0) {
1113 // constant serves as a mask so any number masked with it
1114 // gets a [0, constant] value range.
1115 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1116 GetGraph()->GetArena(),
1117 ValueBound(nullptr, 0),
1118 ValueBound(nullptr, constant));
Aart Bik1d239822016-02-09 14:26:34 -08001119 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang4559f002015-02-27 14:43:53 -08001120 }
1121 }
1122 }
1123
Aart Bik4a342772015-11-30 10:17:46 -08001124 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Mingyao Yang0304e182015-01-30 16:41:29 -08001125 HInstruction* len = new_array->InputAt(0);
1126 if (!len->IsIntConstant()) {
1127 HInstruction *left;
1128 int32_t right_const;
1129 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1130 // (left + right_const) is used as size to new the array.
1131 // We record "-right_const <= left <= new_array - right_const";
1132 ValueBound lower = ValueBound(nullptr, -right_const);
1133 // We use new_array for the bound instead of new_array.length,
1134 // which isn't available as an instruction yet. new_array will
1135 // be treated the same as new_array.length when it's used in a ValueBound.
1136 ValueBound upper = ValueBound(new_array, -right_const);
1137 ValueRange* range = new (GetGraph()->GetArena())
1138 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001139 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1140 if (existing_range != nullptr) {
1141 range = existing_range->Narrow(range);
1142 }
Aart Bik1d239822016-02-09 14:26:34 -08001143 AssignRange(new_array->GetBlock(), left, range);
Mingyao Yang0304e182015-01-30 16:41:29 -08001144 }
1145 }
1146 }
1147
Aart Bik4a342772015-11-30 10:17:46 -08001148 /**
1149 * After null/bounds checks are eliminated, some invariant array references
1150 * may be exposed underneath which can be hoisted out of the loop to the
1151 * preheader or, in combination with dynamic bce, the deoptimization block.
1152 *
1153 * for (int i = 0; i < n; i++) {
1154 * <-------+
1155 * for (int j = 0; j < n; j++) |
1156 * a[i][j] = 0; --a[i]--+
1157 * }
1158 *
Aart Bik1d239822016-02-09 14:26:34 -08001159 * Note: this optimization is no longer applied after dominator-based dynamic deoptimization
1160 * has occurred (see AddCompareWithDeoptimization()), since in those cases it would be
1161 * unsafe to hoist array references across their deoptimization instruction inside a loop.
Aart Bik4a342772015-11-30 10:17:46 -08001162 */
1163 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
Aart Bik1d239822016-02-09 14:26:34 -08001164 if (!has_dom_based_dynamic_bce_ && array_get->IsInLoop()) {
Aart Bik4a342772015-11-30 10:17:46 -08001165 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001166 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1167 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001168 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1169 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Anton Shaminf89381f2016-05-16 16:44:13 +06001170 // We can hoist ArrayGet only if its execution is guaranteed on every iteration.
1171 // In other words only if array_get_bb dominates all back branches.
1172 if (loop->DominatesAllBackEdges(array_get->GetBlock())) {
1173 HoistToPreHeaderOrDeoptBlock(loop, array_get);
1174 }
Aart Bik4a342772015-11-30 10:17:46 -08001175 }
1176 }
1177 }
1178 }
1179
Aart Bik67def592016-07-14 17:19:43 -07001180 /** Performs dominator-based dynamic elimination on suitable set of bounds checks. */
Aart Bik1d239822016-02-09 14:26:34 -08001181 void AddCompareWithDeoptimization(HBasicBlock* block,
1182 HInstruction* array_length,
1183 HInstruction* base,
1184 int32_t min_c, int32_t max_c) {
1185 HBoundsCheck* bounds_check =
1186 first_index_bounds_check_map_.Get(array_length->GetId())->AsBoundsCheck();
1187 // Construct deoptimization on single or double bounds on range [base-min_c,base+max_c],
1188 // for example either for a[0]..a[3] just 3 or for a[base-1]..a[base+3] both base-1
1189 // and base+3, since we made the assumption any in between value may occur too.
Aart Bik67def592016-07-14 17:19:43 -07001190 // In code, using unsigned comparisons:
1191 // (1) constants only
1192 // if (max_c >= a.length) deoptimize;
1193 // (2) general case
1194 // if (base-min_c > base+max_c) deoptimize;
1195 // if (base+max_c >= a.length ) deoptimize;
Aart Bik1d239822016-02-09 14:26:34 -08001196 static_assert(kMaxLengthForAddingDeoptimize < std::numeric_limits<int32_t>::max(),
1197 "Incorrect max length may be subject to arithmetic wrap-around");
1198 HInstruction* upper = GetGraph()->GetIntConstant(max_c);
1199 if (base == nullptr) {
1200 DCHECK_GE(min_c, 0);
1201 } else {
1202 HInstruction* lower = new (GetGraph()->GetArena())
1203 HAdd(Primitive::kPrimInt, base, GetGraph()->GetIntConstant(min_c));
1204 upper = new (GetGraph()->GetArena()) HAdd(Primitive::kPrimInt, base, upper);
1205 block->InsertInstructionBefore(lower, bounds_check);
1206 block->InsertInstructionBefore(upper, bounds_check);
1207 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAbove(lower, upper));
1208 }
1209 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAboveOrEqual(upper, array_length));
1210 // Flag that this kind of deoptimization has occurred.
1211 has_dom_based_dynamic_bce_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001212 }
1213
Aart Bik67def592016-07-14 17:19:43 -07001214 /** Attempts dominator-based dynamic elimination on remaining candidates. */
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001215 void AddComparesWithDeoptimization(HBasicBlock* block) {
Vladimir Markoda571cb2016-02-15 17:54:56 +00001216 for (const auto& entry : first_index_bounds_check_map_) {
1217 HBoundsCheck* bounds_check = entry.second;
Aart Bik1d239822016-02-09 14:26:34 -08001218 HInstruction* index = bounds_check->InputAt(0);
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001219 HInstruction* array_length = bounds_check->InputAt(1);
1220 if (!array_length->IsArrayLength()) {
Aart Bik1d239822016-02-09 14:26:34 -08001221 continue; // disregard phis and constants
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001222 }
Aart Bik1ae88742016-03-14 14:11:26 -07001223 // Collect all bounds checks that are still there and that are related as "a[base + constant]"
Aart Bik1d239822016-02-09 14:26:34 -08001224 // for a base instruction (possibly absent) and various constants. Note that no attempt
1225 // is made to partition the set into matching subsets (viz. a[0], a[1] and a[base+1] and
1226 // a[base+2] are considered as one set).
1227 // TODO: would such a partitioning be worthwhile?
1228 ValueBound value = ValueBound::AsValueBound(index);
1229 HInstruction* base = value.GetInstruction();
1230 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1231 int32_t max_c = value.GetConstant();
1232 ArenaVector<HBoundsCheck*> candidates(
1233 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1234 ArenaVector<HBoundsCheck*> standby(
1235 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
Vladimir Marko46817b82016-03-29 12:21:58 +01001236 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
Aart Bik1d239822016-02-09 14:26:34 -08001237 // Another bounds check in same or dominated block?
Vladimir Marko46817b82016-03-29 12:21:58 +01001238 HInstruction* user = use.GetUser();
Aart Bik1d239822016-02-09 14:26:34 -08001239 HBasicBlock* other_block = user->GetBlock();
1240 if (user->IsBoundsCheck() && block->Dominates(other_block)) {
1241 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1242 HInstruction* other_index = other_bounds_check->InputAt(0);
1243 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1244 ValueBound other_value = ValueBound::AsValueBound(other_index);
1245 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik1ae88742016-03-14 14:11:26 -07001246 // Reject certain OOB if BoundsCheck(l, l) occurs on considered subset.
1247 if (array_length == other_index) {
1248 candidates.clear();
1249 standby.clear();
1250 break;
1251 }
Aart Bik1d239822016-02-09 14:26:34 -08001252 // Since a subsequent dominated block could be under a conditional, only accept
1253 // the other bounds check if it is in same block or both blocks dominate the exit.
1254 // TODO: we could improve this by testing proper post-dominance, or even if this
1255 // constant is seen along *all* conditional paths that follow.
1256 HBasicBlock* exit = GetGraph()->GetExitBlock();
1257 if (block == user->GetBlock() ||
1258 (block->Dominates(exit) && other_block->Dominates(exit))) {
Aart Bik1ae88742016-03-14 14:11:26 -07001259 int32_t other_c = other_value.GetConstant();
Aart Bik1d239822016-02-09 14:26:34 -08001260 min_c = std::min(min_c, other_c);
1261 max_c = std::max(max_c, other_c);
1262 candidates.push_back(other_bounds_check);
1263 } else {
1264 // Add this candidate later only if it falls into the range.
1265 standby.push_back(other_bounds_check);
1266 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001267 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001268 }
1269 }
Aart Bik1d239822016-02-09 14:26:34 -08001270 // Add standby candidates that fall in selected range.
Vladimir Markoda571cb2016-02-15 17:54:56 +00001271 for (HBoundsCheck* other_bounds_check : standby) {
Aart Bik1d239822016-02-09 14:26:34 -08001272 HInstruction* other_index = other_bounds_check->InputAt(0);
1273 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1274 if (min_c <= other_c && other_c <= max_c) {
1275 candidates.push_back(other_bounds_check);
1276 }
1277 }
Aart Bik67def592016-07-14 17:19:43 -07001278 // Perform dominator-based deoptimization if it seems profitable, where we eliminate
1279 // bounds checks and replace these with deopt checks that guard against any possible
1280 // OOB. Note that we reject cases where the distance min_c:max_c range gets close to
1281 // the maximum possible array length, since those cases are likely to always deopt
1282 // (such situations do not necessarily go OOB, though, since the array could be really
1283 // large, or the programmer could rely on arithmetic wrap-around from max to min).
Aart Bik1d239822016-02-09 14:26:34 -08001284 size_t threshold = kThresholdForAddingDeoptimize + (base == nullptr ? 0 : 1); // extra test?
1285 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1286 if (candidates.size() >= threshold &&
1287 (base != nullptr || min_c >= 0) && // reject certain OOB
1288 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1289 AddCompareWithDeoptimization(block, array_length, base, min_c, max_c);
Aart Bik67def592016-07-14 17:19:43 -07001290 for (HBoundsCheck* other_bounds_check : candidates) {
Aart Bik1ae88742016-03-14 14:11:26 -07001291 // Only replace if still in the graph. This avoids visiting the same
1292 // bounds check twice if it occurred multiple times in the use list.
1293 if (other_bounds_check->IsInBlock()) {
1294 ReplaceInstruction(other_bounds_check, other_bounds_check->InputAt(0));
1295 }
Aart Bik1d239822016-02-09 14:26:34 -08001296 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001297 }
1298 }
1299 }
1300
Aart Bik4a342772015-11-30 10:17:46 -08001301 /**
1302 * Returns true if static range analysis based on induction variables can determine the bounds
1303 * check on the given array range is always satisfied with the computed index range. The output
1304 * parameter try_dynamic_bce is set to false if OOB is certain.
1305 */
1306 bool InductionRangeFitsIn(ValueRange* array_range,
Aart Bik52be7e72016-06-23 11:20:41 -07001307 HBoundsCheck* context,
Aart Bik4a342772015-11-30 10:17:46 -08001308 bool* try_dynamic_bce) {
1309 InductionVarRange::Value v1;
1310 InductionVarRange::Value v2;
1311 bool needs_finite_test = false;
Aart Bik52be7e72016-06-23 11:20:41 -07001312 HInstruction* index = context->InputAt(0);
1313 HInstruction* hint = ValueBound::HuntForDeclaration(context->InputAt(1));
1314 if (induction_range_.GetInductionRange(context, index, hint, &v1, &v2, &needs_finite_test)) {
1315 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1316 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1317 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1318 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1319 ValueRange index_range(GetGraph()->GetArena(),
1320 ValueBound(v1.instruction, v1.b_constant),
1321 ValueBound(v2.instruction, v2.b_constant));
1322 // If analysis reveals a certain OOB, disable dynamic BCE. Otherwise,
1323 // use analysis for static bce only if loop is finite.
1324 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1325 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1326 *try_dynamic_bce = false;
1327 } else if (!needs_finite_test && index_range.FitsIn(array_range)) {
1328 return true;
Aart Bikb738d4f2015-12-03 11:23:35 -08001329 }
Aart Bik52be7e72016-06-23 11:20:41 -07001330 }
Aart Bik1fc3afb2016-02-02 13:26:16 -08001331 }
Aart Bik4a342772015-11-30 10:17:46 -08001332 return false;
1333 }
1334
1335 /**
Aart Bik67def592016-07-14 17:19:43 -07001336 * Performs loop-based dynamic elimination on a bounds check. In order to minimize the
1337 * number of eventually generated tests, related bounds checks with tests that can be
1338 * combined with tests for the given bounds check are collected first.
Aart Bik4a342772015-11-30 10:17:46 -08001339 */
Aart Bik67def592016-07-14 17:19:43 -07001340 void TransformLoopForDynamicBCE(HLoopInformation* loop, HBoundsCheck* bounds_check) {
1341 HInstruction* index = bounds_check->InputAt(0);
1342 HInstruction* array_length = bounds_check->InputAt(1);
1343 DCHECK(loop->IsDefinedOutOfTheLoop(array_length)); // pre-checked
1344 DCHECK(loop->DominatesAllBackEdges(bounds_check->GetBlock()));
1345 // Collect all bounds checks in the same loop that are related as "a[base + constant]"
1346 // for a base instruction (possibly absent) and various constants.
1347 ValueBound value = ValueBound::AsValueBound(index);
1348 HInstruction* base = value.GetInstruction();
1349 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1350 int32_t max_c = value.GetConstant();
1351 ArenaVector<HBoundsCheck*> candidates(
1352 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1353 ArenaVector<HBoundsCheck*> standby(
1354 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1355 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
1356 HInstruction* user = use.GetUser();
1357 if (user->IsBoundsCheck() && loop == user->GetBlock()->GetLoopInformation()) {
1358 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1359 HInstruction* other_index = other_bounds_check->InputAt(0);
1360 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1361 ValueBound other_value = ValueBound::AsValueBound(other_index);
1362 int32_t other_c = other_value.GetConstant();
1363 if (array_length == other_array_length && base == other_value.GetInstruction()) {
1364 // Does the current basic block dominate all back edges? If not,
1365 // add this candidate later only if it falls into the range.
1366 if (!loop->DominatesAllBackEdges(user->GetBlock())) {
1367 standby.push_back(other_bounds_check);
1368 continue;
1369 }
1370 min_c = std::min(min_c, other_c);
1371 max_c = std::max(max_c, other_c);
1372 candidates.push_back(other_bounds_check);
1373 }
Aart Bik4a342772015-11-30 10:17:46 -08001374 }
Aart Bik4a342772015-11-30 10:17:46 -08001375 }
Aart Bik67def592016-07-14 17:19:43 -07001376 // Add standby candidates that fall in selected range.
1377 for (HBoundsCheck* other_bounds_check : standby) {
1378 HInstruction* other_index = other_bounds_check->InputAt(0);
1379 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1380 if (min_c <= other_c && other_c <= max_c) {
1381 candidates.push_back(other_bounds_check);
1382 }
1383 }
1384 // Perform loop-based deoptimization if it seems profitable, where we eliminate bounds
1385 // checks and replace these with deopt checks that guard against any possible OOB.
1386 DCHECK_LT(0u, candidates.size());
1387 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1388 if ((base != nullptr || min_c >= 0) && // reject certain OOB
1389 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1390 HBasicBlock* block = GetPreHeader(loop, bounds_check);
1391 HInstruction* min_lower = nullptr;
1392 HInstruction* min_upper = nullptr;
1393 HInstruction* max_lower = nullptr;
1394 HInstruction* max_upper = nullptr;
1395 // Iterate over all bounds checks.
1396 for (HBoundsCheck* other_bounds_check : candidates) {
1397 // Only handle if still in the graph. This avoids visiting the same
1398 // bounds check twice if it occurred multiple times in the use list.
1399 if (other_bounds_check->IsInBlock()) {
1400 HInstruction* other_index = other_bounds_check->InputAt(0);
1401 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1402 // Generate code for either the maximum or minimum. Range analysis already was queried
1403 // whether code generation on the original and, thus, related bounds check was possible.
1404 // It handles either loop invariants (lower is not set) or unit strides.
1405 if (other_c == max_c) {
Aart Bik16d3a652016-09-09 10:33:50 -07001406 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001407 other_bounds_check, other_index, GetGraph(), block, &max_lower, &max_upper);
1408 } else if (other_c == min_c && base != nullptr) {
Aart Bik16d3a652016-09-09 10:33:50 -07001409 induction_range_.GenerateRange(
Aart Bik67def592016-07-14 17:19:43 -07001410 other_bounds_check, other_index, GetGraph(), block, &min_lower, &min_upper);
1411 }
1412 ReplaceInstruction(other_bounds_check, other_index);
1413 }
1414 }
1415 // In code, using unsigned comparisons:
1416 // (1) constants only
1417 // if (max_upper >= a.length ) deoptimize;
1418 // (2) two symbolic invariants
1419 // if (min_upper > max_upper) deoptimize; unless min_c == max_c
1420 // if (max_upper >= a.length ) deoptimize;
1421 // (3) general case, unit strides (where lower would exceed upper for arithmetic wrap-around)
1422 // if (min_lower > max_lower) deoptimize; unless min_c == max_c
1423 // if (max_lower > max_upper) deoptimize;
1424 // if (max_upper >= a.length ) deoptimize;
1425 if (base == nullptr) {
1426 // Constants only.
1427 DCHECK_GE(min_c, 0);
1428 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1429 max_lower == nullptr && max_upper != nullptr);
1430 } else if (max_lower == nullptr) {
1431 // Two symbolic invariants.
1432 if (min_c != max_c) {
1433 DCHECK(min_lower == nullptr && min_upper != nullptr &&
1434 max_lower == nullptr && max_upper != nullptr);
1435 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(min_upper, max_upper));
1436 } else {
1437 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1438 max_lower == nullptr && max_upper != nullptr);
1439 }
1440 } else {
1441 // General case, unit strides.
1442 if (min_c != max_c) {
1443 DCHECK(min_lower != nullptr && min_upper != nullptr &&
1444 max_lower != nullptr && max_upper != nullptr);
1445 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(min_lower, max_lower));
1446 } else {
1447 DCHECK(min_lower == nullptr && min_upper == nullptr &&
1448 max_lower != nullptr && max_upper != nullptr);
1449 }
1450 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(max_lower, max_upper));
1451 }
1452 InsertDeoptInLoop(
1453 loop, block, new (GetGraph()->GetArena()) HAboveOrEqual(max_upper, array_length));
1454 } else {
1455 // TODO: if rejected, avoid doing this again for subsequent instructions in this set?
1456 }
Aart Bik4a342772015-11-30 10:17:46 -08001457 }
1458
1459 /**
1460 * Returns true if heuristics indicate that dynamic bce may be profitable.
1461 */
1462 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1463 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001464 // The loop preheader of an irreducible loop does not dominate all the blocks in
1465 // the loop. We would need to find the common dominator of all blocks in the loop.
1466 if (loop->IsIrreducible()) {
1467 return false;
1468 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001469 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
1470 // code dominated by the deoptimization.
1471 if (GetGraph()->IsCompilingOsr()) {
1472 return false;
1473 }
Aart Bik4a342772015-11-30 10:17:46 -08001474 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001475 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001476 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1477 return false;
1478 }
1479 // Does loop have early-exits? If so, the full range may not be covered by the loop
1480 // at runtime and testing the range may apply deoptimization unnecessarily.
1481 if (IsEarlyExitLoop(loop)) {
1482 return false;
1483 }
1484 // Does the current basic block dominate all back edges? If not,
1485 // don't apply dynamic bce to something that may not be executed.
Anton Shaminf89381f2016-05-16 16:44:13 +06001486 return loop->DominatesAllBackEdges(block);
Aart Bik4a342772015-11-30 10:17:46 -08001487 }
1488 return false;
1489 }
1490
1491 /**
1492 * Returns true if the loop has early exits, which implies it may not cover
1493 * the full range computed by range analysis based on induction variables.
1494 */
1495 bool IsEarlyExitLoop(HLoopInformation* loop) {
1496 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1497 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1498 auto it = early_exit_loop_.find(loop_id);
1499 if (it != early_exit_loop_.end()) {
1500 return it->second;
1501 }
1502 // First time early-exit analysis for this loop. Since analysis requires scanning
1503 // the full loop-body, results of the analysis is stored for subsequent queries.
1504 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1505 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1506 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1507 if (!loop->Contains(*successor)) {
1508 early_exit_loop_.Put(loop_id, true);
1509 return true;
1510 }
1511 }
1512 }
1513 early_exit_loop_.Put(loop_id, false);
1514 return false;
1515 }
1516
1517 /**
1518 * Returns true if the array length is already loop invariant, or can be made so
1519 * by handling the null check under the hood of the array length operation.
1520 */
1521 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001522 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001523 return true;
1524 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1525 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001526 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001527 return true;
1528 }
1529 }
1530 return false;
1531 }
1532
1533 /**
1534 * Returns true if the null check is already loop invariant, or can be made so
1535 * by generating a deoptimization test.
1536 */
1537 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001538 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001539 return true;
1540 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1541 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001542 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001543 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001544 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1545 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001546 HInstruction* cond =
1547 new (GetGraph()->GetArena()) HEqual(array, GetGraph()->GetNullConstant());
Aart Bik1d239822016-02-09 14:26:34 -08001548 InsertDeoptInLoop(loop, block, cond);
Aart Bik4a342772015-11-30 10:17:46 -08001549 ReplaceInstruction(check, array);
1550 return true;
1551 }
1552 }
1553 return false;
1554 }
1555
1556 /**
1557 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1558 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1559 * the range analysis evaluation code by "overshooting" the computed range.
1560 * Since deoptimization would be a bad choice, and there is no other version
1561 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1562 * ensure the loop is finite.
1563 */
Aart Bik67def592016-07-14 17:19:43 -07001564 bool CanHandleInfiniteLoop(HLoopInformation* loop, HInstruction* index, bool needs_infinite_test) {
Aart Bik4a342772015-11-30 10:17:46 -08001565 if (needs_infinite_test) {
1566 // If we already forced the loop to be finite, allow directly.
1567 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1568 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1569 return true;
1570 }
1571 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1572 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1573 // ensure upper bound cannot cause an infinite loop.
1574 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1575 if (control->IsIf()) {
1576 HInstruction* if_expr = control->AsIf()->InputAt(0);
1577 if (if_expr->IsCondition()) {
1578 HCondition* condition = if_expr->AsCondition();
1579 if (index == condition->InputAt(0) ||
1580 index == condition->InputAt(1)) {
1581 finite_loop_.insert(loop_id);
1582 return true;
1583 }
1584 }
1585 }
1586 return false;
1587 }
1588 return true;
1589 }
1590
Aart Bik55b14df2016-01-12 14:12:47 -08001591 /**
1592 * Returns appropriate preheader for the loop, depending on whether the
1593 * instruction appears in the loop header or proper loop-body.
1594 */
1595 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1596 // Use preheader unless there is an earlier generated deoptimization block since
1597 // hoisted expressions may depend on and/or used by the deoptimization tests.
1598 HBasicBlock* header = loop->GetHeader();
1599 const uint32_t loop_id = header->GetBlockId();
1600 auto it = taken_test_loop_.find(loop_id);
1601 if (it != taken_test_loop_.end()) {
1602 HBasicBlock* block = it->second;
1603 // If always taken, keep it that way by returning the original preheader,
1604 // which can be found by following the predecessor of the true-block twice.
1605 if (instruction->GetBlock() == header) {
1606 return block->GetSinglePredecessor()->GetSinglePredecessor();
1607 }
1608 return block;
1609 }
1610 return loop->GetPreHeader();
1611 }
1612
Aart Bik1d239822016-02-09 14:26:34 -08001613 /** Inserts a deoptimization test in a loop preheader. */
1614 void InsertDeoptInLoop(HLoopInformation* loop, HBasicBlock* block, HInstruction* condition) {
Aart Bik4a342772015-11-30 10:17:46 -08001615 HInstruction* suspend = loop->GetSuspendCheck();
1616 block->InsertInstructionBefore(condition, block->GetLastInstruction());
1617 HDeoptimize* deoptimize =
1618 new (GetGraph()->GetArena()) HDeoptimize(condition, suspend->GetDexPc());
1619 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1620 if (suspend->HasEnvironment()) {
1621 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1622 suspend->GetEnvironment(), loop->GetHeader());
1623 }
1624 }
1625
Aart Bik1d239822016-02-09 14:26:34 -08001626 /** Inserts a deoptimization test right before a bounds check. */
1627 void InsertDeoptInBlock(HBoundsCheck* bounds_check, HInstruction* condition) {
1628 HBasicBlock* block = bounds_check->GetBlock();
1629 block->InsertInstructionBefore(condition, bounds_check);
1630 HDeoptimize* deoptimize =
1631 new (GetGraph()->GetArena()) HDeoptimize(condition, bounds_check->GetDexPc());
1632 block->InsertInstructionBefore(deoptimize, bounds_check);
1633 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
1634 }
1635
Aart Bik4a342772015-11-30 10:17:46 -08001636 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001637 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1638 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001639 DCHECK(!instruction->HasEnvironment());
1640 instruction->MoveBefore(block->GetLastInstruction());
1641 }
1642
1643 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001644 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001645 * The taken-test protects range analysis evaluation code to avoid any
1646 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1647 *
Aart Bik4a342772015-11-30 10:17:46 -08001648 * old_preheader
1649 * |
1650 * if_block <- taken-test protects deoptimization block
1651 * / \
1652 * true_block false_block <- deoptimizations/invariants are placed in true_block
1653 * \ /
1654 * new_preheader <- may require phi nodes to preserve SSA structure
1655 * |
1656 * header
1657 *
1658 * For example, this loop:
1659 *
1660 * for (int i = lower; i < upper; i++) {
1661 * array[i] = 0;
1662 * }
1663 *
1664 * will be transformed to:
1665 *
1666 * if (lower < upper) {
1667 * if (array == null) deoptimize;
1668 * array_length = array.length;
1669 * if (lower > upper) deoptimize; // unsigned
1670 * if (upper >= array_length) deoptimize; // unsigned
1671 * } else {
1672 * array_length = 0;
1673 * }
1674 * for (int i = lower; i < upper; i++) {
1675 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1676 * array[i] = 0;
1677 * }
1678 */
Aart Bik55b14df2016-01-12 14:12:47 -08001679 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1680 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001681 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001682 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1683 return;
Aart Bik4a342772015-11-30 10:17:46 -08001684 }
1685
1686 // Generate top test structure.
1687 HBasicBlock* header = loop->GetHeader();
1688 GetGraph()->TransformLoopHeaderForBCE(header);
1689 HBasicBlock* new_preheader = loop->GetPreHeader();
1690 HBasicBlock* if_block = new_preheader->GetDominator();
1691 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1692 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1693
1694 // Goto instructions.
1695 true_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1696 false_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1697 new_preheader->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1698
1699 // Insert the taken-test to see if the loop body is entered. If the
1700 // loop isn't entered at all, it jumps around the deoptimization block.
1701 if_block->AddInstruction(new (GetGraph()->GetArena()) HGoto()); // placeholder
Aart Bik16d3a652016-09-09 10:33:50 -07001702 HInstruction* condition = induction_range_.GenerateTakenTest(
1703 header->GetLastInstruction(), GetGraph(), if_block);
Aart Bik4a342772015-11-30 10:17:46 -08001704 DCHECK(condition != nullptr);
1705 if_block->RemoveInstruction(if_block->GetLastInstruction());
1706 if_block->AddInstruction(new (GetGraph()->GetArena()) HIf(condition));
1707
1708 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001709 }
1710
1711 /**
1712 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1713 * All uses of instructions in the deoptimization block that reach the loop need
1714 * a phi node in the new loop preheader to fix the dominance relation.
1715 *
1716 * Example:
1717 * if_block
1718 * / \
1719 * x_0 = .. false_block
1720 * \ /
1721 * x_1 = phi(x_0, null) <- synthetic phi
1722 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001723 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001724 */
1725 void InsertPhiNodes() {
1726 // Scan all new deoptimization blocks.
1727 for (auto it1 = taken_test_loop_.begin(); it1 != taken_test_loop_.end(); ++it1) {
1728 HBasicBlock* true_block = it1->second;
1729 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1730 // Scan all instructions in a new deoptimization block.
1731 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1732 HInstruction* instruction = it.Current();
1733 Primitive::Type type = instruction->GetType();
1734 HPhi* phi = nullptr;
1735 // Scan all uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001736 const HUseList<HInstruction*>& uses = instruction->GetUses();
1737 for (auto it2 = uses.begin(), end2 = uses.end(); it2 != end2; /* ++it2 below */) {
1738 HInstruction* user = it2->GetUser();
1739 size_t index = it2->GetIndex();
1740 // Increment `it2` now because `*it2` may disappear thanks to user->ReplaceInput().
1741 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001742 if (user->GetBlock() != true_block) {
1743 if (phi == nullptr) {
1744 phi = NewPhi(new_preheader, instruction, type);
1745 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001746 user->ReplaceInput(phi, index); // Removes the use node from the list.
Aart Bik4a342772015-11-30 10:17:46 -08001747 }
1748 }
1749 // Scan all environment uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001750 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1751 for (auto it2 = env_uses.begin(), end2 = env_uses.end(); it2 != end2; /* ++it2 below */) {
1752 HEnvironment* user = it2->GetUser();
1753 size_t index = it2->GetIndex();
1754 // Increment `it2` now because `*it2` may disappear thanks to user->RemoveAsUserOfInput().
1755 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001756 if (user->GetHolder()->GetBlock() != true_block) {
1757 if (phi == nullptr) {
1758 phi = NewPhi(new_preheader, instruction, type);
1759 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001760 user->RemoveAsUserOfInput(index);
1761 user->SetRawEnvAt(index, phi);
1762 phi->AddEnvUseAt(user, index);
Aart Bik4a342772015-11-30 10:17:46 -08001763 }
1764 }
1765 }
1766 }
1767 }
1768
1769 /**
1770 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1771 * These are synthetic phi nodes without a virtual register.
1772 */
1773 HPhi* NewPhi(HBasicBlock* new_preheader,
1774 HInstruction* instruction,
1775 Primitive::Type type) {
1776 HGraph* graph = GetGraph();
1777 HInstruction* zero;
1778 switch (type) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001779 case Primitive::kPrimNot: zero = graph->GetNullConstant(); break;
1780 case Primitive::kPrimFloat: zero = graph->GetFloatConstant(0); break;
1781 case Primitive::kPrimDouble: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001782 default: zero = graph->GetConstant(type, 0); break;
1783 }
1784 HPhi* phi = new (graph->GetArena())
1785 HPhi(graph->GetArena(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
1786 phi->SetRawInputAt(0, instruction);
1787 phi->SetRawInputAt(1, zero);
David Brazdil4833f5a2015-12-16 10:37:39 +00001788 if (type == Primitive::kPrimNot) {
1789 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1790 }
Aart Bik4a342772015-11-30 10:17:46 -08001791 new_preheader->AddPhi(phi);
1792 return phi;
1793 }
1794
1795 /** Helper method to replace an instruction with another instruction. */
1796 static void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1797 instruction->ReplaceWith(replacement);
1798 instruction->GetBlock()->RemoveInstruction(instruction);
1799 }
1800
1801 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko5233f932015-09-29 19:01:15 +01001802 ArenaVector<ArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001803
Aart Bik1d239822016-02-09 14:26:34 -08001804 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction
1805 // in a block that checks an index against that HArrayLength.
1806 ArenaSafeMap<int, HBoundsCheck*> first_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001807
Aart Bik4a342772015-11-30 10:17:46 -08001808 // Early-exit loop bookkeeping.
1809 ArenaSafeMap<uint32_t, bool> early_exit_loop_;
1810
1811 // Taken-test loop bookkeeping.
1812 ArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
1813
1814 // Finite loop bookkeeping.
1815 ArenaSet<uint32_t> finite_loop_;
1816
Aart Bik1d239822016-02-09 14:26:34 -08001817 // Flag that denotes whether dominator-based dynamic elimination has occurred.
1818 bool has_dom_based_dynamic_bce_;
Aart Bik4a342772015-11-30 10:17:46 -08001819
Mingyao Yang3584bce2015-05-19 16:01:59 -07001820 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001821 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001822
Aart Bik4a342772015-11-30 10:17:46 -08001823 // Side effects.
1824 const SideEffectsAnalysis& side_effects_;
1825
Aart Bik22af3be2015-09-10 12:50:58 -07001826 // Range analysis based on induction variables.
1827 InductionVarRange induction_range_;
1828
Mingyao Yangf384f882014-10-22 16:08:18 -07001829 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1830};
1831
1832void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001833 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001834 return;
1835 }
1836
Mingyao Yangf384f882014-10-22 16:08:18 -07001837 // Reverse post order guarantees a node's dominators are visited first.
1838 // We want to visit in the dominator-based order since if a value is known to
1839 // be bounded by a range at one instruction, it must be true that all uses of
1840 // that value dominated by that instruction fits in that range. Range of that
1841 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001842 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001843 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1844 HBasicBlock* current = it.Current();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001845 if (visitor.IsAddedBlock(current)) {
1846 // Skip added blocks. Their effects are already taken care of.
1847 continue;
1848 }
1849 visitor.VisitBasicBlock(current);
Aart Bikb6347b72016-02-29 13:56:44 -08001850 // Skip forward to the current block in case new basic blocks were inserted
1851 // (which always appear earlier in reverse post order) to avoid visiting the
1852 // same basic block twice.
1853 for ( ; !it.Done() && it.Current() != current; it.Advance()) {
1854 }
Mingyao Yang3584bce2015-05-19 16:01:59 -07001855 }
Aart Bik4a342772015-11-30 10:17:46 -08001856
1857 // Perform cleanup.
1858 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001859}
1860
1861} // namespace art