blob: 0d953900a94753bf8ef2551dba77ff515747d099 [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"
Aart Bik22af3be2015-09-10 12:50:58 -070019#include "induction_var_range.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070020#include "nodes.h"
Mingyao Yangf384f882014-10-22 16:08:18 -070021
22namespace art {
23
24class MonotonicValueRange;
25
26/**
27 * A value bound is represented as a pair of value and constant,
28 * e.g. array.length - 1.
29 */
30class ValueBound : public ValueObject {
31 public:
Mingyao Yang0304e182015-01-30 16:41:29 -080032 ValueBound(HInstruction* instruction, int32_t constant) {
Mingyao Yang64197522014-12-05 15:56:23 -080033 if (instruction != nullptr && instruction->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -080034 // Normalize ValueBound with constant instruction.
35 int32_t instr_const = instruction->AsIntConstant()->GetValue();
Mingyao Yang8c8bad82015-02-09 18:13:26 -080036 if (!WouldAddOverflowOrUnderflow(instr_const, constant)) {
Mingyao Yang64197522014-12-05 15:56:23 -080037 instruction_ = nullptr;
38 constant_ = instr_const + constant;
39 return;
40 }
Mingyao Yangf384f882014-10-22 16:08:18 -070041 }
Mingyao Yang64197522014-12-05 15:56:23 -080042 instruction_ = instruction;
43 constant_ = constant;
44 }
45
Mingyao Yang8c8bad82015-02-09 18:13:26 -080046 // Return whether (left + right) overflows or underflows.
47 static bool WouldAddOverflowOrUnderflow(int32_t left, int32_t right) {
48 if (right == 0) {
49 return false;
50 }
51 if ((right > 0) && (left <= INT_MAX - right)) {
52 // No overflow.
53 return false;
54 }
55 if ((right < 0) && (left >= INT_MIN - right)) {
56 // No underflow.
57 return false;
58 }
59 return true;
60 }
61
Mingyao Yang0304e182015-01-30 16:41:29 -080062 static bool IsAddOrSubAConstant(HInstruction* instruction,
63 HInstruction** left_instruction,
64 int* right_constant) {
65 if (instruction->IsAdd() || instruction->IsSub()) {
66 HBinaryOperation* bin_op = instruction->AsBinaryOperation();
67 HInstruction* left = bin_op->GetLeft();
68 HInstruction* right = bin_op->GetRight();
69 if (right->IsIntConstant()) {
70 *left_instruction = left;
71 int32_t c = right->AsIntConstant()->GetValue();
72 *right_constant = instruction->IsAdd() ? c : -c;
73 return true;
74 }
75 }
76 *left_instruction = nullptr;
77 *right_constant = 0;
78 return false;
79 }
80
Mingyao Yang64197522014-12-05 15:56:23 -080081 // Try to detect useful value bound format from an instruction, e.g.
82 // a constant or array length related value.
83 static ValueBound DetectValueBoundFromValue(HInstruction* instruction, bool* found) {
84 DCHECK(instruction != nullptr);
Mingyao Yangf384f882014-10-22 16:08:18 -070085 if (instruction->IsIntConstant()) {
Mingyao Yang64197522014-12-05 15:56:23 -080086 *found = true;
87 return ValueBound(nullptr, instruction->AsIntConstant()->GetValue());
Mingyao Yangf384f882014-10-22 16:08:18 -070088 }
Mingyao Yang64197522014-12-05 15:56:23 -080089
90 if (instruction->IsArrayLength()) {
91 *found = true;
92 return ValueBound(instruction, 0);
93 }
94 // Try to detect (array.length + c) format.
Mingyao Yang0304e182015-01-30 16:41:29 -080095 HInstruction *left;
96 int32_t right;
97 if (IsAddOrSubAConstant(instruction, &left, &right)) {
98 if (left->IsArrayLength()) {
Mingyao Yang64197522014-12-05 15:56:23 -080099 *found = true;
Mingyao Yang0304e182015-01-30 16:41:29 -0800100 return ValueBound(left, right);
Mingyao Yang64197522014-12-05 15:56:23 -0800101 }
102 }
103
104 // No useful bound detected.
105 *found = false;
106 return ValueBound::Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700107 }
108
109 HInstruction* GetInstruction() const { return instruction_; }
Mingyao Yang0304e182015-01-30 16:41:29 -0800110 int32_t GetConstant() const { return constant_; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700111
Mingyao Yang0304e182015-01-30 16:41:29 -0800112 bool IsRelatedToArrayLength() const {
113 // Some bounds are created with HNewArray* as the instruction instead
114 // of HArrayLength*. They are treated the same.
115 return (instruction_ != nullptr) &&
116 (instruction_->IsArrayLength() || instruction_->IsNewArray());
Mingyao Yangf384f882014-10-22 16:08:18 -0700117 }
118
119 bool IsConstant() const {
120 return instruction_ == nullptr;
121 }
122
123 static ValueBound Min() { return ValueBound(nullptr, INT_MIN); }
124 static ValueBound Max() { return ValueBound(nullptr, INT_MAX); }
125
126 bool Equals(ValueBound bound) const {
127 return instruction_ == bound.instruction_ && constant_ == bound.constant_;
128 }
129
Aart Bik22af3be2015-09-10 12:50:58 -0700130 /*
131 * Hunt "under the hood" of array lengths (leading to array references),
132 * null checks (also leading to array references), and new arrays
133 * (leading to the actual length). This makes it more likely related
134 * instructions become actually comparable.
135 */
136 static HInstruction* HuntForDeclaration(HInstruction* instruction) {
137 while (instruction->IsArrayLength() ||
138 instruction->IsNullCheck() ||
139 instruction->IsNewArray()) {
140 instruction = instruction->InputAt(0);
Mingyao Yang0304e182015-01-30 16:41:29 -0800141 }
142 return instruction;
143 }
144
145 static bool Equal(HInstruction* instruction1, HInstruction* instruction2) {
146 if (instruction1 == instruction2) {
147 return true;
148 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800149 if (instruction1 == nullptr || instruction2 == nullptr) {
Mingyao Yangf384f882014-10-22 16:08:18 -0700150 return false;
151 }
Aart Bik22af3be2015-09-10 12:50:58 -0700152 instruction1 = HuntForDeclaration(instruction1);
153 instruction2 = HuntForDeclaration(instruction2);
Mingyao Yang0304e182015-01-30 16:41:29 -0800154 return instruction1 == instruction2;
155 }
156
157 // Returns if it's certain this->bound >= `bound`.
158 bool GreaterThanOrEqualTo(ValueBound bound) const {
159 if (Equal(instruction_, bound.instruction_)) {
160 return constant_ >= bound.constant_;
161 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700162 // Not comparable. Just return false.
163 return false;
164 }
165
Mingyao Yang0304e182015-01-30 16:41:29 -0800166 // Returns if it's certain this->bound <= `bound`.
167 bool LessThanOrEqualTo(ValueBound bound) const {
168 if (Equal(instruction_, bound.instruction_)) {
169 return constant_ <= bound.constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700170 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700171 // Not comparable. Just return false.
172 return false;
173 }
174
175 // Try to narrow lower bound. Returns the greatest of the two if possible.
176 // Pick one if they are not comparable.
177 static ValueBound NarrowLowerBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800178 if (bound1.GreaterThanOrEqualTo(bound2)) {
179 return bound1;
180 }
181 if (bound2.GreaterThanOrEqualTo(bound1)) {
182 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700183 }
184
185 // Not comparable. Just pick one. We may lose some info, but that's ok.
186 // Favor constant as lower bound.
187 return bound1.IsConstant() ? bound1 : bound2;
188 }
189
190 // Try to narrow upper bound. Returns the lowest of the two if possible.
191 // Pick one if they are not comparable.
192 static ValueBound NarrowUpperBound(ValueBound bound1, ValueBound bound2) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800193 if (bound1.LessThanOrEqualTo(bound2)) {
194 return bound1;
195 }
196 if (bound2.LessThanOrEqualTo(bound1)) {
197 return bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700198 }
199
200 // Not comparable. Just pick one. We may lose some info, but that's ok.
201 // Favor array length as upper bound.
Mingyao Yang0304e182015-01-30 16:41:29 -0800202 return bound1.IsRelatedToArrayLength() ? bound1 : bound2;
Mingyao Yangf384f882014-10-22 16:08:18 -0700203 }
204
Mingyao Yang0304e182015-01-30 16:41:29 -0800205 // Add a constant to a ValueBound.
206 // `overflow` or `underflow` will return whether the resulting bound may
207 // overflow or underflow an int.
208 ValueBound Add(int32_t c, bool* overflow, bool* underflow) const {
209 *overflow = *underflow = false;
Mingyao Yangf384f882014-10-22 16:08:18 -0700210 if (c == 0) {
211 return *this;
212 }
213
Mingyao Yang0304e182015-01-30 16:41:29 -0800214 int32_t new_constant;
Mingyao Yangf384f882014-10-22 16:08:18 -0700215 if (c > 0) {
216 if (constant_ > INT_MAX - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800217 *overflow = true;
Mingyao Yang64197522014-12-05 15:56:23 -0800218 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700219 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800220
221 new_constant = constant_ + c;
222 // (array.length + non-positive-constant) won't overflow an int.
223 if (IsConstant() || (IsRelatedToArrayLength() && new_constant <= 0)) {
224 return ValueBound(instruction_, new_constant);
225 }
226 // Be conservative.
227 *overflow = true;
228 return Max();
Mingyao Yangf384f882014-10-22 16:08:18 -0700229 } else {
230 if (constant_ < INT_MIN - c) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800231 *underflow = true;
232 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700233 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800234
235 new_constant = constant_ + c;
236 // Regardless of the value new_constant, (array.length+new_constant) will
237 // never underflow since array.length is no less than 0.
238 if (IsConstant() || IsRelatedToArrayLength()) {
239 return ValueBound(instruction_, new_constant);
240 }
241 // Be conservative.
242 *underflow = true;
243 return Min();
Mingyao Yangf384f882014-10-22 16:08:18 -0700244 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700245 }
246
247 private:
Mingyao Yangf384f882014-10-22 16:08:18 -0700248 HInstruction* instruction_;
Mingyao Yang0304e182015-01-30 16:41:29 -0800249 int32_t constant_;
Mingyao Yangf384f882014-10-22 16:08:18 -0700250};
251
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700252// Collect array access data for a loop.
253// TODO: make it work for multiple arrays inside the loop.
254class ArrayAccessInsideLoopFinder : public ValueObject {
255 public:
256 explicit ArrayAccessInsideLoopFinder(HInstruction* induction_variable)
257 : induction_variable_(induction_variable),
258 found_array_length_(nullptr),
259 offset_low_(INT_MAX),
260 offset_high_(INT_MIN) {
261 Run();
262 }
263
264 HArrayLength* GetFoundArrayLength() const { return found_array_length_; }
265 bool HasFoundArrayLength() const { return found_array_length_ != nullptr; }
266 int32_t GetOffsetLow() const { return offset_low_; }
267 int32_t GetOffsetHigh() const { return offset_high_; }
268
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700269 // Returns if `block` that is in loop_info may exit the loop, unless it's
270 // the loop header for loop_info.
271 static bool EarlyExit(HBasicBlock* block, HLoopInformation* loop_info) {
272 DCHECK(loop_info->Contains(*block));
273 if (block == loop_info->GetHeader()) {
274 // Loop header of loop_info. Exiting loop is normal.
275 return false;
276 }
Vladimir Marko60584552015-09-03 13:35:12 +0000277 for (HBasicBlock* successor : block->GetSuccessors()) {
278 if (!loop_info->Contains(*successor)) {
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700279 // One of the successors exits the loop.
280 return true;
281 }
282 }
283 return false;
284 }
285
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100286 static bool DominatesAllBackEdges(HBasicBlock* block, HLoopInformation* loop_info) {
287 for (size_t i = 0, e = loop_info->GetBackEdges().Size(); i < e; ++i) {
288 HBasicBlock* back_edge = loop_info->GetBackEdges().Get(i);
289 if (!block->Dominates(back_edge)) {
290 return false;
291 }
292 }
293 return true;
294 }
295
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700296 void Run() {
297 HLoopInformation* loop_info = induction_variable_->GetBlock()->GetLoopInformation();
Mingyao Yang3584bce2015-05-19 16:01:59 -0700298 HBlocksInLoopReversePostOrderIterator it_loop(*loop_info);
299 HBasicBlock* block = it_loop.Current();
300 DCHECK(block == induction_variable_->GetBlock());
301 // Skip loop header. Since narrowed value range of a MonotonicValueRange only
302 // applies to the loop body (after the test at the end of the loop header).
303 it_loop.Advance();
304 for (; !it_loop.Done(); it_loop.Advance()) {
305 block = it_loop.Current();
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700306 DCHECK(block->IsInLoop());
Nicolas Geoffraydb216f42015-05-05 17:02:20 +0100307 if (!DominatesAllBackEdges(block, loop_info)) {
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700308 // In order not to trigger deoptimization unnecessarily, make sure
309 // that all array accesses collected are really executed in the loop.
310 // For array accesses in a branch inside the loop, don't collect the
311 // access. The bounds check in that branch might not be eliminated.
312 continue;
313 }
314 if (EarlyExit(block, loop_info)) {
315 // If the loop body can exit loop (like break, return, etc.), it's not guaranteed
316 // that the loop will loop through the full monotonic value range from
317 // initial_ to end_. So adding deoptimization might be too aggressive and can
318 // trigger deoptimization unnecessarily even if the loop won't actually throw
Mingyao Yang3584bce2015-05-19 16:01:59 -0700319 // AIOOBE.
Mingyao Yang9d750ef2015-04-26 18:15:30 -0700320 found_array_length_ = nullptr;
321 return;
322 }
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700323 for (HInstruction* instruction = block->GetFirstInstruction();
324 instruction != nullptr;
325 instruction = instruction->GetNext()) {
Mingyao Yang3584bce2015-05-19 16:01:59 -0700326 if (!instruction->IsBoundsCheck()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700327 continue;
328 }
329
Mingyao Yang3584bce2015-05-19 16:01:59 -0700330 HInstruction* length_value = instruction->InputAt(1);
331 if (length_value->IsIntConstant()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700332 // TODO: may optimize for constant case.
333 continue;
334 }
335
Mingyao Yang3584bce2015-05-19 16:01:59 -0700336 if (length_value->IsPhi()) {
Nicolas Geoffray3cde6222015-06-17 10:17:49 +0100337 // When adding deoptimizations in outer loops, we might create
338 // a phi for the array length, and update all uses of the
339 // length in the loop to that phi. Therefore, inner loops having
340 // bounds checks on the same array will use that phi.
341 // TODO: handle these cases.
Mingyao Yang3584bce2015-05-19 16:01:59 -0700342 continue;
343 }
344
345 DCHECK(length_value->IsArrayLength());
346 HArrayLength* array_length = length_value->AsArrayLength();
347
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700348 HInstruction* array = array_length->InputAt(0);
349 if (array->IsNullCheck()) {
350 array = array->AsNullCheck()->InputAt(0);
351 }
352 if (loop_info->Contains(*array->GetBlock())) {
353 // Array is defined inside the loop. Skip.
354 continue;
355 }
356
357 if (found_array_length_ != nullptr && found_array_length_ != array_length) {
358 // There is already access for another array recorded for the loop.
359 // TODO: handle multiple arrays.
360 continue;
361 }
362
Mingyao Yang3584bce2015-05-19 16:01:59 -0700363 HInstruction* index = instruction->AsBoundsCheck()->InputAt(0);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700364 HInstruction* left = index;
365 int32_t right = 0;
366 if (left == induction_variable_ ||
367 (ValueBound::IsAddOrSubAConstant(index, &left, &right) &&
368 left == induction_variable_)) {
369 // For patterns like array[i] or array[i + 2].
370 if (right < offset_low_) {
371 offset_low_ = right;
372 }
373 if (right > offset_high_) {
374 offset_high_ = right;
375 }
376 } else {
377 // Access not in induction_variable/(induction_variable_ + constant)
378 // format. Skip.
379 continue;
380 }
381 // Record this array.
382 found_array_length_ = array_length;
383 }
384 }
385 }
386
387 private:
388 // The instruction that corresponds to a MonotonicValueRange.
389 HInstruction* induction_variable_;
390
Mingyao Yang3584bce2015-05-19 16:01:59 -0700391 // The array length of the array that's accessed inside the loop body.
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700392 HArrayLength* found_array_length_;
393
394 // The lowest and highest constant offsets relative to induction variable
395 // instruction_ in all array accesses.
396 // If array access are: array[i-1], array[i], array[i+1],
397 // offset_low_ is -1 and offset_high is 1.
398 int32_t offset_low_;
399 int32_t offset_high_;
400
401 DISALLOW_COPY_AND_ASSIGN(ArrayAccessInsideLoopFinder);
402};
403
Mingyao Yangf384f882014-10-22 16:08:18 -0700404/**
405 * Represent a range of lower bound and upper bound, both being inclusive.
406 * Currently a ValueRange may be generated as a result of the following:
407 * comparisons related to array bounds, array bounds check, add/sub on top
Mingyao Yang0304e182015-01-30 16:41:29 -0800408 * of an existing value range, NewArray or a loop phi corresponding to an
Mingyao Yangf384f882014-10-22 16:08:18 -0700409 * incrementing/decrementing array index (MonotonicValueRange).
410 */
411class ValueRange : public ArenaObject<kArenaAllocMisc> {
412 public:
413 ValueRange(ArenaAllocator* allocator, ValueBound lower, ValueBound upper)
414 : allocator_(allocator), lower_(lower), upper_(upper) {}
415
416 virtual ~ValueRange() {}
417
Mingyao Yang57e04752015-02-09 18:13:26 -0800418 virtual MonotonicValueRange* AsMonotonicValueRange() { return nullptr; }
419 bool IsMonotonicValueRange() {
Mingyao Yangf384f882014-10-22 16:08:18 -0700420 return AsMonotonicValueRange() != nullptr;
421 }
422
423 ArenaAllocator* GetAllocator() const { return allocator_; }
424 ValueBound GetLower() const { return lower_; }
425 ValueBound GetUpper() const { return upper_; }
426
Mingyao Yang3584bce2015-05-19 16:01:59 -0700427 bool IsConstantValueRange() { return lower_.IsConstant() && upper_.IsConstant(); }
428
Mingyao Yangf384f882014-10-22 16:08:18 -0700429 // If it's certain that this value range fits in other_range.
430 virtual bool FitsIn(ValueRange* other_range) const {
431 if (other_range == nullptr) {
432 return true;
433 }
434 DCHECK(!other_range->IsMonotonicValueRange());
Mingyao Yang0304e182015-01-30 16:41:29 -0800435 return lower_.GreaterThanOrEqualTo(other_range->lower_) &&
436 upper_.LessThanOrEqualTo(other_range->upper_);
Mingyao Yangf384f882014-10-22 16:08:18 -0700437 }
438
439 // Returns the intersection of this and range.
440 // If it's not possible to do intersection because some
441 // bounds are not comparable, it's ok to pick either bound.
442 virtual ValueRange* Narrow(ValueRange* range) {
443 if (range == nullptr) {
444 return this;
445 }
446
447 if (range->IsMonotonicValueRange()) {
448 return this;
449 }
450
451 return new (allocator_) ValueRange(
452 allocator_,
453 ValueBound::NarrowLowerBound(lower_, range->lower_),
454 ValueBound::NarrowUpperBound(upper_, range->upper_));
455 }
456
Mingyao Yang0304e182015-01-30 16:41:29 -0800457 // Shift a range by a constant.
458 ValueRange* Add(int32_t constant) const {
459 bool overflow, underflow;
460 ValueBound lower = lower_.Add(constant, &overflow, &underflow);
461 if (underflow) {
462 // Lower bound underflow will wrap around to positive values
463 // and invalidate the upper bound.
464 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700465 }
Mingyao Yang0304e182015-01-30 16:41:29 -0800466 ValueBound upper = upper_.Add(constant, &overflow, &underflow);
467 if (overflow) {
468 // Upper bound overflow will wrap around to negative values
469 // and invalidate the lower bound.
470 return nullptr;
Mingyao Yangf384f882014-10-22 16:08:18 -0700471 }
472 return new (allocator_) ValueRange(allocator_, lower, upper);
473 }
474
Mingyao Yangf384f882014-10-22 16:08:18 -0700475 private:
476 ArenaAllocator* const allocator_;
477 const ValueBound lower_; // inclusive
478 const ValueBound upper_; // inclusive
479
480 DISALLOW_COPY_AND_ASSIGN(ValueRange);
481};
482
483/**
484 * A monotonically incrementing/decrementing value range, e.g.
485 * the variable i in "for (int i=0; i<array.length; i++)".
486 * Special care needs to be taken to account for overflow/underflow
487 * of such value ranges.
488 */
489class MonotonicValueRange : public ValueRange {
490 public:
Mingyao Yang64197522014-12-05 15:56:23 -0800491 MonotonicValueRange(ArenaAllocator* allocator,
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700492 HPhi* induction_variable,
Mingyao Yang64197522014-12-05 15:56:23 -0800493 HInstruction* initial,
Mingyao Yang0304e182015-01-30 16:41:29 -0800494 int32_t increment,
Mingyao Yang64197522014-12-05 15:56:23 -0800495 ValueBound bound)
496 // To be conservative, give it full range [INT_MIN, INT_MAX] in case it's
497 // used as a regular value range, due to possible overflow/underflow.
498 : ValueRange(allocator, ValueBound::Min(), ValueBound::Max()),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700499 induction_variable_(induction_variable),
Mingyao Yang64197522014-12-05 15:56:23 -0800500 initial_(initial),
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700501 end_(nullptr),
502 inclusive_(false),
Mingyao Yang64197522014-12-05 15:56:23 -0800503 increment_(increment),
504 bound_(bound) {}
Mingyao Yangf384f882014-10-22 16:08:18 -0700505
506 virtual ~MonotonicValueRange() {}
507
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700508 HInstruction* GetInductionVariable() const { return induction_variable_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800509 int32_t GetIncrement() const { return increment_; }
Mingyao Yang57e04752015-02-09 18:13:26 -0800510 ValueBound GetBound() const { return bound_; }
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700511 void SetEnd(HInstruction* end) { end_ = end; }
512 void SetInclusive(bool inclusive) { inclusive_ = inclusive; }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700513 HBasicBlock* GetLoopHeader() const {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700514 DCHECK(induction_variable_->GetBlock()->IsLoopHeader());
515 return induction_variable_->GetBlock();
516 }
Mingyao Yang57e04752015-02-09 18:13:26 -0800517
518 MonotonicValueRange* AsMonotonicValueRange() OVERRIDE { return this; }
Mingyao Yangf384f882014-10-22 16:08:18 -0700519
Mingyao Yang3584bce2015-05-19 16:01:59 -0700520 HBasicBlock* GetLoopHeaderSuccesorInLoop() {
521 HBasicBlock* header = GetLoopHeader();
522 HInstruction* instruction = header->GetLastInstruction();
523 DCHECK(instruction->IsIf());
524 HIf* h_if = instruction->AsIf();
525 HLoopInformation* loop_info = header->GetLoopInformation();
526 bool true_successor_in_loop = loop_info->Contains(*h_if->IfTrueSuccessor());
527 bool false_successor_in_loop = loop_info->Contains(*h_if->IfFalseSuccessor());
528
529 // Just in case it's some strange loop structure.
530 if (true_successor_in_loop && false_successor_in_loop) {
531 return nullptr;
532 }
533 DCHECK(true_successor_in_loop || false_successor_in_loop);
534 return false_successor_in_loop ? h_if->IfFalseSuccessor() : h_if->IfTrueSuccessor();
535 }
536
Mingyao Yangf384f882014-10-22 16:08:18 -0700537 // If it's certain that this value range fits in other_range.
538 bool FitsIn(ValueRange* other_range) const OVERRIDE {
539 if (other_range == nullptr) {
540 return true;
541 }
542 DCHECK(!other_range->IsMonotonicValueRange());
543 return false;
544 }
545
546 // Try to narrow this MonotonicValueRange given another range.
547 // Ideally it will return a normal ValueRange. But due to
548 // possible overflow/underflow, that may not be possible.
549 ValueRange* Narrow(ValueRange* range) OVERRIDE {
550 if (range == nullptr) {
551 return this;
552 }
553 DCHECK(!range->IsMonotonicValueRange());
554
555 if (increment_ > 0) {
556 // Monotonically increasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800557 ValueBound lower = ValueBound::NarrowLowerBound(bound_, range->GetLower());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700558 if (!lower.IsConstant() || lower.GetConstant() == INT_MIN) {
559 // Lower bound isn't useful. Leave it to deoptimization.
560 return this;
561 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700562
563 // We currently conservatively assume max array length is INT_MAX. If we can
564 // make assumptions about the max array length, e.g. due to the max heap size,
565 // divided by the element size (such as 4 bytes for each integer array), we can
566 // lower this number and rule out some possible overflows.
Mingyao Yang0304e182015-01-30 16:41:29 -0800567 int32_t max_array_len = INT_MAX;
Mingyao Yangf384f882014-10-22 16:08:18 -0700568
Mingyao Yang0304e182015-01-30 16:41:29 -0800569 // max possible integer value of range's upper value.
570 int32_t upper = INT_MAX;
571 // Try to lower upper.
572 ValueBound upper_bound = range->GetUpper();
573 if (upper_bound.IsConstant()) {
574 upper = upper_bound.GetConstant();
575 } else if (upper_bound.IsRelatedToArrayLength() && upper_bound.GetConstant() <= 0) {
576 // Normal case. e.g. <= array.length - 1.
577 upper = max_array_len + upper_bound.GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700578 }
579
580 // If we can prove for the last number in sequence of initial_,
581 // initial_ + increment_, initial_ + 2 x increment_, ...
582 // that's <= upper, (last_num_in_sequence + increment_) doesn't trigger overflow,
583 // then this MonoticValueRange is narrowed to a normal value range.
584
585 // Be conservative first, assume last number in the sequence hits upper.
Mingyao Yang0304e182015-01-30 16:41:29 -0800586 int32_t last_num_in_sequence = upper;
Mingyao Yangf384f882014-10-22 16:08:18 -0700587 if (initial_->IsIntConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800588 int32_t initial_constant = initial_->AsIntConstant()->GetValue();
Mingyao Yangf384f882014-10-22 16:08:18 -0700589 if (upper <= initial_constant) {
590 last_num_in_sequence = upper;
591 } else {
Mingyao Yang0304e182015-01-30 16:41:29 -0800592 // Cast to int64_t for the substraction part to avoid int32_t overflow.
Mingyao Yangf384f882014-10-22 16:08:18 -0700593 last_num_in_sequence = initial_constant +
594 ((int64_t)upper - (int64_t)initial_constant) / increment_ * increment_;
595 }
596 }
597 if (last_num_in_sequence <= INT_MAX - increment_) {
598 // No overflow. The sequence will be stopped by the upper bound test as expected.
599 return new (GetAllocator()) ValueRange(GetAllocator(), lower, range->GetUpper());
600 }
601
602 // There might be overflow. Give up narrowing.
603 return this;
604 } else {
605 DCHECK_NE(increment_, 0);
606 // Monotonically decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -0800607 ValueBound upper = ValueBound::NarrowUpperBound(bound_, range->GetUpper());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700608 if ((!upper.IsConstant() || upper.GetConstant() == INT_MAX) &&
609 !upper.IsRelatedToArrayLength()) {
610 // Upper bound isn't useful. Leave it to deoptimization.
611 return this;
612 }
Mingyao Yangf384f882014-10-22 16:08:18 -0700613
614 // Need to take care of underflow. Try to prove underflow won't happen
Mingyao Yang0304e182015-01-30 16:41:29 -0800615 // for common cases.
Mingyao Yangf384f882014-10-22 16:08:18 -0700616 if (range->GetLower().IsConstant()) {
Mingyao Yang0304e182015-01-30 16:41:29 -0800617 int32_t constant = range->GetLower().GetConstant();
Mingyao Yangf384f882014-10-22 16:08:18 -0700618 if (constant >= INT_MIN - increment_) {
619 return new (GetAllocator()) ValueRange(GetAllocator(), range->GetLower(), upper);
620 }
621 }
622
Mingyao Yang0304e182015-01-30 16:41:29 -0800623 // For non-constant lower bound, just assume might be underflow. Give up narrowing.
Mingyao Yangf384f882014-10-22 16:08:18 -0700624 return this;
625 }
626 }
627
Mingyao Yang3584bce2015-05-19 16:01:59 -0700628 // Try to add HDeoptimize's in the loop pre-header first to narrow this range.
629 // For example, this loop:
630 //
631 // for (int i = start; i < end; i++) {
632 // array[i - 1] = array[i] + array[i + 1];
633 // }
634 //
635 // will be transformed to:
636 //
637 // int array_length_in_loop_body_if_needed;
638 // if (start >= end) {
639 // array_length_in_loop_body_if_needed = 0;
640 // } else {
641 // if (start < 1) deoptimize();
642 // if (array == null) deoptimize();
643 // array_length = array.length;
644 // if (end > array_length - 1) deoptimize;
645 // array_length_in_loop_body_if_needed = array_length;
646 // }
647 // for (int i = start; i < end; i++) {
648 // // No more null check and bounds check.
649 // // array.length value is replaced with array_length_in_loop_body_if_needed
650 // // in the loop body.
651 // array[i - 1] = array[i] + array[i + 1];
652 // }
653 //
654 // We basically first go through the loop body and find those array accesses whose
655 // index is at a constant offset from the induction variable ('i' in the above example),
656 // and update offset_low and offset_high along the way. We then add the following
657 // deoptimizations in the loop pre-header (suppose end is not inclusive).
658 // if (start < -offset_low) deoptimize();
659 // if (end >= array.length - offset_high) deoptimize();
660 // It might be necessary to first hoist array.length (and the null check on it) out of
661 // the loop with another deoptimization.
662 //
663 // In order not to trigger deoptimization unnecessarily, we want to make a strong
664 // guarantee that no deoptimization is triggered if the loop body itself doesn't
665 // throw AIOOBE. (It's the same as saying if deoptimization is triggered, the loop
666 // body must throw AIOOBE).
667 // This is achieved by the following:
668 // 1) We only process loops that iterate through the full monotonic range from
669 // initial_ to end_. We do the following checks to make sure that's the case:
670 // a) The loop doesn't have early exit (via break, return, etc.)
671 // b) The increment_ is 1/-1. An increment of 2, for example, may skip end_.
672 // 2) We only collect array accesses of blocks in the loop body that dominate
673 // all loop back edges, these array accesses are guaranteed to happen
674 // at each loop iteration.
675 // With 1) and 2), if the loop body doesn't throw AIOOBE, collected array accesses
676 // when the induction variable is at initial_ and end_ must be in a legal range.
677 // Since the added deoptimizations are basically checking the induction variable
678 // at initial_ and end_ values, no deoptimization will be triggered either.
679 //
680 // A special case is the loop body isn't entered at all. In that case, we may still
681 // add deoptimization due to the analysis described above. In order not to trigger
682 // deoptimization, we do a test between initial_ and end_ first and skip over
683 // the added deoptimization.
684 ValueRange* NarrowWithDeoptimization() {
685 if (increment_ != 1 && increment_ != -1) {
686 // In order not to trigger deoptimization unnecessarily, we want to
687 // make sure the loop iterates through the full range from initial_ to
688 // end_ so that boundaries are covered by the loop. An increment of 2,
689 // for example, may skip end_.
690 return this;
691 }
692
693 if (end_ == nullptr) {
694 // No full info to add deoptimization.
695 return this;
696 }
697
698 HBasicBlock* header = induction_variable_->GetBlock();
699 DCHECK(header->IsLoopHeader());
700 HBasicBlock* pre_header = header->GetLoopInformation()->GetPreHeader();
701 if (!initial_->GetBlock()->Dominates(pre_header) ||
702 !end_->GetBlock()->Dominates(pre_header)) {
703 // Can't add a check in loop pre-header if the value isn't available there.
704 return this;
705 }
706
707 ArrayAccessInsideLoopFinder finder(induction_variable_);
708
709 if (!finder.HasFoundArrayLength()) {
710 // No array access was found inside the loop that can benefit
711 // from deoptimization.
712 return this;
713 }
714
715 if (!AddDeoptimization(finder)) {
716 return this;
717 }
718
719 // After added deoptimizations, induction variable fits in
720 // [-offset_low, array.length-1-offset_high], adjusted with collected offsets.
721 ValueBound lower = ValueBound(0, -finder.GetOffsetLow());
722 ValueBound upper = ValueBound(finder.GetFoundArrayLength(), -1 - finder.GetOffsetHigh());
723 // We've narrowed the range after added deoptimizations.
724 return new (GetAllocator()) ValueRange(GetAllocator(), lower, upper);
725 }
726
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700727 // Returns true if adding a (constant >= value) check for deoptimization
728 // is allowed and will benefit compiled code.
Mingyao Yang3584bce2015-05-19 16:01:59 -0700729 bool CanAddDeoptimizationConstant(HInstruction* value, int32_t constant, bool* is_proven) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700730 *is_proven = false;
Mingyao Yang3584bce2015-05-19 16:01:59 -0700731 HBasicBlock* header = induction_variable_->GetBlock();
732 DCHECK(header->IsLoopHeader());
733 HBasicBlock* pre_header = header->GetLoopInformation()->GetPreHeader();
734 DCHECK(value->GetBlock()->Dominates(pre_header));
735
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700736 // See if we can prove the relationship first.
737 if (value->IsIntConstant()) {
738 if (value->AsIntConstant()->GetValue() >= constant) {
739 // Already true.
740 *is_proven = true;
741 return true;
742 } else {
743 // May throw exception. Don't add deoptimization.
744 // Keep bounds checks in the loops.
745 return false;
746 }
747 }
748 // Can benefit from deoptimization.
749 return true;
750 }
751
Mingyao Yang3584bce2015-05-19 16:01:59 -0700752 // Try to filter out cases that the loop entry test will never be true.
753 bool LoopEntryTestUseful() {
754 if (initial_->IsIntConstant() && end_->IsIntConstant()) {
755 int32_t initial_val = initial_->AsIntConstant()->GetValue();
756 int32_t end_val = end_->AsIntConstant()->GetValue();
757 if (increment_ == 1) {
758 if (inclusive_) {
759 return initial_val > end_val;
760 } else {
761 return initial_val >= end_val;
762 }
763 } else {
Andreas Gampe45d68f12015-06-10 18:33:26 -0700764 DCHECK_EQ(increment_, -1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700765 if (inclusive_) {
766 return initial_val < end_val;
767 } else {
768 return initial_val <= end_val;
769 }
770 }
771 }
772 return true;
773 }
774
775 // Returns the block for adding deoptimization.
776 HBasicBlock* TransformLoopForDeoptimizationIfNeeded() {
777 HBasicBlock* header = induction_variable_->GetBlock();
778 DCHECK(header->IsLoopHeader());
779 HBasicBlock* pre_header = header->GetLoopInformation()->GetPreHeader();
780 // Deoptimization is only added when both initial_ and end_ are defined
781 // before the loop.
782 DCHECK(initial_->GetBlock()->Dominates(pre_header));
783 DCHECK(end_->GetBlock()->Dominates(pre_header));
784
785 // If it can be proven the loop body is definitely entered (unless exception
786 // is thrown in the loop header for which triggering deoptimization is fine),
787 // there is no need for tranforming the loop. In that case, deoptimization
788 // will just be added in the loop pre-header.
789 if (!LoopEntryTestUseful()) {
790 return pre_header;
791 }
792
793 HGraph* graph = header->GetGraph();
794 graph->TransformLoopHeaderForBCE(header);
795 HBasicBlock* new_pre_header = header->GetDominator();
796 DCHECK(new_pre_header == header->GetLoopInformation()->GetPreHeader());
797 HBasicBlock* if_block = new_pre_header->GetDominator();
Vladimir Marko60584552015-09-03 13:35:12 +0000798 HBasicBlock* dummy_block = if_block->GetSuccessor(0); // True successor.
799 HBasicBlock* deopt_block = if_block->GetSuccessor(1); // False successor.
Mingyao Yang3584bce2015-05-19 16:01:59 -0700800
801 dummy_block->AddInstruction(new (graph->GetArena()) HGoto());
802 deopt_block->AddInstruction(new (graph->GetArena()) HGoto());
803 new_pre_header->AddInstruction(new (graph->GetArena()) HGoto());
804 return deopt_block;
805 }
806
807 // Adds a test between initial_ and end_ to see if the loop body is entered.
808 // If the loop body isn't entered at all, it jumps to the loop pre-header (after
809 // transformation) to avoid any deoptimization.
810 void AddLoopBodyEntryTest() {
811 HBasicBlock* header = induction_variable_->GetBlock();
812 DCHECK(header->IsLoopHeader());
813 HBasicBlock* pre_header = header->GetLoopInformation()->GetPreHeader();
814 HBasicBlock* if_block = pre_header->GetDominator();
815 HGraph* graph = header->GetGraph();
816
817 HCondition* cond;
818 if (increment_ == 1) {
819 if (inclusive_) {
820 cond = new (graph->GetArena()) HGreaterThan(initial_, end_);
821 } else {
822 cond = new (graph->GetArena()) HGreaterThanOrEqual(initial_, end_);
823 }
824 } else {
Andreas Gampe45d68f12015-06-10 18:33:26 -0700825 DCHECK_EQ(increment_, -1);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700826 if (inclusive_) {
827 cond = new (graph->GetArena()) HLessThan(initial_, end_);
828 } else {
829 cond = new (graph->GetArena()) HLessThanOrEqual(initial_, end_);
830 }
831 }
832 HIf* h_if = new (graph->GetArena()) HIf(cond);
833 if_block->AddInstruction(cond);
834 if_block->AddInstruction(h_if);
835 }
836
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700837 // Adds a check that (value >= constant), and HDeoptimize otherwise.
838 void AddDeoptimizationConstant(HInstruction* value,
Mingyao Yang3584bce2015-05-19 16:01:59 -0700839 int32_t constant,
840 HBasicBlock* deopt_block,
841 bool loop_entry_test_block_added) {
842 HBasicBlock* header = induction_variable_->GetBlock();
843 DCHECK(header->IsLoopHeader());
844 HBasicBlock* pre_header = header->GetDominator();
845 if (loop_entry_test_block_added) {
Vladimir Marko60584552015-09-03 13:35:12 +0000846 DCHECK(deopt_block->GetSuccessor(0) == pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700847 } else {
848 DCHECK(deopt_block == pre_header);
849 }
850 HGraph* graph = header->GetGraph();
851 HSuspendCheck* suspend_check = header->GetLoopInformation()->GetSuspendCheck();
852 if (loop_entry_test_block_added) {
Vladimir Marko60584552015-09-03 13:35:12 +0000853 DCHECK_EQ(deopt_block, header->GetDominator()->GetDominator()->GetSuccessor(1));
Mingyao Yang3584bce2015-05-19 16:01:59 -0700854 }
855
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700856 HIntConstant* const_instr = graph->GetIntConstant(constant);
857 HCondition* cond = new (graph->GetArena()) HLessThan(value, const_instr);
858 HDeoptimize* deoptimize = new (graph->GetArena())
859 HDeoptimize(cond, suspend_check->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -0700860 deopt_block->InsertInstructionBefore(cond, deopt_block->GetLastInstruction());
861 deopt_block->InsertInstructionBefore(deoptimize, deopt_block->GetLastInstruction());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700862 deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
Mingyao Yang3584bce2015-05-19 16:01:59 -0700863 suspend_check->GetEnvironment(), header);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700864 }
865
866 // Returns true if adding a (value <= array_length + offset) check for deoptimization
867 // is allowed and will benefit compiled code.
868 bool CanAddDeoptimizationArrayLength(HInstruction* value,
869 HArrayLength* array_length,
870 int32_t offset,
871 bool* is_proven) {
872 *is_proven = false;
Mingyao Yang3584bce2015-05-19 16:01:59 -0700873 HBasicBlock* header = induction_variable_->GetBlock();
874 DCHECK(header->IsLoopHeader());
875 HBasicBlock* pre_header = header->GetLoopInformation()->GetPreHeader();
876 DCHECK(value->GetBlock()->Dominates(pre_header));
877
878 if (array_length->GetBlock() == header) {
879 // array_length_in_loop_body_if_needed only has correct value when the loop
880 // body is entered. We bail out in this case. Usually array_length defined
881 // in the loop header is already hoisted by licm.
882 return false;
883 } else {
884 // array_length is defined either before the loop header already, or in
885 // the loop body since it's used in the loop body. If it's defined in the loop body,
886 // a phi array_length_in_loop_body_if_needed is used to replace it. In that case,
887 // all the uses of array_length must be dominated by its definition in the loop
888 // body. array_length_in_loop_body_if_needed is guaranteed to be the same as
889 // array_length once the loop body is entered so all the uses of the phi will
890 // use the correct value.
891 }
892
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700893 if (offset > 0) {
894 // There might be overflow issue.
895 // TODO: handle this, possibly with some distance relationship between
896 // offset_low and offset_high, or using another deoptimization to make
897 // sure (array_length + offset) doesn't overflow.
898 return false;
899 }
900
901 // See if we can prove the relationship first.
902 if (value == array_length) {
903 if (offset >= 0) {
904 // Already true.
905 *is_proven = true;
906 return true;
907 } else {
908 // May throw exception. Don't add deoptimization.
909 // Keep bounds checks in the loops.
910 return false;
911 }
912 }
913 // Can benefit from deoptimization.
914 return true;
915 }
916
917 // Adds a check that (value <= array_length + offset), and HDeoptimize otherwise.
918 void AddDeoptimizationArrayLength(HInstruction* value,
919 HArrayLength* array_length,
Mingyao Yang3584bce2015-05-19 16:01:59 -0700920 int32_t offset,
921 HBasicBlock* deopt_block,
922 bool loop_entry_test_block_added) {
923 HBasicBlock* header = induction_variable_->GetBlock();
924 DCHECK(header->IsLoopHeader());
925 HBasicBlock* pre_header = header->GetDominator();
926 if (loop_entry_test_block_added) {
Vladimir Marko60584552015-09-03 13:35:12 +0000927 DCHECK(deopt_block->GetSuccessor(0) == pre_header);
Mingyao Yang3584bce2015-05-19 16:01:59 -0700928 } else {
929 DCHECK(deopt_block == pre_header);
930 }
931 HGraph* graph = header->GetGraph();
932 HSuspendCheck* suspend_check = header->GetLoopInformation()->GetSuspendCheck();
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700933
934 // We may need to hoist null-check and array_length out of loop first.
Mingyao Yang3584bce2015-05-19 16:01:59 -0700935 if (!array_length->GetBlock()->Dominates(deopt_block)) {
936 // array_length must be defined in the loop body.
937 DCHECK(header->GetLoopInformation()->Contains(*array_length->GetBlock()));
938 DCHECK(array_length->GetBlock() != header);
939
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700940 HInstruction* array = array_length->InputAt(0);
941 HNullCheck* null_check = array->AsNullCheck();
942 if (null_check != nullptr) {
943 array = null_check->InputAt(0);
944 }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700945 // We've already made sure the array is defined before the loop when collecting
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700946 // array accesses for the loop.
Mingyao Yang3584bce2015-05-19 16:01:59 -0700947 DCHECK(array->GetBlock()->Dominates(deopt_block));
948 if (null_check != nullptr && !null_check->GetBlock()->Dominates(deopt_block)) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700949 // Hoist null check out of loop with a deoptimization.
950 HNullConstant* null_constant = graph->GetNullConstant();
951 HCondition* null_check_cond = new (graph->GetArena()) HEqual(array, null_constant);
952 // TODO: for one dex_pc, share the same deoptimization slow path.
953 HDeoptimize* null_check_deoptimize = new (graph->GetArena())
954 HDeoptimize(null_check_cond, suspend_check->GetDexPc());
Mingyao Yang3584bce2015-05-19 16:01:59 -0700955 deopt_block->InsertInstructionBefore(
956 null_check_cond, deopt_block->GetLastInstruction());
957 deopt_block->InsertInstructionBefore(
958 null_check_deoptimize, deopt_block->GetLastInstruction());
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700959 // Eliminate null check in the loop.
960 null_check->ReplaceWith(array);
961 null_check->GetBlock()->RemoveInstruction(null_check);
962 null_check_deoptimize->CopyEnvironmentFromWithLoopPhiAdjustment(
Mingyao Yang3584bce2015-05-19 16:01:59 -0700963 suspend_check->GetEnvironment(), header);
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700964 }
Mingyao Yang3584bce2015-05-19 16:01:59 -0700965
966 HArrayLength* new_array_length = new (graph->GetArena()) HArrayLength(array);
967 deopt_block->InsertInstructionBefore(new_array_length, deopt_block->GetLastInstruction());
968
969 if (loop_entry_test_block_added) {
970 // Replace array_length defined inside the loop body with a phi
971 // array_length_in_loop_body_if_needed. This is a synthetic phi so there is
972 // no vreg number for it.
973 HPhi* phi = new (graph->GetArena()) HPhi(
974 graph->GetArena(), kNoRegNumber, 2, Primitive::kPrimInt);
975 // Set to 0 if the loop body isn't entered.
976 phi->SetRawInputAt(0, graph->GetIntConstant(0));
977 // Set to array.length if the loop body is entered.
978 phi->SetRawInputAt(1, new_array_length);
979 pre_header->AddPhi(phi);
980 array_length->ReplaceWith(phi);
981 // Make sure phi is only used after the loop body is entered.
982 if (kIsDebugBuild) {
983 for (HUseIterator<HInstruction*> it(phi->GetUses());
984 !it.Done();
985 it.Advance()) {
986 HInstruction* user = it.Current()->GetUser();
987 DCHECK(GetLoopHeaderSuccesorInLoop()->Dominates(user->GetBlock()));
988 }
989 }
990 } else {
991 array_length->ReplaceWith(new_array_length);
992 }
993
994 array_length->GetBlock()->RemoveInstruction(array_length);
995 // Use new_array_length for deopt.
996 array_length = new_array_length;
Mingyao Yang206d6fd2015-04-13 16:46:28 -0700997 }
998
Mingyao Yang3584bce2015-05-19 16:01:59 -0700999 HInstruction* added = array_length;
1000 if (offset != 0) {
1001 HIntConstant* offset_instr = graph->GetIntConstant(offset);
1002 added = new (graph->GetArena()) HAdd(Primitive::kPrimInt, array_length, offset_instr);
1003 deopt_block->InsertInstructionBefore(added, deopt_block->GetLastInstruction());
1004 }
1005 HCondition* cond = new (graph->GetArena()) HGreaterThan(value, added);
1006 HDeoptimize* deopt = new (graph->GetArena()) HDeoptimize(cond, suspend_check->GetDexPc());
1007 deopt_block->InsertInstructionBefore(cond, deopt_block->GetLastInstruction());
1008 deopt_block->InsertInstructionBefore(deopt, deopt_block->GetLastInstruction());
1009 deopt->CopyEnvironmentFromWithLoopPhiAdjustment(suspend_check->GetEnvironment(), header);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001010 }
1011
Mingyao Yang3584bce2015-05-19 16:01:59 -07001012 // Adds deoptimizations in loop pre-header with the collected array access
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001013 // data so that value ranges can be established in loop body.
1014 // Returns true if deoptimizations are successfully added, or if it's proven
1015 // it's not necessary.
1016 bool AddDeoptimization(const ArrayAccessInsideLoopFinder& finder) {
1017 int32_t offset_low = finder.GetOffsetLow();
1018 int32_t offset_high = finder.GetOffsetHigh();
1019 HArrayLength* array_length = finder.GetFoundArrayLength();
1020
1021 HBasicBlock* pre_header =
1022 induction_variable_->GetBlock()->GetLoopInformation()->GetPreHeader();
1023 if (!initial_->GetBlock()->Dominates(pre_header) ||
1024 !end_->GetBlock()->Dominates(pre_header)) {
1025 // Can't move initial_ or end_ into pre_header for comparisons.
1026 return false;
1027 }
1028
Mingyao Yang3584bce2015-05-19 16:01:59 -07001029 HBasicBlock* deopt_block;
1030 bool loop_entry_test_block_added = false;
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001031 bool is_constant_proven, is_length_proven;
Mingyao Yang3584bce2015-05-19 16:01:59 -07001032
1033 HInstruction* const_comparing_instruction;
1034 int32_t const_compared_to;
1035 HInstruction* array_length_comparing_instruction;
1036 int32_t array_length_offset;
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001037 if (increment_ == 1) {
1038 // Increasing from initial_ to end_.
Mingyao Yang3584bce2015-05-19 16:01:59 -07001039 const_comparing_instruction = initial_;
1040 const_compared_to = -offset_low;
1041 array_length_comparing_instruction = end_;
1042 array_length_offset = inclusive_ ? -offset_high - 1 : -offset_high;
1043 } else {
1044 const_comparing_instruction = end_;
1045 const_compared_to = inclusive_ ? -offset_low : -offset_low - 1;
1046 array_length_comparing_instruction = initial_;
1047 array_length_offset = -offset_high - 1;
1048 }
1049
1050 if (CanAddDeoptimizationConstant(const_comparing_instruction,
1051 const_compared_to,
1052 &is_constant_proven) &&
1053 CanAddDeoptimizationArrayLength(array_length_comparing_instruction,
1054 array_length,
1055 array_length_offset,
1056 &is_length_proven)) {
1057 if (!is_constant_proven || !is_length_proven) {
1058 deopt_block = TransformLoopForDeoptimizationIfNeeded();
1059 loop_entry_test_block_added = (deopt_block != pre_header);
1060 if (loop_entry_test_block_added) {
1061 // Loop body may be entered.
1062 AddLoopBodyEntryTest();
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001063 }
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001064 }
Mingyao Yang3584bce2015-05-19 16:01:59 -07001065 if (!is_constant_proven) {
1066 AddDeoptimizationConstant(const_comparing_instruction,
1067 const_compared_to,
1068 deopt_block,
1069 loop_entry_test_block_added);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001070 }
Mingyao Yang3584bce2015-05-19 16:01:59 -07001071 if (!is_length_proven) {
1072 AddDeoptimizationArrayLength(array_length_comparing_instruction,
1073 array_length,
1074 array_length_offset,
1075 deopt_block,
1076 loop_entry_test_block_added);
1077 }
1078 return true;
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001079 }
1080 return false;
1081 }
1082
Mingyao Yangf384f882014-10-22 16:08:18 -07001083 private:
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001084 HPhi* const induction_variable_; // Induction variable for this monotonic value range.
1085 HInstruction* const initial_; // Initial value.
1086 HInstruction* end_; // End value.
1087 bool inclusive_; // Whether end value is inclusive.
1088 const int32_t increment_; // Increment for each loop iteration.
1089 const ValueBound bound_; // Additional value bound info for initial_.
Mingyao Yangf384f882014-10-22 16:08:18 -07001090
1091 DISALLOW_COPY_AND_ASSIGN(MonotonicValueRange);
1092};
1093
1094class BCEVisitor : public HGraphVisitor {
1095 public:
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001096 // The least number of bounds checks that should be eliminated by triggering
1097 // the deoptimization technique.
1098 static constexpr size_t kThresholdForAddingDeoptimize = 2;
1099
1100 // Very large constant index is considered as an anomaly. This is a threshold
1101 // beyond which we don't bother to apply the deoptimization technique since
1102 // it's likely some AIOOBE will be thrown.
1103 static constexpr int32_t kMaxConstantForAddingDeoptimize = INT_MAX - 1024 * 1024;
1104
Mingyao Yang3584bce2015-05-19 16:01:59 -07001105 // Added blocks for loop body entry test.
1106 bool IsAddedBlock(HBasicBlock* block) const {
1107 return block->GetBlockId() >= initial_block_size_;
1108 }
1109
Aart Bik22af3be2015-09-10 12:50:58 -07001110 BCEVisitor(HGraph* graph, HInductionVarAnalysis* induction_analysis)
1111 : HGraphVisitor(graph),
1112 maps_(graph->GetBlocks().Size()),
1113 need_to_revisit_block_(false),
1114 initial_block_size_(graph->GetBlocks().Size()),
1115 induction_range_(induction_analysis) {}
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001116
1117 void VisitBasicBlock(HBasicBlock* block) OVERRIDE {
Mingyao Yang3584bce2015-05-19 16:01:59 -07001118 DCHECK(!IsAddedBlock(block));
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001119 first_constant_index_bounds_check_map_.clear();
1120 HGraphVisitor::VisitBasicBlock(block);
1121 if (need_to_revisit_block_) {
1122 AddComparesWithDeoptimization(block);
1123 need_to_revisit_block_ = false;
1124 first_constant_index_bounds_check_map_.clear();
1125 GetValueRangeMap(block)->clear();
1126 HGraphVisitor::VisitBasicBlock(block);
1127 }
1128 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001129
1130 private:
1131 // Return the map of proven value ranges at the beginning of a basic block.
1132 ArenaSafeMap<int, ValueRange*>* GetValueRangeMap(HBasicBlock* basic_block) {
Mingyao Yang3584bce2015-05-19 16:01:59 -07001133 if (IsAddedBlock(basic_block)) {
1134 // Added blocks don't keep value ranges.
1135 return nullptr;
1136 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001137 int block_id = basic_block->GetBlockId();
1138 if (maps_.at(block_id) == nullptr) {
1139 std::unique_ptr<ArenaSafeMap<int, ValueRange*>> map(
1140 new ArenaSafeMap<int, ValueRange*>(
1141 std::less<int>(), GetGraph()->GetArena()->Adapter()));
1142 maps_.at(block_id) = std::move(map);
1143 }
1144 return maps_.at(block_id).get();
1145 }
1146
1147 // Traverse up the dominator tree to look for value range info.
1148 ValueRange* LookupValueRange(HInstruction* instruction, HBasicBlock* basic_block) {
1149 while (basic_block != nullptr) {
1150 ArenaSafeMap<int, ValueRange*>* map = GetValueRangeMap(basic_block);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001151 if (map != nullptr) {
1152 if (map->find(instruction->GetId()) != map->end()) {
1153 return map->Get(instruction->GetId());
1154 }
1155 } else {
1156 DCHECK(IsAddedBlock(basic_block));
Mingyao Yangf384f882014-10-22 16:08:18 -07001157 }
1158 basic_block = basic_block->GetDominator();
1159 }
1160 // Didn't find any.
1161 return nullptr;
1162 }
1163
Aart Bik22af3be2015-09-10 12:50:58 -07001164 // Return the range resulting from induction variable analysis of "instruction" when the value
1165 // is used from "context", for example, an index used from a bounds-check inside a loop body.
1166 ValueRange* LookupInductionRange(HInstruction* context, HInstruction* instruction) {
1167 InductionVarRange::Value v1 = induction_range_.GetMinInduction(context, instruction);
1168 InductionVarRange::Value v2 = induction_range_.GetMaxInduction(context, instruction);
1169 if ((v1.a_constant == 0 || v1.a_constant == 1) && v1.b_constant != INT_MIN &&
1170 (v2.a_constant == 0 || v2.a_constant == 1) && v2.b_constant != INT_MAX) {
1171 DCHECK(v1.a_constant == 1 || v1.instruction == nullptr);
1172 DCHECK(v2.a_constant == 1 || v2.instruction == nullptr);
1173 ValueBound low = ValueBound(v1.instruction, v1.b_constant);
1174 ValueBound up = ValueBound(v2.instruction, v2.b_constant);
1175 return new (GetGraph()->GetArena()) ValueRange(GetGraph()->GetArena(), low, up);
1176 }
1177 // Didn't find anything useful.
1178 return nullptr;
1179 }
1180
Mingyao Yang0304e182015-01-30 16:41:29 -08001181 // Narrow the value range of `instruction` at the end of `basic_block` with `range`,
1182 // and push the narrowed value range to `successor`.
Mingyao Yangf384f882014-10-22 16:08:18 -07001183 void ApplyRangeFromComparison(HInstruction* instruction, HBasicBlock* basic_block,
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001184 HBasicBlock* successor, ValueRange* range) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001185 ValueRange* existing_range = LookupValueRange(instruction, basic_block);
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001186 if (existing_range == nullptr) {
1187 if (range != nullptr) {
1188 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), range);
1189 }
1190 return;
1191 }
1192 if (existing_range->IsMonotonicValueRange()) {
1193 DCHECK(instruction->IsLoopHeaderPhi());
1194 // Make sure the comparison is in the loop header so each increment is
1195 // checked with a comparison.
1196 if (instruction->GetBlock() != basic_block) {
1197 return;
1198 }
1199 }
1200 ValueRange* narrowed_range = existing_range->Narrow(range);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001201 GetValueRangeMap(successor)->Overwrite(instruction->GetId(), narrowed_range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001202 }
1203
Mingyao Yang57e04752015-02-09 18:13:26 -08001204 // Special case that we may simultaneously narrow two MonotonicValueRange's to
1205 // regular value ranges.
1206 void HandleIfBetweenTwoMonotonicValueRanges(HIf* instruction,
1207 HInstruction* left,
1208 HInstruction* right,
1209 IfCondition cond,
1210 MonotonicValueRange* left_range,
1211 MonotonicValueRange* right_range) {
1212 DCHECK(left->IsLoopHeaderPhi());
1213 DCHECK(right->IsLoopHeaderPhi());
1214 if (instruction->GetBlock() != left->GetBlock()) {
1215 // Comparison needs to be in loop header to make sure it's done after each
1216 // increment/decrement.
1217 return;
1218 }
1219
1220 // Handle common cases which also don't have overflow/underflow concerns.
1221 if (left_range->GetIncrement() == 1 &&
1222 left_range->GetBound().IsConstant() &&
1223 right_range->GetIncrement() == -1 &&
1224 right_range->GetBound().IsRelatedToArrayLength() &&
1225 right_range->GetBound().GetConstant() < 0) {
Mingyao Yang57e04752015-02-09 18:13:26 -08001226 HBasicBlock* successor = nullptr;
1227 int32_t left_compensation = 0;
1228 int32_t right_compensation = 0;
1229 if (cond == kCondLT) {
1230 left_compensation = -1;
1231 right_compensation = 1;
1232 successor = instruction->IfTrueSuccessor();
1233 } else if (cond == kCondLE) {
1234 successor = instruction->IfTrueSuccessor();
1235 } else if (cond == kCondGT) {
1236 successor = instruction->IfFalseSuccessor();
1237 } else if (cond == kCondGE) {
1238 left_compensation = -1;
1239 right_compensation = 1;
1240 successor = instruction->IfFalseSuccessor();
1241 } else {
1242 // We don't handle '=='/'!=' test in case left and right can cross and
1243 // miss each other.
1244 return;
1245 }
1246
1247 if (successor != nullptr) {
1248 bool overflow;
1249 bool underflow;
1250 ValueRange* new_left_range = new (GetGraph()->GetArena()) ValueRange(
1251 GetGraph()->GetArena(),
1252 left_range->GetBound(),
1253 right_range->GetBound().Add(left_compensation, &overflow, &underflow));
1254 if (!overflow && !underflow) {
1255 ApplyRangeFromComparison(left, instruction->GetBlock(), successor,
1256 new_left_range);
1257 }
1258
1259 ValueRange* new_right_range = new (GetGraph()->GetArena()) ValueRange(
1260 GetGraph()->GetArena(),
1261 left_range->GetBound().Add(right_compensation, &overflow, &underflow),
1262 right_range->GetBound());
1263 if (!overflow && !underflow) {
1264 ApplyRangeFromComparison(right, instruction->GetBlock(), successor,
1265 new_right_range);
1266 }
1267 }
1268 }
1269 }
1270
Mingyao Yangf384f882014-10-22 16:08:18 -07001271 // Handle "if (left cmp_cond right)".
1272 void HandleIf(HIf* instruction, HInstruction* left, HInstruction* right, IfCondition cond) {
1273 HBasicBlock* block = instruction->GetBlock();
1274
1275 HBasicBlock* true_successor = instruction->IfTrueSuccessor();
1276 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +00001277 DCHECK_EQ(true_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -07001278
1279 HBasicBlock* false_successor = instruction->IfFalseSuccessor();
1280 // There should be no critical edge at this point.
Vladimir Marko60584552015-09-03 13:35:12 +00001281 DCHECK_EQ(false_successor->GetPredecessors().size(), 1u);
Mingyao Yangf384f882014-10-22 16:08:18 -07001282
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001283 ValueRange* left_range = LookupValueRange(left, block);
1284 MonotonicValueRange* left_monotonic_range = nullptr;
1285 if (left_range != nullptr) {
1286 left_monotonic_range = left_range->AsMonotonicValueRange();
1287 if (left_monotonic_range != nullptr) {
Mingyao Yang3584bce2015-05-19 16:01:59 -07001288 HBasicBlock* loop_head = left_monotonic_range->GetLoopHeader();
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001289 if (instruction->GetBlock() != loop_head) {
1290 // For monotonic value range, don't handle `instruction`
1291 // if it's not defined in the loop header.
1292 return;
1293 }
1294 }
1295 }
1296
Mingyao Yang64197522014-12-05 15:56:23 -08001297 bool found;
1298 ValueBound bound = ValueBound::DetectValueBoundFromValue(right, &found);
Mingyao Yang0304e182015-01-30 16:41:29 -08001299 // Each comparison can establish a lower bound and an upper bound
1300 // for the left hand side.
Mingyao Yangf384f882014-10-22 16:08:18 -07001301 ValueBound lower = bound;
1302 ValueBound upper = bound;
1303 if (!found) {
Mingyao Yang0304e182015-01-30 16:41:29 -08001304 // No constant or array.length+c format bound found.
Mingyao Yangf384f882014-10-22 16:08:18 -07001305 // 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 -08001306 ValueRange* right_range = LookupValueRange(right, block);
1307 if (right_range != nullptr) {
1308 if (right_range->IsMonotonicValueRange()) {
Mingyao Yang57e04752015-02-09 18:13:26 -08001309 if (left_range != nullptr && left_range->IsMonotonicValueRange()) {
1310 HandleIfBetweenTwoMonotonicValueRanges(instruction, left, right, cond,
1311 left_range->AsMonotonicValueRange(),
1312 right_range->AsMonotonicValueRange());
1313 return;
1314 }
1315 }
1316 lower = right_range->GetLower();
1317 upper = right_range->GetUpper();
Mingyao Yangf384f882014-10-22 16:08:18 -07001318 } else {
1319 lower = ValueBound::Min();
1320 upper = ValueBound::Max();
1321 }
1322 }
1323
Mingyao Yang0304e182015-01-30 16:41:29 -08001324 bool overflow, underflow;
Mingyao Yangf384f882014-10-22 16:08:18 -07001325 if (cond == kCondLT || cond == kCondLE) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001326 if (left_monotonic_range != nullptr) {
1327 // Update the info for monotonic value range.
1328 if (left_monotonic_range->GetInductionVariable() == left &&
1329 left_monotonic_range->GetIncrement() < 0 &&
Mingyao Yang3584bce2015-05-19 16:01:59 -07001330 block == left_monotonic_range->GetLoopHeader() &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001331 instruction->IfFalseSuccessor()->GetLoopInformation() == block->GetLoopInformation()) {
1332 left_monotonic_range->SetEnd(right);
1333 left_monotonic_range->SetInclusive(cond == kCondLT);
1334 }
1335 }
1336
Mingyao Yangf384f882014-10-22 16:08:18 -07001337 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -08001338 int32_t compensation = (cond == kCondLT) ? -1 : 0; // upper bound is inclusive
1339 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
1340 if (overflow || underflow) {
1341 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001342 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001343 ValueRange* new_range = new (GetGraph()->GetArena())
1344 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
1345 ApplyRangeFromComparison(left, block, true_successor, new_range);
1346 }
1347
1348 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -08001349 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
1350 int32_t compensation = (cond == kCondLE) ? 1 : 0; // lower bound is inclusive
1351 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
1352 if (overflow || underflow) {
1353 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001354 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001355 ValueRange* new_range = new (GetGraph()->GetArena())
1356 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
1357 ApplyRangeFromComparison(left, block, false_successor, new_range);
1358 }
1359 } else if (cond == kCondGT || cond == kCondGE) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001360 if (left_monotonic_range != nullptr) {
1361 // Update the info for monotonic value range.
1362 if (left_monotonic_range->GetInductionVariable() == left &&
1363 left_monotonic_range->GetIncrement() > 0 &&
Mingyao Yang3584bce2015-05-19 16:01:59 -07001364 block == left_monotonic_range->GetLoopHeader() &&
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001365 instruction->IfFalseSuccessor()->GetLoopInformation() == block->GetLoopInformation()) {
1366 left_monotonic_range->SetEnd(right);
1367 left_monotonic_range->SetInclusive(cond == kCondGT);
1368 }
1369 }
1370
Mingyao Yangf384f882014-10-22 16:08:18 -07001371 // array.length as a lower bound isn't considered useful.
Mingyao Yang0304e182015-01-30 16:41:29 -08001372 if (!lower.Equals(ValueBound::Min()) && !lower.IsRelatedToArrayLength()) {
1373 int32_t compensation = (cond == kCondGT) ? 1 : 0; // lower bound is inclusive
1374 ValueBound new_lower = lower.Add(compensation, &overflow, &underflow);
1375 if (overflow || underflow) {
1376 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001377 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001378 ValueRange* new_range = new (GetGraph()->GetArena())
1379 ValueRange(GetGraph()->GetArena(), new_lower, ValueBound::Max());
1380 ApplyRangeFromComparison(left, block, true_successor, new_range);
1381 }
1382
1383 if (!upper.Equals(ValueBound::Max())) {
Mingyao Yang0304e182015-01-30 16:41:29 -08001384 int32_t compensation = (cond == kCondGE) ? -1 : 0; // upper bound is inclusive
1385 ValueBound new_upper = upper.Add(compensation, &overflow, &underflow);
1386 if (overflow || underflow) {
1387 return;
Mingyao Yang64197522014-12-05 15:56:23 -08001388 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001389 ValueRange* new_range = new (GetGraph()->GetArena())
1390 ValueRange(GetGraph()->GetArena(), ValueBound::Min(), new_upper);
1391 ApplyRangeFromComparison(left, block, false_successor, new_range);
1392 }
1393 }
1394 }
1395
1396 void VisitBoundsCheck(HBoundsCheck* bounds_check) {
1397 HBasicBlock* block = bounds_check->GetBlock();
1398 HInstruction* index = bounds_check->InputAt(0);
1399 HInstruction* array_length = bounds_check->InputAt(1);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001400 DCHECK(array_length->IsIntConstant() ||
1401 array_length->IsArrayLength() ||
1402 array_length->IsPhi());
1403
1404 if (array_length->IsPhi()) {
1405 // Input 1 of the phi contains the real array.length once the loop body is
1406 // entered. That value will be used for bound analysis. The graph is still
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001407 // strictly in SSA form.
Mingyao Yang3584bce2015-05-19 16:01:59 -07001408 array_length = array_length->AsPhi()->InputAt(1)->AsArrayLength();
1409 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001410
Mingyao Yang0304e182015-01-30 16:41:29 -08001411 if (!index->IsIntConstant()) {
Aart Bik22af3be2015-09-10 12:50:58 -07001412 ValueBound lower = ValueBound(nullptr, 0); // constant 0
1413 ValueBound upper = ValueBound(array_length, -1); // array_length - 1
1414 ValueRange array_range(GetGraph()->GetArena(), lower, upper);
1415 // Try range obtained by local analysis.
Mingyao Yang0304e182015-01-30 16:41:29 -08001416 ValueRange* index_range = LookupValueRange(index, block);
Aart Bik22af3be2015-09-10 12:50:58 -07001417 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
1418 ReplaceBoundsCheck(bounds_check, index);
1419 return;
1420 }
1421 // Try range obtained by induction variable analysis.
1422 index_range = LookupInductionRange(bounds_check, index);
1423 if (index_range != nullptr && index_range->FitsIn(&array_range)) {
1424 ReplaceBoundsCheck(bounds_check, index);
1425 return;
Mingyao Yangf384f882014-10-22 16:08:18 -07001426 }
Mingyao Yang0304e182015-01-30 16:41:29 -08001427 } else {
1428 int32_t constant = index->AsIntConstant()->GetValue();
1429 if (constant < 0) {
1430 // Will always throw exception.
1431 return;
1432 }
1433 if (array_length->IsIntConstant()) {
1434 if (constant < array_length->AsIntConstant()->GetValue()) {
1435 ReplaceBoundsCheck(bounds_check, index);
1436 }
1437 return;
1438 }
1439
1440 DCHECK(array_length->IsArrayLength());
1441 ValueRange* existing_range = LookupValueRange(array_length, block);
1442 if (existing_range != nullptr) {
1443 ValueBound lower = existing_range->GetLower();
1444 DCHECK(lower.IsConstant());
1445 if (constant < lower.GetConstant()) {
1446 ReplaceBoundsCheck(bounds_check, index);
1447 return;
1448 } else {
1449 // Existing range isn't strong enough to eliminate the bounds check.
1450 // Fall through to update the array_length range with info from this
1451 // bounds check.
1452 }
1453 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001454
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001455 if (first_constant_index_bounds_check_map_.find(array_length->GetId()) ==
1456 first_constant_index_bounds_check_map_.end()) {
1457 // Remember the first bounds check against array_length of a constant index.
1458 // That bounds check instruction has an associated HEnvironment where we
1459 // may add an HDeoptimize to eliminate bounds checks of constant indices
1460 // against array_length.
1461 first_constant_index_bounds_check_map_.Put(array_length->GetId(), bounds_check);
1462 } else {
1463 // We've seen it at least twice. It's beneficial to introduce a compare with
1464 // deoptimization fallback to eliminate the bounds checks.
1465 need_to_revisit_block_ = true;
1466 }
1467
Mingyao Yangf384f882014-10-22 16:08:18 -07001468 // Once we have an array access like 'array[5] = 1', we record array.length >= 6.
Mingyao Yang0304e182015-01-30 16:41:29 -08001469 // We currently don't do it for non-constant index since a valid array[i] can't prove
1470 // a valid array[i-1] yet due to the lower bound side.
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001471 if (constant == INT_MAX) {
1472 // INT_MAX as an index will definitely throw AIOOBE.
1473 return;
1474 }
Mingyao Yang64197522014-12-05 15:56:23 -08001475 ValueBound lower = ValueBound(nullptr, constant + 1);
Mingyao Yangf384f882014-10-22 16:08:18 -07001476 ValueBound upper = ValueBound::Max();
1477 ValueRange* range = new (GetGraph()->GetArena())
1478 ValueRange(GetGraph()->GetArena(), lower, upper);
Mingyao Yang0304e182015-01-30 16:41:29 -08001479 GetValueRangeMap(block)->Overwrite(array_length->GetId(), range);
Mingyao Yangf384f882014-10-22 16:08:18 -07001480 }
1481 }
1482
1483 void ReplaceBoundsCheck(HInstruction* bounds_check, HInstruction* index) {
1484 bounds_check->ReplaceWith(index);
1485 bounds_check->GetBlock()->RemoveInstruction(bounds_check);
1486 }
1487
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001488 static bool HasSameInputAtBackEdges(HPhi* phi) {
1489 DCHECK(phi->IsLoopHeaderPhi());
1490 // Start with input 1. Input 0 is from the incoming block.
1491 HInstruction* input1 = phi->InputAt(1);
1492 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Marko60584552015-09-03 13:35:12 +00001493 *phi->GetBlock()->GetPredecessor(1)));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001494 for (size_t i = 2, e = phi->InputCount(); i < e; ++i) {
1495 DCHECK(phi->GetBlock()->GetLoopInformation()->IsBackEdge(
Vladimir Marko60584552015-09-03 13:35:12 +00001496 *phi->GetBlock()->GetPredecessor(i)));
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001497 if (input1 != phi->InputAt(i)) {
1498 return false;
1499 }
1500 }
1501 return true;
1502 }
1503
Mingyao Yangf384f882014-10-22 16:08:18 -07001504 void VisitPhi(HPhi* phi) {
Nicolas Geoffraydb216f42015-05-05 17:02:20 +01001505 if (phi->IsLoopHeaderPhi()
1506 && (phi->GetType() == Primitive::kPrimInt)
1507 && HasSameInputAtBackEdges(phi)) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001508 HInstruction* instruction = phi->InputAt(1);
Mingyao Yang0304e182015-01-30 16:41:29 -08001509 HInstruction *left;
1510 int32_t increment;
1511 if (ValueBound::IsAddOrSubAConstant(instruction, &left, &increment)) {
1512 if (left == phi) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001513 HInstruction* initial_value = phi->InputAt(0);
1514 ValueRange* range = nullptr;
Mingyao Yang64197522014-12-05 15:56:23 -08001515 if (increment == 0) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001516 // Add constant 0. It's really a fixed value.
1517 range = new (GetGraph()->GetArena()) ValueRange(
1518 GetGraph()->GetArena(),
Mingyao Yang64197522014-12-05 15:56:23 -08001519 ValueBound(initial_value, 0),
1520 ValueBound(initial_value, 0));
Mingyao Yangf384f882014-10-22 16:08:18 -07001521 } else {
1522 // Monotonically increasing/decreasing.
Mingyao Yang64197522014-12-05 15:56:23 -08001523 bool found;
1524 ValueBound bound = ValueBound::DetectValueBoundFromValue(
1525 initial_value, &found);
1526 if (!found) {
1527 // No constant or array.length+c bound found.
1528 // For i=j, we can still use j's upper bound as i's upper bound.
1529 // Same for lower.
1530 ValueRange* initial_range = LookupValueRange(initial_value, phi->GetBlock());
1531 if (initial_range != nullptr) {
1532 bound = increment > 0 ? initial_range->GetLower() :
1533 initial_range->GetUpper();
1534 } else {
1535 bound = increment > 0 ? ValueBound::Min() : ValueBound::Max();
1536 }
1537 }
1538 range = new (GetGraph()->GetArena()) MonotonicValueRange(
Mingyao Yangf384f882014-10-22 16:08:18 -07001539 GetGraph()->GetArena(),
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001540 phi,
Mingyao Yangf384f882014-10-22 16:08:18 -07001541 initial_value,
Mingyao Yang64197522014-12-05 15:56:23 -08001542 increment,
1543 bound);
Mingyao Yangf384f882014-10-22 16:08:18 -07001544 }
1545 GetValueRangeMap(phi->GetBlock())->Overwrite(phi->GetId(), range);
1546 }
1547 }
1548 }
1549 }
1550
1551 void VisitIf(HIf* instruction) {
1552 if (instruction->InputAt(0)->IsCondition()) {
1553 HCondition* cond = instruction->InputAt(0)->AsCondition();
1554 IfCondition cmp = cond->GetCondition();
1555 if (cmp == kCondGT || cmp == kCondGE ||
1556 cmp == kCondLT || cmp == kCondLE) {
1557 HInstruction* left = cond->GetLeft();
1558 HInstruction* right = cond->GetRight();
1559 HandleIf(instruction, left, right, cmp);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001560
1561 HBasicBlock* block = instruction->GetBlock();
1562 ValueRange* left_range = LookupValueRange(left, block);
1563 if (left_range == nullptr) {
1564 return;
1565 }
1566
1567 if (left_range->IsMonotonicValueRange() &&
Mingyao Yang3584bce2015-05-19 16:01:59 -07001568 block == left_range->AsMonotonicValueRange()->GetLoopHeader()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001569 // The comparison is for an induction variable in the loop header.
1570 DCHECK(left == left_range->AsMonotonicValueRange()->GetInductionVariable());
Mingyao Yang3584bce2015-05-19 16:01:59 -07001571 HBasicBlock* loop_body_successor =
1572 left_range->AsMonotonicValueRange()->GetLoopHeaderSuccesorInLoop();
1573 if (loop_body_successor == nullptr) {
1574 // In case it's some strange loop structure.
1575 return;
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001576 }
1577 ValueRange* new_left_range = LookupValueRange(left, loop_body_successor);
Mingyao Yang3584bce2015-05-19 16:01:59 -07001578 if ((new_left_range == left_range) ||
1579 // Range narrowed with deoptimization is usually more useful than
1580 // a constant range.
1581 new_left_range->IsConstantValueRange()) {
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001582 // We are not successful in narrowing the monotonic value range to
1583 // a regular value range. Try using deoptimization.
1584 new_left_range = left_range->AsMonotonicValueRange()->
1585 NarrowWithDeoptimization();
1586 if (new_left_range != left_range) {
Mingyao Yang3584bce2015-05-19 16:01:59 -07001587 GetValueRangeMap(loop_body_successor)->Overwrite(left->GetId(), new_left_range);
Mingyao Yang206d6fd2015-04-13 16:46:28 -07001588 }
1589 }
1590 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001591 }
1592 }
1593 }
1594
1595 void VisitAdd(HAdd* add) {
1596 HInstruction* right = add->GetRight();
1597 if (right->IsIntConstant()) {
1598 ValueRange* left_range = LookupValueRange(add->GetLeft(), add->GetBlock());
1599 if (left_range == nullptr) {
1600 return;
1601 }
1602 ValueRange* range = left_range->Add(right->AsIntConstant()->GetValue());
1603 if (range != nullptr) {
1604 GetValueRangeMap(add->GetBlock())->Overwrite(add->GetId(), range);
1605 }
1606 }
1607 }
1608
1609 void VisitSub(HSub* sub) {
1610 HInstruction* left = sub->GetLeft();
1611 HInstruction* right = sub->GetRight();
1612 if (right->IsIntConstant()) {
1613 ValueRange* left_range = LookupValueRange(left, sub->GetBlock());
1614 if (left_range == nullptr) {
1615 return;
1616 }
1617 ValueRange* range = left_range->Add(-right->AsIntConstant()->GetValue());
1618 if (range != nullptr) {
1619 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
1620 return;
1621 }
1622 }
1623
1624 // Here we are interested in the typical triangular case of nested loops,
1625 // such as the inner loop 'for (int j=0; j<array.length-i; j++)' where i
1626 // 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 -08001627
1628 // Try to handle (array.length - i) or (array.length + c - i) format.
1629 HInstruction* left_of_left; // left input of left.
1630 int32_t right_const = 0;
1631 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &right_const)) {
1632 left = left_of_left;
1633 }
1634 // The value of left input of the sub equals (left + right_const).
1635
Mingyao Yangf384f882014-10-22 16:08:18 -07001636 if (left->IsArrayLength()) {
1637 HInstruction* array_length = left->AsArrayLength();
1638 ValueRange* right_range = LookupValueRange(right, sub->GetBlock());
1639 if (right_range != nullptr) {
1640 ValueBound lower = right_range->GetLower();
1641 ValueBound upper = right_range->GetUpper();
Mingyao Yang0304e182015-01-30 16:41:29 -08001642 if (lower.IsConstant() && upper.IsRelatedToArrayLength()) {
Mingyao Yangf384f882014-10-22 16:08:18 -07001643 HInstruction* upper_inst = upper.GetInstruction();
Mingyao Yang0304e182015-01-30 16:41:29 -08001644 // Make sure it's the same array.
1645 if (ValueBound::Equal(array_length, upper_inst)) {
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001646 int32_t c0 = right_const;
1647 int32_t c1 = lower.GetConstant();
1648 int32_t c2 = upper.GetConstant();
1649 // (array.length + c0 - v) where v is in [c1, array.length + c2]
1650 // gets [c0 - c2, array.length + c0 - c1] as its value range.
1651 if (!ValueBound::WouldAddOverflowOrUnderflow(c0, -c2) &&
1652 !ValueBound::WouldAddOverflowOrUnderflow(c0, -c1)) {
1653 if ((c0 - c1) <= 0) {
1654 // array.length + (c0 - c1) won't overflow/underflow.
1655 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1656 GetGraph()->GetArena(),
1657 ValueBound(nullptr, right_const - upper.GetConstant()),
1658 ValueBound(array_length, right_const - lower.GetConstant()));
1659 GetValueRangeMap(sub->GetBlock())->Overwrite(sub->GetId(), range);
1660 }
1661 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001662 }
1663 }
1664 }
1665 }
1666 }
1667
Mingyao Yang8c8bad82015-02-09 18:13:26 -08001668 void FindAndHandlePartialArrayLength(HBinaryOperation* instruction) {
1669 DCHECK(instruction->IsDiv() || instruction->IsShr() || instruction->IsUShr());
1670 HInstruction* right = instruction->GetRight();
1671 int32_t right_const;
1672 if (right->IsIntConstant()) {
1673 right_const = right->AsIntConstant()->GetValue();
1674 // Detect division by two or more.
1675 if ((instruction->IsDiv() && right_const <= 1) ||
1676 (instruction->IsShr() && right_const < 1) ||
1677 (instruction->IsUShr() && right_const < 1)) {
1678 return;
1679 }
1680 } else {
1681 return;
1682 }
1683
1684 // Try to handle array.length/2 or (array.length-1)/2 format.
1685 HInstruction* left = instruction->GetLeft();
1686 HInstruction* left_of_left; // left input of left.
1687 int32_t c = 0;
1688 if (ValueBound::IsAddOrSubAConstant(left, &left_of_left, &c)) {
1689 left = left_of_left;
1690 }
1691 // The value of left input of instruction equals (left + c).
1692
1693 // (array_length + 1) or smaller divided by two or more
1694 // always generate a value in [INT_MIN, array_length].
1695 // This is true even if array_length is INT_MAX.
1696 if (left->IsArrayLength() && c <= 1) {
1697 if (instruction->IsUShr() && c < 0) {
1698 // Make sure for unsigned shift, left side is not negative.
1699 // e.g. if array_length is 2, ((array_length - 3) >>> 2) is way bigger
1700 // than array_length.
1701 return;
1702 }
1703 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1704 GetGraph()->GetArena(),
1705 ValueBound(nullptr, INT_MIN),
1706 ValueBound(left, 0));
1707 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1708 }
1709 }
1710
1711 void VisitDiv(HDiv* div) {
1712 FindAndHandlePartialArrayLength(div);
1713 }
1714
1715 void VisitShr(HShr* shr) {
1716 FindAndHandlePartialArrayLength(shr);
1717 }
1718
1719 void VisitUShr(HUShr* ushr) {
1720 FindAndHandlePartialArrayLength(ushr);
1721 }
1722
Mingyao Yang4559f002015-02-27 14:43:53 -08001723 void VisitAnd(HAnd* instruction) {
1724 if (instruction->GetRight()->IsIntConstant()) {
1725 int32_t constant = instruction->GetRight()->AsIntConstant()->GetValue();
1726 if (constant > 0) {
1727 // constant serves as a mask so any number masked with it
1728 // gets a [0, constant] value range.
1729 ValueRange* range = new (GetGraph()->GetArena()) ValueRange(
1730 GetGraph()->GetArena(),
1731 ValueBound(nullptr, 0),
1732 ValueBound(nullptr, constant));
1733 GetValueRangeMap(instruction->GetBlock())->Overwrite(instruction->GetId(), range);
1734 }
1735 }
1736 }
1737
Mingyao Yang0304e182015-01-30 16:41:29 -08001738 void VisitNewArray(HNewArray* new_array) {
1739 HInstruction* len = new_array->InputAt(0);
1740 if (!len->IsIntConstant()) {
1741 HInstruction *left;
1742 int32_t right_const;
1743 if (ValueBound::IsAddOrSubAConstant(len, &left, &right_const)) {
1744 // (left + right_const) is used as size to new the array.
1745 // We record "-right_const <= left <= new_array - right_const";
1746 ValueBound lower = ValueBound(nullptr, -right_const);
1747 // We use new_array for the bound instead of new_array.length,
1748 // which isn't available as an instruction yet. new_array will
1749 // be treated the same as new_array.length when it's used in a ValueBound.
1750 ValueBound upper = ValueBound(new_array, -right_const);
1751 ValueRange* range = new (GetGraph()->GetArena())
1752 ValueRange(GetGraph()->GetArena(), lower, upper);
Nicolas Geoffraya09ff9c2015-06-24 10:38:27 +01001753 ValueRange* existing_range = LookupValueRange(left, new_array->GetBlock());
1754 if (existing_range != nullptr) {
1755 range = existing_range->Narrow(range);
1756 }
Mingyao Yang0304e182015-01-30 16:41:29 -08001757 GetValueRangeMap(new_array->GetBlock())->Overwrite(left->GetId(), range);
1758 }
1759 }
1760 }
1761
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001762 void VisitDeoptimize(HDeoptimize* deoptimize) {
1763 // Right now it's only HLessThanOrEqual.
1764 DCHECK(deoptimize->InputAt(0)->IsLessThanOrEqual());
1765 HLessThanOrEqual* less_than_or_equal = deoptimize->InputAt(0)->AsLessThanOrEqual();
1766 HInstruction* instruction = less_than_or_equal->InputAt(0);
1767 if (instruction->IsArrayLength()) {
1768 HInstruction* constant = less_than_or_equal->InputAt(1);
1769 DCHECK(constant->IsIntConstant());
1770 DCHECK(constant->AsIntConstant()->GetValue() <= kMaxConstantForAddingDeoptimize);
1771 ValueBound lower = ValueBound(nullptr, constant->AsIntConstant()->GetValue() + 1);
1772 ValueRange* range = new (GetGraph()->GetArena())
1773 ValueRange(GetGraph()->GetArena(), lower, ValueBound::Max());
1774 GetValueRangeMap(deoptimize->GetBlock())->Overwrite(instruction->GetId(), range);
1775 }
1776 }
1777
1778 void AddCompareWithDeoptimization(HInstruction* array_length,
1779 HIntConstant* const_instr,
1780 HBasicBlock* block) {
1781 DCHECK(array_length->IsArrayLength());
1782 ValueRange* range = LookupValueRange(array_length, block);
1783 ValueBound lower_bound = range->GetLower();
1784 DCHECK(lower_bound.IsConstant());
1785 DCHECK(const_instr->GetValue() <= kMaxConstantForAddingDeoptimize);
Nicolas Geoffray8d82a0c2015-06-20 23:49:01 +01001786 // Note that the lower bound of the array length may have been refined
1787 // through other instructions (such as `HNewArray(length - 4)`).
1788 DCHECK_LE(const_instr->GetValue() + 1, lower_bound.GetConstant());
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001789
1790 // If array_length is less than lower_const, deoptimize.
1791 HBoundsCheck* bounds_check = first_constant_index_bounds_check_map_.Get(
1792 array_length->GetId())->AsBoundsCheck();
1793 HCondition* cond = new (GetGraph()->GetArena()) HLessThanOrEqual(array_length, const_instr);
1794 HDeoptimize* deoptimize = new (GetGraph()->GetArena())
1795 HDeoptimize(cond, bounds_check->GetDexPc());
1796 block->InsertInstructionBefore(cond, bounds_check);
1797 block->InsertInstructionBefore(deoptimize, bounds_check);
Nicolas Geoffray3dcd58c2015-04-03 11:02:38 +01001798 deoptimize->CopyEnvironmentFrom(bounds_check->GetEnvironment());
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001799 }
1800
1801 void AddComparesWithDeoptimization(HBasicBlock* block) {
1802 for (ArenaSafeMap<int, HBoundsCheck*>::iterator it =
1803 first_constant_index_bounds_check_map_.begin();
1804 it != first_constant_index_bounds_check_map_.end();
1805 ++it) {
1806 HBoundsCheck* bounds_check = it->second;
Nicolas Geoffray8df886b2015-06-24 14:57:44 +01001807 HInstruction* array_length = bounds_check->InputAt(1);
1808 if (!array_length->IsArrayLength()) {
1809 // Prior deoptimizations may have changed the array length to a phi.
1810 // TODO(mingyao): propagate the range to the phi?
1811 DCHECK(array_length->IsPhi()) << array_length->DebugName();
1812 continue;
1813 }
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001814 HIntConstant* lower_bound_const_instr = nullptr;
1815 int32_t lower_bound_const = INT_MIN;
1816 size_t counter = 0;
1817 // Count the constant indexing for which bounds checks haven't
1818 // been removed yet.
1819 for (HUseIterator<HInstruction*> it2(array_length->GetUses());
1820 !it2.Done();
1821 it2.Advance()) {
1822 HInstruction* user = it2.Current()->GetUser();
1823 if (user->GetBlock() == block &&
1824 user->IsBoundsCheck() &&
1825 user->AsBoundsCheck()->InputAt(0)->IsIntConstant()) {
1826 DCHECK_EQ(array_length, user->AsBoundsCheck()->InputAt(1));
1827 HIntConstant* const_instr = user->AsBoundsCheck()->InputAt(0)->AsIntConstant();
1828 if (const_instr->GetValue() > lower_bound_const) {
1829 lower_bound_const = const_instr->GetValue();
1830 lower_bound_const_instr = const_instr;
1831 }
1832 counter++;
1833 }
1834 }
1835 if (counter >= kThresholdForAddingDeoptimize &&
1836 lower_bound_const_instr->GetValue() <= kMaxConstantForAddingDeoptimize) {
1837 AddCompareWithDeoptimization(array_length, lower_bound_const_instr, block);
1838 }
1839 }
1840 }
1841
Mingyao Yangf384f882014-10-22 16:08:18 -07001842 std::vector<std::unique_ptr<ArenaSafeMap<int, ValueRange*>>> maps_;
1843
Mingyao Yangd43b3ac2015-04-01 14:03:04 -07001844 // Map an HArrayLength instruction's id to the first HBoundsCheck instruction in
1845 // a block that checks a constant index against that HArrayLength.
1846 SafeMap<int, HBoundsCheck*> first_constant_index_bounds_check_map_;
1847
1848 // For the block, there is at least one HArrayLength instruction for which there
1849 // is more than one bounds check instruction with constant indexing. And it's
1850 // beneficial to add a compare instruction that has deoptimization fallback and
1851 // eliminate those bounds checks.
1852 bool need_to_revisit_block_;
1853
Mingyao Yang3584bce2015-05-19 16:01:59 -07001854 // Initial number of blocks.
1855 int32_t initial_block_size_;
1856
Aart Bik22af3be2015-09-10 12:50:58 -07001857 // Range analysis based on induction variables.
1858 InductionVarRange induction_range_;
1859
Mingyao Yangf384f882014-10-22 16:08:18 -07001860 DISALLOW_COPY_AND_ASSIGN(BCEVisitor);
1861};
1862
1863void BoundsCheckElimination::Run() {
Mark Mendell1152c922015-04-24 17:06:35 -04001864 if (!graph_->HasBoundsChecks()) {
Mingyao Yange4335eb2015-03-02 15:14:13 -08001865 return;
1866 }
1867
Aart Bik22af3be2015-09-10 12:50:58 -07001868 BCEVisitor visitor(graph_, induction_analysis_);
Mingyao Yangf384f882014-10-22 16:08:18 -07001869 // Reverse post order guarantees a node's dominators are visited first.
1870 // We want to visit in the dominator-based order since if a value is known to
1871 // be bounded by a range at one instruction, it must be true that all uses of
1872 // that value dominated by that instruction fits in that range. Range of that
1873 // value can be narrowed further down in the dominator tree.
1874 //
1875 // TODO: only visit blocks that dominate some array accesses.
Mingyao Yang3584bce2015-05-19 16:01:59 -07001876 HBasicBlock* last_visited_block = nullptr;
1877 for (HReversePostOrderIterator it(*graph_); !it.Done(); it.Advance()) {
1878 HBasicBlock* current = it.Current();
1879 if (current == last_visited_block) {
1880 // We may insert blocks into the reverse post order list when processing
1881 // a loop header. Don't process it again.
1882 DCHECK(current->IsLoopHeader());
1883 continue;
1884 }
1885 if (visitor.IsAddedBlock(current)) {
1886 // Skip added blocks. Their effects are already taken care of.
1887 continue;
1888 }
1889 visitor.VisitBasicBlock(current);
1890 last_visited_block = current;
1891 }
Mingyao Yangf384f882014-10-22 16:08:18 -07001892}
1893
1894} // namespace art