• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "induction_var_range.h"
18 
19 #include <limits>
20 
21 namespace art {
22 
23 /** Returns true if 64-bit constant fits in 32-bit constant. */
CanLongValueFitIntoInt(int64_t c)24 static bool CanLongValueFitIntoInt(int64_t c) {
25   return std::numeric_limits<int32_t>::min() <= c && c <= std::numeric_limits<int32_t>::max();
26 }
27 
28 /** Returns true if 32-bit addition can be done safely. */
IsSafeAdd(int32_t c1,int32_t c2)29 static bool IsSafeAdd(int32_t c1, int32_t c2) {
30   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) + static_cast<int64_t>(c2));
31 }
32 
33 /** Returns true if 32-bit subtraction can be done safely. */
IsSafeSub(int32_t c1,int32_t c2)34 static bool IsSafeSub(int32_t c1, int32_t c2) {
35   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) - static_cast<int64_t>(c2));
36 }
37 
38 /** Returns true if 32-bit multiplication can be done safely. */
IsSafeMul(int32_t c1,int32_t c2)39 static bool IsSafeMul(int32_t c1, int32_t c2) {
40   return CanLongValueFitIntoInt(static_cast<int64_t>(c1) * static_cast<int64_t>(c2));
41 }
42 
43 /** Returns true if 32-bit division can be done safely. */
IsSafeDiv(int32_t c1,int32_t c2)44 static bool IsSafeDiv(int32_t c1, int32_t c2) {
45   return c2 != 0 && CanLongValueFitIntoInt(static_cast<int64_t>(c1) / static_cast<int64_t>(c2));
46 }
47 
48 /** Computes a * b for a,b > 0 (at least until first overflow happens). */
SafeMul(int64_t a,int64_t b,bool * overflow)49 static int64_t SafeMul(int64_t a, int64_t b, /*out*/ bool* overflow) {
50   if (a > 0 && b > 0 && a > (std::numeric_limits<int64_t>::max() / b)) {
51     *overflow = true;
52   }
53   return a * b;
54 }
55 
56 /** Returns b^e for b,e > 0. Sets overflow if arithmetic wrap-around occurred. */
IntPow(int64_t b,int64_t e,bool * overflow)57 static int64_t IntPow(int64_t b, int64_t e, /*out*/ bool* overflow) {
58   DCHECK_LT(0, b);
59   DCHECK_LT(0, e);
60   int64_t pow = 1;
61   while (e) {
62     if (e & 1) {
63       pow = SafeMul(pow, b, overflow);
64     }
65     e >>= 1;
66     if (e) {
67       b = SafeMul(b, b, overflow);
68     }
69   }
70   return pow;
71 }
72 
73 /** Hunts "under the hood" for a suitable instruction at the hint. */
IsMaxAtHint(HInstruction * instruction,HInstruction * hint,HInstruction ** suitable)74 static bool IsMaxAtHint(
75     HInstruction* instruction, HInstruction* hint, /*out*/HInstruction** suitable) {
76   if (instruction->IsMin()) {
77     // For MIN(x, y), return most suitable x or y as maximum.
78     return IsMaxAtHint(instruction->InputAt(0), hint, suitable) ||
79            IsMaxAtHint(instruction->InputAt(1), hint, suitable);
80   } else {
81     *suitable = instruction;
82     return HuntForDeclaration(instruction) == hint;
83   }
84 }
85 
86 /** Post-analysis simplification of a minimum value that makes the bound more useful to clients. */
SimplifyMin(InductionVarRange::Value v)87 static InductionVarRange::Value SimplifyMin(InductionVarRange::Value v) {
88   if (v.is_known && v.a_constant == 1 && v.b_constant <= 0) {
89     // If a == 1,  instruction >= 0 and b <= 0, just return the constant b.
90     // No arithmetic wrap-around can occur.
91     if (IsGEZero(v.instruction)) {
92       return InductionVarRange::Value(v.b_constant);
93     }
94   }
95   return v;
96 }
97 
98 /** Post-analysis simplification of a maximum value that makes the bound more useful to clients. */
SimplifyMax(InductionVarRange::Value v,HInstruction * hint)99 static InductionVarRange::Value SimplifyMax(InductionVarRange::Value v, HInstruction* hint) {
100   if (v.is_known && v.a_constant >= 1) {
101     // An upper bound a * (length / a) + b, where a >= 1, can be conservatively rewritten as
102     // length + b because length >= 0 is true.
103     int64_t value;
104     if (v.instruction->IsDiv() &&
105         v.instruction->InputAt(0)->IsArrayLength() &&
106         IsInt64AndGet(v.instruction->InputAt(1), &value) && v.a_constant == value) {
107       return InductionVarRange::Value(v.instruction->InputAt(0), 1, v.b_constant);
108     }
109     // If a == 1, the most suitable one suffices as maximum value.
110     HInstruction* suitable = nullptr;
111     if (v.a_constant == 1 && IsMaxAtHint(v.instruction, hint, &suitable)) {
112       return InductionVarRange::Value(suitable, 1, v.b_constant);
113     }
114   }
115   return v;
116 }
117 
118 /** Tests for a constant value. */
IsConstantValue(InductionVarRange::Value v)119 static bool IsConstantValue(InductionVarRange::Value v) {
120   return v.is_known && v.a_constant == 0;
121 }
122 
123 /** Corrects a value for type to account for arithmetic wrap-around in lower precision. */
CorrectForType(InductionVarRange::Value v,DataType::Type type)124 static InductionVarRange::Value CorrectForType(InductionVarRange::Value v, DataType::Type type) {
125   switch (type) {
126     case DataType::Type::kUint8:
127     case DataType::Type::kInt8:
128     case DataType::Type::kUint16:
129     case DataType::Type::kInt16: {
130       // Constants within range only.
131       // TODO: maybe some room for improvement, like allowing widening conversions
132       int32_t min = DataType::MinValueOfIntegralType(type);
133       int32_t max = DataType::MaxValueOfIntegralType(type);
134       return (IsConstantValue(v) && min <= v.b_constant && v.b_constant <= max)
135           ? v
136           : InductionVarRange::Value();
137     }
138     default:
139       return v;
140   }
141 }
142 
143 /** Inserts an instruction. */
Insert(HBasicBlock * block,HInstruction * instruction)144 static HInstruction* Insert(HBasicBlock* block, HInstruction* instruction) {
145   DCHECK(block != nullptr);
146   DCHECK(block->GetLastInstruction() != nullptr) << block->GetBlockId();
147   DCHECK(instruction != nullptr);
148   block->InsertInstructionBefore(instruction, block->GetLastInstruction());
149   return instruction;
150 }
151 
152 /** Obtains loop's control instruction. */
GetLoopControl(const HLoopInformation * loop)153 static HInstruction* GetLoopControl(const HLoopInformation* loop) {
154   DCHECK(loop != nullptr);
155   return loop->GetHeader()->GetLastInstruction();
156 }
157 
158 /** Determines whether the `context` is in the body of the `loop`. */
IsContextInBody(const HBasicBlock * context,const HLoopInformation * loop)159 static bool IsContextInBody(const HBasicBlock* context, const HLoopInformation* loop) {
160   DCHECK(loop != nullptr);
161   // We're currently classifying trip count only for the exit condition from loop header.
162   // All other blocks in the loop are considered loop body.
163   return context != loop->GetHeader() && loop->Contains(*context);
164 }
165 
166 /** Determines whether to use the full trip count for given `context`, `loop` and `is_min`. */
UseFullTripCount(const HBasicBlock * context,const HLoopInformation * loop,bool is_min)167 bool UseFullTripCount(const HBasicBlock* context, const HLoopInformation* loop, bool is_min) {
168   // We're currently classifying trip count only for the exit condition from loop header.
169   // So, we should call this helper function only if the loop control is an `HIf` with
170   // one edge leaving the loop. The loop header is the only block that's both inside
171   // the loop and not in the loop body.
172   DCHECK(GetLoopControl(loop)->IsIf());
173   DCHECK_NE(loop->Contains(*GetLoopControl(loop)->AsIf()->IfTrueSuccessor()),
174             loop->Contains(*GetLoopControl(loop)->AsIf()->IfFalseSuccessor()));
175   if (loop->Contains(*context)) {
176     // Use the full trip count if determining the maximum and context is not in the loop body.
177     DCHECK_NE(context == loop->GetHeader(), IsContextInBody(context, loop));
178     return !is_min && context == loop->GetHeader();
179   } else {
180     // Trip count after the loop is always the maximum (ignoring `is_min`),
181     // as long as the `context` is dominated by the loop control exit block.
182     // If there are additional exit edges, the value is unknown on those paths.
183     HInstruction* loop_control = GetLoopControl(loop);
184     HBasicBlock* then_block = loop_control->AsIf()->IfTrueSuccessor();
185     HBasicBlock* else_block = loop_control->AsIf()->IfFalseSuccessor();
186     HBasicBlock* loop_exit_block = loop->Contains(*then_block) ? else_block : then_block;
187     return loop_exit_block->Dominates(context);
188   }
189 }
190 
191 //
192 // Public class methods.
193 //
194 
InductionVarRange(HInductionVarAnalysis * induction_analysis)195 InductionVarRange::InductionVarRange(HInductionVarAnalysis* induction_analysis)
196     : induction_analysis_(induction_analysis),
197       chase_hint_(nullptr) {
198   DCHECK(induction_analysis != nullptr);
199 }
200 
GetInductionRange(const HBasicBlock * context,HInstruction * instruction,HInstruction * chase_hint,Value * min_val,Value * max_val,bool * needs_finite_test)201 bool InductionVarRange::GetInductionRange(const HBasicBlock* context,
202                                           HInstruction* instruction,
203                                           HInstruction* chase_hint,
204                                           /*out*/Value* min_val,
205                                           /*out*/Value* max_val,
206                                           /*out*/bool* needs_finite_test) {
207   const HLoopInformation* loop = nullptr;
208   HInductionVarAnalysis::InductionInfo* info = nullptr;
209   HInductionVarAnalysis::InductionInfo* trip = nullptr;
210   if (!HasInductionInfo(context, instruction, &loop, &info, &trip)) {
211     return false;
212   }
213   // Type int or lower (this is not too restrictive since intended clients, like
214   // bounds check elimination, will have truncated higher precision induction
215   // at their use point already).
216   switch (info->type) {
217     case DataType::Type::kUint8:
218     case DataType::Type::kInt8:
219     case DataType::Type::kUint16:
220     case DataType::Type::kInt16:
221     case DataType::Type::kInt32:
222       break;
223     default:
224       return false;
225   }
226   // Find range.
227   chase_hint_ = chase_hint;
228   int64_t stride_value = 0;
229   *min_val = SimplifyMin(GetVal(context, loop, info, trip, /*is_min=*/ true));
230   *max_val = SimplifyMax(GetVal(context, loop, info, trip, /*is_min=*/ false), chase_hint);
231   *needs_finite_test =
232       NeedsTripCount(context, loop, info, &stride_value) && IsUnsafeTripCount(trip);
233   chase_hint_ = nullptr;
234   // Retry chasing constants for wrap-around (merge sensitive).
235   if (!min_val->is_known && info->induction_class == HInductionVarAnalysis::kWrapAround) {
236     *min_val = SimplifyMin(GetVal(context, loop, info, trip, /*is_min=*/ true));
237   }
238   return true;
239 }
240 
CanGenerateRange(const HBasicBlock * context,HInstruction * instruction,bool * needs_finite_test,bool * needs_taken_test)241 bool InductionVarRange::CanGenerateRange(const HBasicBlock* context,
242                                          HInstruction* instruction,
243                                          /*out*/bool* needs_finite_test,
244                                          /*out*/bool* needs_taken_test) {
245   bool is_last_value = false;
246   int64_t stride_value = 0;
247   return GenerateRangeOrLastValue(context,
248                                   instruction,
249                                   is_last_value,
250                                   nullptr,
251                                   nullptr,
252                                   nullptr,
253                                   nullptr,
254                                   nullptr,  // nothing generated yet
255                                   &stride_value,
256                                   needs_finite_test,
257                                   needs_taken_test)
258       && (stride_value == -1 ||
259           stride_value == 0 ||
260           stride_value == 1);  // avoid arithmetic wrap-around anomalies.
261 }
262 
GenerateRange(const HBasicBlock * context,HInstruction * instruction,HGraph * graph,HBasicBlock * block,HInstruction ** lower,HInstruction ** upper)263 void InductionVarRange::GenerateRange(const HBasicBlock* context,
264                                       HInstruction* instruction,
265                                       HGraph* graph,
266                                       HBasicBlock* block,
267                                       /*out*/HInstruction** lower,
268                                       /*out*/HInstruction** upper) {
269   bool is_last_value = false;
270   int64_t stride_value = 0;
271   bool b1, b2;  // unused
272   if (!GenerateRangeOrLastValue(context,
273                                 instruction,
274                                 is_last_value,
275                                 graph,
276                                 block,
277                                 lower,
278                                 upper,
279                                 nullptr,
280                                 &stride_value,
281                                 &b1,
282                                 &b2)) {
283     LOG(FATAL) << "Failed precondition: CanGenerateRange()";
284   }
285 }
286 
GenerateTakenTest(HInstruction * loop_control,HGraph * graph,HBasicBlock * block)287 HInstruction* InductionVarRange::GenerateTakenTest(HInstruction* loop_control,
288                                                    HGraph* graph,
289                                                    HBasicBlock* block) {
290   const HBasicBlock* context = loop_control->GetBlock();
291   HInstruction* taken_test = nullptr;
292   bool is_last_value = false;
293   int64_t stride_value = 0;
294   bool b1, b2;  // unused
295   if (!GenerateRangeOrLastValue(context,
296                                 loop_control,
297                                 is_last_value,
298                                 graph,
299                                 block,
300                                 nullptr,
301                                 nullptr,
302                                 &taken_test,
303                                 &stride_value,
304                                 &b1,
305                                 &b2)) {
306     LOG(FATAL) << "Failed precondition: CanGenerateRange()";
307   }
308   return taken_test;
309 }
310 
CanGenerateLastValue(HInstruction * instruction)311 bool InductionVarRange::CanGenerateLastValue(HInstruction* instruction) {
312   const HBasicBlock* context = instruction->GetBlock();
313   bool is_last_value = true;
314   int64_t stride_value = 0;
315   bool needs_finite_test = false;
316   bool needs_taken_test = false;
317   return GenerateRangeOrLastValue(context,
318                                   instruction,
319                                   is_last_value,
320                                   nullptr,
321                                   nullptr,
322                                   nullptr,
323                                   nullptr,
324                                   nullptr,  // nothing generated yet
325                                   &stride_value,
326                                   &needs_finite_test,
327                                   &needs_taken_test)
328       && !needs_finite_test && !needs_taken_test;
329 }
330 
GenerateLastValue(HInstruction * instruction,HGraph * graph,HBasicBlock * block)331 HInstruction* InductionVarRange::GenerateLastValue(HInstruction* instruction,
332                                                    HGraph* graph,
333                                                    HBasicBlock* block) {
334   const HBasicBlock* context = instruction->GetBlock();
335   HInstruction* last_value = nullptr;
336   bool is_last_value = true;
337   int64_t stride_value = 0;
338   bool b1, b2;  // unused
339   if (!GenerateRangeOrLastValue(context,
340                                 instruction,
341                                 is_last_value,
342                                 graph,
343                                 block,
344                                 &last_value,
345                                 &last_value,
346                                 nullptr,
347                                 &stride_value,
348                                 &b1,
349                                 &b2)) {
350     LOG(FATAL) << "Failed precondition: CanGenerateLastValue()";
351   }
352   return last_value;
353 }
354 
Replace(HInstruction * instruction,HInstruction * fetch,HInstruction * replacement)355 void InductionVarRange::Replace(HInstruction* instruction,
356                                 HInstruction* fetch,
357                                 HInstruction* replacement) {
358   for (HLoopInformation* lp = instruction->GetBlock()->GetLoopInformation();  // closest enveloping loop
359        lp != nullptr;
360        lp = lp->GetPreHeader()->GetLoopInformation()) {
361     // Update instruction's information.
362     ReplaceInduction(induction_analysis_->LookupInfo(lp, instruction), fetch, replacement);
363     // Update loop's trip-count information.
364     ReplaceInduction(induction_analysis_->LookupInfo(lp, GetLoopControl(lp)), fetch, replacement);
365   }
366 }
367 
IsFinite(const HLoopInformation * loop,int64_t * trip_count) const368 bool InductionVarRange::IsFinite(const HLoopInformation* loop, /*out*/ int64_t* trip_count) const {
369   bool is_constant_unused = false;
370   return CheckForFiniteAndConstantProps(loop, &is_constant_unused, trip_count);
371 }
372 
HasKnownTripCount(const HLoopInformation * loop,int64_t * trip_count) const373 bool InductionVarRange::HasKnownTripCount(const HLoopInformation* loop,
374                                           /*out*/ int64_t* trip_count) const {
375   bool is_constant = false;
376   CheckForFiniteAndConstantProps(loop, &is_constant, trip_count);
377   return is_constant;
378 }
379 
IsUnitStride(const HBasicBlock * context,HInstruction * instruction,HGraph * graph,HInstruction ** offset) const380 bool InductionVarRange::IsUnitStride(const HBasicBlock* context,
381                                      HInstruction* instruction,
382                                      HGraph* graph,
383                                      /*out*/ HInstruction** offset) const {
384   const HLoopInformation* loop = nullptr;
385   HInductionVarAnalysis::InductionInfo* info = nullptr;
386   HInductionVarAnalysis::InductionInfo* trip = nullptr;
387   if (HasInductionInfo(context, instruction, &loop, &info, &trip)) {
388     if (info->induction_class == HInductionVarAnalysis::kLinear &&
389         !HInductionVarAnalysis::IsNarrowingLinear(info)) {
390       int64_t stride_value = 0;
391       if (IsConstant(context, loop, info->op_a, kExact, &stride_value) && stride_value == 1) {
392         int64_t off_value = 0;
393         if (IsConstant(context, loop, info->op_b, kExact, &off_value)) {
394           *offset = graph->GetConstant(info->op_b->type, off_value);
395         } else if (info->op_b->operation == HInductionVarAnalysis::kFetch) {
396           *offset = info->op_b->fetch;
397         } else {
398           return false;
399         }
400         return true;
401       }
402     }
403   }
404   return false;
405 }
406 
GenerateTripCount(const HLoopInformation * loop,HGraph * graph,HBasicBlock * block)407 HInstruction* InductionVarRange::GenerateTripCount(const HLoopInformation* loop,
408                                                    HGraph* graph,
409                                                    HBasicBlock* block) {
410   HInstruction* loop_control = GetLoopControl(loop);
411   HInductionVarAnalysis::InductionInfo *trip = induction_analysis_->LookupInfo(loop, loop_control);
412   if (trip != nullptr && !IsUnsafeTripCount(trip)) {
413     const HBasicBlock* context = loop_control->GetBlock();
414     HInstruction* taken_test = nullptr;
415     HInstruction* trip_expr = nullptr;
416     if (IsBodyTripCount(trip)) {
417       if (!GenerateCode(context,
418                         loop,
419                         trip->op_b,
420                         /*trip=*/ nullptr,
421                         graph,
422                         block,
423                         /*is_min=*/ false,
424                         &taken_test)) {
425         return nullptr;
426       }
427     }
428     if (GenerateCode(context,
429                      loop,
430                      trip->op_a,
431                      /*trip=*/ nullptr,
432                      graph,
433                      block,
434                      /*is_min=*/ false,
435                      &trip_expr)) {
436       if (taken_test != nullptr) {
437         HInstruction* zero = graph->GetConstant(trip->type, 0);
438         ArenaAllocator* allocator = graph->GetAllocator();
439         trip_expr = Insert(block, new (allocator) HSelect(taken_test, trip_expr, zero, kNoDexPc));
440       }
441       return trip_expr;
442     }
443   }
444   return nullptr;
445 }
446 
447 //
448 // Private class methods.
449 //
450 
CheckForFiniteAndConstantProps(const HLoopInformation * loop,bool * is_constant,int64_t * trip_count) const451 bool InductionVarRange::CheckForFiniteAndConstantProps(const HLoopInformation* loop,
452                                                        /*out*/ bool* is_constant,
453                                                        /*out*/ int64_t* trip_count) const {
454   HInstruction* loop_control = GetLoopControl(loop);
455   HInductionVarAnalysis::InductionInfo *trip = induction_analysis_->LookupInfo(loop, loop_control);
456   if (trip != nullptr && !IsUnsafeTripCount(trip)) {
457     const HBasicBlock* context = loop_control->GetBlock();
458     *is_constant = IsConstant(context, loop, trip->op_a, kExact, trip_count);
459     return true;
460   }
461   return false;
462 }
463 
IsConstant(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,ConstantRequest request,int64_t * value) const464 bool InductionVarRange::IsConstant(const HBasicBlock* context,
465                                    const HLoopInformation* loop,
466                                    HInductionVarAnalysis::InductionInfo* info,
467                                    ConstantRequest request,
468                                    /*out*/ int64_t* value) const {
469   if (info != nullptr) {
470     // A direct 32-bit or 64-bit constant fetch. This immediately satisfies
471     // any of the three requests (kExact, kAtMost, and KAtLeast).
472     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
473         info->operation == HInductionVarAnalysis::kFetch) {
474       if (IsInt64AndGet(info->fetch, value)) {
475         return true;
476       }
477     }
478     // Try range analysis on the invariant, only accept a proper range
479     // to avoid arithmetic wrap-around anomalies.
480     Value min_val = GetVal(context, loop, info, /*trip=*/ nullptr, /*is_min=*/ true);
481     Value max_val = GetVal(context, loop, info, /*trip=*/ nullptr, /*is_min=*/ false);
482     if (IsConstantValue(min_val) &&
483         IsConstantValue(max_val) && min_val.b_constant <= max_val.b_constant) {
484       if ((request == kExact && min_val.b_constant == max_val.b_constant) || request == kAtMost) {
485         *value = max_val.b_constant;
486         return true;
487       } else if (request == kAtLeast) {
488         *value = min_val.b_constant;
489         return true;
490       }
491     }
492   }
493   return false;
494 }
495 
HasInductionInfo(const HBasicBlock * context,HInstruction * instruction,const HLoopInformation ** loop,HInductionVarAnalysis::InductionInfo ** info,HInductionVarAnalysis::InductionInfo ** trip) const496 bool InductionVarRange::HasInductionInfo(
497     const HBasicBlock* context,
498     HInstruction* instruction,
499     /*out*/ const HLoopInformation** loop,
500     /*out*/ HInductionVarAnalysis::InductionInfo** info,
501     /*out*/ HInductionVarAnalysis::InductionInfo** trip) const {
502   DCHECK(context != nullptr);
503   HLoopInformation* lp = context->GetLoopInformation();  // closest enveloping loop
504   if (lp != nullptr) {
505     HInductionVarAnalysis::InductionInfo* i = induction_analysis_->LookupInfo(lp, instruction);
506     if (i != nullptr) {
507       *loop = lp;
508       *info = i;
509       *trip = induction_analysis_->LookupInfo(lp, GetLoopControl(lp));
510       return true;
511     }
512   }
513   return false;
514 }
515 
IsWellBehavedTripCount(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * trip) const516 bool InductionVarRange::IsWellBehavedTripCount(const HBasicBlock* context,
517                                                const HLoopInformation* loop,
518                                                HInductionVarAnalysis::InductionInfo* trip) const {
519   if (trip != nullptr) {
520     // Both bounds that define a trip-count are well-behaved if they either are not defined
521     // in any loop, or are contained in a proper interval. This allows finding the min/max
522     // of an expression by chasing outward.
523     InductionVarRange range(induction_analysis_);
524     HInductionVarAnalysis::InductionInfo* lower = trip->op_b->op_a;
525     HInductionVarAnalysis::InductionInfo* upper = trip->op_b->op_b;
526     int64_t not_used = 0;
527     return
528         (!HasFetchInLoop(lower) || range.IsConstant(context, loop, lower, kAtLeast, &not_used)) &&
529         (!HasFetchInLoop(upper) || range.IsConstant(context, loop, upper, kAtLeast, &not_used));
530   }
531   return true;
532 }
533 
HasFetchInLoop(HInductionVarAnalysis::InductionInfo * info) const534 bool InductionVarRange::HasFetchInLoop(HInductionVarAnalysis::InductionInfo* info) const {
535   if (info != nullptr) {
536     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
537         info->operation == HInductionVarAnalysis::kFetch) {
538       return info->fetch->GetBlock()->GetLoopInformation() != nullptr;
539     }
540     return HasFetchInLoop(info->op_a) || HasFetchInLoop(info->op_b);
541   }
542   return false;
543 }
544 
NeedsTripCount(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,int64_t * stride_value) const545 bool InductionVarRange::NeedsTripCount(const HBasicBlock* context,
546                                        const HLoopInformation* loop,
547                                        HInductionVarAnalysis::InductionInfo* info,
548                                        int64_t* stride_value) const {
549   if (info != nullptr) {
550     if (info->induction_class == HInductionVarAnalysis::kLinear) {
551       return IsConstant(context, loop, info->op_a, kExact, stride_value);
552     } else if (info->induction_class == HInductionVarAnalysis::kPolynomial) {
553       return NeedsTripCount(context, loop, info->op_a, stride_value);
554     } else if (info->induction_class == HInductionVarAnalysis::kWrapAround) {
555       return NeedsTripCount(context, loop, info->op_b, stride_value);
556     }
557   }
558   return false;
559 }
560 
IsBodyTripCount(HInductionVarAnalysis::InductionInfo * trip) const561 bool InductionVarRange::IsBodyTripCount(HInductionVarAnalysis::InductionInfo* trip) const {
562   if (trip != nullptr) {
563     if (trip->induction_class == HInductionVarAnalysis::kInvariant) {
564       return trip->operation == HInductionVarAnalysis::kTripCountInBody ||
565              trip->operation == HInductionVarAnalysis::kTripCountInBodyUnsafe;
566     }
567   }
568   return false;
569 }
570 
IsUnsafeTripCount(HInductionVarAnalysis::InductionInfo * trip) const571 bool InductionVarRange::IsUnsafeTripCount(HInductionVarAnalysis::InductionInfo* trip) const {
572   if (trip != nullptr) {
573     if (trip->induction_class == HInductionVarAnalysis::kInvariant) {
574       return trip->operation == HInductionVarAnalysis::kTripCountInBodyUnsafe ||
575              trip->operation == HInductionVarAnalysis::kTripCountInLoopUnsafe;
576     }
577   }
578   return false;
579 }
580 
GetLinear(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const581 InductionVarRange::Value InductionVarRange::GetLinear(const HBasicBlock* context,
582                                                       const HLoopInformation* loop,
583                                                       HInductionVarAnalysis::InductionInfo* info,
584                                                       HInductionVarAnalysis::InductionInfo* trip,
585                                                       bool is_min) const {
586   DCHECK(info != nullptr);
587   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kLinear);
588   // Detect common situation where an offset inside the trip-count cancels out during range
589   // analysis (finding max a * (TC - 1) + OFFSET for a == 1 and TC = UPPER - OFFSET or finding
590   // min a * (TC - 1) + OFFSET for a == -1 and TC = OFFSET - UPPER) to avoid losing information
591   // with intermediate results that only incorporate single instructions.
592   if (trip != nullptr) {
593     HInductionVarAnalysis::InductionInfo* trip_expr = trip->op_a;
594     if (trip_expr->type == info->type && trip_expr->operation == HInductionVarAnalysis::kSub) {
595       int64_t stride_value = 0;
596       if (IsConstant(context, loop, info->op_a, kExact, &stride_value)) {
597         if (!is_min && stride_value == 1) {
598           // Test original trip's negative operand (trip_expr->op_b) against offset of induction.
599           if (HInductionVarAnalysis::InductionEqual(trip_expr->op_b, info->op_b)) {
600             // Analyze cancelled trip with just the positive operand (trip_expr->op_a).
601             HInductionVarAnalysis::InductionInfo cancelled_trip(
602                 trip->induction_class,
603                 trip->operation,
604                 trip_expr->op_a,
605                 trip->op_b,
606                 nullptr,
607                 trip->type);
608             return GetVal(context, loop, &cancelled_trip, trip, is_min);
609           }
610         } else if (is_min && stride_value == -1) {
611           // Test original trip's positive operand (trip_expr->op_a) against offset of induction.
612           if (HInductionVarAnalysis::InductionEqual(trip_expr->op_a, info->op_b)) {
613             // Analyze cancelled trip with just the negative operand (trip_expr->op_b).
614             HInductionVarAnalysis::InductionInfo neg(
615                 HInductionVarAnalysis::kInvariant,
616                 HInductionVarAnalysis::kNeg,
617                 nullptr,
618                 trip_expr->op_b,
619                 nullptr,
620                 trip->type);
621             HInductionVarAnalysis::InductionInfo cancelled_trip(
622                 trip->induction_class, trip->operation, &neg, trip->op_b, nullptr, trip->type);
623             return SubValue(Value(0), GetVal(context, loop, &cancelled_trip, trip, !is_min));
624           }
625         }
626       }
627     }
628   }
629   // General rule of linear induction a * i + b, for normalized 0 <= i < TC.
630   return AddValue(GetMul(context, loop, info->op_a, trip, trip, is_min),
631                   GetVal(context, loop, info->op_b, trip, is_min));
632 }
633 
GetPolynomial(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const634 InductionVarRange::Value InductionVarRange::GetPolynomial(
635     const HBasicBlock* context,
636     const HLoopInformation* loop,
637     HInductionVarAnalysis::InductionInfo* info,
638     HInductionVarAnalysis::InductionInfo* trip,
639     bool is_min) const {
640   DCHECK(info != nullptr);
641   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPolynomial);
642   int64_t a = 0;
643   int64_t b = 0;
644   if (IsConstant(context, loop, info->op_a->op_a, kExact, &a) &&
645       CanLongValueFitIntoInt(a) &&
646       a >= 0 &&
647       IsConstant(context, loop, info->op_a->op_b, kExact, &b) &&
648       CanLongValueFitIntoInt(b) &&
649       b >= 0) {
650     // Evaluate bounds on sum_i=0^m-1(a * i + b) + c with a,b >= 0 for
651     // maximum index value m as a * (m * (m-1)) / 2 + b * m + c.
652     // Do not simply return `c` as minimum because the trip count may be non-zero
653     // if the `context` is after the `loop` (and therefore ignoring `is_min`).
654     Value c = GetVal(context, loop, info->op_b, trip, is_min);
655     Value m = GetVal(context, loop, trip, trip, is_min);
656     Value t = DivValue(MulValue(m, SubValue(m, Value(1))), Value(2));
657     Value x = MulValue(Value(a), t);
658     Value y = MulValue(Value(b), m);
659     return AddValue(AddValue(x, y), c);
660   }
661   return Value();
662 }
663 
GetGeometric(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const664 InductionVarRange::Value InductionVarRange::GetGeometric(const HBasicBlock* context,
665                                                          const HLoopInformation* loop,
666                                                          HInductionVarAnalysis::InductionInfo* info,
667                                                          HInductionVarAnalysis::InductionInfo* trip,
668                                                          bool is_min) const {
669   DCHECK(info != nullptr);
670   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kGeometric);
671   int64_t a = 0;
672   int64_t f = 0;
673   if (IsConstant(context, loop, info->op_a, kExact, &a) &&
674       CanLongValueFitIntoInt(a) &&
675       IsInt64AndGet(info->fetch, &f) && f >= 1) {
676     // Conservative bounds on a * f^-i + b with f >= 1 can be computed without
677     // trip count. Other forms would require a much more elaborate evaluation.
678     const bool is_min_a = a >= 0 ? is_min : !is_min;
679     if (info->operation == HInductionVarAnalysis::kDiv) {
680       Value b = GetVal(context, loop, info->op_b, trip, is_min);
681       return is_min_a ? b : AddValue(Value(a), b);
682     }
683   }
684   return Value();
685 }
686 
GetFetch(const HBasicBlock * context,const HLoopInformation * loop,HInstruction * instruction,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const687 InductionVarRange::Value InductionVarRange::GetFetch(const HBasicBlock* context,
688                                                      const HLoopInformation* loop,
689                                                      HInstruction* instruction,
690                                                      HInductionVarAnalysis::InductionInfo* trip,
691                                                      bool is_min) const {
692   // Special case when chasing constants: single instruction that denotes trip count in the
693   // loop-body is minimal 1 and maximal, with safe trip-count, max int,
694   if (chase_hint_ == nullptr &&
695       IsContextInBody(context, loop) &&
696       trip != nullptr &&
697       instruction == trip->op_a->fetch) {
698     if (is_min) {
699       return Value(1);
700     } else if (!instruction->IsConstant() && !IsUnsafeTripCount(trip)) {
701       return Value(std::numeric_limits<int32_t>::max());
702     }
703   }
704   // Unless at a constant or hint, chase the instruction a bit deeper into the HIR tree, so that
705   // it becomes more likely range analysis will compare the same instructions as terminal nodes.
706   int64_t value;
707   if (IsInt64AndGet(instruction, &value) && CanLongValueFitIntoInt(value)) {
708     // Proper constant reveals best information.
709     return Value(static_cast<int32_t>(value));
710   } else if (instruction == chase_hint_) {
711     // At hint, fetch is represented by itself.
712     return Value(instruction, 1, 0);
713   } else if (instruction->IsAdd()) {
714     // Incorporate suitable constants in the chased value.
715     if (IsInt64AndGet(instruction->InputAt(0), &value) && CanLongValueFitIntoInt(value)) {
716       return AddValue(Value(static_cast<int32_t>(value)),
717                       GetFetch(context, loop, instruction->InputAt(1), trip, is_min));
718     } else if (IsInt64AndGet(instruction->InputAt(1), &value) && CanLongValueFitIntoInt(value)) {
719       return AddValue(GetFetch(context, loop, instruction->InputAt(0), trip, is_min),
720                       Value(static_cast<int32_t>(value)));
721     }
722   } else if (instruction->IsSub()) {
723     // Incorporate suitable constants in the chased value.
724     if (IsInt64AndGet(instruction->InputAt(0), &value) && CanLongValueFitIntoInt(value)) {
725       return SubValue(Value(static_cast<int32_t>(value)),
726                       GetFetch(context, loop, instruction->InputAt(1), trip, !is_min));
727     } else if (IsInt64AndGet(instruction->InputAt(1), &value) && CanLongValueFitIntoInt(value)) {
728       return SubValue(GetFetch(context, loop, instruction->InputAt(0), trip, is_min),
729                       Value(static_cast<int32_t>(value)));
730     }
731   } else if (instruction->IsArrayLength()) {
732     // Exploit length properties when chasing constants or chase into a new array declaration.
733     if (chase_hint_ == nullptr) {
734       return is_min ? Value(0) : Value(std::numeric_limits<int32_t>::max());
735     } else if (instruction->InputAt(0)->IsNewArray()) {
736       return GetFetch(
737           context, loop, instruction->InputAt(0)->AsNewArray()->GetLength(), trip, is_min);
738     }
739   } else if (instruction->IsTypeConversion()) {
740     // Since analysis is 32-bit (or narrower), chase beyond widening along the path.
741     // For example, this discovers the length in: for (long i = 0; i < a.length; i++);
742     if (instruction->AsTypeConversion()->GetInputType() == DataType::Type::kInt32 &&
743         instruction->AsTypeConversion()->GetResultType() == DataType::Type::kInt64) {
744       return GetFetch(context, loop, instruction->InputAt(0), trip, is_min);
745     }
746   }
747   // Chase an invariant fetch that is defined by another loop if the trip-count used
748   // so far is well-behaved in both bounds and the next trip-count is safe.
749   // Example:
750   //   for (int i = 0; i <= 100; i++)  // safe
751   //     for (int j = 0; j <= i; j++)  // well-behaved
752   //       j is in range [0, i  ] (if i is chase hint)
753   //         or in range [0, 100] (otherwise)
754   // Example:
755   //   for (i = 0; i < 100; ++i)
756   //     <some-code>
757   //   for (j = 0; j < 10; ++j)
758   //     sum += i;  // The `i` is a "fetch" of a loop Phi from the previous loop.
759   const HLoopInformation* next_loop = nullptr;
760   HInductionVarAnalysis::InductionInfo* next_info = nullptr;
761   HInductionVarAnalysis::InductionInfo* next_trip = nullptr;
762   if (HasInductionInfo(instruction->GetBlock(), instruction, &next_loop, &next_info, &next_trip) &&
763       IsWellBehavedTripCount(context, next_loop, trip) &&
764       !IsUnsafeTripCount(next_trip)) {
765     return GetVal(context, next_loop, next_info, next_trip, is_min);
766   }
767   // Fetch is represented by itself.
768   return Value(instruction, 1, 0);
769 }
770 
GetVal(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const771 InductionVarRange::Value InductionVarRange::GetVal(const HBasicBlock* context,
772                                                    const HLoopInformation* loop,
773                                                    HInductionVarAnalysis::InductionInfo* info,
774                                                    HInductionVarAnalysis::InductionInfo* trip,
775                                                    bool is_min) const {
776   if (info != nullptr) {
777     switch (info->induction_class) {
778       case HInductionVarAnalysis::kInvariant:
779         // Invariants.
780         switch (info->operation) {
781           case HInductionVarAnalysis::kAdd:
782             return AddValue(GetVal(context, loop, info->op_a, trip, is_min),
783                             GetVal(context, loop, info->op_b, trip, is_min));
784           case HInductionVarAnalysis::kSub:  // second reversed!
785             return SubValue(GetVal(context, loop, info->op_a, trip, is_min),
786                             GetVal(context, loop, info->op_b, trip, !is_min));
787           case HInductionVarAnalysis::kNeg:  // second reversed!
788             return SubValue(Value(0),
789                             GetVal(context, loop, info->op_b, trip, !is_min));
790           case HInductionVarAnalysis::kMul:
791             return GetMul(context, loop, info->op_a, info->op_b, trip, is_min);
792           case HInductionVarAnalysis::kDiv:
793             return GetDiv(context, loop, info->op_a, info->op_b, trip, is_min);
794           case HInductionVarAnalysis::kRem:
795             return GetRem(context, loop, info->op_a, info->op_b);
796           case HInductionVarAnalysis::kXor:
797             return GetXor(context, loop, info->op_a, info->op_b);
798           case HInductionVarAnalysis::kFetch:
799             return GetFetch(context, loop, info->fetch, trip, is_min);
800           case HInductionVarAnalysis::kTripCountInLoop:
801           case HInductionVarAnalysis::kTripCountInLoopUnsafe:
802             if (UseFullTripCount(context, loop, is_min)) {
803               // Return the full trip count (do not subtract 1 as we do in loop body).
804               return GetVal(context, loop, info->op_a, trip, /*is_min=*/ false);
805             }
806             FALLTHROUGH_INTENDED;
807           case HInductionVarAnalysis::kTripCountInBody:
808           case HInductionVarAnalysis::kTripCountInBodyUnsafe:
809             if (is_min) {
810               return Value(0);
811             } else if (IsContextInBody(context, loop)) {
812               return SubValue(GetVal(context, loop, info->op_a, trip, is_min), Value(1));
813             }
814             break;
815           default:
816             break;
817         }
818         break;
819       case HInductionVarAnalysis::kLinear:
820         return CorrectForType(GetLinear(context, loop, info, trip, is_min), info->type);
821       case HInductionVarAnalysis::kPolynomial:
822         return GetPolynomial(context, loop, info, trip, is_min);
823       case HInductionVarAnalysis::kGeometric:
824         return GetGeometric(context, loop, info, trip, is_min);
825       case HInductionVarAnalysis::kWrapAround:
826       case HInductionVarAnalysis::kPeriodic:
827         return MergeVal(GetVal(context, loop, info->op_a, trip, is_min),
828                         GetVal(context, loop, info->op_b, trip, is_min),
829                         is_min);
830     }
831   }
832   return Value();
833 }
834 
GetMul(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const835 InductionVarRange::Value InductionVarRange::GetMul(const HBasicBlock* context,
836                                                    const HLoopInformation* loop,
837                                                    HInductionVarAnalysis::InductionInfo* info1,
838                                                    HInductionVarAnalysis::InductionInfo* info2,
839                                                    HInductionVarAnalysis::InductionInfo* trip,
840                                                    bool is_min) const {
841   // Constant times range.
842   int64_t value = 0;
843   if (IsConstant(context, loop, info1, kExact, &value)) {
844     return MulRangeAndConstant(context, loop, value, info2, trip, is_min);
845   } else if (IsConstant(context, loop, info2, kExact, &value)) {
846     return MulRangeAndConstant(context, loop, value, info1, trip, is_min);
847   }
848   // Interval ranges.
849   Value v1_min = GetVal(context, loop, info1, trip, /*is_min=*/ true);
850   Value v1_max = GetVal(context, loop, info1, trip, /*is_min=*/ false);
851   Value v2_min = GetVal(context, loop, info2, trip, /*is_min=*/ true);
852   Value v2_max = GetVal(context, loop, info2, trip, /*is_min=*/ false);
853   // Positive range vs. positive or negative range.
854   if (IsConstantValue(v1_min) && v1_min.b_constant >= 0) {
855     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
856       return is_min ? MulValue(v1_min, v2_min) : MulValue(v1_max, v2_max);
857     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
858       return is_min ? MulValue(v1_max, v2_min) : MulValue(v1_min, v2_max);
859     }
860   }
861   // Negative range vs. positive or negative range.
862   if (IsConstantValue(v1_max) && v1_max.b_constant <= 0) {
863     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
864       return is_min ? MulValue(v1_min, v2_max) : MulValue(v1_max, v2_min);
865     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
866       return is_min ? MulValue(v1_max, v2_max) : MulValue(v1_min, v2_min);
867     }
868   }
869   return Value();
870 }
871 
GetDiv(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const872 InductionVarRange::Value InductionVarRange::GetDiv(const HBasicBlock* context,
873                                                    const HLoopInformation* loop,
874                                                    HInductionVarAnalysis::InductionInfo* info1,
875                                                    HInductionVarAnalysis::InductionInfo* info2,
876                                                    HInductionVarAnalysis::InductionInfo* trip,
877                                                    bool is_min) const {
878   // Range divided by constant.
879   int64_t value = 0;
880   if (IsConstant(context, loop, info2, kExact, &value)) {
881     return DivRangeAndConstant(context, loop, value, info1, trip, is_min);
882   }
883   // Interval ranges.
884   Value v1_min = GetVal(context, loop, info1, trip, /*is_min=*/ true);
885   Value v1_max = GetVal(context, loop, info1, trip, /*is_min=*/ false);
886   Value v2_min = GetVal(context, loop, info2, trip, /*is_min=*/ true);
887   Value v2_max = GetVal(context, loop, info2, trip, /*is_min=*/ false);
888   // Positive range vs. positive or negative range.
889   if (IsConstantValue(v1_min) && v1_min.b_constant >= 0) {
890     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
891       return is_min ? DivValue(v1_min, v2_max) : DivValue(v1_max, v2_min);
892     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
893       return is_min ? DivValue(v1_max, v2_max) : DivValue(v1_min, v2_min);
894     }
895   }
896   // Negative range vs. positive or negative range.
897   if (IsConstantValue(v1_max) && v1_max.b_constant <= 0) {
898     if (IsConstantValue(v2_min) && v2_min.b_constant >= 0) {
899       return is_min ? DivValue(v1_min, v2_min) : DivValue(v1_max, v2_max);
900     } else if (IsConstantValue(v2_max) && v2_max.b_constant <= 0) {
901       return is_min ? DivValue(v1_max, v2_min) : DivValue(v1_min, v2_max);
902     }
903   }
904   return Value();
905 }
906 
GetRem(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2) const907 InductionVarRange::Value InductionVarRange::GetRem(
908     const HBasicBlock* context,
909     const HLoopInformation* loop,
910     HInductionVarAnalysis::InductionInfo* info1,
911     HInductionVarAnalysis::InductionInfo* info2) const {
912   int64_t v1 = 0;
913   int64_t v2 = 0;
914   // Only accept exact values.
915   if (IsConstant(context, loop, info1, kExact, &v1) &&
916       IsConstant(context, loop, info2, kExact, &v2) &&
917       v2 != 0) {
918     int64_t value = v1 % v2;
919     if (CanLongValueFitIntoInt(value)) {
920       return Value(static_cast<int32_t>(value));
921     }
922   }
923   return Value();
924 }
925 
GetXor(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info1,HInductionVarAnalysis::InductionInfo * info2) const926 InductionVarRange::Value InductionVarRange::GetXor(
927     const HBasicBlock* context,
928     const HLoopInformation* loop,
929     HInductionVarAnalysis::InductionInfo* info1,
930     HInductionVarAnalysis::InductionInfo* info2) const {
931   int64_t v1 = 0;
932   int64_t v2 = 0;
933   // Only accept exact values.
934   if (IsConstant(context, loop, info1, kExact, &v1) &&
935       IsConstant(context, loop, info2, kExact, &v2)) {
936     int64_t value = v1 ^ v2;
937     if (CanLongValueFitIntoInt(value)) {
938       return Value(static_cast<int32_t>(value));
939     }
940   }
941   return Value();
942 }
943 
MulRangeAndConstant(const HBasicBlock * context,const HLoopInformation * loop,int64_t value,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const944 InductionVarRange::Value InductionVarRange::MulRangeAndConstant(
945     const HBasicBlock* context,
946     const HLoopInformation* loop,
947     int64_t value,
948     HInductionVarAnalysis::InductionInfo* info,
949     HInductionVarAnalysis::InductionInfo* trip,
950     bool is_min) const {
951   if (CanLongValueFitIntoInt(value)) {
952     Value c(static_cast<int32_t>(value));
953     return MulValue(GetVal(context, loop, info, trip, is_min == value >= 0), c);
954   }
955   return Value();
956 }
957 
DivRangeAndConstant(const HBasicBlock * context,const HLoopInformation * loop,int64_t value,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,bool is_min) const958 InductionVarRange::Value InductionVarRange::DivRangeAndConstant(
959     const HBasicBlock* context,
960     const HLoopInformation* loop,
961     int64_t value,
962     HInductionVarAnalysis::InductionInfo* info,
963     HInductionVarAnalysis::InductionInfo* trip,
964     bool is_min) const {
965   if (CanLongValueFitIntoInt(value)) {
966     Value c(static_cast<int32_t>(value));
967     return DivValue(GetVal(context, loop, info, trip, is_min == value >= 0), c);
968   }
969   return Value();
970 }
971 
AddValue(Value v1,Value v2) const972 InductionVarRange::Value InductionVarRange::AddValue(Value v1, Value v2) const {
973   if (v1.is_known && v2.is_known && IsSafeAdd(v1.b_constant, v2.b_constant)) {
974     int32_t b = v1.b_constant + v2.b_constant;
975     if (v1.a_constant == 0) {
976       return Value(v2.instruction, v2.a_constant, b);
977     } else if (v2.a_constant == 0) {
978       return Value(v1.instruction, v1.a_constant, b);
979     } else if (v1.instruction == v2.instruction && IsSafeAdd(v1.a_constant, v2.a_constant)) {
980       return Value(v1.instruction, v1.a_constant + v2.a_constant, b);
981     }
982   }
983   return Value();
984 }
985 
SubValue(Value v1,Value v2) const986 InductionVarRange::Value InductionVarRange::SubValue(Value v1, Value v2) const {
987   if (v1.is_known && v2.is_known && IsSafeSub(v1.b_constant, v2.b_constant)) {
988     int32_t b = v1.b_constant - v2.b_constant;
989     if (v1.a_constant == 0 && IsSafeSub(0, v2.a_constant)) {
990       return Value(v2.instruction, -v2.a_constant, b);
991     } else if (v2.a_constant == 0) {
992       return Value(v1.instruction, v1.a_constant, b);
993     } else if (v1.instruction == v2.instruction && IsSafeSub(v1.a_constant, v2.a_constant)) {
994       return Value(v1.instruction, v1.a_constant - v2.a_constant, b);
995     }
996   }
997   return Value();
998 }
999 
MulValue(Value v1,Value v2) const1000 InductionVarRange::Value InductionVarRange::MulValue(Value v1, Value v2) const {
1001   if (v1.is_known && v2.is_known) {
1002     if (v1.a_constant == 0) {
1003       if (IsSafeMul(v1.b_constant, v2.a_constant) && IsSafeMul(v1.b_constant, v2.b_constant)) {
1004         return Value(v2.instruction, v1.b_constant * v2.a_constant, v1.b_constant * v2.b_constant);
1005       }
1006     } else if (v2.a_constant == 0) {
1007       if (IsSafeMul(v1.a_constant, v2.b_constant) && IsSafeMul(v1.b_constant, v2.b_constant)) {
1008         return Value(v1.instruction, v1.a_constant * v2.b_constant, v1.b_constant * v2.b_constant);
1009       }
1010     }
1011   }
1012   return Value();
1013 }
1014 
DivValue(Value v1,Value v2) const1015 InductionVarRange::Value InductionVarRange::DivValue(Value v1, Value v2) const {
1016   if (v1.is_known && v2.is_known && v1.a_constant == 0 && v2.a_constant == 0) {
1017     if (IsSafeDiv(v1.b_constant, v2.b_constant)) {
1018       return Value(v1.b_constant / v2.b_constant);
1019     }
1020   }
1021   return Value();
1022 }
1023 
MergeVal(Value v1,Value v2,bool is_min) const1024 InductionVarRange::Value InductionVarRange::MergeVal(Value v1, Value v2, bool is_min) const {
1025   if (v1.is_known && v2.is_known) {
1026     if (v1.instruction == v2.instruction && v1.a_constant == v2.a_constant) {
1027       return Value(v1.instruction, v1.a_constant,
1028                    is_min ? std::min(v1.b_constant, v2.b_constant)
1029                           : std::max(v1.b_constant, v2.b_constant));
1030     }
1031   }
1032   return Value();
1033 }
1034 
GenerateRangeOrLastValue(const HBasicBlock * context,HInstruction * instruction,bool is_last_value,HGraph * graph,HBasicBlock * block,HInstruction ** lower,HInstruction ** upper,HInstruction ** taken_test,int64_t * stride_value,bool * needs_finite_test,bool * needs_taken_test) const1035 bool InductionVarRange::GenerateRangeOrLastValue(const HBasicBlock* context,
1036                                                  HInstruction* instruction,
1037                                                  bool is_last_value,
1038                                                  HGraph* graph,
1039                                                  HBasicBlock* block,
1040                                                  /*out*/HInstruction** lower,
1041                                                  /*out*/HInstruction** upper,
1042                                                  /*out*/HInstruction** taken_test,
1043                                                  /*out*/int64_t* stride_value,
1044                                                  /*out*/bool* needs_finite_test,
1045                                                  /*out*/bool* needs_taken_test) const {
1046   const HLoopInformation* loop = nullptr;
1047   HInductionVarAnalysis::InductionInfo* info = nullptr;
1048   HInductionVarAnalysis::InductionInfo* trip = nullptr;
1049   if (!HasInductionInfo(context, instruction, &loop, &info, &trip) || trip == nullptr) {
1050     return false;  // codegen needs all information, including tripcount
1051   }
1052   // Determine what tests are needed. A finite test is needed if the evaluation code uses the
1053   // trip-count and the loop maybe unsafe (because in such cases, the index could "overshoot"
1054   // the computed range). A taken test is needed for any unknown trip-count, even if evaluation
1055   // code does not use the trip-count explicitly (since there could be an implicit relation
1056   // between e.g. an invariant subscript and a not-taken condition).
1057   *stride_value = 0;
1058   *needs_finite_test = NeedsTripCount(context, loop, info, stride_value) && IsUnsafeTripCount(trip);
1059   *needs_taken_test = IsBodyTripCount(trip);
1060   // Handle last value request.
1061   if (is_last_value) {
1062     DCHECK(!IsContextInBody(context, loop));
1063     switch (info->induction_class) {
1064       case HInductionVarAnalysis::kLinear:
1065         if (*stride_value > 0) {
1066           lower = nullptr;
1067         } else {
1068           upper = nullptr;
1069         }
1070         break;
1071       case HInductionVarAnalysis::kPolynomial:
1072         return GenerateLastValuePolynomial(context, loop, info, trip, graph, block, lower);
1073       case HInductionVarAnalysis::kGeometric:
1074         return GenerateLastValueGeometric(context, loop, info, trip, graph, block, lower);
1075       case HInductionVarAnalysis::kWrapAround:
1076         return GenerateLastValueWrapAround(context, loop, info, trip, graph, block, lower);
1077       case HInductionVarAnalysis::kPeriodic:
1078         return GenerateLastValuePeriodic(
1079             context, loop, info, trip, graph, block, lower, needs_taken_test);
1080       default:
1081         return false;
1082     }
1083   }
1084   // Code generation for taken test: generate the code when requested or otherwise analyze
1085   // if code generation is feasible when taken test is needed.
1086   if (taken_test != nullptr) {
1087     return GenerateCode(context,
1088                         loop,
1089                         trip->op_b,
1090                         /*trip=*/ nullptr,
1091                         graph,
1092                         block,
1093                         /*is_min=*/ false,
1094                         taken_test);
1095   } else if (*needs_taken_test) {
1096     if (!GenerateCode(context,
1097                       loop,
1098                       trip->op_b,
1099                       /*trip=*/ nullptr,
1100                       /*graph=*/ nullptr,
1101                       /*block=*/ nullptr,
1102                       /*is_min=*/ false,
1103                       /*result=*/ nullptr)) {
1104       return false;
1105     }
1106   }
1107   // Code generation for lower and upper.
1108   return
1109       // Success on lower if invariant (not set), or code can be generated.
1110       ((info->induction_class == HInductionVarAnalysis::kInvariant) ||
1111           GenerateCode(context, loop, info, trip, graph, block, /*is_min=*/ true, lower)) &&
1112       // And success on upper.
1113       GenerateCode(context, loop, info, trip, graph, block, /*is_min=*/ false, upper);
1114 }
1115 
GenerateLastValuePolynomial(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1116 bool InductionVarRange::GenerateLastValuePolynomial(const HBasicBlock* context,
1117                                                     const HLoopInformation* loop,
1118                                                     HInductionVarAnalysis::InductionInfo* info,
1119                                                     HInductionVarAnalysis::InductionInfo* trip,
1120                                                     HGraph* graph,
1121                                                     HBasicBlock* block,
1122                                                     /*out*/HInstruction** result) const {
1123   DCHECK(info != nullptr);
1124   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPolynomial);
1125   // Detect known coefficients and trip count (always taken).
1126   int64_t a = 0;
1127   int64_t b = 0;
1128   int64_t m = 0;
1129   if (IsConstant(context, loop, info->op_a->op_a, kExact, &a) &&
1130       IsConstant(context, loop, info->op_a->op_b, kExact, &b) &&
1131       IsConstant(context, loop, trip->op_a, kExact, &m) &&
1132       m >= 1) {
1133     // Evaluate bounds on sum_i=0^m-1(a * i + b) + c for known
1134     // maximum index value m as a * (m * (m-1)) / 2 + b * m + c.
1135     HInstruction* c = nullptr;
1136     if (GenerateCode(context,
1137                      loop,
1138                      info->op_b,
1139                      /*trip=*/ nullptr,
1140                      graph,
1141                      block,
1142                      /*is_min=*/ false,
1143                      graph ? &c : nullptr)) {
1144       if (graph != nullptr) {
1145         DataType::Type type = info->type;
1146         int64_t sum = a * ((m * (m - 1)) / 2) + b * m;
1147         if (type != DataType::Type::kInt64) {
1148           sum = static_cast<int32_t>(sum);  // okay to truncate
1149         }
1150         *result =
1151             Insert(block, new (graph->GetAllocator()) HAdd(type, graph->GetConstant(type, sum), c));
1152       }
1153       return true;
1154     }
1155   }
1156   return false;
1157 }
1158 
GenerateLastValueGeometric(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1159 bool InductionVarRange::GenerateLastValueGeometric(const HBasicBlock* context,
1160                                                    const HLoopInformation* loop,
1161                                                    HInductionVarAnalysis::InductionInfo* info,
1162                                                    HInductionVarAnalysis::InductionInfo* trip,
1163                                                    HGraph* graph,
1164                                                    HBasicBlock* block,
1165                                                    /*out*/HInstruction** result) const {
1166   DCHECK(info != nullptr);
1167   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kGeometric);
1168   // Detect known base and trip count (always taken).
1169   int64_t f = 0;
1170   int64_t m = 0;
1171   if (IsInt64AndGet(info->fetch, &f) &&
1172       f >= 1 &&
1173       IsConstant(context, loop, trip->op_a, kExact, &m) &&
1174       m >= 1) {
1175     HInstruction* opa = nullptr;
1176     HInstruction* opb = nullptr;
1177     if (GenerateCode(
1178             context, loop, info->op_a, /*trip=*/ nullptr, graph, block, /*is_min=*/ false, &opa) &&
1179         GenerateCode(
1180             context, loop, info->op_b, /*trip=*/ nullptr, graph, block, /*is_min=*/ false, &opb)) {
1181       if (graph != nullptr) {
1182         DataType::Type type = info->type;
1183         // Compute f ^ m for known maximum index value m.
1184         bool overflow = false;
1185         int64_t fpow = IntPow(f, m, &overflow);
1186         if (info->operation == HInductionVarAnalysis::kDiv) {
1187           // For division, any overflow truncates to zero.
1188           if (overflow || (type != DataType::Type::kInt64 && !CanLongValueFitIntoInt(fpow))) {
1189             fpow = 0;
1190           }
1191         } else if (type != DataType::Type::kInt64) {
1192           // For multiplication, okay to truncate to required precision.
1193           DCHECK(info->operation == HInductionVarAnalysis::kMul);
1194           fpow = static_cast<int32_t>(fpow);
1195         }
1196         // Generate code.
1197         if (fpow == 0) {
1198           // Special case: repeated mul/div always yields zero.
1199           *result = graph->GetConstant(type, 0);
1200         } else {
1201           // Last value: a * f ^ m + b or a * f ^ -m + b.
1202           HInstruction* e = nullptr;
1203           ArenaAllocator* allocator = graph->GetAllocator();
1204           if (info->operation == HInductionVarAnalysis::kMul) {
1205             e = new (allocator) HMul(type, opa, graph->GetConstant(type, fpow));
1206           } else {
1207             e = new (allocator) HDiv(type, opa, graph->GetConstant(type, fpow), kNoDexPc);
1208           }
1209           *result = Insert(block, new (allocator) HAdd(type, Insert(block, e), opb));
1210         }
1211       }
1212       return true;
1213     }
1214   }
1215   return false;
1216 }
1217 
GenerateLastValueWrapAround(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result) const1218 bool InductionVarRange::GenerateLastValueWrapAround(const HBasicBlock* context,
1219                                                     const HLoopInformation* loop,
1220                                                     HInductionVarAnalysis::InductionInfo* info,
1221                                                     HInductionVarAnalysis::InductionInfo* trip,
1222                                                     HGraph* graph,
1223                                                     HBasicBlock* block,
1224                                                     /*out*/HInstruction** result) const {
1225   DCHECK(info != nullptr);
1226   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kWrapAround);
1227   // Count depth.
1228   int32_t depth = 0;
1229   for (; info->induction_class == HInductionVarAnalysis::kWrapAround;
1230        info = info->op_b, ++depth) {}
1231   // Handle wrap(x, wrap(.., y)) if trip count reaches an invariant at end.
1232   // TODO: generalize, but be careful to adjust the terminal.
1233   int64_t m = 0;
1234   if (info->induction_class == HInductionVarAnalysis::kInvariant &&
1235       IsConstant(context, loop, trip->op_a, kExact, &m) &&
1236       m >= depth) {
1237     return GenerateCode(
1238         context, loop, info, /*trip=*/ nullptr, graph, block, /*is_min=*/ false, result);
1239   }
1240   return false;
1241 }
1242 
GenerateLastValuePeriodic(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,HInstruction ** result,bool * needs_taken_test) const1243 bool InductionVarRange::GenerateLastValuePeriodic(const HBasicBlock* context,
1244                                                   const HLoopInformation* loop,
1245                                                   HInductionVarAnalysis::InductionInfo* info,
1246                                                   HInductionVarAnalysis::InductionInfo* trip,
1247                                                   HGraph* graph,
1248                                                   HBasicBlock* block,
1249                                                   /*out*/HInstruction** result,
1250                                                   /*out*/bool* needs_taken_test) const {
1251   DCHECK(info != nullptr);
1252   DCHECK_EQ(info->induction_class, HInductionVarAnalysis::kPeriodic);
1253   // Count period and detect all-invariants.
1254   int64_t period = 1;
1255   bool all_invariants = true;
1256   HInductionVarAnalysis::InductionInfo* p = info;
1257   for (; p->induction_class == HInductionVarAnalysis::kPeriodic; p = p->op_b, ++period) {
1258     DCHECK_EQ(p->op_a->induction_class, HInductionVarAnalysis::kInvariant);
1259     if (p->op_a->operation != HInductionVarAnalysis::kFetch) {
1260       all_invariants = false;
1261     }
1262   }
1263   DCHECK_EQ(p->induction_class, HInductionVarAnalysis::kInvariant);
1264   if (p->operation != HInductionVarAnalysis::kFetch) {
1265     all_invariants = false;
1266   }
1267   // Don't rely on FP arithmetic to be precise, unless the full period
1268   // consist of pre-computed expressions only.
1269   if (info->type == DataType::Type::kFloat32 || info->type == DataType::Type::kFloat64) {
1270     if (!all_invariants) {
1271       return false;
1272     }
1273   }
1274   // Handle any periodic(x, periodic(.., y)) for known maximum index value m.
1275   int64_t m = 0;
1276   if (IsConstant(context, loop, trip->op_a, kExact, &m) && m >= 1) {
1277     int64_t li = m % period;
1278     for (int64_t i = 0; i < li; info = info->op_b, i++) {}
1279     if (info->induction_class == HInductionVarAnalysis::kPeriodic) {
1280       info = info->op_a;
1281     }
1282     return GenerateCode(
1283         context, loop, info, /*trip=*/ nullptr, graph, block, /*is_min=*/ false, result);
1284   }
1285   // Handle periodic(x, y) using even/odd-select on trip count. Enter trip count expression
1286   // directly to obtain the maximum index value t even if taken test is needed.
1287   HInstruction* x = nullptr;
1288   HInstruction* y = nullptr;
1289   HInstruction* t = nullptr;
1290   if (period == 2 &&
1291       GenerateCode(context,
1292                    loop,
1293                    info->op_a,
1294                    /*trip=*/ nullptr,
1295                    graph,
1296                    block,
1297                    /*is_min=*/ false,
1298                    graph ? &x : nullptr) &&
1299       GenerateCode(context,
1300                    loop,
1301                    info->op_b,
1302                    /*trip=*/ nullptr,
1303                    graph,
1304                    block,
1305                    /*is_min=*/ false,
1306                    graph ? &y : nullptr) &&
1307       GenerateCode(context,
1308                    loop,
1309                    trip->op_a,
1310                    /*trip=*/ nullptr,
1311                    graph,
1312                    block,
1313                    /*is_min=*/ false,
1314                    graph ? &t : nullptr)) {
1315     // During actual code generation (graph != nullptr), generate is_even ? x : y.
1316     if (graph != nullptr) {
1317       DataType::Type type = trip->type;
1318       ArenaAllocator* allocator = graph->GetAllocator();
1319       HInstruction* msk =
1320           Insert(block, new (allocator) HAnd(type, t, graph->GetConstant(type, 1)));
1321       HInstruction* is_even =
1322           Insert(block, new (allocator) HEqual(msk, graph->GetConstant(type, 0), kNoDexPc));
1323       *result = Insert(block, new (graph->GetAllocator()) HSelect(is_even, x, y, kNoDexPc));
1324     }
1325     // Guard select with taken test if needed.
1326     if (*needs_taken_test) {
1327       HInstruction* is_taken = nullptr;
1328       if (GenerateCode(context,
1329                        loop,
1330                        trip->op_b,
1331                        /*trip=*/ nullptr,
1332                        graph,
1333                        block,
1334                        /*is_min=*/ false,
1335                        graph ? &is_taken : nullptr)) {
1336         if (graph != nullptr) {
1337           ArenaAllocator* allocator = graph->GetAllocator();
1338           *result = Insert(block, new (allocator) HSelect(is_taken, *result, x, kNoDexPc));
1339         }
1340         *needs_taken_test = false;  // taken care of
1341       } else {
1342         return false;
1343       }
1344     }
1345     return true;
1346   }
1347   return false;
1348 }
1349 
GenerateCode(const HBasicBlock * context,const HLoopInformation * loop,HInductionVarAnalysis::InductionInfo * info,HInductionVarAnalysis::InductionInfo * trip,HGraph * graph,HBasicBlock * block,bool is_min,HInstruction ** result) const1350 bool InductionVarRange::GenerateCode(const HBasicBlock* context,
1351                                      const HLoopInformation* loop,
1352                                      HInductionVarAnalysis::InductionInfo* info,
1353                                      HInductionVarAnalysis::InductionInfo* trip,
1354                                      HGraph* graph,  // when set, code is generated
1355                                      HBasicBlock* block,
1356                                      bool is_min,
1357                                      /*out*/HInstruction** result) const {
1358   if (info != nullptr) {
1359     // If during codegen, the result is not needed (nullptr), simply return success.
1360     if (graph != nullptr && result == nullptr) {
1361       return true;
1362     }
1363     // Handle current operation.
1364     DataType::Type type = info->type;
1365     HInstruction* opa = nullptr;
1366     HInstruction* opb = nullptr;
1367     switch (info->induction_class) {
1368       case HInductionVarAnalysis::kInvariant:
1369         // Invariants (note that since invariants only have other invariants as
1370         // sub expressions, viz. no induction, there is no need to adjust is_min).
1371         switch (info->operation) {
1372           case HInductionVarAnalysis::kAdd:
1373           case HInductionVarAnalysis::kSub:
1374           case HInductionVarAnalysis::kMul:
1375           case HInductionVarAnalysis::kDiv:
1376           case HInductionVarAnalysis::kRem:
1377           case HInductionVarAnalysis::kXor:
1378           case HInductionVarAnalysis::kLT:
1379           case HInductionVarAnalysis::kLE:
1380           case HInductionVarAnalysis::kGT:
1381           case HInductionVarAnalysis::kGE:
1382             if (GenerateCode(context, loop, info->op_a, trip, graph, block, is_min, &opa) &&
1383                 GenerateCode(context, loop, info->op_b, trip, graph, block, is_min, &opb)) {
1384               if (graph != nullptr) {
1385                 HInstruction* operation = nullptr;
1386                 switch (info->operation) {
1387                   case HInductionVarAnalysis::kAdd:
1388                     operation = new (graph->GetAllocator()) HAdd(type, opa, opb); break;
1389                   case HInductionVarAnalysis::kSub:
1390                     operation = new (graph->GetAllocator()) HSub(type, opa, opb); break;
1391                   case HInductionVarAnalysis::kMul:
1392                     operation = new (graph->GetAllocator()) HMul(type, opa, opb, kNoDexPc); break;
1393                   case HInductionVarAnalysis::kDiv:
1394                     operation = new (graph->GetAllocator()) HDiv(type, opa, opb, kNoDexPc); break;
1395                   case HInductionVarAnalysis::kRem:
1396                     operation = new (graph->GetAllocator()) HRem(type, opa, opb, kNoDexPc); break;
1397                   case HInductionVarAnalysis::kXor:
1398                     operation = new (graph->GetAllocator()) HXor(type, opa, opb); break;
1399                   case HInductionVarAnalysis::kLT:
1400                     operation = new (graph->GetAllocator()) HLessThan(opa, opb); break;
1401                   case HInductionVarAnalysis::kLE:
1402                     operation = new (graph->GetAllocator()) HLessThanOrEqual(opa, opb); break;
1403                   case HInductionVarAnalysis::kGT:
1404                     operation = new (graph->GetAllocator()) HGreaterThan(opa, opb); break;
1405                   case HInductionVarAnalysis::kGE:
1406                     operation = new (graph->GetAllocator()) HGreaterThanOrEqual(opa, opb); break;
1407                   default:
1408                     LOG(FATAL) << "unknown operation";
1409                 }
1410                 *result = Insert(block, operation);
1411               }
1412               return true;
1413             }
1414             break;
1415           case HInductionVarAnalysis::kNeg:
1416             if (GenerateCode(context, loop, info->op_b, trip, graph, block, !is_min, &opb)) {
1417               if (graph != nullptr) {
1418                 *result = Insert(block, new (graph->GetAllocator()) HNeg(type, opb));
1419               }
1420               return true;
1421             }
1422             break;
1423           case HInductionVarAnalysis::kFetch:
1424             if (graph != nullptr) {
1425               *result = info->fetch;  // already in HIR
1426             }
1427             return true;
1428           case HInductionVarAnalysis::kTripCountInLoop:
1429           case HInductionVarAnalysis::kTripCountInLoopUnsafe:
1430             if (UseFullTripCount(context, loop, is_min)) {
1431               // Generate the full trip count (do not subtract 1 as we do in loop body).
1432               return GenerateCode(
1433                   context, loop, info->op_a, trip, graph, block, /*is_min=*/ false, result);
1434             }
1435             FALLTHROUGH_INTENDED;
1436           case HInductionVarAnalysis::kTripCountInBody:
1437           case HInductionVarAnalysis::kTripCountInBodyUnsafe:
1438             if (is_min) {
1439               if (graph != nullptr) {
1440                 *result = graph->GetConstant(type, 0);
1441               }
1442               return true;
1443             } else if (IsContextInBody(context, loop)) {
1444               if (GenerateCode(context, loop, info->op_a, trip, graph, block, is_min, &opb)) {
1445                 if (graph != nullptr) {
1446                   ArenaAllocator* allocator = graph->GetAllocator();
1447                   *result =
1448                       Insert(block, new (allocator) HSub(type, opb, graph->GetConstant(type, 1)));
1449                 }
1450                 return true;
1451               }
1452             }
1453             break;
1454           case HInductionVarAnalysis::kNop:
1455             LOG(FATAL) << "unexpected invariant nop";
1456         }  // switch invariant operation
1457         break;
1458       case HInductionVarAnalysis::kLinear: {
1459         // Linear induction a * i + b, for normalized 0 <= i < TC. For ranges, this should
1460         // be restricted to a unit stride to avoid arithmetic wrap-around situations that
1461         // are harder to guard against. For a last value, requesting min/max based on any
1462         // known stride yields right value. Always avoid any narrowing linear induction or
1463         // any type mismatch between the linear induction and the trip count expression.
1464         // TODO: careful runtime type conversions could generalize this latter restriction.
1465         if (!HInductionVarAnalysis::IsNarrowingLinear(info) && trip->type == type) {
1466           int64_t stride_value = 0;
1467           if (IsConstant(context, loop, info->op_a, kExact, &stride_value) &&
1468               CanLongValueFitIntoInt(stride_value)) {
1469             const bool is_min_a = stride_value >= 0 ? is_min : !is_min;
1470             if (GenerateCode(context, loop, trip,       trip, graph, block, is_min_a, &opa) &&
1471                 GenerateCode(context, loop, info->op_b, trip, graph, block, is_min,   &opb)) {
1472               if (graph != nullptr) {
1473                 ArenaAllocator* allocator = graph->GetAllocator();
1474                 HInstruction* oper;
1475                 if (stride_value == 1) {
1476                   oper = new (allocator) HAdd(type, opa, opb);
1477                 } else if (stride_value == -1) {
1478                   oper = new (graph->GetAllocator()) HSub(type, opb, opa);
1479                 } else {
1480                   HInstruction* mul =
1481                       new (allocator) HMul(type, graph->GetConstant(type, stride_value), opa);
1482                   oper = new (allocator) HAdd(type, Insert(block, mul), opb);
1483                 }
1484                 *result = Insert(block, oper);
1485               }
1486               return true;
1487             }
1488           }
1489         }
1490         break;
1491       }
1492       case HInductionVarAnalysis::kPolynomial:
1493       case HInductionVarAnalysis::kGeometric:
1494         break;
1495       case HInductionVarAnalysis::kWrapAround:
1496       case HInductionVarAnalysis::kPeriodic: {
1497         // Wrap-around and periodic inductions are restricted to constants only, so that extreme
1498         // values are easy to test at runtime without complications of arithmetic wrap-around.
1499         Value extreme = GetVal(context, loop, info, trip, is_min);
1500         if (IsConstantValue(extreme)) {
1501           if (graph != nullptr) {
1502             *result = graph->GetConstant(type, extreme.b_constant);
1503           }
1504           return true;
1505         }
1506         break;
1507       }
1508     }  // switch induction class
1509   }
1510   return false;
1511 }
1512 
ReplaceInduction(HInductionVarAnalysis::InductionInfo * info,HInstruction * fetch,HInstruction * replacement)1513 void InductionVarRange::ReplaceInduction(HInductionVarAnalysis::InductionInfo* info,
1514                                          HInstruction* fetch,
1515                                          HInstruction* replacement) {
1516   if (info != nullptr) {
1517     if (info->induction_class == HInductionVarAnalysis::kInvariant &&
1518         info->operation == HInductionVarAnalysis::kFetch &&
1519         info->fetch == fetch) {
1520       info->fetch = replacement;
1521     }
1522     ReplaceInduction(info->op_a, fetch, replacement);
1523     ReplaceInduction(info->op_b, fetch, replacement);
1524   }
1525 }
1526 
1527 }  // namespace art
1528