blob: f2602fbf8c576a1f3c87bd18698e3fa9ee710962 [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
Aart Bikcc42be02016-10-20 16:14:16 -070026 * classification, the lexicographically first loop-phi is rotated to the front.
Aart Bik22af3be2015-09-10 12:50:58 -070027 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
Aart Bikcc42be02016-10-20 16:14:16 -070031 // Find very first loop-phi.
Aart Bik22af3be2015-09-10 12:50:58 -070032 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
Aart Bikcc42be02016-10-20 16:14:16 -070044 // If found, bring that loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -070045 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)),
Vladimir Marko5233f932015-09-29 19:01:15 +010090 map_(std::less<HInstruction*>(),
91 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Aart Bik7dc96932016-10-12 10:01:05 -070092 scc_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko5233f932015-09-29 19:01:15 +010093 cycle_(std::less<HInstruction*>(),
94 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
Aart Bik7dc96932016-10-12 10:01:05 -070095 type_(Primitive::kPrimVoid),
Vladimir Marko5233f932015-09-29 19:01:15 +010096 induction_(std::less<HLoopInformation*>(),
Aart Bikcc42be02016-10-20 16:14:16 -070097 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
98 cycles_(std::less<HPhi*>(),
99 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700100}
101
102void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800103 // Detects sequence variables (generalized induction variables) during an outer to inner
104 // traversal of all loops using Gerlek's algorithm. The order is important to enable
105 // range analysis on outer loop while visiting inner loops.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100106 for (HBasicBlock* graph_block : graph_->GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000107 // Don't analyze irreducible loops.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000108 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700109 VisitLoop(graph_block->GetLoopInformation());
110 }
111 }
112}
113
114void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
115 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
116 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
117 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700118 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700119 map_.clear();
120
121 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
122 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700123 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700124 if (loop_block->GetLoopInformation() != loop) {
Aart Bik7dc96932016-10-12 10:01:05 -0700125 continue; // Inner loops visited later.
Aart Bik30efb4e2015-07-30 12:14:31 -0700126 }
127 // Visit phi-operations and instructions.
128 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
129 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700130 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700131 VisitNode(loop, instruction);
132 }
133 }
134 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
135 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700136 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700137 VisitNode(loop, instruction);
138 }
139 }
140 }
141
Aart Bike609b7c2015-08-27 13:46:58 -0700142 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700143 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700144
Aart Bik78296912016-03-25 13:14:53 -0700145 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700146 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700147}
148
149void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700150 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700151 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700152 stack_.push_back(instruction);
153
154 // Visit all descendants.
155 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100156 for (HInstruction* input : instruction->GetInputs()) {
157 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700158 }
159
160 // Lower or found SCC?
161 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700162 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700163 } else {
164 scc_.clear();
165 cycle_.clear();
166
167 // Pop the stack to build the SCC for classification.
168 while (!stack_.empty()) {
169 HInstruction* x = stack_.back();
170 scc_.push_back(x);
171 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700172 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700173 if (x == instruction) {
174 break;
175 }
176 }
177
Aart Bik0d345cf2016-03-16 10:49:38 -0700178 // Type of induction.
179 type_ = scc_[0]->GetType();
180
Aart Bik30efb4e2015-07-30 12:14:31 -0700181 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700182 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700183 ClassifyTrivial(loop, scc_[0]);
184 } else {
185 ClassifyNonTrivial(loop);
186 }
187
188 scc_.clear();
189 cycle_.clear();
190 }
191}
192
193uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
194 // If the definition is either outside the loop (loop invariant entry value)
195 // or assigned in inner loop (inner exit value), the traversal stops.
196 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
197 if (otherLoop != loop) {
198 return global_depth_;
199 }
200
201 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700202 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700203 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700204 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700205 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700206 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700207 return it->second.done ? global_depth_ : it->second.depth;
208 }
209}
210
211void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
212 InductionInfo* info = nullptr;
213 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700214 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700215 } else if (instruction->IsAdd()) {
216 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
217 LookupInfo(loop, instruction->InputAt(1)), kAdd);
218 } else if (instruction->IsSub()) {
219 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
220 LookupInfo(loop, instruction->InputAt(1)), kSub);
221 } else if (instruction->IsMul()) {
222 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
223 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700224 } else if (instruction->IsShl()) {
225 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
226 LookupInfo(loop, instruction->InputAt(1)),
227 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700228 } else if (instruction->IsNeg()) {
229 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik0d345cf2016-03-16 10:49:38 -0700230 } else if (instruction->IsTypeConversion()) {
231 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
232 instruction->AsTypeConversion()->GetInputType(),
233 instruction->AsTypeConversion()->GetResultType());
234
Aart Bike609b7c2015-08-27 13:46:58 -0700235 } else if (instruction->IsBoundsCheck()) {
236 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700237 }
238
239 // Successfully classified?
240 if (info != nullptr) {
241 AssignInfo(loop, instruction, info);
242 }
243}
244
245void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
246 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700247 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700248
Aart Bikcc42be02016-10-20 16:14:16 -0700249 // Rotate proper loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -0700250 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100251 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700252 RotateEntryPhiFirst(loop, &scc_, &other);
253 }
254
Aart Bikcc42be02016-10-20 16:14:16 -0700255 // Analyze from loop-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700256 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700257 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700258 return;
259 }
Aart Bikf475bee2015-09-16 12:50:25 -0700260
261 // External link should be loop invariant.
262 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700263 if (initial == nullptr || initial->induction_class != kInvariant) {
264 return;
265 }
266
Aart Bikcc42be02016-10-20 16:14:16 -0700267 // Store interesting cycle.
268 AssignCycle(phi->AsPhi());
269
Aart Bikf475bee2015-09-16 12:50:25 -0700270 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700271 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700272 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700273 if (update != nullptr) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700274 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update, type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700275 }
276 return;
277 }
278
279 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700280 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700281 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700282 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700283 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700284 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700285 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700286 } else if (instruction->IsAdd()) {
287 update = SolveAddSub(
288 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
289 } else if (instruction->IsSub()) {
290 update = SolveAddSub(
291 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik7dc96932016-10-12 10:01:05 -0700292 } else if (instruction->IsXor()) {
Aart Bik639cc8c2016-10-18 13:03:31 -0700293 update = SolveXor(loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1));
294 } else if (instruction->IsEqual()) {
295 update = SolveTest(loop, phi, instruction, 0);
296 } else if (instruction->IsNotEqual()) {
297 update = SolveTest(loop, phi, instruction, 1);
Aart Bik0d345cf2016-03-16 10:49:38 -0700298 } else if (instruction->IsTypeConversion()) {
299 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700300 }
301 if (update == nullptr) {
302 return;
303 }
Aart Bike609b7c2015-08-27 13:46:58 -0700304 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700305 }
306
Aart Bikf475bee2015-09-16 12:50:25 -0700307 // Success if all internal links received the same temporary meaning.
308 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
309 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700310 switch (induction->induction_class) {
311 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700312 // Classify first phi and then the rest of the cycle "on-demand".
313 // Statements are scanned in order.
Aart Bik0d345cf2016-03-16 10:49:38 -0700314 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial, type_));
Aart Bik22af3be2015-09-10 12:50:58 -0700315 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700316 ClassifyTrivial(loop, scc_[i]);
317 }
318 break;
319 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700320 // Classify all elements in the cycle with the found periodic induction while
321 // rotating each first element to the end. Lastly, phi is classified.
322 // Statements are scanned in reverse order.
323 for (size_t i = size - 1; i >= 1; i--) {
324 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700325 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
326 }
327 AssignInfo(loop, phi, induction);
328 break;
329 default:
330 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700331 }
332 }
333}
334
Aart Bike609b7c2015-08-27 13:46:58 -0700335HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
336 InductionInfo* induction,
337 InductionInfo* last) {
338 // Rotates a periodic induction of the form
339 // (a, b, c, d, e)
340 // into
341 // (b, c, d, e, a)
342 // in preparation of assigning this to the previous variable in the sequence.
343 if (induction->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700344 return CreateInduction(kPeriodic, induction, last, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700345 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700346 return CreateInduction(
347 kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last), type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700348}
349
Aart Bikf475bee2015-09-16 12:50:25 -0700350HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
351 HInstruction* phi,
352 size_t input_index) {
353 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100354 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100355 DCHECK_LT(input_index, inputs.size());
356 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
357 for (size_t i = input_index + 1; i < inputs.size(); i++) {
358 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700359 if (!InductionEqual(a, b)) {
360 return nullptr;
361 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700362 }
Aart Bikf475bee2015-09-16 12:50:25 -0700363 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700364}
365
366HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
367 InductionInfo* b,
368 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700369 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
370 // can be combined with an invariant to yield a similar result. Even two linear inputs can
371 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700372 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700373 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700374 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700375 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700376 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700377 return CreateInduction(kLinear,
378 TransferAddSub(a->op_a, b->op_a, op),
379 TransferAddSub(a->op_b, b->op_b, op),
380 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700381 } else if (a->induction_class == kInvariant) {
382 InductionInfo* new_a = b->op_a;
383 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
384 if (b->induction_class != kLinear) {
385 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
386 new_a = TransferAddSub(a, new_a, op);
387 } else if (op == kSub) { // Negation required.
388 new_a = TransferNeg(new_a);
389 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700390 return CreateInduction(b->induction_class, new_a, new_b, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700391 } else if (b->induction_class == kInvariant) {
392 InductionInfo* new_a = a->op_a;
393 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
394 if (a->induction_class != kLinear) {
395 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
396 new_a = TransferAddSub(new_a, b, op);
397 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700398 return CreateInduction(a->induction_class, new_a, new_b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700399 }
400 }
401 return nullptr;
402}
403
404HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
405 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700406 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
407 // can be multiplied with an invariant to yield a similar but multiplied result.
408 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700409 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700410 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700411 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700412 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700413 } else if (a->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700414 return CreateInduction(b->induction_class,
415 TransferMul(a, b->op_a),
416 TransferMul(a, b->op_b),
417 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700418 } else if (b->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700419 return CreateInduction(a->induction_class,
420 TransferMul(a->op_a, b),
421 TransferMul(a->op_b, b),
422 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700423 }
424 }
425 return nullptr;
426}
427
428HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
429 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700430 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700431 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700432 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800433 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700434 // Obtain the constant needed for the multiplication. This yields an existing instruction
435 // if the constants is already there. Otherwise, this has a side effect on the HIR.
436 // The restriction on the shift factor avoids generating a negative constant
437 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
438 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700439 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
440 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
441 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700442 }
443 }
444 return nullptr;
445}
446
447HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700448 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
449 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700450 if (a != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700451 type_ = Narrowest(type_, a->type);
Aart Bik30efb4e2015-07-30 12:14:31 -0700452 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700453 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700454 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700455 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b), type_);
456 }
457 return nullptr;
458}
459
460HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
461 Primitive::Type from,
462 Primitive::Type to) {
463 if (a != nullptr) {
464 // Allow narrowing conversion in certain cases.
465 if (IsNarrowingIntegralConversion(from, to)) {
466 if (a->induction_class == kLinear) {
467 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
468 return CreateInduction(kLinear, a->op_a, a->op_b, to);
469 }
470 }
471 // TODO: other cases useful too?
472 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700473 }
474 return nullptr;
475}
476
Aart Bikf475bee2015-09-16 12:50:25 -0700477HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
478 size_t input_index) {
479 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100480 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100481 DCHECK_LT(input_index, inputs.size());
482 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700483 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100484 for (size_t i = input_index + 1; i < inputs.size(); i++) {
485 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700486 if (itb == cycle_.end() ||
487 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700488 return nullptr;
489 }
490 }
Aart Bikf475bee2015-09-16 12:50:25 -0700491 return ita->second;
492 }
493 return nullptr;
494}
495
496HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
497 HLoopInformation* loop,
498 HInstruction* entry_phi,
499 HInstruction* phi) {
500 // Match all phi inputs.
501 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
502 if (match != nullptr) {
503 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700504 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700505
Aart Bikf475bee2015-09-16 12:50:25 -0700506 // Otherwise, try to solve for a periodic seeded from phi onward.
507 // Only tight multi-statement cycles are considered in order to
508 // simplify rotating the periodic during the final classification.
509 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
510 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700511 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700512 if (phi->InputAt(1) == entry_phi) {
513 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700514 return CreateInduction(kPeriodic, a, initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700515 }
Aart Bikf475bee2015-09-16 12:50:25 -0700516 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
517 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700518 return CreateInduction(kPeriodic, a, b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700519 }
520 }
521 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700522 return nullptr;
523}
524
Aart Bike609b7c2015-08-27 13:46:58 -0700525HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700526 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700527 HInstruction* instruction,
528 HInstruction* x,
529 HInstruction* y,
530 InductionOp op,
531 bool is_first_call) {
532 // Solve within a cycle over an addition or subtraction: adding or subtracting an
533 // invariant value, seeded from phi, keeps adding to the stride of the induction.
534 InductionInfo* b = LookupInfo(loop, y);
535 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700536 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700537 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700538 }
539 auto it = cycle_.find(x);
540 if (it != cycle_.end()) {
541 InductionInfo* a = it->second;
542 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700543 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700544 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700545 }
546 }
Aart Bike609b7c2015-08-27 13:46:58 -0700547
548 // Try some alternatives before failing.
549 if (op == kAdd) {
550 // Try the other way around for an addition if considered for first time.
551 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700552 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700553 }
554 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700555 // Solve within a tight cycle that is formed by exactly two instructions,
556 // one phi and one update, for a periodic idiom of the form k = c - k;
557 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700558 InductionInfo* a = LookupInfo(loop, x);
559 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700560 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700561 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700562 }
563 }
564 }
565
Aart Bik30efb4e2015-07-30 12:14:31 -0700566 return nullptr;
567}
568
Aart Bik7dc96932016-10-12 10:01:05 -0700569HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveXor(HLoopInformation* loop,
570 HInstruction* entry_phi,
571 HInstruction* instruction,
572 HInstruction* x,
Aart Bik639cc8c2016-10-18 13:03:31 -0700573 HInstruction* y) {
574 // Solve within a tight cycle on x = c ^ x or x = x ^ c.
575 if (entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
576 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
577 InductionInfo* a = LookupInfo(loop, x);
578 if (a != nullptr && a->induction_class == kInvariant && entry_phi == y) {
579 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, a, initial), initial, type_);
580 }
581 InductionInfo* b = LookupInfo(loop, y);
582 if (b != nullptr && b->induction_class == kInvariant && entry_phi == x) {
Aart Bik7dc96932016-10-12 10:01:05 -0700583 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, initial, b), initial, type_);
584 }
585 }
Aart Bik639cc8c2016-10-18 13:03:31 -0700586 return nullptr;
587}
588
589HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveTest(HLoopInformation* loop,
590 HInstruction* entry_phi,
591 HInstruction* instruction,
592 int64_t opposite_value) {
593 // Detect hidden XOR construction in tight cycles on x = (x == 0) or x = (x != 1).
594 int64_t value = -1;
595 HInstruction* x = instruction->InputAt(0);
596 HInstruction* y = instruction->InputAt(1);
597 if (IsExact(LookupInfo(loop, x), &value) && value == opposite_value) {
598 return SolveXor(loop, entry_phi, instruction, graph_->GetIntConstant(1), y);
599 } else if (IsExact(LookupInfo(loop, y), &value) && value == opposite_value) {
600 return SolveXor(loop, entry_phi, instruction, x, graph_->GetIntConstant(1));
Aart Bik7dc96932016-10-12 10:01:05 -0700601 }
602 return nullptr;
603}
604
Aart Bik0d345cf2016-03-16 10:49:38 -0700605HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
606 Primitive::Type from = conversion->GetInputType();
607 Primitive::Type to = conversion->GetResultType();
608 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
609 // narrowest encountered type is recorded with the induction to account for the precision loss.
610 if (IsNarrowingIntegralConversion(from, to)) {
611 auto it = cycle_.find(conversion->GetInput());
612 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
613 type_ = Narrowest(type_, to);
614 return it->second;
615 }
616 }
617 return nullptr;
618}
619
Aart Bikd14c5952015-09-08 15:25:15 -0700620void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
621 HInstruction* control = loop->GetHeader()->GetLastInstruction();
622 if (control->IsIf()) {
623 HIf* ifs = control->AsIf();
624 HBasicBlock* if_true = ifs->IfTrueSuccessor();
625 HBasicBlock* if_false = ifs->IfFalseSuccessor();
626 HInstruction* if_expr = ifs->InputAt(0);
627 // Determine if loop has following structure in header.
628 // loop-header: ....
629 // if (condition) goto X
630 if (if_expr->IsCondition()) {
631 HCondition* condition = if_expr->AsCondition();
632 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
633 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
634 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700635 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
636 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
637 if (a == nullptr || b == nullptr) {
638 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700639 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
640 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
641 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
642 VisitCondition(loop, a, b, type, condition->GetCondition());
643 }
644 }
645 }
646}
647
648void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
649 InductionInfo* a,
650 InductionInfo* b,
651 Primitive::Type type,
652 IfCondition cmp) {
653 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700654 // 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 -0700655 switch (cmp) {
656 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
657 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
658 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
659 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700660 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700661 default: break;
662 }
663 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700664 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700665 InductionInfo* lower_expr = a->op_b;
666 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800667 InductionInfo* stride_expr = a->op_a;
668 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700669 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800670 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700671 return;
672 }
Aart Bik358af832016-02-24 14:17:53 -0800673 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
674 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
675 // condition would be always taken).
676 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
677 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700678 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700679 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700680 // Only accept integral condition. A mismatch between the type of condition and the induction
681 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
682 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
683 return; // not integral
684 } else if (type != a->type &&
685 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
686 return; // mismatched type
687 }
Aart Bikf475bee2015-09-16 12:50:25 -0700688 // Normalize a linear loop control with a nonzero stride:
689 // stride > 0, either i < U or i <= U
690 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700691 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
692 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800693 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700694 }
Aart Bikd14c5952015-09-08 15:25:15 -0700695 }
696}
697
698void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700699 InductionInfo* lower_expr,
700 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800701 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700702 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700703 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700704 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700705 // Any loop of the general form:
706 //
707 // for (i = L; i <= U; i += S) // S > 0
708 // or for (i = L; i >= U; i += S) // S < 0
709 // .. i ..
710 //
711 // can be normalized into:
712 //
713 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
714 // .. L + S * n ..
715 //
Aart Bik9401f532015-09-28 16:25:56 -0700716 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700717 //
Aart Bik9401f532015-09-28 16:25:56 -0700718 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
719 // an unsigned entity, for example, as in the following loop that uses the full range:
720 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
721 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700722 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700723 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700724 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700725 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
726 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
727 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700728 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700729 // (4) For loops which early-exits, the TC forms an upper bound, as in:
730 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700731 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700732 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
733 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
734 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700735 if (!cancels) {
736 // Convert exclusive integral inequality into inclusive integral inequality,
737 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700738 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700739 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700740 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700741 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700742 }
743 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800744 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700745 }
Aart Bik97412c922016-02-19 20:14:38 -0800746 trip_count = CreateInvariantOp(
747 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700748 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700749 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700750 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700751 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700752 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700753 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700754 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700755 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700756 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700757 }
Aart Bik22f05872015-10-27 15:56:28 -0700758 InductionOp op = kNop;
759 switch (cmp) {
760 case kCondLT: op = kLT; break;
761 case kCondLE: op = kLE; break;
762 case kCondGT: op = kGT; break;
763 case kCondGE: op = kGE; break;
764 default: LOG(FATAL) << "CONDITION UNREACHABLE";
765 }
Aart Bik009cace2016-09-16 10:15:19 -0700766 // Associate trip count with control instruction, rather than the condition (even
767 // though it's its use) since former provides a convenient use-free placeholder.
768 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700769 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700770 DCHECK(control->IsIf());
771 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700772}
773
774bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
775 InductionInfo* upper_expr,
776 IfCondition cmp) {
777 int64_t lower_value;
778 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800779 switch (cmp) {
780 case kCondLT:
781 return IsAtMost(lower_expr, &lower_value)
782 && IsAtLeast(upper_expr, &upper_value)
783 && lower_value < upper_value;
784 case kCondLE:
785 return IsAtMost(lower_expr, &lower_value)
786 && IsAtLeast(upper_expr, &upper_value)
787 && lower_value <= upper_value;
788 case kCondGT:
789 return IsAtLeast(lower_expr, &lower_value)
790 && IsAtMost(upper_expr, &upper_value)
791 && lower_value > upper_value;
792 case kCondGE:
793 return IsAtLeast(lower_expr, &lower_value)
794 && IsAtMost(upper_expr, &upper_value)
795 && lower_value >= upper_value;
796 default:
797 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700798 }
799 return false; // not certain, may be untaken
800}
801
802bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
803 int64_t stride_value,
804 Primitive::Type type,
805 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700806 const int64_t min = Primitive::MinValueOfIntegralType(type);
807 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700808 // Some rules under which it is certain at compile-time that the loop is finite.
809 int64_t value;
810 switch (cmp) {
811 case kCondLT:
812 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800813 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700814 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800815 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700816 case kCondGT:
817 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800818 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700819 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800820 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700821 default:
822 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700823 }
824 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700825}
826
Aart Bik0d345cf2016-03-16 10:49:38 -0700827bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
828 InductionInfo* upper_expr,
829 int64_t stride_value,
830 Primitive::Type type,
831 IfCondition cmp) {
832 int64_t min = Primitive::MinValueOfIntegralType(type);
833 int64_t max = Primitive::MaxValueOfIntegralType(type);
834 // Inclusive test need one extra.
835 if (stride_value != 1 && stride_value != -1) {
836 return false; // non-unit stride
837 } else if (cmp == kCondLE) {
838 max--;
839 } else if (cmp == kCondGE) {
840 min++;
841 }
842 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000843 // Note: The `value` is initialized to please valgrind - the compiler can reorder
844 // the return value check with the `value` check, b/27651442 .
845 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700846 return IsAtLeast(lower_expr, &value) && value >= min &&
847 IsAtMost(lower_expr, &value) && value <= max &&
848 IsAtLeast(upper_expr, &value) && value >= min &&
849 IsAtMost(upper_expr, &value) && value <= max;
850}
851
Aart Bik30efb4e2015-07-30 12:14:31 -0700852void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
853 HInstruction* instruction,
854 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700855 auto it = induction_.find(loop);
856 if (it == induction_.end()) {
857 it = induction_.Put(loop,
858 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100859 std::less<HInstruction*>(),
860 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700861 }
862 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700863}
864
Aart Bike609b7c2015-08-27 13:46:58 -0700865HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
866 HInstruction* instruction) {
867 auto it = induction_.find(loop);
868 if (it != induction_.end()) {
869 auto loop_it = it->second.find(instruction);
870 if (loop_it != it->second.end()) {
871 return loop_it->second;
872 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700873 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800874 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700875 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700876 AssignInfo(loop, instruction, info);
877 return info;
878 }
879 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700880}
881
Aart Bikd14c5952015-09-08 15:25:15 -0700882HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
883 Primitive::Type type) {
884 if (type == Primitive::kPrimInt) {
885 return CreateInvariantFetch(graph_->GetIntConstant(value));
886 }
887 DCHECK_EQ(type, Primitive::kPrimLong);
888 return CreateInvariantFetch(graph_->GetLongConstant(value));
889}
890
Aart Bik471a2032015-09-04 18:22:11 -0700891HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
892 InductionOp op,
893 InductionInfo* a,
894 InductionInfo* b) {
895 // Perform some light-weight simplifications during construction of a new invariant.
896 // This often safes memory and yields a more concise representation of the induction.
897 // More exhaustive simplifications are done by later phases once induction nodes are
898 // translated back into HIR code (e.g. by loop optimizations or BCE).
899 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800900 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700901 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700902 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
903 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700904 return b;
905 } else if (op == kMul) {
906 return a;
907 }
Aart Bikd14c5952015-09-08 15:25:15 -0700908 } else if (op == kMul) {
909 // Simplify 1 * b = b, -1 * b = -b
910 if (value == 1) {
911 return b;
912 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800913 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700914 }
Aart Bik471a2032015-09-04 18:22:11 -0700915 }
916 }
Aart Bik97412c922016-02-19 20:14:38 -0800917 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700918 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700919 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
920 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700921 return a;
922 } else if (op == kMul || op == kNeg) {
923 return b;
924 }
Aart Bikd14c5952015-09-08 15:25:15 -0700925 } else if (op == kMul || op == kDiv) {
926 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
927 if (value == 1) {
928 return a;
929 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800930 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700931 }
Aart Bik471a2032015-09-04 18:22:11 -0700932 }
933 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700934 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
935 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800936 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700937 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800938 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700939 } else if (op == kNeg) {
940 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700941 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800942 } else if (b->operation == kSub) {
943 // Simplify - (a - b) = b - a.
944 if (op == kNeg) {
945 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
946 }
Aart Bik471a2032015-09-04 18:22:11 -0700947 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700948 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -0700949}
950
Aart Bikcc42be02016-10-20 16:14:16 -0700951
952void HInductionVarAnalysis::AssignCycle(HPhi* phi) {
953 ArenaSet<HInstruction*>* set = &cycles_.Put(phi, ArenaSet<HInstruction*>(
954 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)))->second;
955 for (HInstruction* i : scc_) {
956 set->insert(i);
957 }
958}
959
960ArenaSet<HInstruction*>* HInductionVarAnalysis::LookupCycle(HPhi* phi) {
961 auto it = cycles_.find(phi);
962 if (it != cycles_.end()) {
963 return &it->second;
964 }
965 return nullptr;
966}
967
Aart Bik97412c922016-02-19 20:14:38 -0800968bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
969 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
970}
971
972bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
973 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
974}
975
976bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
977 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800978}
979
Aart Bik30efb4e2015-07-30 12:14:31 -0700980bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
981 InductionInfo* info2) {
982 // Test structural equality only, without accounting for simplifications.
983 if (info1 != nullptr && info2 != nullptr) {
984 return
985 info1->induction_class == info2->induction_class &&
986 info1->operation == info2->operation &&
987 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -0700988 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -0700989 InductionEqual(info1->op_a, info2->op_a) &&
990 InductionEqual(info1->op_b, info2->op_b);
991 }
992 // Otherwise only two nullptrs are considered equal.
993 return info1 == info2;
994}
995
996std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
997 if (info != nullptr) {
998 if (info->induction_class == kInvariant) {
999 std::string inv = "(";
1000 inv += InductionToString(info->op_a);
1001 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -07001002 case kNop: inv += " @ "; break;
1003 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001004 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -07001005 case kNeg: inv += " - "; break;
1006 case kMul: inv += " * "; break;
1007 case kDiv: inv += " / "; break;
Aart Bik7dc96932016-10-12 10:01:05 -07001008 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -07001009 case kLT: inv += " < "; break;
1010 case kLE: inv += " <= "; break;
1011 case kGT: inv += " > "; break;
1012 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001013 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -07001014 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -08001015 if (info->fetch->IsIntConstant()) {
1016 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
1017 } else if (info->fetch->IsLongConstant()) {
1018 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -07001019 } else {
1020 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
1021 }
Aart Bik30efb4e2015-07-30 12:14:31 -07001022 break;
Aart Bik22f05872015-10-27 15:56:28 -07001023 case kTripCountInLoop: inv += " (TC-loop) "; break;
1024 case kTripCountInBody: inv += " (TC-body) "; break;
1025 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
1026 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001027 }
1028 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -07001029 inv += ")";
1030 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -07001031 } else {
Aart Bike609b7c2015-08-27 13:46:58 -07001032 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001033 if (info->induction_class == kLinear) {
1034 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001035 InductionToString(info->op_b) + "):" +
1036 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001037 } else if (info->induction_class == kWrapAround) {
1038 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001039 InductionToString(info->op_b) + "):" +
1040 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001041 } else if (info->induction_class == kPeriodic) {
1042 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001043 InductionToString(info->op_b) + "):" +
1044 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001045 }
1046 }
1047 }
1048 return "";
1049}
1050
1051} // namespace art