blob: b2b54965b5fef1e1fa289c08e879dbf0342d200a [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
Mathieu Chartierb666f482015-02-18 14:33:14 -080017#include "base/arena_containers.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070018#include "bounds_check_elimination.h"
19#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070020
21namespace art {
22
23class MonotonicValueRange;
24
25/**
26 * A value bound is represented as a pair of value and constant,
27 * e.g. array.length - 1.
28 */
29class ValueBound : public ValueObject {
30 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080031 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080032 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080033 // Normalize ValueBound with constant instruction.
34 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080035 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080036 instruction_ = nullptr;
37 constant_ = instr_const + constant;
38 return;
39 }
Mingyao Yangf384f882014-10-22 16:08:18 -070040 }
Mingyao Yang64197522014-12-05 15:56:23 -080041 instruction_ = instruction;
42 constant_ = constant;
43 }
44
Mingyao Yang8c8bad82015-02-09 18:13:26 -080045 // Return whether (left + right) overflows or underflows.
46 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
47 if (right == 0) {
48 return false;
49 }
50 if ((right > 0) && (left <= INT_MAX - right)) {
51 // No overflow.
52 return false;
53 }
54 if ((right < 0) && (left >= INT_MIN - right)) {
55 // No underflow.
56 return false;
57 }
58 return true;
59 }
60
Mingyao Yang0304e182015-01-30 16:41:29 -080061 static bool IsAddOrSubAConstant(HInstruction* instruction,
62 HInstruction** left_instruction,
63 int* right_constant) {
64 if (instruction->IsAdd() || instruction->IsSub()) {
65 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
66 HInstruction* left = bin_op->GetLeft();
67 HInstruction* right = bin_op->GetRight();
68 if (right->IsIntConstant()) {
69 *left_instruction = left;
70 int32_t c = right->AsIntConstant()->GetValue();
71 *right_constant = instruction->IsAdd() ? c : -c;
72 return true;
73 }
74 }
75 *left_instruction = nullptr;
76 *right_constant = 0;
77 return false;
78 }
79
Mingyao Yang64197522014-12-05 15:56:23 -080080 // Try to detect useful value bound format from an instruction, e.g.
81 // a constant or array length related value.
82 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, bool* found) {
83 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -070084 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -080085 *found = true;
86 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -070087 }
Mingyao Yang64197522014-12-05 15:56:23 -080088
89 if (instruction->IsArrayLength()) {
90 *found = true;
91 return ValueBound(instruction, 0);
92 }
93 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -080094 HInstruction *left;
95 int32_t right;
96 if (IsAddOrSubAConstant(instruction, &left, &right)) {
97 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -080098 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -080099 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800100 }
101 }
102
103 // No useful bound detected.
104 *found = false;
105 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700106 }
107
108 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800109 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700110
Mingyao Yang0304e182015-01-30 16:41:29 -0800111 bool IsRelatedToArrayLength() const {
112 // Some bounds are created with HNewArray* as the instruction instead
113 // of HArrayLength*. They are treated the same.
114 return (instruction_ != nullptr) &&
115 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700116 }
117
118 bool IsConstant() const {
119 return instruction_ == nullptr;
120 }
121
122 static ValueBound Min() { return ValueBound(nullptr, INT_MIN); }
123 static ValueBound Max() { return ValueBound(nullptr, INT_MAX); }
124
125 bool Equals(ValueBound bound) const {
126 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
127 }
128
Mingyao Yang0304e182015-01-30 16:41:29 -0800129 static HInstruction* FromArrayLengthToNewArrayIfPossible(HInstruction* instruction) {
130 // Null check on the NewArray should have been eliminated by instruction
131 // simplifier already.
132 if (instruction->IsArrayLength() && instruction->InputAt(0)->IsNewArray()) {
133 return instruction->InputAt(0)->AsNewArray();
134 }
135 return instruction;
136 }
137
138 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
139 if (instruction1 == instruction2) {
140 return true;
141 }
142
143 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700144 return false;
145 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800146
147 // Some bounds are created with HNewArray* as the instruction instead
148 // of HArrayLength*. They are treated the same.
149 instruction1 = FromArrayLengthToNewArrayIfPossible(instruction1);
150 instruction2 = FromArrayLengthToNewArrayIfPossible(instruction2);
151 return instruction1 == instruction2;
152 }
153
154 // Returns if it's certain this->bound >= `bound`.
155 bool GreaterThanOrEqualTo(ValueBound bound) const {
156 if (Equal(instruction_, bound.instruction_)) {
157 return constant_ >= bound.constant_;
158 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700159 // Not comparable. Just return false.
160 return false;
161 }
162
Mingyao Yang0304e182015-01-30 16:41:29 -0800163 // Returns if it's certain this->bound <= `bound`.
164 bool LessThanOrEqualTo(ValueBound bound) const {
165 if (Equal(instruction_, bound.instruction_)) {
166 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700167 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700168 // Not comparable. Just return false.
169 return false;
170 }
171
172 // Try to narrow lower bound. Returns the greatest of the two if possible.
173 // Pick one if they are not comparable.
174 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800175 if (bound1.GreaterThanOrEqualTo(bound2)) {
176 return bound1;
177 }
178 if (bound2.GreaterThanOrEqualTo(bound1)) {
179 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700180 }
181
182 // Not comparable. Just pick one. We may lose some info, but that's ok.
183 // Favor constant as lower bound.
184 return bound1.IsConstant() ? bound1 : bound2;
185 }
186
187 // Try to narrow upper bound. Returns the lowest of the two if possible.
188 // Pick one if they are not comparable.
189 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800190 if (bound1.LessThanOrEqualTo(bound2)) {
191 return bound1;
192 }
193 if (bound2.LessThanOrEqualTo(bound1)) {
194 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700195 }
196
197 // Not comparable. Just pick one. We may lose some info, but that's ok.
198 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800199 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700200 }
201
Mingyao Yang0304e182015-01-30 16:41:29 -0800202 // Add a constant to a ValueBound.
203 // `overflow` or `underflow` will return whether the resulting bound may
204 // overflow or underflow an int.
205 ValueBound Add(int32_t c, bool* overflow, bool* underflow) const {
206 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700207 if (c == 0) {
208 return *this;
209 }
210
Mingyao Yang0304e182015-01-30 16:41:29 -0800211 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700212 if (c > 0) {
213 if (constant_ > INT_MAX - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800214 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800215 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700216 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800217
218 new_constant = constant_ + c;
219 // (array.length + non-positive-constant) won't overflow an int.
220 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
221 return ValueBound(instruction_, new_constant);
222 }
223 // Be conservative.
224 *overflow = true;
225 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700226 } else {
227 if (constant_ < INT_MIN - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800228 *underflow = true;
229 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700230 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800231
232 new_constant = constant_ + c;
233 // Regardless of the value new_constant, (array.length+new_constant) will
234 // never underflow since array.length is no less than 0.
235 if (IsConstant() || IsRelatedToArrayLength()) {
236 return ValueBound(instruction_, new_constant);
237 }
238 // Be conservative.
239 *underflow = true;
240 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700241 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700242 }
243
244 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700245 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800246 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700247};
248
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700249// Collect array access data for a loop.
250// TODO: make it work for multiple arrays inside the loop.
251class ArrayAccessInsideLoopFinder : public ValueObject {
252 public:
253 explicit ArrayAccessInsideLoopFinder(HInstruction* induction_variable)
254 : induction_variable_(induction_variable),
255 found_array_length_(nullptr),
256 offset_low_(INT_MAX),
257 offset_high_(INT_MIN) {
258 Run();
259 }
260
261 HArrayLength* GetFoundArrayLength() const { return found_array_length_; }
262 bool HasFoundArrayLength() const { return found_array_length_ != nullptr; }
263 int32_t GetOffsetLow() const { return offset_low_; }
264 int32_t GetOffsetHigh() const { return offset_high_; }
265
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700266 // Returns if `block` that is in loop_info may exit the loop, unless it's
267 // the loop header for loop_info.
268 static bool EarlyExit(HBasicBlock* block, HLoopInformation* loop_info) {
269 DCHECK(loop_info->Contains(*block));
270 if (block == loop_info->GetHeader()) {
271 // Loop header of loop_info. Exiting loop is normal.
272 return false;
273 }
274 const GrowableArray<HBasicBlock*> successors = block->GetSuccessors();
275 for (size_t i = 0; i < successors.Size(); i++) {
276 if (!loop_info->Contains(*successors.Get(i))) {
277 // One of the successors exits the loop.
278 return true;
279 }
280 }
281 return false;
282 }
283
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100284 static bool DominatesAllBackEdges(HBasicBlock* block, HLoopInformation* loop_info) {
285 for (size_t i = 0, e = loop_info->GetBackEdges().Size(); i < e; ++i) {
286 HBasicBlock* back_edge = loop_info->GetBackEdges().Get(i);
287 if (!block->Dominates(back_edge)) {
288 return false;
289 }
290 }
291 return true;
292 }
293
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700294 void Run() {
295 HLoopInformation* loop_info = induction_variable_->GetBlock()->GetLoopInformation();
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700296 for (HBlocksInLoopIterator it_loop(*loop_info); !it_loop.Done(); it_loop.Advance()) {
297 HBasicBlock* block = it_loop.Current();
298 DCHECK(block->IsInLoop());
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100299 if (!DominatesAllBackEdges(block, loop_info)) {
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700300 // In order not to trigger deoptimization unnecessarily, make sure
301 // that all array accesses collected are really executed in the loop.
302 // For array accesses in a branch inside the loop, don't collect the
303 // access. The bounds check in that branch might not be eliminated.
304 continue;
305 }
306 if (EarlyExit(block, loop_info)) {
307 // If the loop body can exit loop (like break, return, etc.), it's not guaranteed
308 // that the loop will loop through the full monotonic value range from
309 // initial_ to end_. So adding deoptimization might be too aggressive and can
310 // trigger deoptimization unnecessarily even if the loop won't actually throw
311 // AIOOBE. Otherwise, the loop induction variable is going to cover the full
312 // monotonic value range from initial_ to end_, and deoptimizations are added
313 // iff the loop will throw AIOOBE.
314 found_array_length_ = nullptr;
315 return;
316 }
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700317 for (HInstruction* instruction = block->GetFirstInstruction();
318 instruction != nullptr;
319 instruction = instruction->GetNext()) {
320 if (!instruction->IsArrayGet() && !instruction->IsArraySet()) {
321 continue;
322 }
323 HInstruction* index = instruction->InputAt(1);
324 if (!index->IsBoundsCheck()) {
325 continue;
326 }
327
328 HArrayLength* array_length = index->InputAt(1)->AsArrayLength();
329 if (array_length == nullptr) {
330 DCHECK(index->InputAt(1)->IsIntConstant());
331 // TODO: may optimize for constant case.
332 continue;
333 }
334
335 HInstruction* array = array_length->InputAt(0);
336 if (array->IsNullCheck()) {
337 array = array->AsNullCheck()->InputAt(0);
338 }
339 if (loop_info->Contains(*array->GetBlock())) {
340 // Array is defined inside the loop. Skip.
341 continue;
342 }
343
344 if (found_array_length_ != nullptr && found_array_length_ != array_length) {
345 // There is already access for another array recorded for the loop.
346 // TODO: handle multiple arrays.
347 continue;
348 }
349
350 index = index->AsBoundsCheck()->InputAt(0);
351 HInstruction* left = index;
352 int32_t right = 0;
353 if (left == induction_variable_ ||
354 (ValueBound::IsAddOrSubAConstant(index, &left, &right) &&
355 left == induction_variable_)) {
356 // For patterns like array[i] or array[i + 2].
357 if (right < offset_low_) {
358 offset_low_ = right;
359 }
360 if (right > offset_high_) {
361 offset_high_ = right;
362 }
363 } else {
364 // Access not in induction_variable/(induction_variable_ + constant)
365 // format. Skip.
366 continue;
367 }
368 // Record this array.
369 found_array_length_ = array_length;
370 }
371 }
372 }
373
374 private:
375 // The instruction that corresponds to a MonotonicValueRange.
376 HInstruction* induction_variable_;
377
378 // The array length of the array that's accessed inside the loop.
379 HArrayLength* found_array_length_;
380
381 // The lowest and highest constant offsets relative to induction variable
382 // instruction_ in all array accesses.
383 // If array access are: array[i-1], array[i], array[i+1],
384 // offset_low_ is -1 and offset_high is 1.
385 int32_t offset_low_;
386 int32_t offset_high_;
387
388 DISALLOW_COPY_AND_ASSIGN(ArrayAccessInsideLoopFinder);
389};
390
Mingyao Yangf384f882014-10-22 16:08:18 -0700391/**
392 * Represent a range of lower bound and upper bound, both being inclusive.
393 * Currently a ValueRange may be generated as a result of the following:
394 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800395 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700396 * incrementing/decrementing array index (MonotonicValueRange).
397 */
398class ValueRange : public ArenaObject<kArenaAllocMisc> {
399 public:
400 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
401 : allocator_(allocator), lower_(lower), upper_(upper) {}
402
403 virtual ~ValueRange() {}
404
Mingyao Yang57e04752015-02-09 18:13:26 -0800405 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
406 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700407 return AsMonotonicValueRange() != nullptr;
408 }
409
410 ArenaAllocator* GetAllocator() const { return allocator_; }
411 ValueBound GetLower() const { return lower_; }
412 ValueBound GetUpper() const { return upper_; }
413
414 // If it's certain that this value range fits in other_range.
415 virtual bool FitsIn(ValueRange* other_range) const {
416 if (other_range == nullptr) {
417 return true;
418 }
419 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800420 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
421 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700422 }
423
424 // Returns the intersection of this and range.
425 // If it's not possible to do intersection because some
426 // bounds are not comparable, it's ok to pick either bound.
427 virtual ValueRange* Narrow(ValueRange* range) {
428 if (range == nullptr) {
429 return this;
430 }
431
432 if (range->IsMonotonicValueRange()) {
433 return this;
434 }
435
436 return new (allocator_) ValueRange(
437 allocator_,
438 ValueBound::NarrowLowerBound(lower_, range->lower_),
439 ValueBound::NarrowUpperBound(upper_, range->upper_));
440 }
441
Mingyao Yang0304e182015-01-30 16:41:29 -0800442 // Shift a range by a constant.
443 ValueRange* Add(int32_t constant) const {
444 bool overflow, underflow;
445 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
446 if (underflow) {
447 // Lower bound underflow will wrap around to positive values
448 // and invalidate the upper bound.
449 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700450 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800451 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
452 if (overflow) {
453 // Upper bound overflow will wrap around to negative values
454 // and invalidate the lower bound.
455 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700456 }
457 return new (allocator_) ValueRange(allocator_, lower, upper);
458 }
459
Mingyao Yangf384f882014-10-22 16:08:18 -0700460 private:
461 ArenaAllocator* const allocator_;
462 const ValueBound lower_; // inclusive
463 const ValueBound upper_; // inclusive
464
465 DISALLOW_COPY_AND_ASSIGN(ValueRange);
466};
467
468/**
469 * A monotonically incrementing/decrementing value range, e.g.
470 * the variable i in "for (int i=0; i<array.length; i++)".
471 * Special care needs to be taken to account for overflow/underflow
472 * of such value ranges.
473 */
474class MonotonicValueRange : public ValueRange {
475 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800476 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700477 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800478 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800479 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800480 ValueBound bound)
481 // To be conservative, give it full range [INT_MIN, INT_MAX] in case it's
482 // used as a regular value range, due to possible overflow/underflow.
483 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700484 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800485 initial_(initial),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700486 end_(nullptr),
487 inclusive_(false),
Mingyao Yang64197522014-12-05 15:56:23 -0800488 increment_(increment),
489 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700490
491 virtual ~MonotonicValueRange() {}
492
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700493 HInstruction* GetInductionVariable() const { return induction_variable_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800494 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800495 ValueBound GetBound() const { return bound_; }
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700496 void SetEnd(HInstruction* end) { end_ = end; }
497 void SetInclusive(bool inclusive) { inclusive_ = inclusive; }
498 HBasicBlock* GetLoopHead() const {
499 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
500 return induction_variable_->GetBlock();
501 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800502
503 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700504
505 // If it's certain that this value range fits in other_range.
506 bool FitsIn(ValueRange* other_range) const OVERRIDE {
507 if (other_range == nullptr) {
508 return true;
509 }
510 DCHECK(!other_range->IsMonotonicValueRange());
511 return false;
512 }
513
514 // Try to narrow this MonotonicValueRange given another range.
515 // Ideally it will return a normal ValueRange. But due to
516 // possible overflow/underflow, that may not be possible.
517 ValueRange* Narrow(ValueRange* range) OVERRIDE {
518 if (range == nullptr) {
519 return this;
520 }
521 DCHECK(!range->IsMonotonicValueRange());
522
523 if (increment_ > 0) {
524 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800525 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700526 if (!lower.IsConstant() || lower.GetConstant() == INT_MIN) {
527 // Lower bound isn't useful. Leave it to deoptimization.
528 return this;
529 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700530
531 // We currently conservatively assume max array length is INT_MAX. If we can
532 // make assumptions about the max array length, e.g. due to the max heap size,
533 // divided by the element size (such as 4 bytes for each integer array), we can
534 // lower this number and rule out some possible overflows.
Mingyao Yang0304e182015-01-30 16:41:29 -0800535 int32_t max_array_len = INT_MAX;
Mingyao Yangf384f882014-10-22 16:08:18 -0700536
Mingyao Yang0304e182015-01-30 16:41:29 -0800537 // max possible integer value of range's upper value.
538 int32_t upper = INT_MAX;
539 // Try to lower upper.
540 ValueBound upper_bound = range->GetUpper();
541 if (upper_bound.IsConstant()) {
542 upper = upper_bound.GetConstant();
543 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
544 // Normal case. e.g. <= array.length - 1.
545 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700546 }
547
548 // If we can prove for the last number in sequence of initial_,
549 // initial_ + increment_, initial_ + 2 x increment_, ...
550 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
551 // then this MonoticValueRange is narrowed to a normal value range.
552
553 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800554 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700555 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800556 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700557 if (upper <= initial_constant) {
558 last_num_in_sequence = upper;
559 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800560 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700561 last_num_in_sequence = initial_constant +
562 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
563 }
564 }
565 if (last_num_in_sequence <= INT_MAX - increment_) {
566 // No overflow. The sequence will be stopped by the upper bound test as expected.
567 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
568 }
569
570 // There might be overflow. Give up narrowing.
571 return this;
572 } else {
573 DCHECK_NE(increment_, 0);
574 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800575 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700576 if ((!upper.IsConstant() || upper.GetConstant() == INT_MAX) &&
577 !upper.IsRelatedToArrayLength()) {
578 // Upper bound isn't useful. Leave it to deoptimization.
579 return this;
580 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700581
582 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800583 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700584 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800585 int32_t constant = range->GetLower().GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700586 if (constant >= INT_MIN - increment_) {
587 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
588 }
589 }
590
Mingyao Yang0304e182015-01-30 16:41:29 -0800591 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700592 return this;
593 }
594 }
595
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700596 // Returns true if adding a (constant >= value) check for deoptimization
597 // is allowed and will benefit compiled code.
598 bool CanAddDeoptimizationConstant(HInstruction* value,
599 int32_t constant,
600 bool* is_proven) {
601 *is_proven = false;
602 // See if we can prove the relationship first.
603 if (value->IsIntConstant()) {
604 if (value->AsIntConstant()->GetValue() >= constant) {
605 // Already true.
606 *is_proven = true;
607 return true;
608 } else {
609 // May throw exception. Don't add deoptimization.
610 // Keep bounds checks in the loops.
611 return false;
612 }
613 }
614 // Can benefit from deoptimization.
615 return true;
616 }
617
618 // Adds a check that (value >= constant), and HDeoptimize otherwise.
619 void AddDeoptimizationConstant(HInstruction* value,
620 int32_t constant) {
621 HBasicBlock* block = induction_variable_->GetBlock();
622 DCHECK(block->IsLoopHeader());
623 HGraph* graph = block->GetGraph();
624 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
625 HSuspendCheck* suspend_check = block->GetLoopInformation()->GetSuspendCheck();
626 HIntConstant* const_instr = graph->GetIntConstant(constant);
627 HCondition* cond = new (graph->GetArena()) HLessThan(value, const_instr);
628 HDeoptimize* deoptimize = new (graph->GetArena())
629 HDeoptimize(cond, suspend_check->GetDexPc());
630 pre_header->InsertInstructionBefore(cond, pre_header->GetLastInstruction());
631 pre_header->InsertInstructionBefore(deoptimize, pre_header->GetLastInstruction());
632 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
633 suspend_check->GetEnvironment(), block);
634 }
635
636 // Returns true if adding a (value <= array_length + offset) check for deoptimization
637 // is allowed and will benefit compiled code.
638 bool CanAddDeoptimizationArrayLength(HInstruction* value,
639 HArrayLength* array_length,
640 int32_t offset,
641 bool* is_proven) {
642 *is_proven = false;
643 if (offset > 0) {
644 // There might be overflow issue.
645 // TODO: handle this, possibly with some distance relationship between
646 // offset_low and offset_high, or using another deoptimization to make
647 // sure (array_length + offset) doesn't overflow.
648 return false;
649 }
650
651 // See if we can prove the relationship first.
652 if (value == array_length) {
653 if (offset >= 0) {
654 // Already true.
655 *is_proven = true;
656 return true;
657 } else {
658 // May throw exception. Don't add deoptimization.
659 // Keep bounds checks in the loops.
660 return false;
661 }
662 }
663 // Can benefit from deoptimization.
664 return true;
665 }
666
667 // Adds a check that (value <= array_length + offset), and HDeoptimize otherwise.
668 void AddDeoptimizationArrayLength(HInstruction* value,
669 HArrayLength* array_length,
670 int32_t offset) {
671 HBasicBlock* block = induction_variable_->GetBlock();
672 DCHECK(block->IsLoopHeader());
673 HGraph* graph = block->GetGraph();
674 HBasicBlock* pre_header = block->GetLoopInformation()->GetPreHeader();
675 HSuspendCheck* suspend_check = block->GetLoopInformation()->GetSuspendCheck();
676
677 // We may need to hoist null-check and array_length out of loop first.
678 if (!array_length->GetBlock()->Dominates(pre_header)) {
679 HInstruction* array = array_length->InputAt(0);
680 HNullCheck* null_check = array->AsNullCheck();
681 if (null_check != nullptr) {
682 array = null_check->InputAt(0);
683 }
684 // We've already made sure array is defined before the loop when collecting
685 // array accesses for the loop.
686 DCHECK(array->GetBlock()->Dominates(pre_header));
687 if (null_check != nullptr && !null_check->GetBlock()->Dominates(pre_header)) {
688 // Hoist null check out of loop with a deoptimization.
689 HNullConstant* null_constant = graph->GetNullConstant();
690 HCondition* null_check_cond = new (graph->GetArena()) HEqual(array, null_constant);
691 // TODO: for one dex_pc, share the same deoptimization slow path.
692 HDeoptimize* null_check_deoptimize = new (graph->GetArena())
693 HDeoptimize(null_check_cond, suspend_check->GetDexPc());
694 pre_header->InsertInstructionBefore(null_check_cond, pre_header->GetLastInstruction());
695 pre_header->InsertInstructionBefore(
696 null_check_deoptimize, pre_header->GetLastInstruction());
697 // Eliminate null check in the loop.
698 null_check->ReplaceWith(array);
699 null_check->GetBlock()->RemoveInstruction(null_check);
700 null_check_deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
701 suspend_check->GetEnvironment(), block);
702 }
703 // Hoist array_length out of loop.
704 array_length->MoveBefore(pre_header->GetLastInstruction());
705 }
706
707 HIntConstant* offset_instr = graph->GetIntConstant(offset);
708 HAdd* add = new (graph->GetArena()) HAdd(Primitive::kPrimInt, array_length, offset_instr);
709 HCondition* cond = new (graph->GetArena()) HGreaterThan(value, add);
710 HDeoptimize* deoptimize = new (graph->GetArena())
711 HDeoptimize(cond, suspend_check->GetDexPc());
712 pre_header->InsertInstructionBefore(add, pre_header->GetLastInstruction());
713 pre_header->InsertInstructionBefore(cond, pre_header->GetLastInstruction());
714 pre_header->InsertInstructionBefore(deoptimize, pre_header->GetLastInstruction());
715 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
716 suspend_check->GetEnvironment(), block);
717 }
718
719 // Add deoptimizations in loop pre-header with the collected array access
720 // data so that value ranges can be established in loop body.
721 // Returns true if deoptimizations are successfully added, or if it's proven
722 // it's not necessary.
723 bool AddDeoptimization(const ArrayAccessInsideLoopFinder& finder) {
724 int32_t offset_low = finder.GetOffsetLow();
725 int32_t offset_high = finder.GetOffsetHigh();
726 HArrayLength* array_length = finder.GetFoundArrayLength();
727
728 HBasicBlock* pre_header =
729 induction_variable_->GetBlock()->GetLoopInformation()->GetPreHeader();
730 if (!initial_->GetBlock()->Dominates(pre_header) ||
731 !end_->GetBlock()->Dominates(pre_header)) {
732 // Can't move initial_ or end_ into pre_header for comparisons.
733 return false;
734 }
735
736 bool is_constant_proven, is_length_proven;
737 if (increment_ == 1) {
738 // Increasing from initial_ to end_.
739 int32_t offset = inclusive_ ? -offset_high - 1 : -offset_high;
740 if (CanAddDeoptimizationConstant(initial_, -offset_low, &is_constant_proven) &&
741 CanAddDeoptimizationArrayLength(end_, array_length, offset, &is_length_proven)) {
742 if (!is_constant_proven) {
743 AddDeoptimizationConstant(initial_, -offset_low);
744 }
745 if (!is_length_proven) {
746 AddDeoptimizationArrayLength(end_, array_length, offset);
747 }
748 return true;
749 }
750 } else if (increment_ == -1) {
751 // Decreasing from initial_ to end_.
752 int32_t constant = inclusive_ ? -offset_low : -offset_low - 1;
753 if (CanAddDeoptimizationConstant(end_, constant, &is_constant_proven) &&
754 CanAddDeoptimizationArrayLength(
755 initial_, array_length, -offset_high - 1, &is_length_proven)) {
756 if (!is_constant_proven) {
757 AddDeoptimizationConstant(end_, constant);
758 }
759 if (!is_length_proven) {
760 AddDeoptimizationArrayLength(initial_, array_length, -offset_high - 1);
761 }
762 return true;
763 }
764 }
765 return false;
766 }
767
768 // Try to add HDeoptimize's in the loop pre-header first to narrow this range.
769 ValueRange* NarrowWithDeoptimization() {
770 if (increment_ != 1 && increment_ != -1) {
771 // TODO: possibly handle overflow/underflow issues with deoptimization.
772 return this;
773 }
774
775 if (end_ == nullptr) {
776 // No full info to add deoptimization.
777 return this;
778 }
779
780 ArrayAccessInsideLoopFinder finder(induction_variable_);
781
782 if (!finder.HasFoundArrayLength()) {
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700783 // No array access was found inside the loop that can benefit
784 // from deoptimization.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700785 return this;
786 }
787
788 if (!AddDeoptimization(finder)) {
789 return this;
790 }
791
792 // After added deoptimizations, induction variable fits in
793 // [-offset_low, array.length-1-offset_high], adjusted with collected offsets.
794 ValueBound lower = ValueBound(0, -finder.GetOffsetLow());
795 ValueBound upper = ValueBound(finder.GetFoundArrayLength(), -1 - finder.GetOffsetHigh());
796 // We've narrowed the range after added deoptimizations.
797 return new (GetAllocator()) ValueRange(GetAllocator(), lower, upper);
798 }
799
Mingyao Yangf384f882014-10-22 16:08:18 -0700800 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700801 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
802 HInstruction* const initial_; // Initial value.
803 HInstruction* end_; // End value.
804 bool inclusive_; // Whether end value is inclusive.
805 const int32_t increment_; // Increment for each loop iteration.
806 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -0700807
808 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
809};
810
811class BCEVisitor : public HGraphVisitor {
812 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700813 // The least number of bounds checks that should be eliminated by triggering
814 // the deoptimization technique.
815 static constexpr size_t kThresholdForAddingDeoptimize = 2;
816
817 // Very large constant index is considered as an anomaly. This is a threshold
818 // beyond which we don't bother to apply the deoptimization technique since
819 // it's likely some AIOOBE will be thrown.
820 static constexpr int32_t kMaxConstantForAddingDeoptimize = INT_MAX - 1024 * 1024;
821
Andreas Gampe0418b5b2014-12-04 17:24:50 -0800822 explicit BCEVisitor(HGraph* graph)
Mingyao Yangf384f882014-10-22 16:08:18 -0700823 : HGraphVisitor(graph),
Mingyao Yangd43b3ac2015-04-01 14:03:04 -0700824 maps_(graph->GetBlocks().Size()),
825 need_to_revisit_block_(false) {}
826
827 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
828 first_constant_index_bounds_check_map_.clear();
829 HGraphVisitor::VisitBasicBlock(block);
830 if (need_to_revisit_block_) {
831 AddComparesWithDeoptimization(block);
832 need_to_revisit_block_ = false;
833 first_constant_index_bounds_check_map_.clear();
834 GetValueRangeMap(block)->clear();
835 HGraphVisitor::VisitBasicBlock(block);
836 }
837 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700838
839 private:
840 // Return the map of proven value ranges at the beginning of a basic block.
841 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
842 int block_id = basic_block->GetBlockId();
843 if (maps_.at(block_id) == nullptr) {
844 std::unique_ptr<ArenaSafeMap<int, ValueRange*>> map(
845 new ArenaSafeMap<int, ValueRange*>(
846 std::less<int>(), GetGraph()->GetArena()->Adapter()));
847 maps_.at(block_id) = std::move(map);
848 }
849 return maps_.at(block_id).get();
850 }
851
852 // Traverse up the dominator tree to look for value range info.
853 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
854 while (basic_block != nullptr) {
855 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
856 if (map->find(instruction->GetId()) != map->end()) {
857 return map->Get(instruction->GetId());
858 }
859 basic_block = basic_block->GetDominator();
860 }
861 // Didn't find any.
862 return nullptr;
863 }
864
Mingyao Yang0304e182015-01-30 16:41:29 -0800865 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
866 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -0700867 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800868 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700869 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -0800870 if (existing_range == nullptr) {
871 if (range != nullptr) {
872 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), range);
873 }
874 return;
875 }
876 if (existing_range->IsMonotonicValueRange()) {
877 DCHECK(instruction->IsLoopHeaderPhi());
878 // Make sure the comparison is in the loop header so each increment is
879 // checked with a comparison.
880 if (instruction->GetBlock() != basic_block) {
881 return;
882 }
883 }
884 ValueRange* narrowed_range = existing_range->Narrow(range);
Mingyao Yangf384f882014-10-22 16:08:18 -0700885 if (narrowed_range != nullptr) {
886 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), narrowed_range);
887 }
888 }
889
Mingyao Yang57e04752015-02-09 18:13:26 -0800890 // Special case that we may simultaneously narrow two MonotonicValueRange's to
891 // regular value ranges.
892 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
893 HInstruction* left,
894 HInstruction* right,
895 IfCondition cond,
896 MonotonicValueRange* left_range,
897 MonotonicValueRange* right_range) {
898 DCHECK(left->IsLoopHeaderPhi());
899 DCHECK(right->IsLoopHeaderPhi());
900 if (instruction->GetBlock() != left->GetBlock()) {
901 // Comparison needs to be in loop header to make sure it's done after each
902 // increment/decrement.
903 return;
904 }
905
906 // Handle common cases which also don't have overflow/underflow concerns.
907 if (left_range->GetIncrement() == 1 &&
908 left_range->GetBound().IsConstant() &&
909 right_range->GetIncrement() == -1 &&
910 right_range->GetBound().IsRelatedToArrayLength() &&
911 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800912 HBasicBlock* successor = nullptr;
913 int32_t left_compensation = 0;
914 int32_t right_compensation = 0;
915 if (cond == kCondLT) {
916 left_compensation = -1;
917 right_compensation = 1;
918 successor = instruction->IfTrueSuccessor();
919 } else if (cond == kCondLE) {
920 successor = instruction->IfTrueSuccessor();
921 } else if (cond == kCondGT) {
922 successor = instruction->IfFalseSuccessor();
923 } else if (cond == kCondGE) {
924 left_compensation = -1;
925 right_compensation = 1;
926 successor = instruction->IfFalseSuccessor();
927 } else {
928 // We don't handle '=='/'!=' test in case left and right can cross and
929 // miss each other.
930 return;
931 }
932
933 if (successor != nullptr) {
934 bool overflow;
935 bool underflow;
936 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
937 GetGraph()->GetArena(),
938 left_range->GetBound(),
939 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
940 if (!overflow && !underflow) {
941 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
942 new_left_range);
943 }
944
945 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
946 GetGraph()->GetArena(),
947 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
948 right_range->GetBound());
949 if (!overflow && !underflow) {
950 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
951 new_right_range);
952 }
953 }
954 }
955 }
956
Mingyao Yangf384f882014-10-22 16:08:18 -0700957 // Handle "if (left cmp_cond right)".
958 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
959 HBasicBlock* block = instruction->GetBlock();
960
961 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
962 // There should be no critical edge at this point.
963 DCHECK_EQ(true_successor->GetPredecessors().Size(), 1u);
964
965 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
966 // There should be no critical edge at this point.
967 DCHECK_EQ(false_successor->GetPredecessors().Size(), 1u);
968
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700969 ValueRange* left_range = LookupValueRange(left, block);
970 MonotonicValueRange* left_monotonic_range = nullptr;
971 if (left_range != nullptr) {
972 left_monotonic_range = left_range->AsMonotonicValueRange();
973 if (left_monotonic_range != nullptr) {
974 HBasicBlock* loop_head = left_monotonic_range->GetLoopHead();
975 if (instruction->GetBlock() != loop_head) {
976 // For monotonic value range, don't handle `instruction`
977 // if it's not defined in the loop header.
978 return;
979 }
980 }
981 }
982
Mingyao Yang64197522014-12-05 15:56:23 -0800983 bool found;
984 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -0800985 // Each comparison can establish a lower bound and an upper bound
986 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -0700987 ValueBound lower = bound;
988 ValueBound upper = bound;
989 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800990 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -0700991 // 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 -0800992 ValueRange* right_range = LookupValueRange(right, block);
993 if (right_range != nullptr) {
994 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -0800995 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
996 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
997 left_range->AsMonotonicValueRange(),
998 right_range->AsMonotonicValueRange());
999 return;
1000 }
1001 }
1002 lower = right_range->GetLower();
1003 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -07001004 } else {
1005 lower = ValueBound::Min();
1006 upper = ValueBound::Max();
1007 }
1008 }
1009
Mingyao Yang0304e182015-01-30 16:41:29 -08001010 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -07001011 if (cond == kCondLT || cond == kCondLE) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001012 if (left_monotonic_range != nullptr) {
1013 // Update the info for monotonic value range.
1014 if (left_monotonic_range->GetInductionVariable() == left &&
1015 left_monotonic_range->GetIncrement() < 0 &&
1016 block == left_monotonic_range->GetLoopHead() &&
1017 instruction->IfFalseSuccessor()->GetLoopInformation() == block->GetLoopInformation()) {
1018 left_monotonic_range->SetEnd(right);
1019 left_monotonic_range->SetInclusive(cond == kCondLT);
1020 }
1021 }
1022
Mingyao Yangf384f882014-10-22 16:08:18 -07001023 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -08001024 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
1025 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
1026 if (overflow || underflow) {
1027 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001028 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001029 ValueRange* new_range = new (GetGraph()->GetArena())
1030 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
1031 ApplyRangeFromComparison(left, block, true_successor, new_range);
1032 }
1033
1034 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -08001035 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
1036 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
1037 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
1038 if (overflow || underflow) {
1039 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001040 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001041 ValueRange* new_range = new (GetGraph()->GetArena())
1042 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
1043 ApplyRangeFromComparison(left, block, false_successor, new_range);
1044 }
1045 } else if (cond == kCondGT || cond == kCondGE) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001046 if (left_monotonic_range != nullptr) {
1047 // Update the info for monotonic value range.
1048 if (left_monotonic_range->GetInductionVariable() == left &&
1049 left_monotonic_range->GetIncrement() > 0 &&
1050 block == left_monotonic_range->GetLoopHead() &&
1051 instruction->IfFalseSuccessor()->GetLoopInformation() == block->GetLoopInformation()) {
1052 left_monotonic_range->SetEnd(right);
1053 left_monotonic_range->SetInclusive(cond == kCondGT);
1054 }
1055 }
1056
Mingyao Yangf384f882014-10-22 16:08:18 -07001057 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -08001058 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
1059 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
1060 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
1061 if (overflow || underflow) {
1062 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001063 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001064 ValueRange* new_range = new (GetGraph()->GetArena())
1065 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
1066 ApplyRangeFromComparison(left, block, true_successor, new_range);
1067 }
1068
1069 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -08001070 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
1071 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
1072 if (overflow || underflow) {
1073 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001074 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001075 ValueRange* new_range = new (GetGraph()->GetArena())
1076 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
1077 ApplyRangeFromComparison(left, block, false_successor, new_range);
1078 }
1079 }
1080 }
1081
1082 void VisitBoundsCheck(HBoundsCheck* bounds_check) {
1083 HBasicBlock* block = bounds_check->GetBlock();
1084 HInstruction* index = bounds_check->InputAt(0);
1085 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -08001086 DCHECK(array_length->IsIntConstant() || array_length->IsArrayLength());
Mingyao Yangf384f882014-10-22 16:08:18 -07001087
Mingyao Yang0304e182015-01-30 16:41:29 -08001088 if (!index->IsIntConstant()) {
1089 ValueRange* index_range = LookupValueRange(index, block);
1090 if (index_range != nullptr) {
1091 ValueBound lower = ValueBound(nullptr, 0); // constant 0
1092 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
1093 ValueRange* array_range = new (GetGraph()->GetArena())
1094 ValueRange(GetGraph()->GetArena(), lower, upper);
1095 if (index_range->FitsIn(array_range)) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001096 ReplaceBoundsCheck(bounds_check, index);
1097 return;
1098 }
1099 }
Mingyao Yang0304e182015-01-30 16:41:29 -08001100 } else {
1101 int32_t constant = index->AsIntConstant()->GetValue();
1102 if (constant < 0) {
1103 // Will always throw exception.
1104 return;
1105 }
1106 if (array_length->IsIntConstant()) {
1107 if (constant < array_length->AsIntConstant()->GetValue()) {
1108 ReplaceBoundsCheck(bounds_check, index);
1109 }
1110 return;
1111 }
1112
1113 DCHECK(array_length->IsArrayLength());
1114 ValueRange* existing_range = LookupValueRange(array_length, block);
1115 if (existing_range != nullptr) {
1116 ValueBound lower = existing_range->GetLower();
1117 DCHECK(lower.IsConstant());
1118 if (constant < lower.GetConstant()) {
1119 ReplaceBoundsCheck(bounds_check, index);
1120 return;
1121 } else {
1122 // Existing range isn't strong enough to eliminate the bounds check.
1123 // Fall through to update the array_length range with info from this
1124 // bounds check.
1125 }
1126 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001127
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001128 if (first_constant_index_bounds_check_map_.find(array_length->GetId()) ==
1129 first_constant_index_bounds_check_map_.end()) {
1130 // Remember the first bounds check against array_length of a constant index.
1131 // That bounds check instruction has an associated HEnvironment where we
1132 // may add an HDeoptimize to eliminate bounds checks of constant indices
1133 // against array_length.
1134 first_constant_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
1135 } else {
1136 // We've seen it at least twice. It's beneficial to introduce a compare with
1137 // deoptimization fallback to eliminate the bounds checks.
1138 need_to_revisit_block_ = true;
1139 }
1140
Mingyao Yangf384f882014-10-22 16:08:18 -07001141 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -08001142 // We currently don't do it for non-constant index since a valid array[i] can't prove
1143 // a valid array[i-1] yet due to the lower bound side.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001144 if (constant == INT_MAX) {
1145 // INT_MAX as an index will definitely throw AIOOBE.
1146 return;
1147 }
Mingyao Yang64197522014-12-05 15:56:23 -08001148 ValueBound lower = ValueBound(nullptr, constant + 1);
Mingyao Yangf384f882014-10-22 16:08:18 -07001149 ValueBound upper = ValueBound::Max();
1150 ValueRange* range = new (GetGraph()->GetArena())
1151 ValueRange(GetGraph()->GetArena(), lower, upper);
Mingyao Yang0304e182015-01-30 16:41:29 -08001152 GetValueRangeMap(block)->Overwrite(array_length->GetId(), range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001153 }
1154 }
1155
1156 void ReplaceBoundsCheck(HInstruction* bounds_check, HInstruction* index) {
1157 bounds_check->ReplaceWith(index);
1158 bounds_check->GetBlock()->RemoveInstruction(bounds_check);
1159 }
1160
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001161 static bool HasSameInputAtBackEdges(HPhi* phi) {
1162 DCHECK(phi->IsLoopHeaderPhi());
1163 // Start with input 1. Input 0 is from the incoming block.
1164 HInstruction* input1 = phi->InputAt(1);
1165 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
1166 *phi->GetBlock()->GetPredecessors().Get(1)));
1167 for (size_t i = 2, e = phi->InputCount(); i < e; ++i) {
1168 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
1169 *phi->GetBlock()->GetPredecessors().Get(i)));
1170 if (input1 != phi->InputAt(i)) {
1171 return false;
1172 }
1173 }
1174 return true;
1175 }
1176
Mingyao Yangf384f882014-10-22 16:08:18 -07001177 void VisitPhi(HPhi* phi) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001178 if (phi->IsLoopHeaderPhi()
1179 && (phi->GetType() == Primitive::kPrimInt)
1180 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001181 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -08001182 HInstruction *left;
1183 int32_t increment;
1184 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
1185 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001186 HInstruction* initial_value = phi->InputAt(0);
1187 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -08001188 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001189 // Add constant 0. It's really a fixed value.
1190 range = new (GetGraph()->GetArena()) ValueRange(
1191 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -08001192 ValueBound(initial_value, 0),
1193 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -07001194 } else {
1195 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -08001196 bool found;
1197 ValueBound bound = ValueBound::DetectValueBoundFromValue(
1198 initial_value, &found);
1199 if (!found) {
1200 // No constant or array.length+c bound found.
1201 // For i=j, we can still use j's upper bound as i's upper bound.
1202 // Same for lower.
1203 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
1204 if (initial_range != nullptr) {
1205 bound = increment > 0 ? initial_range->GetLower() :
1206 initial_range->GetUpper();
1207 } else {
1208 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
1209 }
1210 }
1211 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -07001212 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001213 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -07001214 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -08001215 increment,
1216 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -07001217 }
1218 GetValueRangeMap(phi->GetBlock())->Overwrite(phi->GetId(), range);
1219 }
1220 }
1221 }
1222 }
1223
1224 void VisitIf(HIf* instruction) {
1225 if (instruction->InputAt(0)->IsCondition()) {
1226 HCondition* cond = instruction->InputAt(0)->AsCondition();
1227 IfCondition cmp = cond->GetCondition();
1228 if (cmp == kCondGT || cmp == kCondGE ||
1229 cmp == kCondLT || cmp == kCondLE) {
1230 HInstruction* left = cond->GetLeft();
1231 HInstruction* right = cond->GetRight();
1232 HandleIf(instruction, left, right, cmp);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001233
1234 HBasicBlock* block = instruction->GetBlock();
1235 ValueRange* left_range = LookupValueRange(left, block);
1236 if (left_range == nullptr) {
1237 return;
1238 }
1239
1240 if (left_range->IsMonotonicValueRange() &&
1241 block == left_range->AsMonotonicValueRange()->GetLoopHead()) {
1242 // The comparison is for an induction variable in the loop header.
1243 DCHECK(left == left_range->AsMonotonicValueRange()->GetInductionVariable());
1244 HBasicBlock* loop_body_successor;
Mingyao Yang9d750ef2015-04-26 18:15:30 -07001245 if (LIKELY(block->GetLoopInformation()->
1246 Contains(*instruction->IfFalseSuccessor()))) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001247 loop_body_successor = instruction->IfFalseSuccessor();
Mingyao Yang9d750ef2015-04-26 18:15:30 -07001248 } else {
1249 loop_body_successor = instruction->IfTrueSuccessor();
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001250 }
1251 ValueRange* new_left_range = LookupValueRange(left, loop_body_successor);
1252 if (new_left_range == left_range) {
1253 // We are not successful in narrowing the monotonic value range to
1254 // a regular value range. Try using deoptimization.
1255 new_left_range = left_range->AsMonotonicValueRange()->
1256 NarrowWithDeoptimization();
1257 if (new_left_range != left_range) {
1258 GetValueRangeMap(instruction->IfFalseSuccessor())->
1259 Overwrite(left->GetId(), new_left_range);
1260 }
1261 }
1262 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001263 }
1264 }
1265 }
1266
1267 void VisitAdd(HAdd* add) {
1268 HInstruction* right = add->GetRight();
1269 if (right->IsIntConstant()) {
1270 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
1271 if (left_range == nullptr) {
1272 return;
1273 }
1274 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
1275 if (range != nullptr) {
1276 GetValueRangeMap(add->GetBlock())->Overwrite(add->GetId(), range);
1277 }
1278 }
1279 }
1280
1281 void VisitSub(HSub* sub) {
1282 HInstruction* left = sub->GetLeft();
1283 HInstruction* right = sub->GetRight();
1284 if (right->IsIntConstant()) {
1285 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1286 if (left_range == nullptr) {
1287 return;
1288 }
1289 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1290 if (range != nullptr) {
1291 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
1292 return;
1293 }
1294 }
1295
1296 // Here we are interested in the typical triangular case of nested loops,
1297 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1298 // 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 -08001299
1300 // Try to handle (array.length - i) or (array.length + c - i) format.
1301 HInstruction* left_of_left; // left input of left.
1302 int32_t right_const = 0;
1303 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1304 left = left_of_left;
1305 }
1306 // The value of left input of the sub equals (left + right_const).
1307
Mingyao Yangf384f882014-10-22 16:08:18 -07001308 if (left->IsArrayLength()) {
1309 HInstruction* array_length = left->AsArrayLength();
1310 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1311 if (right_range != nullptr) {
1312 ValueBound lower = right_range->GetLower();
1313 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001314 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001315 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001316 // Make sure it's the same array.
1317 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001318 int32_t c0 = right_const;
1319 int32_t c1 = lower.GetConstant();
1320 int32_t c2 = upper.GetConstant();
1321 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1322 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1323 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1324 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1325 if ((c0 - c1) <= 0) {
1326 // array.length + (c0 - c1) won't overflow/underflow.
1327 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1328 GetGraph()->GetArena(),
1329 ValueBound(nullptr, right_const - upper.GetConstant()),
1330 ValueBound(array_length, right_const - lower.GetConstant()));
1331 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
1332 }
1333 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001334 }
1335 }
1336 }
1337 }
1338 }
1339
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001340 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1341 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1342 HInstruction* right = instruction->GetRight();
1343 int32_t right_const;
1344 if (right->IsIntConstant()) {
1345 right_const = right->AsIntConstant()->GetValue();
1346 // Detect division by two or more.
1347 if ((instruction->IsDiv() && right_const <= 1) ||
1348 (instruction->IsShr() && right_const < 1) ||
1349 (instruction->IsUShr() && right_const < 1)) {
1350 return;
1351 }
1352 } else {
1353 return;
1354 }
1355
1356 // Try to handle array.length/2 or (array.length-1)/2 format.
1357 HInstruction* left = instruction->GetLeft();
1358 HInstruction* left_of_left; // left input of left.
1359 int32_t c = 0;
1360 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1361 left = left_of_left;
1362 }
1363 // The value of left input of instruction equals (left + c).
1364
1365 // (array_length + 1) or smaller divided by two or more
1366 // always generate a value in [INT_MIN, array_length].
1367 // This is true even if array_length is INT_MAX.
1368 if (left->IsArrayLength() && c <= 1) {
1369 if (instruction->IsUShr() && c < 0) {
1370 // Make sure for unsigned shift, left side is not negative.
1371 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1372 // than array_length.
1373 return;
1374 }
1375 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1376 GetGraph()->GetArena(),
1377 ValueBound(nullptr, INT_MIN),
1378 ValueBound(left, 0));
1379 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1380 }
1381 }
1382
1383 void VisitDiv(HDiv* div) {
1384 FindAndHandlePartialArrayLength(div);
1385 }
1386
1387 void VisitShr(HShr* shr) {
1388 FindAndHandlePartialArrayLength(shr);
1389 }
1390
1391 void VisitUShr(HUShr* ushr) {
1392 FindAndHandlePartialArrayLength(ushr);
1393 }
1394
Mingyao Yang4559f002015-02-27 14:43:53 -08001395 void VisitAnd(HAnd* instruction) {
1396 if (instruction->GetRight()->IsIntConstant()) {
1397 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1398 if (constant > 0) {
1399 // constant serves as a mask so any number masked with it
1400 // gets a [0, constant] value range.
1401 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1402 GetGraph()->GetArena(),
1403 ValueBound(nullptr, 0),
1404 ValueBound(nullptr, constant));
1405 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1406 }
1407 }
1408 }
1409
Mingyao Yang0304e182015-01-30 16:41:29 -08001410 void VisitNewArray(HNewArray* new_array) {
1411 HInstruction* len = new_array->InputAt(0);
1412 if (!len->IsIntConstant()) {
1413 HInstruction *left;
1414 int32_t right_const;
1415 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1416 // (left + right_const) is used as size to new the array.
1417 // We record "-right_const <= left <= new_array - right_const";
1418 ValueBound lower = ValueBound(nullptr, -right_const);
1419 // We use new_array for the bound instead of new_array.length,
1420 // which isn't available as an instruction yet. new_array will
1421 // be treated the same as new_array.length when it's used in a ValueBound.
1422 ValueBound upper = ValueBound(new_array, -right_const);
1423 ValueRange* range = new (GetGraph()->GetArena())
1424 ValueRange(GetGraph()->GetArena(), lower, upper);
1425 GetValueRangeMap(new_array->GetBlock())->Overwrite(left->GetId(), range);
1426 }
1427 }
1428 }
1429
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001430 void VisitDeoptimize(HDeoptimize* deoptimize) {
1431 // Right now it's only HLessThanOrEqual.
1432 DCHECK(deoptimize->InputAt(0)->IsLessThanOrEqual());
1433 HLessThanOrEqual* less_than_or_equal = deoptimize->InputAt(0)->AsLessThanOrEqual();
1434 HInstruction* instruction = less_than_or_equal->InputAt(0);
1435 if (instruction->IsArrayLength()) {
1436 HInstruction* constant = less_than_or_equal->InputAt(1);
1437 DCHECK(constant->IsIntConstant());
1438 DCHECK(constant->AsIntConstant()->GetValue() <= kMaxConstantForAddingDeoptimize);
1439 ValueBound lower = ValueBound(nullptr, constant->AsIntConstant()->GetValue() + 1);
1440 ValueRange* range = new (GetGraph()->GetArena())
1441 ValueRange(GetGraph()->GetArena(), lower, ValueBound::Max());
1442 GetValueRangeMap(deoptimize->GetBlock())->Overwrite(instruction->GetId(), range);
1443 }
1444 }
1445
1446 void AddCompareWithDeoptimization(HInstruction* array_length,
1447 HIntConstant* const_instr,
1448 HBasicBlock* block) {
1449 DCHECK(array_length->IsArrayLength());
1450 ValueRange* range = LookupValueRange(array_length, block);
1451 ValueBound lower_bound = range->GetLower();
1452 DCHECK(lower_bound.IsConstant());
1453 DCHECK(const_instr->GetValue() <= kMaxConstantForAddingDeoptimize);
1454 DCHECK_EQ(lower_bound.GetConstant(), const_instr->GetValue() + 1);
1455
1456 // If array_length is less than lower_const, deoptimize.
1457 HBoundsCheck* bounds_check = first_constant_index_bounds_check_map_.Get(
1458 array_length->GetId())->AsBoundsCheck();
1459 HCondition* cond = new (GetGraph()->GetArena()) HLessThanOrEqual(array_length, const_instr);
1460 HDeoptimize* deoptimize = new (GetGraph()->GetArena())
1461 HDeoptimize(cond, bounds_check->GetDexPc());
1462 block->InsertInstructionBefore(cond, bounds_check);
1463 block->InsertInstructionBefore(deoptimize, bounds_check);
Nicolas Geoffray3dcd58c2015-04-03 11:02:38 +01001464 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001465 }
1466
1467 void AddComparesWithDeoptimization(HBasicBlock* block) {
1468 for (ArenaSafeMap<int, HBoundsCheck*>::iterator it =
1469 first_constant_index_bounds_check_map_.begin();
1470 it != first_constant_index_bounds_check_map_.end();
1471 ++it) {
1472 HBoundsCheck* bounds_check = it->second;
1473 HArrayLength* array_length = bounds_check->InputAt(1)->AsArrayLength();
1474 HIntConstant* lower_bound_const_instr = nullptr;
1475 int32_t lower_bound_const = INT_MIN;
1476 size_t counter = 0;
1477 // Count the constant indexing for which bounds checks haven't
1478 // been removed yet.
1479 for (HUseIterator<HInstruction*> it2(array_length->GetUses());
1480 !it2.Done();
1481 it2.Advance()) {
1482 HInstruction* user = it2.Current()->GetUser();
1483 if (user->GetBlock() == block &&
1484 user->IsBoundsCheck() &&
1485 user->AsBoundsCheck()->InputAt(0)->IsIntConstant()) {
1486 DCHECK_EQ(array_length, user->AsBoundsCheck()->InputAt(1));
1487 HIntConstant* const_instr = user->AsBoundsCheck()->InputAt(0)->AsIntConstant();
1488 if (const_instr->GetValue() > lower_bound_const) {
1489 lower_bound_const = const_instr->GetValue();
1490 lower_bound_const_instr = const_instr;
1491 }
1492 counter++;
1493 }
1494 }
1495 if (counter >= kThresholdForAddingDeoptimize &&
1496 lower_bound_const_instr->GetValue() <= kMaxConstantForAddingDeoptimize) {
1497 AddCompareWithDeoptimization(array_length, lower_bound_const_instr, block);
1498 }
1499 }
1500 }
1501
Mingyao Yangf384f882014-10-22 16:08:18 -07001502 std::vector<std::unique_ptr<ArenaSafeMap<int, ValueRange*>>> maps_;
1503
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001504 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction in
1505 // a block that checks a constant index against that HArrayLength.
1506 SafeMap<int, HBoundsCheck*> first_constant_index_bounds_check_map_;
1507
1508 // For the block, there is at least one HArrayLength instruction for which there
1509 // is more than one bounds check instruction with constant indexing. And it's
1510 // beneficial to add a compare instruction that has deoptimization fallback and
1511 // eliminate those bounds checks.
1512 bool need_to_revisit_block_;
1513
Mingyao Yangf384f882014-10-22 16:08:18 -07001514 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1515};
1516
1517void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001518 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001519 return;
1520 }
1521
Mingyao Yangf384f882014-10-22 16:08:18 -07001522 BCEVisitor visitor(graph_);
1523 // Reverse post order guarantees a node's dominators are visited first.
1524 // We want to visit in the dominator-based order since if a value is known to
1525 // be bounded by a range at one instruction, it must be true that all uses of
1526 // that value dominated by that instruction fits in that range. Range of that
1527 // value can be narrowed further down in the dominator tree.
1528 //
1529 // TODO: only visit blocks that dominate some array accesses.
1530 visitor.VisitReversePostOrder();
1531}
1532
1533} // namespace art