blob: d786e82d11d5540a3c82230a8503070944a545c4 [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 Bik591ad292016-03-01 10:39:25 -0800536 dynamic_bce_standby_(
537 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Vladimir Markob75878e2016-03-14 13:56:02 +0000538 record_dynamic_bce_standby_(true),
Aart Bik4a342772015-11-30 10:17:46 -0800539 early_exit_loop_(
540 std::less<uint32_t>(),
541 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
542 taken_test_loop_(
543 std::less<uint32_t>(),
544 graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
545 finite_loop_(graph->GetArena()->Adapter(kArenaAllocBoundsCheckElimination)),
Aart Bik1d239822016-02-09 14:26:34 -0800546 has_dom_based_dynamic_bce_(false),
Vladimir Markofa6b93c2015-09-15 10:15:55 +0100547 initial_block_size_(graph->GetBlocks().size()),
Aart Bik4a342772015-11-30 10:17:46 -0800548 side_effects_(side_effects),
Aart Bik22af3be2015-09-10 12:50:58 -0700549 induction_range_(induction_analysis) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700550
551 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700552 DCHECK(!IsAddedBlock(block));
Aart Bik1d239822016-02-09 14:26:34 -0800553 first_index_bounds_check_map_.clear();
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700554 HGraphVisitor::VisitBasicBlock(block);
Nicolas Geoffray93a18c52016-04-22 13:16:14 +0100555 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
556 // code dominated by the deoptimization.
557 if (!GetGraph()->IsCompilingOsr()) {
558 AddComparesWithDeoptimization(block);
559 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700560 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700561
Aart Bik4a342772015-11-30 10:17:46 -0800562 void Finish() {
Aart Bik591ad292016-03-01 10:39:25 -0800563 // Retry dynamic bce candidates on standby that are still in the graph.
Vladimir Markob75878e2016-03-14 13:56:02 +0000564 record_dynamic_bce_standby_ = false;
Aart Bik591ad292016-03-01 10:39:25 -0800565 for (HBoundsCheck* bounds_check : dynamic_bce_standby_) {
566 if (bounds_check->IsInBlock()) {
567 TryDynamicBCE(bounds_check);
568 }
569 }
570
Aart Bik4a342772015-11-30 10:17:46 -0800571 // Preserve SSA structure which may have been broken by adding one or more
572 // new taken-test structures (see TransformLoopForDeoptimizationIfNeeded()).
573 InsertPhiNodes();
574
575 // Clear the loop data structures.
576 early_exit_loop_.clear();
577 taken_test_loop_.clear();
578 finite_loop_.clear();
Aart Bik591ad292016-03-01 10:39:25 -0800579 dynamic_bce_standby_.clear();
Aart Bik4a342772015-11-30 10:17:46 -0800580 }
581
Mingyao Yangf384f882014-10-22 16:08:18 -0700582 private:
583 // Return the map of proven value ranges at the beginning of a basic block.
584 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700585 if (IsAddedBlock(basic_block)) {
586 // Added blocks don't keep value ranges.
587 return nullptr;
588 }
Aart Bik1d239822016-02-09 14:26:34 -0800589 return &maps_[basic_block->GetBlockId()];
Mingyao Yangf384f882014-10-22 16:08:18 -0700590 }
591
592 // Traverse up the dominator tree to look for value range info.
593 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
594 while (basic_block != nullptr) {
595 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700596 if (map != nullptr) {
597 if (map->find(instruction->GetId()) != map->end()) {
598 return map->Get(instruction->GetId());
599 }
600 } else {
601 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -0700602 }
603 basic_block = basic_block->GetDominator();
604 }
605 // Didn't find any.
606 return nullptr;
607 }
608
Aart Bik1d239822016-02-09 14:26:34 -0800609 // Helper method to assign a new range to an instruction in given basic block.
610 void AssignRange(HBasicBlock* basic_block, HInstruction* instruction, ValueRange* range) {
611 GetValueRangeMap(basic_block)->Overwrite(instruction->GetId(), range);
612 }
613
Mingyao Yang0304e182015-01-30 16:41:29 -0800614 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
615 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700616 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800617 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700618 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800619 if (existing_range == nullptr) {
620 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800621 AssignRange(successor, instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800622 }
623 return;
624 }
625 if (existing_range->IsMonotonicValueRange()) {
626 DCHECK(instruction->IsLoopHeaderPhi());
627 // Make sure the comparison is in the loop header so each increment is
628 // checked with a comparison.
629 if (instruction->GetBlock() != basic_block) {
630 return;
631 }
632 }
Aart Bik1d239822016-02-09 14:26:34 -0800633 AssignRange(successor, instruction, existing_range->Narrow(range));
Mingyao Yangf384f882014-10-22 16:08:18 -0700634 }
635
Mingyao Yang57e04752015-02-09 18:13:26 -0800636 // Special case that we may simultaneously narrow two MonotonicValueRange's to
637 // regular value ranges.
638 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
639 HInstruction* left,
640 HInstruction* right,
641 IfCondition cond,
642 MonotonicValueRange* left_range,
643 MonotonicValueRange* right_range) {
644 DCHECK(left->IsLoopHeaderPhi());
645 DCHECK(right->IsLoopHeaderPhi());
646 if (instruction->GetBlock() != left->GetBlock()) {
647 // Comparison needs to be in loop header to make sure it's done after each
648 // increment/decrement.
649 return;
650 }
651
652 // Handle common cases which also don't have overflow/underflow concerns.
653 if (left_range->GetIncrement() == 1 &&
654 left_range->GetBound().IsConstant() &&
655 right_range->GetIncrement() == -1 &&
656 right_range->GetBound().IsRelatedToArrayLength() &&
657 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800658 HBasicBlock* successor = nullptr;
659 int32_t left_compensation = 0;
660 int32_t right_compensation = 0;
661 if (cond == kCondLT) {
662 left_compensation = -1;
663 right_compensation = 1;
664 successor = instruction->IfTrueSuccessor();
665 } else if (cond == kCondLE) {
666 successor = instruction->IfTrueSuccessor();
667 } else if (cond == kCondGT) {
668 successor = instruction->IfFalseSuccessor();
669 } else if (cond == kCondGE) {
670 left_compensation = -1;
671 right_compensation = 1;
672 successor = instruction->IfFalseSuccessor();
673 } else {
674 // We don't handle '=='/'!=' test in case left and right can cross and
675 // miss each other.
676 return;
677 }
678
679 if (successor != nullptr) {
680 bool overflow;
681 bool underflow;
682 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
683 GetGraph()->GetArena(),
684 left_range->GetBound(),
685 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
686 if (!overflow && !underflow) {
687 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
688 new_left_range);
689 }
690
691 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
692 GetGraph()->GetArena(),
693 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
694 right_range->GetBound());
695 if (!overflow && !underflow) {
696 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
697 new_right_range);
698 }
699 }
700 }
701 }
702
Mingyao Yangf384f882014-10-22 16:08:18 -0700703 // Handle "if (left cmp_cond right)".
704 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
705 HBasicBlock* block = instruction->GetBlock();
706
707 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
708 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000709 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700710
711 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
712 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +0000713 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -0700714
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700715 ValueRange* left_range = LookupValueRange(left, block);
716 MonotonicValueRange* left_monotonic_range = nullptr;
717 if (left_range != nullptr) {
718 left_monotonic_range = left_range->AsMonotonicValueRange();
719 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700720 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700721 if (instruction->GetBlock() != loop_head) {
722 // For monotonic value range, don't handle `instruction`
723 // if it's not defined in the loop header.
724 return;
725 }
726 }
727 }
728
Mingyao Yang64197522014-12-05 15:56:23 -0800729 bool found;
730 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800731 // Each comparison can establish a lower bound and an upper bound
732 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700733 ValueBound lower = bound;
734 ValueBound upper = bound;
735 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800736 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700737 // 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 -0800738 ValueRange* right_range = LookupValueRange(right, block);
739 if (right_range != nullptr) {
740 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800741 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
742 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
743 left_range->AsMonotonicValueRange(),
744 right_range->AsMonotonicValueRange());
745 return;
746 }
747 }
748 lower = right_range->GetLower();
749 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -0700750 } else {
751 lower = ValueBound::Min();
752 upper = ValueBound::Max();
753 }
754 }
755
Mingyao Yang0304e182015-01-30 16:41:29 -0800756 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -0700757 if (cond == kCondLT || cond == kCondLE) {
758 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800759 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
760 ValueBound new_upper = upper.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(), ValueBound::Min(), new_upper);
766 ApplyRangeFromComparison(left, block, true_successor, new_range);
767 }
768
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 == kCondLE) ? 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, false_successor, new_range);
779 }
780 } else if (cond == kCondGT || cond == kCondGE) {
781 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -0800782 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
783 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
784 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
785 if (overflow || underflow) {
786 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800787 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700788 ValueRange* new_range = new (GetGraph()->GetArena())
789 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
790 ApplyRangeFromComparison(left, block, true_successor, new_range);
791 }
792
793 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800794 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
795 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
796 if (overflow || underflow) {
797 return;
Mingyao Yang64197522014-12-05 15:56:23 -0800798 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700799 ValueRange* new_range = new (GetGraph()->GetArena())
800 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
801 ApplyRangeFromComparison(left, block, false_successor, new_range);
802 }
Aart Bika2106892016-05-04 14:00:55 -0700803 } else if (cond == kCondNE || cond == kCondEQ) {
804 if (left->IsArrayLength() && lower.IsConstant() && upper.IsConstant()) {
805 // Special case:
806 // length == [c,d] yields [c, d] along true
807 // length != [c,d] yields [c, d] along false
808 if (!lower.Equals(ValueBound::Min()) || !upper.Equals(ValueBound::Max())) {
809 ValueRange* new_range = new (GetGraph()->GetArena())
810 ValueRange(GetGraph()->GetArena(), lower, upper);
811 ApplyRangeFromComparison(
812 left, block, cond == kCondEQ ? true_successor : false_successor, new_range);
813 }
814 // In addition:
815 // length == 0 yields [1, max] along false
816 // length != 0 yields [1, max] along true
817 if (lower.GetConstant() == 0 && upper.GetConstant() == 0) {
818 ValueRange* new_range = new (GetGraph()->GetArena())
819 ValueRange(GetGraph()->GetArena(), ValueBound(nullptr, 1), ValueBound::Max());
820 ApplyRangeFromComparison(
821 left, block, cond == kCondEQ ? false_successor : true_successor, new_range);
822 }
823 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700824 }
825 }
826
Aart Bik4a342772015-11-30 10:17:46 -0800827 void VisitBoundsCheck(HBoundsCheck* bounds_check) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700828 HBasicBlock* block = bounds_check->GetBlock();
829 HInstruction* index = bounds_check->InputAt(0);
830 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700831 DCHECK(array_length->IsIntConstant() ||
832 array_length->IsArrayLength() ||
833 array_length->IsPhi());
Aart Bik4a342772015-11-30 10:17:46 -0800834 bool try_dynamic_bce = true;
Mingyao Yangf384f882014-10-22 16:08:18 -0700835
Aart Bik1d239822016-02-09 14:26:34 -0800836 // Analyze index range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800837 if (!index->IsIntConstant()) {
Aart Bik1d239822016-02-09 14:26:34 -0800838 // Non-constant index.
Aart Bik22af3be2015-09-10 12:50:58 -0700839 ValueBound lower = ValueBound(nullptr, 0); // constant 0
840 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
841 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
Aart Bik1d239822016-02-09 14:26:34 -0800842 // Try index range obtained by dominator-based analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -0800843 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -0700844 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
Aart Bik4a342772015-11-30 10:17:46 -0800845 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700846 return;
847 }
Aart Bik1d239822016-02-09 14:26:34 -0800848 // Try index range obtained by induction variable analysis.
Aart Bik4a342772015-11-30 10:17:46 -0800849 // Disables dynamic bce if OOB is certain.
Aart Bik52be7e72016-06-23 11:20:41 -0700850 if (InductionRangeFitsIn(&array_range, bounds_check, &try_dynamic_bce)) {
Aart Bik4a342772015-11-30 10:17:46 -0800851 ReplaceInstruction(bounds_check, index);
Aart Bik22af3be2015-09-10 12:50:58 -0700852 return;
Mingyao Yangf384f882014-10-22 16:08:18 -0700853 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800854 } else {
Aart Bik1d239822016-02-09 14:26:34 -0800855 // Constant index.
Mingyao Yang0304e182015-01-30 16:41:29 -0800856 int32_t constant = index->AsIntConstant()->GetValue();
857 if (constant < 0) {
858 // Will always throw exception.
859 return;
Aart Bik1d239822016-02-09 14:26:34 -0800860 } else if (array_length->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800861 if (constant < array_length->AsIntConstant()->GetValue()) {
Aart Bik4a342772015-11-30 10:17:46 -0800862 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800863 }
864 return;
865 }
Aart Bik1d239822016-02-09 14:26:34 -0800866 // Analyze array length range.
Mingyao Yang0304e182015-01-30 16:41:29 -0800867 DCHECK(array_length->IsArrayLength());
868 ValueRange* existing_range = LookupValueRange(array_length, block);
869 if (existing_range != nullptr) {
870 ValueBound lower = existing_range->GetLower();
871 DCHECK(lower.IsConstant());
872 if (constant < lower.GetConstant()) {
Aart Bik4a342772015-11-30 10:17:46 -0800873 ReplaceInstruction(bounds_check, index);
Mingyao Yang0304e182015-01-30 16:41:29 -0800874 return;
875 } else {
876 // Existing range isn't strong enough to eliminate the bounds check.
877 // Fall through to update the array_length range with info from this
878 // bounds check.
879 }
880 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700881 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -0800882 // We currently don't do it for non-constant index since a valid array[i] can't prove
883 // a valid array[i-1] yet due to the lower bound side.
Aart Bikaab5b752015-09-23 11:18:57 -0700884 if (constant == std::numeric_limits<int32_t>::max()) {
885 // Max() as an index will definitely throw AIOOBE.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700886 return;
Aart Bik1d239822016-02-09 14:26:34 -0800887 } else {
888 ValueBound lower = ValueBound(nullptr, constant + 1);
889 ValueBound upper = ValueBound::Max();
890 ValueRange* range = new (GetGraph()->GetArena())
891 ValueRange(GetGraph()->GetArena(), lower, upper);
892 AssignRange(block, array_length, range);
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700893 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700894 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700895
Aart Bik4a342772015-11-30 10:17:46 -0800896 // If static analysis fails, and OOB is not certain, try dynamic elimination.
897 if (try_dynamic_bce) {
Aart Bik1d239822016-02-09 14:26:34 -0800898 // Try loop-based dynamic elimination.
899 if (TryDynamicBCE(bounds_check)) {
900 return;
901 }
902 // Prepare dominator-based dynamic elimination.
903 if (first_index_bounds_check_map_.find(array_length->GetId()) ==
904 first_index_bounds_check_map_.end()) {
905 // Remember the first bounds check against each array_length. That bounds check
906 // instruction has an associated HEnvironment where we may add an HDeoptimize
907 // to eliminate subsequent bounds checks against the same array_length.
908 first_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
909 }
Aart Bik4a342772015-11-30 10:17:46 -0800910 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700911 }
912
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100913 static bool HasSameInputAtBackEdges(HPhi* phi) {
914 DCHECK(phi->IsLoopHeaderPhi());
Vladimir Marko372f10e2016-05-17 16:30:10 +0100915 auto&& inputs = phi->GetInputs();
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100916 // Start with input 1. Input 0 is from the incoming block.
Vladimir Marko372f10e2016-05-17 16:30:10 +0100917 HInstruction* input1 = inputs[1];
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100918 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100919 *phi->GetBlock()->GetPredecessors()[1]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100920 for (size_t i = 2; i < inputs.size(); ++i) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100921 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Markoec7802a2015-10-01 20:57:57 +0100922 *phi->GetBlock()->GetPredecessors()[i]));
Vladimir Marko372f10e2016-05-17 16:30:10 +0100923 if (input1 != inputs[i]) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100924 return false;
925 }
926 }
927 return true;
928 }
929
Aart Bik4a342772015-11-30 10:17:46 -0800930 void VisitPhi(HPhi* phi) OVERRIDE {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100931 if (phi->IsLoopHeaderPhi()
932 && (phi->GetType() == Primitive::kPrimInt)
933 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700934 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -0800935 HInstruction *left;
936 int32_t increment;
937 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
938 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700939 HInstruction* initial_value = phi->InputAt(0);
940 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -0800941 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700942 // Add constant 0. It's really a fixed value.
943 range = new (GetGraph()->GetArena()) ValueRange(
944 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -0800945 ValueBound(initial_value, 0),
946 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -0700947 } else {
948 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800949 bool found;
950 ValueBound bound = ValueBound::DetectValueBoundFromValue(
951 initial_value, &found);
952 if (!found) {
953 // No constant or array.length+c bound found.
954 // For i=j, we can still use j's upper bound as i's upper bound.
955 // Same for lower.
956 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
957 if (initial_range != nullptr) {
958 bound = increment > 0 ? initial_range->GetLower() :
959 initial_range->GetUpper();
960 } else {
961 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
962 }
963 }
964 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -0700965 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700966 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -0700967 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -0800968 increment,
969 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -0700970 }
Aart Bik1d239822016-02-09 14:26:34 -0800971 AssignRange(phi->GetBlock(), phi, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700972 }
973 }
974 }
975 }
976
Aart Bik4a342772015-11-30 10:17:46 -0800977 void VisitIf(HIf* instruction) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700978 if (instruction->InputAt(0)->IsCondition()) {
979 HCondition* cond = instruction->InputAt(0)->AsCondition();
Aart Bika2106892016-05-04 14:00:55 -0700980 HandleIf(instruction, cond->GetLeft(), cond->GetRight(), cond->GetCondition());
Mingyao Yangf384f882014-10-22 16:08:18 -0700981 }
982 }
983
Aart Bik4a342772015-11-30 10:17:46 -0800984 void VisitAdd(HAdd* add) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700985 HInstruction* right = add->GetRight();
986 if (right->IsIntConstant()) {
987 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
988 if (left_range == nullptr) {
989 return;
990 }
991 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
992 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -0800993 AssignRange(add->GetBlock(), add, range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700994 }
995 }
996 }
997
Aart Bik4a342772015-11-30 10:17:46 -0800998 void VisitSub(HSub* sub) OVERRIDE {
Mingyao Yangf384f882014-10-22 16:08:18 -0700999 HInstruction* left = sub->GetLeft();
1000 HInstruction* right = sub->GetRight();
1001 if (right->IsIntConstant()) {
1002 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1003 if (left_range == nullptr) {
1004 return;
1005 }
1006 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1007 if (range != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001008 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001009 return;
1010 }
1011 }
1012
1013 // Here we are interested in the typical triangular case of nested loops,
1014 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1015 // 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 -08001016
1017 // Try to handle (array.length - i) or (array.length + c - i) format.
1018 HInstruction* left_of_left; // left input of left.
1019 int32_t right_const = 0;
1020 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1021 left = left_of_left;
1022 }
1023 // The value of left input of the sub equals (left + right_const).
1024
Mingyao Yangf384f882014-10-22 16:08:18 -07001025 if (left->IsArrayLength()) {
1026 HInstruction* array_length = left->AsArrayLength();
1027 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1028 if (right_range != nullptr) {
1029 ValueBound lower = right_range->GetLower();
1030 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001031 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001032 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001033 // Make sure it's the same array.
1034 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001035 int32_t c0 = right_const;
1036 int32_t c1 = lower.GetConstant();
1037 int32_t c2 = upper.GetConstant();
1038 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1039 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1040 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1041 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1042 if ((c0 - c1) <= 0) {
1043 // array.length + (c0 - c1) won't overflow/underflow.
1044 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1045 GetGraph()->GetArena(),
1046 ValueBound(nullptr, right_const - upper.GetConstant()),
1047 ValueBound(array_length, right_const - lower.GetConstant()));
Aart Bik1d239822016-02-09 14:26:34 -08001048 AssignRange(sub->GetBlock(), sub, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001049 }
1050 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001051 }
1052 }
1053 }
1054 }
1055 }
1056
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001057 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1058 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1059 HInstruction* right = instruction->GetRight();
1060 int32_t right_const;
1061 if (right->IsIntConstant()) {
1062 right_const = right->AsIntConstant()->GetValue();
1063 // Detect division by two or more.
1064 if ((instruction->IsDiv() && right_const <= 1) ||
1065 (instruction->IsShr() && right_const < 1) ||
1066 (instruction->IsUShr() && right_const < 1)) {
1067 return;
1068 }
1069 } else {
1070 return;
1071 }
1072
1073 // Try to handle array.length/2 or (array.length-1)/2 format.
1074 HInstruction* left = instruction->GetLeft();
1075 HInstruction* left_of_left; // left input of left.
1076 int32_t c = 0;
1077 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1078 left = left_of_left;
1079 }
1080 // The value of left input of instruction equals (left + c).
1081
1082 // (array_length + 1) or smaller divided by two or more
Aart Bikaab5b752015-09-23 11:18:57 -07001083 // always generate a value in [Min(), array_length].
1084 // This is true even if array_length is Max().
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001085 if (left->IsArrayLength() && c <= 1) {
1086 if (instruction->IsUShr() && c < 0) {
1087 // Make sure for unsigned shift, left side is not negative.
1088 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1089 // than array_length.
1090 return;
1091 }
1092 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1093 GetGraph()->GetArena(),
Aart Bikaab5b752015-09-23 11:18:57 -07001094 ValueBound(nullptr, std::numeric_limits<int32_t>::min()),
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001095 ValueBound(left, 0));
Aart Bik1d239822016-02-09 14:26:34 -08001096 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001097 }
1098 }
1099
Aart Bik4a342772015-11-30 10:17:46 -08001100 void VisitDiv(HDiv* div) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001101 FindAndHandlePartialArrayLength(div);
1102 }
1103
Aart Bik4a342772015-11-30 10:17:46 -08001104 void VisitShr(HShr* shr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001105 FindAndHandlePartialArrayLength(shr);
1106 }
1107
Aart Bik4a342772015-11-30 10:17:46 -08001108 void VisitUShr(HUShr* ushr) OVERRIDE {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001109 FindAndHandlePartialArrayLength(ushr);
1110 }
1111
Aart Bik4a342772015-11-30 10:17:46 -08001112 void VisitAnd(HAnd* instruction) OVERRIDE {
Mingyao Yang4559f002015-02-27 14:43:53 -08001113 if (instruction->GetRight()->IsIntConstant()) {
1114 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1115 if (constant > 0) {
1116 // constant serves as a mask so any number masked with it
1117 // gets a [0, constant] value range.
1118 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1119 GetGraph()->GetArena(),
1120 ValueBound(nullptr, 0),
1121 ValueBound(nullptr, constant));
Aart Bik1d239822016-02-09 14:26:34 -08001122 AssignRange(instruction->GetBlock(), instruction, range);
Mingyao Yang4559f002015-02-27 14:43:53 -08001123 }
1124 }
1125 }
1126
Aart Bik4a342772015-11-30 10:17:46 -08001127 void VisitNewArray(HNewArray* new_array) OVERRIDE {
Mingyao Yang0304e182015-01-30 16:41:29 -08001128 HInstruction* len = new_array->InputAt(0);
1129 if (!len->IsIntConstant()) {
1130 HInstruction *left;
1131 int32_t right_const;
1132 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1133 // (left + right_const) is used as size to new the array.
1134 // We record "-right_const <= left <= new_array - right_const";
1135 ValueBound lower = ValueBound(nullptr, -right_const);
1136 // We use new_array for the bound instead of new_array.length,
1137 // which isn't available as an instruction yet. new_array will
1138 // be treated the same as new_array.length when it's used in a ValueBound.
1139 ValueBound upper = ValueBound(new_array, -right_const);
1140 ValueRange* range = new (GetGraph()->GetArena())
1141 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001142 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1143 if (existing_range != nullptr) {
1144 range = existing_range->Narrow(range);
1145 }
Aart Bik1d239822016-02-09 14:26:34 -08001146 AssignRange(new_array->GetBlock(), left, range);
Mingyao Yang0304e182015-01-30 16:41:29 -08001147 }
1148 }
1149 }
1150
Aart Bik4a342772015-11-30 10:17:46 -08001151 /**
1152 * After null/bounds checks are eliminated, some invariant array references
1153 * may be exposed underneath which can be hoisted out of the loop to the
1154 * preheader or, in combination with dynamic bce, the deoptimization block.
1155 *
1156 * for (int i = 0; i < n; i++) {
1157 * <-------+
1158 * for (int j = 0; j < n; j++) |
1159 * a[i][j] = 0; --a[i]--+
1160 * }
1161 *
Aart Bik1d239822016-02-09 14:26:34 -08001162 * Note: this optimization is no longer applied after dominator-based dynamic deoptimization
1163 * has occurred (see AddCompareWithDeoptimization()), since in those cases it would be
1164 * unsafe to hoist array references across their deoptimization instruction inside a loop.
Aart Bik4a342772015-11-30 10:17:46 -08001165 */
1166 void VisitArrayGet(HArrayGet* array_get) OVERRIDE {
Aart Bik1d239822016-02-09 14:26:34 -08001167 if (!has_dom_based_dynamic_bce_ && array_get->IsInLoop()) {
Aart Bik4a342772015-11-30 10:17:46 -08001168 HLoopInformation* loop = array_get->GetBlock()->GetLoopInformation();
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001169 if (loop->IsDefinedOutOfTheLoop(array_get->InputAt(0)) &&
1170 loop->IsDefinedOutOfTheLoop(array_get->InputAt(1))) {
Aart Bik4a342772015-11-30 10:17:46 -08001171 SideEffects loop_effects = side_effects_.GetLoopEffects(loop->GetHeader());
1172 if (!array_get->GetSideEffects().MayDependOn(loop_effects)) {
Anton Shaminf89381f2016-05-16 16:44:13 +06001173 // We can hoist ArrayGet only if its execution is guaranteed on every iteration.
1174 // In other words only if array_get_bb dominates all back branches.
1175 if (loop->DominatesAllBackEdges(array_get->GetBlock())) {
1176 HoistToPreHeaderOrDeoptBlock(loop, array_get);
1177 }
Aart Bik4a342772015-11-30 10:17:46 -08001178 }
1179 }
1180 }
1181 }
1182
Aart Bik1d239822016-02-09 14:26:34 -08001183 // Perform dominator-based dynamic elimination on suitable set of bounds checks.
1184 void AddCompareWithDeoptimization(HBasicBlock* block,
1185 HInstruction* array_length,
1186 HInstruction* base,
1187 int32_t min_c, int32_t max_c) {
1188 HBoundsCheck* bounds_check =
1189 first_index_bounds_check_map_.Get(array_length->GetId())->AsBoundsCheck();
1190 // Construct deoptimization on single or double bounds on range [base-min_c,base+max_c],
1191 // for example either for a[0]..a[3] just 3 or for a[base-1]..a[base+3] both base-1
1192 // and base+3, since we made the assumption any in between value may occur too.
1193 static_assert(kMaxLengthForAddingDeoptimize < std::numeric_limits<int32_t>::max(),
1194 "Incorrect max length may be subject to arithmetic wrap-around");
1195 HInstruction* upper = GetGraph()->GetIntConstant(max_c);
1196 if (base == nullptr) {
1197 DCHECK_GE(min_c, 0);
1198 } else {
1199 HInstruction* lower = new (GetGraph()->GetArena())
1200 HAdd(Primitive::kPrimInt, base, GetGraph()->GetIntConstant(min_c));
1201 upper = new (GetGraph()->GetArena()) HAdd(Primitive::kPrimInt, base, upper);
1202 block->InsertInstructionBefore(lower, bounds_check);
1203 block->InsertInstructionBefore(upper, bounds_check);
1204 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAbove(lower, upper));
1205 }
1206 InsertDeoptInBlock(bounds_check, new (GetGraph()->GetArena()) HAboveOrEqual(upper, array_length));
1207 // Flag that this kind of deoptimization has occurred.
1208 has_dom_based_dynamic_bce_ = true;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001209 }
1210
Aart Bik1d239822016-02-09 14:26:34 -08001211 // Attempt dominator-based dynamic elimination on remaining candidates.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001212 void AddComparesWithDeoptimization(HBasicBlock* block) {
Vladimir Markoda571cb2016-02-15 17:54:56 +00001213 for (const auto& entry : first_index_bounds_check_map_) {
1214 HBoundsCheck* bounds_check = entry.second;
Aart Bik1d239822016-02-09 14:26:34 -08001215 HInstruction* index = bounds_check->InputAt(0);
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001216 HInstruction* array_length = bounds_check->InputAt(1);
1217 if (!array_length->IsArrayLength()) {
Aart Bik1d239822016-02-09 14:26:34 -08001218 continue; // disregard phis and constants
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001219 }
Aart Bik1ae88742016-03-14 14:11:26 -07001220 // Collect all bounds checks that are still there and that are related as "a[base + constant]"
Aart Bik1d239822016-02-09 14:26:34 -08001221 // for a base instruction (possibly absent) and various constants. Note that no attempt
1222 // is made to partition the set into matching subsets (viz. a[0], a[1] and a[base+1] and
1223 // a[base+2] are considered as one set).
1224 // TODO: would such a partitioning be worthwhile?
1225 ValueBound value = ValueBound::AsValueBound(index);
1226 HInstruction* base = value.GetInstruction();
1227 int32_t min_c = base == nullptr ? 0 : value.GetConstant();
1228 int32_t max_c = value.GetConstant();
1229 ArenaVector<HBoundsCheck*> candidates(
1230 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
1231 ArenaVector<HBoundsCheck*> standby(
1232 GetGraph()->GetArena()->Adapter(kArenaAllocBoundsCheckElimination));
Vladimir Marko46817b82016-03-29 12:21:58 +01001233 for (const HUseListNode<HInstruction*>& use : array_length->GetUses()) {
Aart Bik1d239822016-02-09 14:26:34 -08001234 // Another bounds check in same or dominated block?
Vladimir Marko46817b82016-03-29 12:21:58 +01001235 HInstruction* user = use.GetUser();
Aart Bik1d239822016-02-09 14:26:34 -08001236 HBasicBlock* other_block = user->GetBlock();
1237 if (user->IsBoundsCheck() && block->Dominates(other_block)) {
1238 HBoundsCheck* other_bounds_check = user->AsBoundsCheck();
1239 HInstruction* other_index = other_bounds_check->InputAt(0);
1240 HInstruction* other_array_length = other_bounds_check->InputAt(1);
1241 ValueBound other_value = ValueBound::AsValueBound(other_index);
1242 if (array_length == other_array_length && base == other_value.GetInstruction()) {
Aart Bik1ae88742016-03-14 14:11:26 -07001243 // Reject certain OOB if BoundsCheck(l, l) occurs on considered subset.
1244 if (array_length == other_index) {
1245 candidates.clear();
1246 standby.clear();
1247 break;
1248 }
Aart Bik1d239822016-02-09 14:26:34 -08001249 // Since a subsequent dominated block could be under a conditional, only accept
1250 // the other bounds check if it is in same block or both blocks dominate the exit.
1251 // TODO: we could improve this by testing proper post-dominance, or even if this
1252 // constant is seen along *all* conditional paths that follow.
1253 HBasicBlock* exit = GetGraph()->GetExitBlock();
1254 if (block == user->GetBlock() ||
1255 (block->Dominates(exit) && other_block->Dominates(exit))) {
Aart Bik1ae88742016-03-14 14:11:26 -07001256 int32_t other_c = other_value.GetConstant();
Aart Bik1d239822016-02-09 14:26:34 -08001257 min_c = std::min(min_c, other_c);
1258 max_c = std::max(max_c, other_c);
1259 candidates.push_back(other_bounds_check);
1260 } else {
1261 // Add this candidate later only if it falls into the range.
1262 standby.push_back(other_bounds_check);
1263 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001264 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001265 }
1266 }
Aart Bik1d239822016-02-09 14:26:34 -08001267 // Add standby candidates that fall in selected range.
Vladimir Markoda571cb2016-02-15 17:54:56 +00001268 for (HBoundsCheck* other_bounds_check : standby) {
Aart Bik1d239822016-02-09 14:26:34 -08001269 HInstruction* other_index = other_bounds_check->InputAt(0);
1270 int32_t other_c = ValueBound::AsValueBound(other_index).GetConstant();
1271 if (min_c <= other_c && other_c <= max_c) {
1272 candidates.push_back(other_bounds_check);
1273 }
1274 }
1275 // Perform dominator-based deoptimization if it seems profitable. Note that we reject cases
1276 // where the distance min_c:max_c range gets close to the maximum possible array length,
1277 // since those cases are likely to always deopt (such situations do not necessarily go
1278 // OOB, though, since the programmer could rely on wrap-around from max to min).
1279 size_t threshold = kThresholdForAddingDeoptimize + (base == nullptr ? 0 : 1); // extra test?
1280 uint32_t distance = static_cast<uint32_t>(max_c) - static_cast<uint32_t>(min_c);
1281 if (candidates.size() >= threshold &&
1282 (base != nullptr || min_c >= 0) && // reject certain OOB
1283 distance <= kMaxLengthForAddingDeoptimize) { // reject likely/certain deopt
1284 AddCompareWithDeoptimization(block, array_length, base, min_c, max_c);
Vladimir Markoda571cb2016-02-15 17:54:56 +00001285 for (HInstruction* other_bounds_check : candidates) {
Aart Bik1ae88742016-03-14 14:11:26 -07001286 // Only replace if still in the graph. This avoids visiting the same
1287 // bounds check twice if it occurred multiple times in the use list.
1288 if (other_bounds_check->IsInBlock()) {
1289 ReplaceInstruction(other_bounds_check, other_bounds_check->InputAt(0));
1290 }
Aart Bik1d239822016-02-09 14:26:34 -08001291 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001292 }
1293 }
1294 }
1295
Aart Bik4a342772015-11-30 10:17:46 -08001296 /**
1297 * Returns true if static range analysis based on induction variables can determine the bounds
1298 * check on the given array range is always satisfied with the computed index range. The output
1299 * parameter try_dynamic_bce is set to false if OOB is certain.
1300 */
1301 bool InductionRangeFitsIn(ValueRange* array_range,
Aart Bik52be7e72016-06-23 11:20:41 -07001302 HBoundsCheck* context,
Aart Bik4a342772015-11-30 10:17:46 -08001303 bool* try_dynamic_bce) {
1304 InductionVarRange::Value v1;
1305 InductionVarRange::Value v2;
1306 bool needs_finite_test = false;
Aart Bik52be7e72016-06-23 11:20:41 -07001307 HInstruction* index = context->InputAt(0);
1308 HInstruction* hint = ValueBound::HuntForDeclaration(context->InputAt(1));
1309 if (induction_range_.GetInductionRange(context, index, hint, &v1, &v2, &needs_finite_test)) {
1310 if (v1.is_known && (v1.a_constant == 0 || v1.a_constant == 1) &&
1311 v2.is_known && (v2.a_constant == 0 || v2.a_constant == 1)) {
1312 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1313 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1314 ValueRange index_range(GetGraph()->GetArena(),
1315 ValueBound(v1.instruction, v1.b_constant),
1316 ValueBound(v2.instruction, v2.b_constant));
1317 // If analysis reveals a certain OOB, disable dynamic BCE. Otherwise,
1318 // use analysis for static bce only if loop is finite.
1319 if (index_range.GetLower().LessThan(array_range->GetLower()) ||
1320 index_range.GetUpper().GreaterThan(array_range->GetUpper())) {
1321 *try_dynamic_bce = false;
1322 } else if (!needs_finite_test && index_range.FitsIn(array_range)) {
1323 return true;
Aart Bikb738d4f2015-12-03 11:23:35 -08001324 }
Aart Bik52be7e72016-06-23 11:20:41 -07001325 }
Aart Bik1fc3afb2016-02-02 13:26:16 -08001326 }
Aart Bik4a342772015-11-30 10:17:46 -08001327 return false;
1328 }
1329
1330 /**
1331 * When the compiler fails to remove a bounds check statically, we try to remove the bounds
1332 * check dynamically by adding runtime tests that trigger a deoptimization in case bounds
1333 * will go out of range (we want to be rather certain of that given the slowdown of
1334 * deoptimization). If no deoptimization occurs, the loop is executed with all corresponding
1335 * bounds checks and related null checks removed.
1336 */
Aart Bik1d239822016-02-09 14:26:34 -08001337 bool TryDynamicBCE(HBoundsCheck* instruction) {
Aart Bik4a342772015-11-30 10:17:46 -08001338 HLoopInformation* loop = instruction->GetBlock()->GetLoopInformation();
1339 HInstruction* index = instruction->InputAt(0);
1340 HInstruction* length = instruction->InputAt(1);
1341 // If dynamic bounds check elimination seems profitable and is possible, then proceed.
1342 bool needs_finite_test = false;
1343 bool needs_taken_test = false;
1344 if (DynamicBCESeemsProfitable(loop, instruction->GetBlock()) &&
1345 induction_range_.CanGenerateCode(
1346 instruction, index, &needs_finite_test, &needs_taken_test) &&
Aart Bik591ad292016-03-01 10:39:25 -08001347 CanHandleInfiniteLoop(loop, instruction, index, needs_finite_test) &&
Aart Bik4a342772015-11-30 10:17:46 -08001348 CanHandleLength(loop, length, needs_taken_test)) { // do this test last (may code gen)
1349 HInstruction* lower = nullptr;
1350 HInstruction* upper = nullptr;
1351 // Generate the following unsigned comparisons
1352 // if (lower > upper) deoptimize;
1353 // if (upper >= length) deoptimize;
1354 // or, for a non-induction index, just the unsigned comparison on its 'upper' value
1355 // if (upper >= length) deoptimize;
1356 // as runtime test. By restricting dynamic bce to unit strides (with a maximum of 32-bit
1357 // iterations) and by not combining access (e.g. a[i], a[i-3], a[i+5] etc.), these tests
1358 // correctly guard against any possible OOB (including arithmetic wrap-around cases).
Aart Bik55b14df2016-01-12 14:12:47 -08001359 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1360 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001361 induction_range_.GenerateRangeCode(instruction, index, GetGraph(), block, &lower, &upper);
1362 if (lower != nullptr) {
Aart Bik1d239822016-02-09 14:26:34 -08001363 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAbove(lower, upper));
Aart Bik4a342772015-11-30 10:17:46 -08001364 }
Aart Bik1d239822016-02-09 14:26:34 -08001365 InsertDeoptInLoop(loop, block, new (GetGraph()->GetArena()) HAboveOrEqual(upper, length));
Aart Bik4a342772015-11-30 10:17:46 -08001366 ReplaceInstruction(instruction, index);
Aart Bik1d239822016-02-09 14:26:34 -08001367 return true;
Aart Bik4a342772015-11-30 10:17:46 -08001368 }
Aart Bik1d239822016-02-09 14:26:34 -08001369 return false;
Aart Bik4a342772015-11-30 10:17:46 -08001370 }
1371
1372 /**
1373 * Returns true if heuristics indicate that dynamic bce may be profitable.
1374 */
1375 bool DynamicBCESeemsProfitable(HLoopInformation* loop, HBasicBlock* block) {
1376 if (loop != nullptr) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001377 // The loop preheader of an irreducible loop does not dominate all the blocks in
1378 // the loop. We would need to find the common dominator of all blocks in the loop.
1379 if (loop->IsIrreducible()) {
1380 return false;
1381 }
Nicolas Geoffray93a18c52016-04-22 13:16:14 +01001382 // We should never deoptimize from an osr method, otherwise we might wrongly optimize
1383 // code dominated by the deoptimization.
1384 if (GetGraph()->IsCompilingOsr()) {
1385 return false;
1386 }
Aart Bik4a342772015-11-30 10:17:46 -08001387 // A try boundary preheader is hard to handle.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +00001388 // TODO: remove this restriction.
Aart Bik4a342772015-11-30 10:17:46 -08001389 if (loop->GetPreHeader()->GetLastInstruction()->IsTryBoundary()) {
1390 return false;
1391 }
1392 // Does loop have early-exits? If so, the full range may not be covered by the loop
1393 // at runtime and testing the range may apply deoptimization unnecessarily.
1394 if (IsEarlyExitLoop(loop)) {
1395 return false;
1396 }
1397 // Does the current basic block dominate all back edges? If not,
1398 // don't apply dynamic bce to something that may not be executed.
Anton Shaminf89381f2016-05-16 16:44:13 +06001399 return loop->DominatesAllBackEdges(block);
Aart Bik4a342772015-11-30 10:17:46 -08001400 }
1401 return false;
1402 }
1403
1404 /**
1405 * Returns true if the loop has early exits, which implies it may not cover
1406 * the full range computed by range analysis based on induction variables.
1407 */
1408 bool IsEarlyExitLoop(HLoopInformation* loop) {
1409 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1410 // If loop has been analyzed earlier for early-exit, don't repeat the analysis.
1411 auto it = early_exit_loop_.find(loop_id);
1412 if (it != early_exit_loop_.end()) {
1413 return it->second;
1414 }
1415 // First time early-exit analysis for this loop. Since analysis requires scanning
1416 // the full loop-body, results of the analysis is stored for subsequent queries.
1417 HBlocksInLoopReversePostOrderIterator it_loop(*loop);
1418 for (it_loop.Advance(); !it_loop.Done(); it_loop.Advance()) {
1419 for (HBasicBlock* successor : it_loop.Current()->GetSuccessors()) {
1420 if (!loop->Contains(*successor)) {
1421 early_exit_loop_.Put(loop_id, true);
1422 return true;
1423 }
1424 }
1425 }
1426 early_exit_loop_.Put(loop_id, false);
1427 return false;
1428 }
1429
1430 /**
1431 * Returns true if the array length is already loop invariant, or can be made so
1432 * by handling the null check under the hood of the array length operation.
1433 */
1434 bool CanHandleLength(HLoopInformation* loop, HInstruction* length, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001435 if (loop->IsDefinedOutOfTheLoop(length)) {
Aart Bik4a342772015-11-30 10:17:46 -08001436 return true;
1437 } else if (length->IsArrayLength() && length->GetBlock()->GetLoopInformation() == loop) {
1438 if (CanHandleNullCheck(loop, length->InputAt(0), needs_taken_test)) {
Aart Bik55b14df2016-01-12 14:12:47 -08001439 HoistToPreHeaderOrDeoptBlock(loop, length);
Aart Bik4a342772015-11-30 10:17:46 -08001440 return true;
1441 }
1442 }
1443 return false;
1444 }
1445
1446 /**
1447 * Returns true if the null check is already loop invariant, or can be made so
1448 * by generating a deoptimization test.
1449 */
1450 bool CanHandleNullCheck(HLoopInformation* loop, HInstruction* check, bool needs_taken_test) {
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001451 if (loop->IsDefinedOutOfTheLoop(check)) {
Aart Bik4a342772015-11-30 10:17:46 -08001452 return true;
1453 } else if (check->IsNullCheck() && check->GetBlock()->GetLoopInformation() == loop) {
1454 HInstruction* array = check->InputAt(0);
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001455 if (loop->IsDefinedOutOfTheLoop(array)) {
Aart Bik4a342772015-11-30 10:17:46 -08001456 // Generate: if (array == null) deoptimize;
Aart Bik55b14df2016-01-12 14:12:47 -08001457 TransformLoopForDeoptimizationIfNeeded(loop, needs_taken_test);
1458 HBasicBlock* block = GetPreHeader(loop, check);
Aart Bik4a342772015-11-30 10:17:46 -08001459 HInstruction* cond =
1460 new (GetGraph()->GetArena()) HEqual(array, GetGraph()->GetNullConstant());
Aart Bik1d239822016-02-09 14:26:34 -08001461 InsertDeoptInLoop(loop, block, cond);
Aart Bik4a342772015-11-30 10:17:46 -08001462 ReplaceInstruction(check, array);
1463 return true;
1464 }
1465 }
1466 return false;
1467 }
1468
1469 /**
1470 * Returns true if compiler can apply dynamic bce to loops that may be infinite
1471 * (e.g. for (int i = 0; i <= U; i++) with U = MAX_INT), which would invalidate
1472 * the range analysis evaluation code by "overshooting" the computed range.
1473 * Since deoptimization would be a bad choice, and there is no other version
1474 * of the loop to use, dynamic bce in such cases is only allowed if other tests
1475 * ensure the loop is finite.
1476 */
1477 bool CanHandleInfiniteLoop(
Aart Bik591ad292016-03-01 10:39:25 -08001478 HLoopInformation* loop, HBoundsCheck* check, HInstruction* index, bool needs_infinite_test) {
Aart Bik4a342772015-11-30 10:17:46 -08001479 if (needs_infinite_test) {
1480 // If we already forced the loop to be finite, allow directly.
1481 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
1482 if (finite_loop_.find(loop_id) != finite_loop_.end()) {
1483 return true;
1484 }
1485 // Otherwise, allow dynamic bce if the index (which is necessarily an induction at
1486 // this point) is the direct loop index (viz. a[i]), since then the runtime tests
1487 // ensure upper bound cannot cause an infinite loop.
1488 HInstruction* control = loop->GetHeader()->GetLastInstruction();
1489 if (control->IsIf()) {
1490 HInstruction* if_expr = control->AsIf()->InputAt(0);
1491 if (if_expr->IsCondition()) {
1492 HCondition* condition = if_expr->AsCondition();
1493 if (index == condition->InputAt(0) ||
1494 index == condition->InputAt(1)) {
1495 finite_loop_.insert(loop_id);
1496 return true;
1497 }
1498 }
1499 }
Aart Bik591ad292016-03-01 10:39:25 -08001500 // If bounds check made it this far, it is worthwhile to check later if
1501 // the loop was forced finite by another candidate.
Vladimir Markob75878e2016-03-14 13:56:02 +00001502 if (record_dynamic_bce_standby_) {
1503 dynamic_bce_standby_.push_back(check);
1504 }
Aart Bik4a342772015-11-30 10:17:46 -08001505 return false;
1506 }
1507 return true;
1508 }
1509
Aart Bik55b14df2016-01-12 14:12:47 -08001510 /**
1511 * Returns appropriate preheader for the loop, depending on whether the
1512 * instruction appears in the loop header or proper loop-body.
1513 */
1514 HBasicBlock* GetPreHeader(HLoopInformation* loop, HInstruction* instruction) {
1515 // Use preheader unless there is an earlier generated deoptimization block since
1516 // hoisted expressions may depend on and/or used by the deoptimization tests.
1517 HBasicBlock* header = loop->GetHeader();
1518 const uint32_t loop_id = header->GetBlockId();
1519 auto it = taken_test_loop_.find(loop_id);
1520 if (it != taken_test_loop_.end()) {
1521 HBasicBlock* block = it->second;
1522 // If always taken, keep it that way by returning the original preheader,
1523 // which can be found by following the predecessor of the true-block twice.
1524 if (instruction->GetBlock() == header) {
1525 return block->GetSinglePredecessor()->GetSinglePredecessor();
1526 }
1527 return block;
1528 }
1529 return loop->GetPreHeader();
1530 }
1531
Aart Bik1d239822016-02-09 14:26:34 -08001532 /** Inserts a deoptimization test in a loop preheader. */
1533 void InsertDeoptInLoop(HLoopInformation* loop, HBasicBlock* block, HInstruction* condition) {
Aart Bik4a342772015-11-30 10:17:46 -08001534 HInstruction* suspend = loop->GetSuspendCheck();
1535 block->InsertInstructionBefore(condition, block->GetLastInstruction());
1536 HDeoptimize* deoptimize =
1537 new (GetGraph()->GetArena()) HDeoptimize(condition, suspend->GetDexPc());
1538 block->InsertInstructionBefore(deoptimize, block->GetLastInstruction());
1539 if (suspend->HasEnvironment()) {
1540 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
1541 suspend->GetEnvironment(), loop->GetHeader());
1542 }
1543 }
1544
Aart Bik1d239822016-02-09 14:26:34 -08001545 /** Inserts a deoptimization test right before a bounds check. */
1546 void InsertDeoptInBlock(HBoundsCheck* bounds_check, HInstruction* condition) {
1547 HBasicBlock* block = bounds_check->GetBlock();
1548 block->InsertInstructionBefore(condition, bounds_check);
1549 HDeoptimize* deoptimize =
1550 new (GetGraph()->GetArena()) HDeoptimize(condition, bounds_check->GetDexPc());
1551 block->InsertInstructionBefore(deoptimize, bounds_check);
1552 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
1553 }
1554
Aart Bik4a342772015-11-30 10:17:46 -08001555 /** Hoists instruction out of the loop to preheader or deoptimization block. */
Aart Bik55b14df2016-01-12 14:12:47 -08001556 void HoistToPreHeaderOrDeoptBlock(HLoopInformation* loop, HInstruction* instruction) {
1557 HBasicBlock* block = GetPreHeader(loop, instruction);
Aart Bik4a342772015-11-30 10:17:46 -08001558 DCHECK(!instruction->HasEnvironment());
1559 instruction->MoveBefore(block->GetLastInstruction());
1560 }
1561
1562 /**
Aart Bik55b14df2016-01-12 14:12:47 -08001563 * Adds a new taken-test structure to a loop if needed and not already done.
Aart Bik4a342772015-11-30 10:17:46 -08001564 * The taken-test protects range analysis evaluation code to avoid any
1565 * deoptimization caused by incorrect trip-count evaluation in non-taken loops.
1566 *
Aart Bik4a342772015-11-30 10:17:46 -08001567 * old_preheader
1568 * |
1569 * if_block <- taken-test protects deoptimization block
1570 * / \
1571 * true_block false_block <- deoptimizations/invariants are placed in true_block
1572 * \ /
1573 * new_preheader <- may require phi nodes to preserve SSA structure
1574 * |
1575 * header
1576 *
1577 * For example, this loop:
1578 *
1579 * for (int i = lower; i < upper; i++) {
1580 * array[i] = 0;
1581 * }
1582 *
1583 * will be transformed to:
1584 *
1585 * if (lower < upper) {
1586 * if (array == null) deoptimize;
1587 * array_length = array.length;
1588 * if (lower > upper) deoptimize; // unsigned
1589 * if (upper >= array_length) deoptimize; // unsigned
1590 * } else {
1591 * array_length = 0;
1592 * }
1593 * for (int i = lower; i < upper; i++) {
1594 * // Loop without null check and bounds check, and any array.length replaced with array_length.
1595 * array[i] = 0;
1596 * }
1597 */
Aart Bik55b14df2016-01-12 14:12:47 -08001598 void TransformLoopForDeoptimizationIfNeeded(HLoopInformation* loop, bool needs_taken_test) {
1599 // Not needed (can use preheader) or already done (can reuse)?
Aart Bik4a342772015-11-30 10:17:46 -08001600 const uint32_t loop_id = loop->GetHeader()->GetBlockId();
Aart Bik55b14df2016-01-12 14:12:47 -08001601 if (!needs_taken_test || taken_test_loop_.find(loop_id) != taken_test_loop_.end()) {
1602 return;
Aart Bik4a342772015-11-30 10:17:46 -08001603 }
1604
1605 // Generate top test structure.
1606 HBasicBlock* header = loop->GetHeader();
1607 GetGraph()->TransformLoopHeaderForBCE(header);
1608 HBasicBlock* new_preheader = loop->GetPreHeader();
1609 HBasicBlock* if_block = new_preheader->GetDominator();
1610 HBasicBlock* true_block = if_block->GetSuccessors()[0]; // True successor.
1611 HBasicBlock* false_block = if_block->GetSuccessors()[1]; // False successor.
1612
1613 // Goto instructions.
1614 true_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1615 false_block->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1616 new_preheader->AddInstruction(new (GetGraph()->GetArena()) HGoto());
1617
1618 // Insert the taken-test to see if the loop body is entered. If the
1619 // loop isn't entered at all, it jumps around the deoptimization block.
1620 if_block->AddInstruction(new (GetGraph()->GetArena()) HGoto()); // placeholder
1621 HInstruction* condition = nullptr;
1622 induction_range_.GenerateTakenTest(header->GetLastInstruction(),
1623 GetGraph(),
1624 if_block,
1625 &condition);
1626 DCHECK(condition != nullptr);
1627 if_block->RemoveInstruction(if_block->GetLastInstruction());
1628 if_block->AddInstruction(new (GetGraph()->GetArena()) HIf(condition));
1629
1630 taken_test_loop_.Put(loop_id, true_block);
Aart Bik4a342772015-11-30 10:17:46 -08001631 }
1632
1633 /**
1634 * Inserts phi nodes that preserve SSA structure in generated top test structures.
1635 * All uses of instructions in the deoptimization block that reach the loop need
1636 * a phi node in the new loop preheader to fix the dominance relation.
1637 *
1638 * Example:
1639 * if_block
1640 * / \
1641 * x_0 = .. false_block
1642 * \ /
1643 * x_1 = phi(x_0, null) <- synthetic phi
1644 * |
Aart Bik55b14df2016-01-12 14:12:47 -08001645 * new_preheader
Aart Bik4a342772015-11-30 10:17:46 -08001646 */
1647 void InsertPhiNodes() {
1648 // Scan all new deoptimization blocks.
1649 for (auto it1 = taken_test_loop_.begin(); it1 != taken_test_loop_.end(); ++it1) {
1650 HBasicBlock* true_block = it1->second;
1651 HBasicBlock* new_preheader = true_block->GetSingleSuccessor();
1652 // Scan all instructions in a new deoptimization block.
1653 for (HInstructionIterator it(true_block->GetInstructions()); !it.Done(); it.Advance()) {
1654 HInstruction* instruction = it.Current();
1655 Primitive::Type type = instruction->GetType();
1656 HPhi* phi = nullptr;
1657 // Scan all uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001658 const HUseList<HInstruction*>& uses = instruction->GetUses();
1659 for (auto it2 = uses.begin(), end2 = uses.end(); it2 != end2; /* ++it2 below */) {
1660 HInstruction* user = it2->GetUser();
1661 size_t index = it2->GetIndex();
1662 // Increment `it2` now because `*it2` may disappear thanks to user->ReplaceInput().
1663 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001664 if (user->GetBlock() != true_block) {
1665 if (phi == nullptr) {
1666 phi = NewPhi(new_preheader, instruction, type);
1667 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001668 user->ReplaceInput(phi, index); // Removes the use node from the list.
Aart Bik4a342772015-11-30 10:17:46 -08001669 }
1670 }
1671 // Scan all environment uses of an instruction and replace each later use with a phi node.
Vladimir Marko46817b82016-03-29 12:21:58 +01001672 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
1673 for (auto it2 = env_uses.begin(), end2 = env_uses.end(); it2 != end2; /* ++it2 below */) {
1674 HEnvironment* user = it2->GetUser();
1675 size_t index = it2->GetIndex();
1676 // Increment `it2` now because `*it2` may disappear thanks to user->RemoveAsUserOfInput().
1677 ++it2;
Aart Bik4a342772015-11-30 10:17:46 -08001678 if (user->GetHolder()->GetBlock() != true_block) {
1679 if (phi == nullptr) {
1680 phi = NewPhi(new_preheader, instruction, type);
1681 }
Vladimir Marko46817b82016-03-29 12:21:58 +01001682 user->RemoveAsUserOfInput(index);
1683 user->SetRawEnvAt(index, phi);
1684 phi->AddEnvUseAt(user, index);
Aart Bik4a342772015-11-30 10:17:46 -08001685 }
1686 }
1687 }
1688 }
1689 }
1690
1691 /**
1692 * Construct a phi(instruction, 0) in the new preheader to fix the dominance relation.
1693 * These are synthetic phi nodes without a virtual register.
1694 */
1695 HPhi* NewPhi(HBasicBlock* new_preheader,
1696 HInstruction* instruction,
1697 Primitive::Type type) {
1698 HGraph* graph = GetGraph();
1699 HInstruction* zero;
1700 switch (type) {
David Brazdil4833f5a2015-12-16 10:37:39 +00001701 case Primitive::kPrimNot: zero = graph->GetNullConstant(); break;
1702 case Primitive::kPrimFloat: zero = graph->GetFloatConstant(0); break;
1703 case Primitive::kPrimDouble: zero = graph->GetDoubleConstant(0); break;
Aart Bik4a342772015-11-30 10:17:46 -08001704 default: zero = graph->GetConstant(type, 0); break;
1705 }
1706 HPhi* phi = new (graph->GetArena())
1707 HPhi(graph->GetArena(), kNoRegNumber, /*number_of_inputs*/ 2, HPhi::ToPhiType(type));
1708 phi->SetRawInputAt(0, instruction);
1709 phi->SetRawInputAt(1, zero);
David Brazdil4833f5a2015-12-16 10:37:39 +00001710 if (type == Primitive::kPrimNot) {
1711 phi->SetReferenceTypeInfo(instruction->GetReferenceTypeInfo());
1712 }
Aart Bik4a342772015-11-30 10:17:46 -08001713 new_preheader->AddPhi(phi);
1714 return phi;
1715 }
1716
1717 /** Helper method to replace an instruction with another instruction. */
1718 static void ReplaceInstruction(HInstruction* instruction, HInstruction* replacement) {
1719 instruction->ReplaceWith(replacement);
1720 instruction->GetBlock()->RemoveInstruction(instruction);
1721 }
1722
1723 // A set of maps, one per basic block, from instruction to range.
Vladimir Marko5233f932015-09-29 19:01:15 +01001724 ArenaVector<ArenaSafeMap<int, ValueRange*>> maps_;
Mingyao Yangf384f882014-10-22 16:08:18 -07001725
Aart Bik1d239822016-02-09 14:26:34 -08001726 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction
1727 // in a block that checks an index against that HArrayLength.
1728 ArenaSafeMap<int, HBoundsCheck*> first_index_bounds_check_map_;
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001729
Aart Bik591ad292016-03-01 10:39:25 -08001730 // Stand by list for dynamic bce.
1731 ArenaVector<HBoundsCheck*> dynamic_bce_standby_;
Vladimir Markob75878e2016-03-14 13:56:02 +00001732 bool record_dynamic_bce_standby_;
Aart Bik591ad292016-03-01 10:39:25 -08001733
Aart Bik4a342772015-11-30 10:17:46 -08001734 // Early-exit loop bookkeeping.
1735 ArenaSafeMap<uint32_t, bool> early_exit_loop_;
1736
1737 // Taken-test loop bookkeeping.
1738 ArenaSafeMap<uint32_t, HBasicBlock*> taken_test_loop_;
1739
1740 // Finite loop bookkeeping.
1741 ArenaSet<uint32_t> finite_loop_;
1742
Aart Bik1d239822016-02-09 14:26:34 -08001743 // Flag that denotes whether dominator-based dynamic elimination has occurred.
1744 bool has_dom_based_dynamic_bce_;
Aart Bik4a342772015-11-30 10:17:46 -08001745
Mingyao Yang3584bce2015-05-19 16:01:59 -07001746 // Initial number of blocks.
Vladimir Markofa6b93c2015-09-15 10:15:55 +01001747 uint32_t initial_block_size_;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001748
Aart Bik4a342772015-11-30 10:17:46 -08001749 // Side effects.
1750 const SideEffectsAnalysis& side_effects_;
1751
Aart Bik22af3be2015-09-10 12:50:58 -07001752 // Range analysis based on induction variables.
1753 InductionVarRange induction_range_;
1754
Mingyao Yangf384f882014-10-22 16:08:18 -07001755 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1756};
1757
1758void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001759 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001760 return;
1761 }
1762
Mingyao Yangf384f882014-10-22 16:08:18 -07001763 // Reverse post order guarantees a node's dominators are visited first.
1764 // We want to visit in the dominator-based order since if a value is known to
1765 // be bounded by a range at one instruction, it must be true that all uses of
1766 // that value dominated by that instruction fits in that range. Range of that
1767 // value can be narrowed further down in the dominator tree.
Aart Bik4a342772015-11-30 10:17:46 -08001768 BCEVisitor visitor(graph_, side_effects_, induction_analysis_);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001769 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1770 HBasicBlock* current = it.Current();
Mingyao Yang3584bce2015-05-19 16:01:59 -07001771 if (visitor.IsAddedBlock(current)) {
1772 // Skip added blocks. Their effects are already taken care of.
1773 continue;
1774 }
1775 visitor.VisitBasicBlock(current);
Aart Bikb6347b72016-02-29 13:56:44 -08001776 // Skip forward to the current block in case new basic blocks were inserted
1777 // (which always appear earlier in reverse post order) to avoid visiting the
1778 // same basic block twice.
1779 for ( ; !it.Done() && it.Current() != current; it.Advance()) {
1780 }
Mingyao Yang3584bce2015-05-19 16:01:59 -07001781 }
Aart Bik4a342772015-11-30 10:17:46 -08001782
1783 // Perform cleanup.
1784 visitor.Finish();
Mingyao Yangf384f882014-10-22 16:08:18 -07001785}
1786
1787} // namespace art