blob: c501ccf80f96a4389c24563832abd53d4135a353 [file] [log] [blame]
Aart Bik30efb4e2015-07-30 12:14:31 -07001/*
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_analysis.h"
Aart Bik22af3be2015-09-10 12:50:58 -070018#include "induction_var_range.h"
Aart Bik30efb4e2015-07-30 12:14:31 -070019
20namespace art {
21
22/**
Aart Bik22af3be2015-09-10 12:50:58 -070023 * Since graph traversal may enter a SCC at any position, an initial representation may be rotated,
24 * along dependences, viz. any of (a, b, c, d), (d, a, b, c) (c, d, a, b), (b, c, d, a) assuming
25 * a chain of dependences (mutual independent items may occur in arbitrary order). For proper
26 * classification, the lexicographically first entry-phi is rotated to the front.
27 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
31 // Find very first entry-phi.
32 const HInstructionList& phis = loop->GetHeader()->GetPhis();
33 HInstruction* phi = nullptr;
34 size_t phi_pos = -1;
35 const size_t size = scc->size();
36 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010037 HInstruction* other = (*scc)[i];
Aart Bikf475bee2015-09-16 12:50:25 -070038 if (other->IsLoopHeaderPhi() && (phi == nullptr || phis.FoundBefore(other, phi))) {
39 phi = other;
Aart Bik22af3be2015-09-10 12:50:58 -070040 phi_pos = i;
41 }
42 }
43
44 // If found, bring that entry-phi to front.
45 if (phi != nullptr) {
46 new_scc->clear();
47 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010048 new_scc->push_back((*scc)[phi_pos]);
Aart Bik22af3be2015-09-10 12:50:58 -070049 if (++phi_pos >= size) phi_pos = 0;
50 }
51 DCHECK_EQ(size, new_scc->size());
52 scc->swap(*new_scc);
53 }
54}
55
Aart Bik0d345cf2016-03-16 10:49:38 -070056/**
57 * Returns true if the from/to types denote a narrowing, integral conversion (precision loss).
58 */
59static bool IsNarrowingIntegralConversion(Primitive::Type from, Primitive::Type to) {
60 switch (from) {
61 case Primitive::kPrimLong:
62 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
63 || to == Primitive::kPrimChar || to == Primitive::kPrimInt;
64 case Primitive::kPrimInt:
65 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
66 || to == Primitive::kPrimChar;
67 case Primitive::kPrimChar:
68 case Primitive::kPrimShort:
69 return to == Primitive::kPrimByte;
70 default:
71 return false;
72 }
73}
74
75/**
76 * Returns narrowest data type.
77 */
78static Primitive::Type Narrowest(Primitive::Type type1, Primitive::Type type2) {
79 return Primitive::ComponentSize(type1) <= Primitive::ComponentSize(type2) ? type1 : type2;
80}
81
Aart Bik30efb4e2015-07-30 12:14:31 -070082//
83// Class methods.
84//
85
86HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph)
87 : HOptimization(graph, kInductionPassName),
88 global_depth_(0),
Vladimir Marko5233f932015-09-29 19:01:15 +010089 stack_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
90 scc_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
91 map_(std::less<HInstruction*>(),
92 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
93 cycle_(std::less<HInstruction*>(),
94 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
95 induction_(std::less<HLoopInformation*>(),
96 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -070097}
98
99void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800100 // Detects sequence variables (generalized induction variables) during an outer to inner
101 // traversal of all loops using Gerlek's algorithm. The order is important to enable
102 // range analysis on outer loop while visiting inner loops.
103 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700104 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000105 // Don't analyze irreducible loops.
106 // TODO(ajcbik): could/should we remove this restriction?
107 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700108 VisitLoop(graph_block->GetLoopInformation());
109 }
110 }
111}
112
113void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
114 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
115 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
116 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700117 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700118 map_.clear();
119
120 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
121 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700122 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700123 if (loop_block->GetLoopInformation() != loop) {
124 continue; // Inner loops already visited.
125 }
126 // Visit phi-operations and instructions.
127 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
128 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700129 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700130 VisitNode(loop, instruction);
131 }
132 }
133 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
134 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700135 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700136 VisitNode(loop, instruction);
137 }
138 }
139 }
140
Aart Bike609b7c2015-08-27 13:46:58 -0700141 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700142 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700143
Aart Bik78296912016-03-25 13:14:53 -0700144 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700145 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700146}
147
148void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700149 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700150 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700151 stack_.push_back(instruction);
152
153 // Visit all descendants.
154 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100155 for (HInstruction* input : instruction->GetInputs()) {
156 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700157 }
158
159 // Lower or found SCC?
160 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700161 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700162 } else {
163 scc_.clear();
164 cycle_.clear();
165
166 // Pop the stack to build the SCC for classification.
167 while (!stack_.empty()) {
168 HInstruction* x = stack_.back();
169 scc_.push_back(x);
170 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700171 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700172 if (x == instruction) {
173 break;
174 }
175 }
176
Aart Bik0d345cf2016-03-16 10:49:38 -0700177 // Type of induction.
178 type_ = scc_[0]->GetType();
179
Aart Bik30efb4e2015-07-30 12:14:31 -0700180 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700181 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700182 ClassifyTrivial(loop, scc_[0]);
183 } else {
184 ClassifyNonTrivial(loop);
185 }
186
187 scc_.clear();
188 cycle_.clear();
189 }
190}
191
192uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
193 // If the definition is either outside the loop (loop invariant entry value)
194 // or assigned in inner loop (inner exit value), the traversal stops.
195 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
196 if (otherLoop != loop) {
197 return global_depth_;
198 }
199
200 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700201 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700202 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700203 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700204 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700205 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700206 return it->second.done ? global_depth_ : it->second.depth;
207 }
208}
209
210void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
211 InductionInfo* info = nullptr;
212 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700213 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700214 } else if (instruction->IsAdd()) {
215 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
216 LookupInfo(loop, instruction->InputAt(1)), kAdd);
217 } else if (instruction->IsSub()) {
218 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
219 LookupInfo(loop, instruction->InputAt(1)), kSub);
220 } else if (instruction->IsMul()) {
221 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
222 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700223 } else if (instruction->IsShl()) {
224 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
225 LookupInfo(loop, instruction->InputAt(1)),
226 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700227 } else if (instruction->IsNeg()) {
228 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik0d345cf2016-03-16 10:49:38 -0700229 } else if (instruction->IsTypeConversion()) {
230 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
231 instruction->AsTypeConversion()->GetInputType(),
232 instruction->AsTypeConversion()->GetResultType());
233
Aart Bike609b7c2015-08-27 13:46:58 -0700234 } else if (instruction->IsBoundsCheck()) {
235 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700236 }
237
238 // Successfully classified?
239 if (info != nullptr) {
240 AssignInfo(loop, instruction, info);
241 }
242}
243
244void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
245 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700246 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700247
248 // Rotate proper entry-phi to front.
249 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100250 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700251 RotateEntryPhiFirst(loop, &scc_, &other);
252 }
253
Aart Bikf475bee2015-09-16 12:50:25 -0700254 // Analyze from entry-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700255 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700256 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700257 return;
258 }
Aart Bikf475bee2015-09-16 12:50:25 -0700259
260 // External link should be loop invariant.
261 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700262 if (initial == nullptr || initial->induction_class != kInvariant) {
263 return;
264 }
265
Aart Bikf475bee2015-09-16 12:50:25 -0700266 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700267 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700268 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700269 if (update != nullptr) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700270 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update, type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700271 }
272 return;
273 }
274
275 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700276 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700277 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700278 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700279 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700280 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700281 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700282 } else if (instruction->IsAdd()) {
283 update = SolveAddSub(
284 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
285 } else if (instruction->IsSub()) {
286 update = SolveAddSub(
287 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik0d345cf2016-03-16 10:49:38 -0700288 } else if (instruction->IsTypeConversion()) {
289 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700290 }
291 if (update == nullptr) {
292 return;
293 }
Aart Bike609b7c2015-08-27 13:46:58 -0700294 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700295 }
296
Aart Bikf475bee2015-09-16 12:50:25 -0700297 // Success if all internal links received the same temporary meaning.
298 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
299 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700300 switch (induction->induction_class) {
301 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700302 // Classify first phi and then the rest of the cycle "on-demand".
303 // Statements are scanned in order.
Aart Bik0d345cf2016-03-16 10:49:38 -0700304 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial, type_));
Aart Bik22af3be2015-09-10 12:50:58 -0700305 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700306 ClassifyTrivial(loop, scc_[i]);
307 }
308 break;
309 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700310 // Classify all elements in the cycle with the found periodic induction while
311 // rotating each first element to the end. Lastly, phi is classified.
312 // Statements are scanned in reverse order.
313 for (size_t i = size - 1; i >= 1; i--) {
314 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700315 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
316 }
317 AssignInfo(loop, phi, induction);
318 break;
319 default:
320 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700321 }
322 }
323}
324
Aart Bike609b7c2015-08-27 13:46:58 -0700325HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
326 InductionInfo* induction,
327 InductionInfo* last) {
328 // Rotates a periodic induction of the form
329 // (a, b, c, d, e)
330 // into
331 // (b, c, d, e, a)
332 // in preparation of assigning this to the previous variable in the sequence.
333 if (induction->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700334 return CreateInduction(kPeriodic, induction, last, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700335 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700336 return CreateInduction(
337 kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last), type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700338}
339
Aart Bikf475bee2015-09-16 12:50:25 -0700340HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
341 HInstruction* phi,
342 size_t input_index) {
343 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100344 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100345 DCHECK_LT(input_index, inputs.size());
346 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
347 for (size_t i = input_index + 1; i < inputs.size(); i++) {
348 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700349 if (!InductionEqual(a, b)) {
350 return nullptr;
351 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700352 }
Aart Bikf475bee2015-09-16 12:50:25 -0700353 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700354}
355
356HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
357 InductionInfo* b,
358 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700359 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
360 // can be combined with an invariant to yield a similar result. Even two linear inputs can
361 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700362 if (a != nullptr && b != nullptr) {
363 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700364 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700365 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700366 return CreateInduction(kLinear,
367 TransferAddSub(a->op_a, b->op_a, op),
368 TransferAddSub(a->op_b, b->op_b, op),
369 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700370 } else if (a->induction_class == kInvariant) {
371 InductionInfo* new_a = b->op_a;
372 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
373 if (b->induction_class != kLinear) {
374 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
375 new_a = TransferAddSub(a, new_a, op);
376 } else if (op == kSub) { // Negation required.
377 new_a = TransferNeg(new_a);
378 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700379 return CreateInduction(b->induction_class, new_a, new_b, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700380 } else if (b->induction_class == kInvariant) {
381 InductionInfo* new_a = a->op_a;
382 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
383 if (a->induction_class != kLinear) {
384 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
385 new_a = TransferAddSub(new_a, b, op);
386 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700387 return CreateInduction(a->induction_class, new_a, new_b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700388 }
389 }
390 return nullptr;
391}
392
393HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
394 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700395 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
396 // can be multiplied with an invariant to yield a similar but multiplied result.
397 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700398 if (a != nullptr && b != nullptr) {
399 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700400 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700401 } else if (a->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700402 return CreateInduction(b->induction_class,
403 TransferMul(a, b->op_a),
404 TransferMul(a, b->op_b),
405 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700406 } else if (b->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700407 return CreateInduction(a->induction_class,
408 TransferMul(a->op_a, b),
409 TransferMul(a->op_b, b),
410 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700411 }
412 }
413 return nullptr;
414}
415
416HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
417 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700418 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700419 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700420 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800421 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700422 // Obtain the constant needed for the multiplication. This yields an existing instruction
423 // if the constants is already there. Otherwise, this has a side effect on the HIR.
424 // The restriction on the shift factor avoids generating a negative constant
425 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
426 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700427 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
428 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
429 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700430 }
431 }
432 return nullptr;
433}
434
435HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700436 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
437 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700438 if (a != nullptr) {
439 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700440 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700441 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700442 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b), type_);
443 }
444 return nullptr;
445}
446
447HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
448 Primitive::Type from,
449 Primitive::Type to) {
450 if (a != nullptr) {
451 // Allow narrowing conversion in certain cases.
452 if (IsNarrowingIntegralConversion(from, to)) {
453 if (a->induction_class == kLinear) {
454 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
455 return CreateInduction(kLinear, a->op_a, a->op_b, to);
456 }
457 }
458 // TODO: other cases useful too?
459 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700460 }
461 return nullptr;
462}
463
Aart Bikf475bee2015-09-16 12:50:25 -0700464HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
465 size_t input_index) {
466 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100467 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100468 DCHECK_LT(input_index, inputs.size());
469 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700470 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100471 for (size_t i = input_index + 1; i < inputs.size(); i++) {
472 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700473 if (itb == cycle_.end() ||
474 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700475 return nullptr;
476 }
477 }
Aart Bikf475bee2015-09-16 12:50:25 -0700478 return ita->second;
479 }
480 return nullptr;
481}
482
483HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
484 HLoopInformation* loop,
485 HInstruction* entry_phi,
486 HInstruction* phi) {
487 // Match all phi inputs.
488 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
489 if (match != nullptr) {
490 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700491 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700492
Aart Bikf475bee2015-09-16 12:50:25 -0700493 // Otherwise, try to solve for a periodic seeded from phi onward.
494 // Only tight multi-statement cycles are considered in order to
495 // simplify rotating the periodic during the final classification.
496 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
497 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700498 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700499 if (phi->InputAt(1) == entry_phi) {
500 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700501 return CreateInduction(kPeriodic, a, initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700502 }
Aart Bikf475bee2015-09-16 12:50:25 -0700503 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
504 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700505 return CreateInduction(kPeriodic, a, b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700506 }
507 }
508 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700509 return nullptr;
510}
511
Aart Bike609b7c2015-08-27 13:46:58 -0700512HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700513 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700514 HInstruction* instruction,
515 HInstruction* x,
516 HInstruction* y,
517 InductionOp op,
518 bool is_first_call) {
519 // Solve within a cycle over an addition or subtraction: adding or subtracting an
520 // invariant value, seeded from phi, keeps adding to the stride of the induction.
521 InductionInfo* b = LookupInfo(loop, y);
522 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700523 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700524 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700525 }
526 auto it = cycle_.find(x);
527 if (it != cycle_.end()) {
528 InductionInfo* a = it->second;
529 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700530 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700531 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700532 }
533 }
Aart Bike609b7c2015-08-27 13:46:58 -0700534
535 // Try some alternatives before failing.
536 if (op == kAdd) {
537 // Try the other way around for an addition if considered for first time.
538 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700539 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700540 }
541 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700542 // Solve within a tight cycle that is formed by exactly two instructions,
543 // one phi and one update, for a periodic idiom of the form k = c - k;
544 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700545 InductionInfo* a = LookupInfo(loop, x);
546 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700547 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700548 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700549 }
550 }
551 }
552
Aart Bik30efb4e2015-07-30 12:14:31 -0700553 return nullptr;
554}
555
Aart Bik0d345cf2016-03-16 10:49:38 -0700556HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
557 Primitive::Type from = conversion->GetInputType();
558 Primitive::Type to = conversion->GetResultType();
559 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
560 // narrowest encountered type is recorded with the induction to account for the precision loss.
561 if (IsNarrowingIntegralConversion(from, to)) {
562 auto it = cycle_.find(conversion->GetInput());
563 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
564 type_ = Narrowest(type_, to);
565 return it->second;
566 }
567 }
568 return nullptr;
569}
570
Aart Bikd14c5952015-09-08 15:25:15 -0700571void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
572 HInstruction* control = loop->GetHeader()->GetLastInstruction();
573 if (control->IsIf()) {
574 HIf* ifs = control->AsIf();
575 HBasicBlock* if_true = ifs->IfTrueSuccessor();
576 HBasicBlock* if_false = ifs->IfFalseSuccessor();
577 HInstruction* if_expr = ifs->InputAt(0);
578 // Determine if loop has following structure in header.
579 // loop-header: ....
580 // if (condition) goto X
581 if (if_expr->IsCondition()) {
582 HCondition* condition = if_expr->AsCondition();
583 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
584 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
585 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700586 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
587 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
588 if (a == nullptr || b == nullptr) {
589 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700590 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
591 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
592 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
593 VisitCondition(loop, a, b, type, condition->GetCondition());
594 }
595 }
596 }
597}
598
599void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
600 InductionInfo* a,
601 InductionInfo* b,
602 Primitive::Type type,
603 IfCondition cmp) {
604 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700605 // Swap condition if induction is at right-hand-side (e.g. U > i is same as i < U).
Aart Bikd14c5952015-09-08 15:25:15 -0700606 switch (cmp) {
607 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
608 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
609 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
610 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700611 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700612 default: break;
613 }
614 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700615 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700616 InductionInfo* lower_expr = a->op_b;
617 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800618 InductionInfo* stride_expr = a->op_a;
619 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700620 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800621 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700622 return;
623 }
Aart Bik358af832016-02-24 14:17:53 -0800624 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
625 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
626 // condition would be always taken).
627 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
628 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700629 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700630 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700631 // Only accept integral condition. A mismatch between the type of condition and the induction
632 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
633 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
634 return; // not integral
635 } else if (type != a->type &&
636 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
637 return; // mismatched type
638 }
Aart Bikf475bee2015-09-16 12:50:25 -0700639 // Normalize a linear loop control with a nonzero stride:
640 // stride > 0, either i < U or i <= U
641 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700642 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
643 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800644 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700645 }
Aart Bikd14c5952015-09-08 15:25:15 -0700646 }
647}
648
649void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700650 InductionInfo* lower_expr,
651 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800652 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700653 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700654 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700655 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700656 // Any loop of the general form:
657 //
658 // for (i = L; i <= U; i += S) // S > 0
659 // or for (i = L; i >= U; i += S) // S < 0
660 // .. i ..
661 //
662 // can be normalized into:
663 //
664 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
665 // .. L + S * n ..
666 //
Aart Bik9401f532015-09-28 16:25:56 -0700667 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700668 //
Aart Bik9401f532015-09-28 16:25:56 -0700669 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
670 // an unsigned entity, for example, as in the following loop that uses the full range:
671 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
672 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700673 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700674 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700675 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700676 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
677 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
678 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700679 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700680 // (4) For loops which early-exits, the TC forms an upper bound, as in:
681 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700682 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700683 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
684 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
685 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700686 if (!cancels) {
687 // Convert exclusive integral inequality into inclusive integral inequality,
688 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700689 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700690 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700691 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700692 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700693 }
694 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800695 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700696 }
Aart Bik97412c922016-02-19 20:14:38 -0800697 trip_count = CreateInvariantOp(
698 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700699 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700700 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700701 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700702 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700703 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700704 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700705 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700706 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700707 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700708 }
Aart Bik22f05872015-10-27 15:56:28 -0700709 InductionOp op = kNop;
710 switch (cmp) {
711 case kCondLT: op = kLT; break;
712 case kCondLE: op = kLE; break;
713 case kCondGT: op = kGT; break;
714 case kCondGE: op = kGE; break;
715 default: LOG(FATAL) << "CONDITION UNREACHABLE";
716 }
Aart Bik009cace2016-09-16 10:15:19 -0700717 // Associate trip count with control instruction, rather than the condition (even
718 // though it's its use) since former provides a convenient use-free placeholder.
719 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700720 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700721 DCHECK(control->IsIf());
722 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700723}
724
725bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
726 InductionInfo* upper_expr,
727 IfCondition cmp) {
728 int64_t lower_value;
729 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800730 switch (cmp) {
731 case kCondLT:
732 return IsAtMost(lower_expr, &lower_value)
733 && IsAtLeast(upper_expr, &upper_value)
734 && lower_value < upper_value;
735 case kCondLE:
736 return IsAtMost(lower_expr, &lower_value)
737 && IsAtLeast(upper_expr, &upper_value)
738 && lower_value <= upper_value;
739 case kCondGT:
740 return IsAtLeast(lower_expr, &lower_value)
741 && IsAtMost(upper_expr, &upper_value)
742 && lower_value > upper_value;
743 case kCondGE:
744 return IsAtLeast(lower_expr, &lower_value)
745 && IsAtMost(upper_expr, &upper_value)
746 && lower_value >= upper_value;
747 default:
748 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700749 }
750 return false; // not certain, may be untaken
751}
752
753bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
754 int64_t stride_value,
755 Primitive::Type type,
756 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700757 const int64_t min = Primitive::MinValueOfIntegralType(type);
758 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700759 // Some rules under which it is certain at compile-time that the loop is finite.
760 int64_t value;
761 switch (cmp) {
762 case kCondLT:
763 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800764 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700765 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800766 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700767 case kCondGT:
768 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800769 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700770 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800771 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700772 default:
773 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700774 }
775 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700776}
777
Aart Bik0d345cf2016-03-16 10:49:38 -0700778bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
779 InductionInfo* upper_expr,
780 int64_t stride_value,
781 Primitive::Type type,
782 IfCondition cmp) {
783 int64_t min = Primitive::MinValueOfIntegralType(type);
784 int64_t max = Primitive::MaxValueOfIntegralType(type);
785 // Inclusive test need one extra.
786 if (stride_value != 1 && stride_value != -1) {
787 return false; // non-unit stride
788 } else if (cmp == kCondLE) {
789 max--;
790 } else if (cmp == kCondGE) {
791 min++;
792 }
793 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000794 // Note: The `value` is initialized to please valgrind - the compiler can reorder
795 // the return value check with the `value` check, b/27651442 .
796 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700797 return IsAtLeast(lower_expr, &value) && value >= min &&
798 IsAtMost(lower_expr, &value) && value <= max &&
799 IsAtLeast(upper_expr, &value) && value >= min &&
800 IsAtMost(upper_expr, &value) && value <= max;
801}
802
Aart Bik30efb4e2015-07-30 12:14:31 -0700803void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
804 HInstruction* instruction,
805 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700806 auto it = induction_.find(loop);
807 if (it == induction_.end()) {
808 it = induction_.Put(loop,
809 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100810 std::less<HInstruction*>(),
811 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700812 }
813 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700814}
815
Aart Bike609b7c2015-08-27 13:46:58 -0700816HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
817 HInstruction* instruction) {
818 auto it = induction_.find(loop);
819 if (it != induction_.end()) {
820 auto loop_it = it->second.find(instruction);
821 if (loop_it != it->second.end()) {
822 return loop_it->second;
823 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700824 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800825 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700826 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700827 AssignInfo(loop, instruction, info);
828 return info;
829 }
830 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700831}
832
Aart Bikd14c5952015-09-08 15:25:15 -0700833HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
834 Primitive::Type type) {
835 if (type == Primitive::kPrimInt) {
836 return CreateInvariantFetch(graph_->GetIntConstant(value));
837 }
838 DCHECK_EQ(type, Primitive::kPrimLong);
839 return CreateInvariantFetch(graph_->GetLongConstant(value));
840}
841
Aart Bik471a2032015-09-04 18:22:11 -0700842HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
843 InductionOp op,
844 InductionInfo* a,
845 InductionInfo* b) {
846 // Perform some light-weight simplifications during construction of a new invariant.
847 // This often safes memory and yields a more concise representation of the induction.
848 // More exhaustive simplifications are done by later phases once induction nodes are
849 // translated back into HIR code (e.g. by loop optimizations or BCE).
850 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800851 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700852 if (value == 0) {
853 // Simplify 0 + b = b, 0 * b = 0.
854 if (op == kAdd) {
855 return b;
856 } else if (op == kMul) {
857 return a;
858 }
Aart Bikd14c5952015-09-08 15:25:15 -0700859 } else if (op == kMul) {
860 // Simplify 1 * b = b, -1 * b = -b
861 if (value == 1) {
862 return b;
863 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800864 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700865 }
Aart Bik471a2032015-09-04 18:22:11 -0700866 }
867 }
Aart Bik97412c922016-02-19 20:14:38 -0800868 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700869 if (value == 0) {
Aart Bikd14c5952015-09-08 15:25:15 -0700870 // Simplify a + 0 = a, a - 0 = a, a * 0 = 0, -0 = 0.
Aart Bik471a2032015-09-04 18:22:11 -0700871 if (op == kAdd || op == kSub) {
872 return a;
873 } else if (op == kMul || op == kNeg) {
874 return b;
875 }
Aart Bikd14c5952015-09-08 15:25:15 -0700876 } else if (op == kMul || op == kDiv) {
877 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
878 if (value == 1) {
879 return a;
880 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800881 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700882 }
Aart Bik471a2032015-09-04 18:22:11 -0700883 }
884 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700885 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
886 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800887 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700888 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800889 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700890 } else if (op == kNeg) {
891 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700892 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800893 } else if (b->operation == kSub) {
894 // Simplify - (a - b) = b - a.
895 if (op == kNeg) {
896 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
897 }
Aart Bik471a2032015-09-04 18:22:11 -0700898 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700899 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -0700900}
901
Aart Bik97412c922016-02-19 20:14:38 -0800902bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
903 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
904}
905
906bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
907 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
908}
909
910bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
911 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800912}
913
Aart Bik30efb4e2015-07-30 12:14:31 -0700914bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
915 InductionInfo* info2) {
916 // Test structural equality only, without accounting for simplifications.
917 if (info1 != nullptr && info2 != nullptr) {
918 return
919 info1->induction_class == info2->induction_class &&
920 info1->operation == info2->operation &&
921 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -0700922 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -0700923 InductionEqual(info1->op_a, info2->op_a) &&
924 InductionEqual(info1->op_b, info2->op_b);
925 }
926 // Otherwise only two nullptrs are considered equal.
927 return info1 == info2;
928}
929
930std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
931 if (info != nullptr) {
932 if (info->induction_class == kInvariant) {
933 std::string inv = "(";
934 inv += InductionToString(info->op_a);
935 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -0700936 case kNop: inv += " @ "; break;
937 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700938 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -0700939 case kNeg: inv += " - "; break;
940 case kMul: inv += " * "; break;
941 case kDiv: inv += " / "; break;
942 case kLT: inv += " < "; break;
943 case kLE: inv += " <= "; break;
944 case kGT: inv += " > "; break;
945 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700946 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -0700947 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800948 if (info->fetch->IsIntConstant()) {
949 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
950 } else if (info->fetch->IsLongConstant()) {
951 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -0700952 } else {
953 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
954 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700955 break;
Aart Bik22f05872015-10-27 15:56:28 -0700956 case kTripCountInLoop: inv += " (TC-loop) "; break;
957 case kTripCountInBody: inv += " (TC-body) "; break;
958 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
959 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700960 }
961 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -0700962 inv += ")";
963 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -0700964 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700965 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700966 if (info->induction_class == kLinear) {
967 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -0700968 InductionToString(info->op_b) + "):" +
969 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700970 } else if (info->induction_class == kWrapAround) {
971 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -0700972 InductionToString(info->op_b) + "):" +
973 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700974 } else if (info->induction_class == kPeriodic) {
975 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -0700976 InductionToString(info->op_b) + "):" +
977 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700978 }
979 }
980 }
981 return "";
982}
983
984} // namespace art