blob: 15615022e3ae491de0595f932457105cd1e95672 [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);
Aart Bikc071a012016-12-01 10:22:31 -0800221 } else if (instruction->IsNeg()) {
222 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik30efb4e2015-07-30 12:14:31 -0700223 } else if (instruction->IsMul()) {
224 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
225 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700226 } else if (instruction->IsShl()) {
Aart Bikc071a012016-12-01 10:22:31 -0800227 HInstruction* mulc = GetMultConstantForShift(loop, instruction);
228 if (mulc != nullptr) {
229 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
230 LookupInfo(loop, mulc));
231 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700232 } else if (instruction->IsTypeConversion()) {
233 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
234 instruction->AsTypeConversion()->GetInputType(),
235 instruction->AsTypeConversion()->GetResultType());
Aart Bike609b7c2015-08-27 13:46:58 -0700236 } else if (instruction->IsBoundsCheck()) {
237 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700238 }
239
240 // Successfully classified?
241 if (info != nullptr) {
242 AssignInfo(loop, instruction, info);
243 }
244}
245
246void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
247 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700248 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700249
Aart Bikcc42be02016-10-20 16:14:16 -0700250 // Rotate proper loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -0700251 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100252 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700253 RotateEntryPhiFirst(loop, &scc_, &other);
254 }
255
Aart Bikcc42be02016-10-20 16:14:16 -0700256 // Analyze from loop-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700257 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700258 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700259 return;
260 }
Aart Bikf475bee2015-09-16 12:50:25 -0700261
262 // External link should be loop invariant.
263 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700264 if (initial == nullptr || initial->induction_class != kInvariant) {
265 return;
266 }
267
Aart Bikcc42be02016-10-20 16:14:16 -0700268 // Store interesting cycle.
269 AssignCycle(phi->AsPhi());
270
Aart Bikf475bee2015-09-16 12:50:25 -0700271 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700272 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700273 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700274 if (update != nullptr) {
Aart Bikc071a012016-12-01 10:22:31 -0800275 AssignInfo(loop, phi, CreateInduction(kWrapAround,
276 kNop,
277 initial,
278 update,
279 /*fetch*/ nullptr,
280 type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700281 }
282 return;
283 }
284
285 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700286 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700287 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700288 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700289 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700290 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700291 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700292 } else if (instruction->IsAdd()) {
293 update = SolveAddSub(
294 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
295 } else if (instruction->IsSub()) {
296 update = SolveAddSub(
297 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bikc071a012016-12-01 10:22:31 -0800298 } else if (instruction->IsMul()) {
299 update = SolveGeo(
300 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kMul);
301 } else if (instruction->IsDiv()) {
302 update = SolveGeo(
303 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kDiv);
304 } else if (instruction->IsRem()) {
305 update = SolveGeo(
306 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kNop);
307 } else if (instruction->IsShl()) {
308 HInstruction* mulc = GetMultConstantForShift(loop, instruction);
309 if (mulc != nullptr) {
310 update = SolveGeo(loop, phi, instruction, instruction->InputAt(0), mulc, kMul);
311 }
Aart Bik7dc96932016-10-12 10:01:05 -0700312 } else if (instruction->IsXor()) {
Aart Bik639cc8c2016-10-18 13:03:31 -0700313 update = SolveXor(loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1));
314 } else if (instruction->IsEqual()) {
315 update = SolveTest(loop, phi, instruction, 0);
316 } else if (instruction->IsNotEqual()) {
317 update = SolveTest(loop, phi, instruction, 1);
Aart Bik0d345cf2016-03-16 10:49:38 -0700318 } else if (instruction->IsTypeConversion()) {
319 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700320 }
321 if (update == nullptr) {
322 return;
323 }
Aart Bike609b7c2015-08-27 13:46:58 -0700324 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700325 }
326
Aart Bikf475bee2015-09-16 12:50:25 -0700327 // Success if all internal links received the same temporary meaning.
328 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
329 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700330 switch (induction->induction_class) {
331 case kInvariant:
Aart Bikc071a012016-12-01 10:22:31 -0800332 // Construct combined stride of the linear induction.
333 induction = CreateInduction(kLinear, kNop, induction, initial, /*fetch*/ nullptr, type_);
334 FALLTHROUGH_INTENDED;
335 case kPolynomial:
336 case kGeometric:
Aart Bik22af3be2015-09-10 12:50:58 -0700337 // Classify first phi and then the rest of the cycle "on-demand".
338 // Statements are scanned in order.
Aart Bikc071a012016-12-01 10:22:31 -0800339 AssignInfo(loop, phi, induction);
Aart Bik22af3be2015-09-10 12:50:58 -0700340 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700341 ClassifyTrivial(loop, scc_[i]);
342 }
343 break;
344 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700345 // Classify all elements in the cycle with the found periodic induction while
346 // rotating each first element to the end. Lastly, phi is classified.
347 // Statements are scanned in reverse order.
348 for (size_t i = size - 1; i >= 1; i--) {
349 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700350 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
351 }
352 AssignInfo(loop, phi, induction);
353 break;
354 default:
355 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700356 }
357 }
358}
359
Aart Bike609b7c2015-08-27 13:46:58 -0700360HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
361 InductionInfo* induction,
362 InductionInfo* last) {
363 // Rotates a periodic induction of the form
364 // (a, b, c, d, e)
365 // into
366 // (b, c, d, e, a)
367 // in preparation of assigning this to the previous variable in the sequence.
368 if (induction->induction_class == kInvariant) {
Aart Bikc071a012016-12-01 10:22:31 -0800369 return CreateInduction(kPeriodic,
370 kNop,
371 induction,
372 last,
373 /*fetch*/ nullptr,
374 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700375 }
Aart Bikc071a012016-12-01 10:22:31 -0800376 return CreateInduction(kPeriodic,
377 kNop,
378 induction->op_a,
379 RotatePeriodicInduction(induction->op_b, last),
380 /*fetch*/ nullptr,
381 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700382}
383
Aart Bikf475bee2015-09-16 12:50:25 -0700384HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
385 HInstruction* phi,
386 size_t input_index) {
387 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100388 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100389 DCHECK_LT(input_index, inputs.size());
390 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
391 for (size_t i = input_index + 1; i < inputs.size(); i++) {
392 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700393 if (!InductionEqual(a, b)) {
394 return nullptr;
395 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700396 }
Aart Bikf475bee2015-09-16 12:50:25 -0700397 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700398}
399
400HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
401 InductionInfo* b,
402 InductionOp op) {
Aart Bikc071a012016-12-01 10:22:31 -0800403 // Transfer over an addition or subtraction: any invariant, linear, polynomial, geometric,
404 // wrap-around, or periodic can be combined with an invariant to yield a similar result.
405 // Even two linear inputs can be combined. Other combinations fail.
Aart Bik30efb4e2015-07-30 12:14:31 -0700406 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700407 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700408 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700409 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700410 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700411 return CreateInduction(kLinear,
Aart Bikc071a012016-12-01 10:22:31 -0800412 kNop,
Aart Bik0d345cf2016-03-16 10:49:38 -0700413 TransferAddSub(a->op_a, b->op_a, op),
414 TransferAddSub(a->op_b, b->op_b, op),
Aart Bikc071a012016-12-01 10:22:31 -0800415 /*fetch*/ nullptr,
Aart Bik0d345cf2016-03-16 10:49:38 -0700416 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700417 } else if (a->induction_class == kInvariant) {
418 InductionInfo* new_a = b->op_a;
419 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
Aart Bikc071a012016-12-01 10:22:31 -0800420 if (b->induction_class == kWrapAround || b->induction_class == kPeriodic) {
Aart Bike609b7c2015-08-27 13:46:58 -0700421 new_a = TransferAddSub(a, new_a, op);
422 } else if (op == kSub) { // Negation required.
423 new_a = TransferNeg(new_a);
424 }
Aart Bikc071a012016-12-01 10:22:31 -0800425 return CreateInduction(b->induction_class, b->operation, new_a, new_b, b->fetch, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700426 } else if (b->induction_class == kInvariant) {
427 InductionInfo* new_a = a->op_a;
428 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
Aart Bikc071a012016-12-01 10:22:31 -0800429 if (a->induction_class == kWrapAround || a->induction_class == kPeriodic) {
Aart Bike609b7c2015-08-27 13:46:58 -0700430 new_a = TransferAddSub(new_a, b, op);
431 }
Aart Bikc071a012016-12-01 10:22:31 -0800432 return CreateInduction(a->induction_class, a->operation, new_a, new_b, a->fetch, type_);
433 }
434 }
435 return nullptr;
436}
437
438HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
439 // Transfer over a unary negation: an invariant, linear, polynomial, geometric (mul),
440 // wrap-around, or periodic input yields a similar but negated induction as result.
441 if (a != nullptr) {
442 type_ = Narrowest(type_, a->type);
443 if (a->induction_class == kInvariant) {
444 return CreateInvariantOp(kNeg, nullptr, a);
445 } else if (a->induction_class != kGeometric || a->operation == kMul) {
446 return CreateInduction(a->induction_class,
447 a->operation,
448 TransferNeg(a->op_a),
449 TransferNeg(a->op_b),
450 a->fetch,
451 type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700452 }
453 }
454 return nullptr;
455}
456
457HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
458 InductionInfo* b) {
Aart Bikc071a012016-12-01 10:22:31 -0800459 // Transfer over a multiplication: any invariant, linear, polynomial, geometric (mul),
460 // wrap-around, or periodic can be multiplied with an invariant to yield a similar
461 // but multiplied result. Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700462 if (a != nullptr && b != nullptr) {
Aart Bikcc42be02016-10-20 16:14:16 -0700463 type_ = Narrowest(type_, Narrowest(a->type, b->type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700464 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700465 return CreateInvariantOp(kMul, a, b);
Aart Bikc071a012016-12-01 10:22:31 -0800466 } else if (a->induction_class == kInvariant && (b->induction_class != kGeometric ||
467 b->operation == kMul)) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700468 return CreateInduction(b->induction_class,
Aart Bikc071a012016-12-01 10:22:31 -0800469 b->operation,
Aart Bik0d345cf2016-03-16 10:49:38 -0700470 TransferMul(a, b->op_a),
471 TransferMul(a, b->op_b),
Aart Bikc071a012016-12-01 10:22:31 -0800472 b->fetch,
Aart Bik0d345cf2016-03-16 10:49:38 -0700473 type_);
Aart Bikc071a012016-12-01 10:22:31 -0800474 } else if (b->induction_class == kInvariant && (a->induction_class != kGeometric ||
475 a->operation == kMul)) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700476 return CreateInduction(a->induction_class,
Aart Bikc071a012016-12-01 10:22:31 -0800477 a->operation,
Aart Bik0d345cf2016-03-16 10:49:38 -0700478 TransferMul(a->op_a, b),
479 TransferMul(a->op_b, b),
Aart Bikc071a012016-12-01 10:22:31 -0800480 a->fetch,
Aart Bik0d345cf2016-03-16 10:49:38 -0700481 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700482 }
483 }
484 return nullptr;
485}
486
Aart Bik0d345cf2016-03-16 10:49:38 -0700487HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
488 Primitive::Type from,
489 Primitive::Type to) {
490 if (a != nullptr) {
Aart Bikc071a012016-12-01 10:22:31 -0800491 // Allow narrowing conversion on linear induction in certain cases.
Aart Bik0d345cf2016-03-16 10:49:38 -0700492 if (IsNarrowingIntegralConversion(from, to)) {
493 if (a->induction_class == kLinear) {
494 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
Aart Bikc071a012016-12-01 10:22:31 -0800495 return CreateInduction(kLinear, kNop, a->op_a, a->op_b, /*fetch*/ nullptr, to);
Aart Bik0d345cf2016-03-16 10:49:38 -0700496 }
497 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700498 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700499 }
500 return nullptr;
501}
502
Aart Bikf475bee2015-09-16 12:50:25 -0700503HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
504 size_t input_index) {
505 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100506 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100507 DCHECK_LT(input_index, inputs.size());
508 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700509 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100510 for (size_t i = input_index + 1; i < inputs.size(); i++) {
511 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700512 if (itb == cycle_.end() ||
513 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700514 return nullptr;
515 }
516 }
Aart Bikf475bee2015-09-16 12:50:25 -0700517 return ita->second;
518 }
519 return nullptr;
520}
521
522HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
523 HLoopInformation* loop,
524 HInstruction* entry_phi,
525 HInstruction* phi) {
526 // Match all phi inputs.
527 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
528 if (match != nullptr) {
529 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700530 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700531
Aart Bikf475bee2015-09-16 12:50:25 -0700532 // Otherwise, try to solve for a periodic seeded from phi onward.
533 // Only tight multi-statement cycles are considered in order to
534 // simplify rotating the periodic during the final classification.
535 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
536 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700537 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700538 if (phi->InputAt(1) == entry_phi) {
539 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bikc071a012016-12-01 10:22:31 -0800540 return CreateInduction(kPeriodic, kNop, a, initial, /*fetch*/ nullptr, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700541 }
Aart Bikf475bee2015-09-16 12:50:25 -0700542 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
543 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bikc071a012016-12-01 10:22:31 -0800544 return CreateInduction(kPeriodic, kNop, a, b, /*fetch*/ nullptr, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700545 }
546 }
547 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700548 return nullptr;
549}
550
Aart Bike609b7c2015-08-27 13:46:58 -0700551HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700552 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700553 HInstruction* instruction,
554 HInstruction* x,
555 HInstruction* y,
556 InductionOp op,
557 bool is_first_call) {
558 // Solve within a cycle over an addition or subtraction: adding or subtracting an
Aart Bikc071a012016-12-01 10:22:31 -0800559 // invariant value, seeded from phi, keeps adding to the stride of the linear induction.
Aart Bike609b7c2015-08-27 13:46:58 -0700560 InductionInfo* b = LookupInfo(loop, y);
561 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700562 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700563 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700564 }
565 auto it = cycle_.find(x);
566 if (it != cycle_.end()) {
567 InductionInfo* a = it->second;
568 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700569 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700570 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700571 }
572 }
Aart Bike609b7c2015-08-27 13:46:58 -0700573
574 // Try some alternatives before failing.
575 if (op == kAdd) {
576 // Try the other way around for an addition if considered for first time.
577 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700578 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700579 }
580 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700581 // Solve within a tight cycle that is formed by exactly two instructions,
Aart Bikc071a012016-12-01 10:22:31 -0800582 // one phi and one update, for a periodic idiom of the form k = c - k.
Aart Bikf475bee2015-09-16 12:50:25 -0700583 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700584 InductionInfo* a = LookupInfo(loop, x);
585 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700586 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bikc071a012016-12-01 10:22:31 -0800587 return CreateInduction(kPeriodic,
588 kNop,
589 CreateInvariantOp(kSub, a, initial),
590 initial,
591 /*fetch*/ nullptr,
592 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700593 }
594 }
595 }
596
Aart Bik30efb4e2015-07-30 12:14:31 -0700597 return nullptr;
598}
599
Aart Bikc071a012016-12-01 10:22:31 -0800600HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveGeo(HLoopInformation* loop,
601 HInstruction* entry_phi,
602 HInstruction* instruction,
603 HInstruction* x,
604 HInstruction* y,
605 InductionOp op) {
606 // Solve within a tight cycle that is formed by exactly two instructions, one phi and
607 // one update, for a geometric induction of the form k = k * c.
608 if (x == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
609 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
610 InductionInfo* b = LookupInfo(loop, y);
611 if (b != nullptr && b->induction_class == kInvariant && b->operation == kFetch) {
612 return CreateInduction(kGeometric,
613 op,
614 initial,
615 CreateConstant(0, type_),
616 b->fetch,
617 type_);
618 }
619 }
620 return nullptr;
621}
622
Aart Bik7dc96932016-10-12 10:01:05 -0700623HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveXor(HLoopInformation* loop,
624 HInstruction* entry_phi,
625 HInstruction* instruction,
626 HInstruction* x,
Aart Bik639cc8c2016-10-18 13:03:31 -0700627 HInstruction* y) {
Aart Bikc071a012016-12-01 10:22:31 -0800628 // Solve within a tight cycle on periodic idiom of the form x = c ^ x or x = x ^ c.
Aart Bik639cc8c2016-10-18 13:03:31 -0700629 if (entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
630 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
631 InductionInfo* a = LookupInfo(loop, x);
632 if (a != nullptr && a->induction_class == kInvariant && entry_phi == y) {
Aart Bikc071a012016-12-01 10:22:31 -0800633 return CreateInduction(kPeriodic,
634 kNop,
635 CreateInvariantOp(kXor, a, initial),
636 initial,
637 /*fetch*/ nullptr,
638 type_);
Aart Bik639cc8c2016-10-18 13:03:31 -0700639 }
640 InductionInfo* b = LookupInfo(loop, y);
641 if (b != nullptr && b->induction_class == kInvariant && entry_phi == x) {
Aart Bikc071a012016-12-01 10:22:31 -0800642 return CreateInduction(kPeriodic,
643 kNop,
644 CreateInvariantOp(kXor, initial, b),
645 initial,
646 /*fetch*/ nullptr,
647 type_);
Aart Bik7dc96932016-10-12 10:01:05 -0700648 }
649 }
Aart Bik639cc8c2016-10-18 13:03:31 -0700650 return nullptr;
651}
652
653HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveTest(HLoopInformation* loop,
654 HInstruction* entry_phi,
655 HInstruction* instruction,
656 int64_t opposite_value) {
Aart Bikc071a012016-12-01 10:22:31 -0800657 // Detect hidden XOR construction in x = (x == false) or x = (x != true).
Aart Bik639cc8c2016-10-18 13:03:31 -0700658 int64_t value = -1;
659 HInstruction* x = instruction->InputAt(0);
660 HInstruction* y = instruction->InputAt(1);
661 if (IsExact(LookupInfo(loop, x), &value) && value == opposite_value) {
662 return SolveXor(loop, entry_phi, instruction, graph_->GetIntConstant(1), y);
663 } else if (IsExact(LookupInfo(loop, y), &value) && value == opposite_value) {
664 return SolveXor(loop, entry_phi, instruction, x, graph_->GetIntConstant(1));
Aart Bik7dc96932016-10-12 10:01:05 -0700665 }
666 return nullptr;
667}
668
Aart Bik0d345cf2016-03-16 10:49:38 -0700669HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
670 Primitive::Type from = conversion->GetInputType();
671 Primitive::Type to = conversion->GetResultType();
672 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
673 // narrowest encountered type is recorded with the induction to account for the precision loss.
674 if (IsNarrowingIntegralConversion(from, to)) {
675 auto it = cycle_.find(conversion->GetInput());
676 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
677 type_ = Narrowest(type_, to);
678 return it->second;
679 }
680 }
681 return nullptr;
682}
683
Aart Bikd14c5952015-09-08 15:25:15 -0700684void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
685 HInstruction* control = loop->GetHeader()->GetLastInstruction();
686 if (control->IsIf()) {
687 HIf* ifs = control->AsIf();
688 HBasicBlock* if_true = ifs->IfTrueSuccessor();
689 HBasicBlock* if_false = ifs->IfFalseSuccessor();
690 HInstruction* if_expr = ifs->InputAt(0);
691 // Determine if loop has following structure in header.
692 // loop-header: ....
693 // if (condition) goto X
694 if (if_expr->IsCondition()) {
695 HCondition* condition = if_expr->AsCondition();
696 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
697 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
698 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700699 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
700 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
701 if (a == nullptr || b == nullptr) {
702 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700703 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
704 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
705 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
706 VisitCondition(loop, a, b, type, condition->GetCondition());
707 }
708 }
709 }
710}
711
712void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
713 InductionInfo* a,
714 InductionInfo* b,
715 Primitive::Type type,
716 IfCondition cmp) {
717 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700718 // 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 -0700719 switch (cmp) {
720 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
721 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
722 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
723 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700724 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700725 default: break;
726 }
727 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700728 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700729 InductionInfo* lower_expr = a->op_b;
730 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800731 InductionInfo* stride_expr = a->op_a;
732 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700733 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800734 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700735 return;
736 }
Aart Bik358af832016-02-24 14:17:53 -0800737 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
738 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
739 // condition would be always taken).
740 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
741 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700742 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700743 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700744 // Only accept integral condition. A mismatch between the type of condition and the induction
745 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
746 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
747 return; // not integral
748 } else if (type != a->type &&
749 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
750 return; // mismatched type
751 }
Aart Bikf475bee2015-09-16 12:50:25 -0700752 // Normalize a linear loop control with a nonzero stride:
753 // stride > 0, either i < U or i <= U
754 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700755 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
756 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800757 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700758 }
Aart Bikd14c5952015-09-08 15:25:15 -0700759 }
760}
761
762void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700763 InductionInfo* lower_expr,
764 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800765 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700766 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700767 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700768 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700769 // Any loop of the general form:
770 //
771 // for (i = L; i <= U; i += S) // S > 0
772 // or for (i = L; i >= U; i += S) // S < 0
773 // .. i ..
774 //
775 // can be normalized into:
776 //
777 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
778 // .. L + S * n ..
779 //
Aart Bik9401f532015-09-28 16:25:56 -0700780 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700781 //
Aart Bik9401f532015-09-28 16:25:56 -0700782 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
783 // an unsigned entity, for example, as in the following loop that uses the full range:
784 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
785 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700786 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700787 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700788 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700789 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
790 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
791 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700792 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700793 // (4) For loops which early-exits, the TC forms an upper bound, as in:
794 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700795 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700796 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
797 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
798 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700799 if (!cancels) {
800 // Convert exclusive integral inequality into inclusive integral inequality,
801 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700802 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700803 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700804 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700805 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700806 }
807 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800808 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700809 }
Aart Bik97412c922016-02-19 20:14:38 -0800810 trip_count = CreateInvariantOp(
811 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700812 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700813 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700814 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700815 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700816 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700817 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700818 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700819 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700820 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700821 }
Aart Bik22f05872015-10-27 15:56:28 -0700822 InductionOp op = kNop;
823 switch (cmp) {
824 case kCondLT: op = kLT; break;
825 case kCondLE: op = kLE; break;
826 case kCondGT: op = kGT; break;
827 case kCondGE: op = kGE; break;
828 default: LOG(FATAL) << "CONDITION UNREACHABLE";
829 }
Aart Bik009cace2016-09-16 10:15:19 -0700830 // Associate trip count with control instruction, rather than the condition (even
831 // though it's its use) since former provides a convenient use-free placeholder.
832 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700833 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700834 DCHECK(control->IsIf());
835 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700836}
837
838bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
839 InductionInfo* upper_expr,
840 IfCondition cmp) {
841 int64_t lower_value;
842 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800843 switch (cmp) {
844 case kCondLT:
845 return IsAtMost(lower_expr, &lower_value)
846 && IsAtLeast(upper_expr, &upper_value)
847 && lower_value < upper_value;
848 case kCondLE:
849 return IsAtMost(lower_expr, &lower_value)
850 && IsAtLeast(upper_expr, &upper_value)
851 && lower_value <= upper_value;
852 case kCondGT:
853 return IsAtLeast(lower_expr, &lower_value)
854 && IsAtMost(upper_expr, &upper_value)
855 && lower_value > upper_value;
856 case kCondGE:
857 return IsAtLeast(lower_expr, &lower_value)
858 && IsAtMost(upper_expr, &upper_value)
859 && lower_value >= upper_value;
860 default:
861 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700862 }
863 return false; // not certain, may be untaken
864}
865
866bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
867 int64_t stride_value,
868 Primitive::Type type,
869 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700870 const int64_t min = Primitive::MinValueOfIntegralType(type);
871 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700872 // Some rules under which it is certain at compile-time that the loop is finite.
873 int64_t value;
874 switch (cmp) {
875 case kCondLT:
876 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800877 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700878 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800879 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700880 case kCondGT:
881 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800882 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700883 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800884 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700885 default:
886 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700887 }
888 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700889}
890
Aart Bik0d345cf2016-03-16 10:49:38 -0700891bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
892 InductionInfo* upper_expr,
893 int64_t stride_value,
894 Primitive::Type type,
895 IfCondition cmp) {
896 int64_t min = Primitive::MinValueOfIntegralType(type);
897 int64_t max = Primitive::MaxValueOfIntegralType(type);
898 // Inclusive test need one extra.
899 if (stride_value != 1 && stride_value != -1) {
900 return false; // non-unit stride
901 } else if (cmp == kCondLE) {
902 max--;
903 } else if (cmp == kCondGE) {
904 min++;
905 }
906 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000907 // Note: The `value` is initialized to please valgrind - the compiler can reorder
908 // the return value check with the `value` check, b/27651442 .
909 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700910 return IsAtLeast(lower_expr, &value) && value >= min &&
911 IsAtMost(lower_expr, &value) && value <= max &&
912 IsAtLeast(upper_expr, &value) && value >= min &&
913 IsAtMost(upper_expr, &value) && value <= max;
914}
915
Aart Bik30efb4e2015-07-30 12:14:31 -0700916void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
917 HInstruction* instruction,
918 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700919 auto it = induction_.find(loop);
920 if (it == induction_.end()) {
921 it = induction_.Put(loop,
922 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100923 std::less<HInstruction*>(),
924 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700925 }
926 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700927}
928
Aart Bike609b7c2015-08-27 13:46:58 -0700929HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
930 HInstruction* instruction) {
931 auto it = induction_.find(loop);
932 if (it != induction_.end()) {
933 auto loop_it = it->second.find(instruction);
934 if (loop_it != it->second.end()) {
935 return loop_it->second;
936 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700937 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800938 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700939 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700940 AssignInfo(loop, instruction, info);
941 return info;
942 }
943 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700944}
945
Aart Bikd14c5952015-09-08 15:25:15 -0700946HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
947 Primitive::Type type) {
Aart Bikc071a012016-12-01 10:22:31 -0800948 HInstruction* constant;
949 switch (type) {
950 case Primitive::kPrimDouble: constant = graph_->GetDoubleConstant(value); break;
951 case Primitive::kPrimFloat: constant = graph_->GetFloatConstant(value); break;
952 case Primitive::kPrimLong: constant = graph_->GetLongConstant(value); break;
953 default: constant = graph_->GetIntConstant(value); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700954 }
Aart Bikc071a012016-12-01 10:22:31 -0800955 return CreateInvariantFetch(constant);
Aart Bikd14c5952015-09-08 15:25:15 -0700956}
957
Aart Bik471a2032015-09-04 18:22:11 -0700958HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
959 InductionOp op,
960 InductionInfo* a,
961 InductionInfo* b) {
962 // Perform some light-weight simplifications during construction of a new invariant.
963 // This often safes memory and yields a more concise representation of the induction.
964 // More exhaustive simplifications are done by later phases once induction nodes are
965 // translated back into HIR code (e.g. by loop optimizations or BCE).
966 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800967 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700968 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700969 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
970 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700971 return b;
972 } else if (op == kMul) {
973 return a;
974 }
Aart Bikd14c5952015-09-08 15:25:15 -0700975 } else if (op == kMul) {
976 // Simplify 1 * b = b, -1 * b = -b
977 if (value == 1) {
978 return b;
979 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800980 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700981 }
Aart Bik471a2032015-09-04 18:22:11 -0700982 }
983 }
Aart Bik97412c922016-02-19 20:14:38 -0800984 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700985 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700986 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
987 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700988 return a;
989 } else if (op == kMul || op == kNeg) {
990 return b;
991 }
Aart Bikd14c5952015-09-08 15:25:15 -0700992 } else if (op == kMul || op == kDiv) {
993 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
994 if (value == 1) {
995 return a;
996 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800997 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700998 }
Aart Bik471a2032015-09-04 18:22:11 -0700999 }
1000 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -07001001 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
1002 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001003 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -07001004 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001005 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -07001006 } else if (op == kNeg) {
1007 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -07001008 }
Aart Bik7d57d7f2015-12-09 14:39:48 -08001009 } else if (b->operation == kSub) {
1010 // Simplify - (a - b) = b - a.
1011 if (op == kNeg) {
1012 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
1013 }
Aart Bik471a2032015-09-04 18:22:11 -07001014 }
Aart Bik0d345cf2016-03-16 10:49:38 -07001015 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -07001016}
1017
Aart Bikc071a012016-12-01 10:22:31 -08001018HInstruction* HInductionVarAnalysis::GetMultConstantForShift(HLoopInformation* loop,
1019 HInstruction* instruction) {
1020 // Obtain the constant needed to treat shift as equivalent multiplication. This yields an
1021 // existing instruction if the constants is already there. Otherwise, this has a side effect
1022 // on the HIR. The restriction on the shift factor avoids generating a negative constant
1023 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization for
1024 // shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
1025 InductionInfo* b = LookupInfo(loop, instruction->InputAt(1));
1026 int64_t value = -1;
1027 if (IsExact(b, &value)) {
1028 Primitive::Type type = instruction->InputAt(0)->GetType();
1029 if (type == Primitive::kPrimInt && 0 <= value && value < 31) {
1030 return graph_->GetIntConstant(1 << value);
1031 }
1032 if (type == Primitive::kPrimLong && 0 <= value && value < 63) {
1033 return graph_->GetLongConstant(1L << value);
1034 }
1035 }
1036 return nullptr;
1037}
Aart Bikcc42be02016-10-20 16:14:16 -07001038
1039void HInductionVarAnalysis::AssignCycle(HPhi* phi) {
1040 ArenaSet<HInstruction*>* set = &cycles_.Put(phi, ArenaSet<HInstruction*>(
1041 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)))->second;
1042 for (HInstruction* i : scc_) {
1043 set->insert(i);
1044 }
1045}
1046
1047ArenaSet<HInstruction*>* HInductionVarAnalysis::LookupCycle(HPhi* phi) {
1048 auto it = cycles_.find(phi);
1049 if (it != cycles_.end()) {
1050 return &it->second;
1051 }
1052 return nullptr;
1053}
1054
Aart Bik97412c922016-02-19 20:14:38 -08001055bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
1056 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
1057}
1058
1059bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
1060 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
1061}
1062
1063bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
1064 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -08001065}
1066
Aart Bik30efb4e2015-07-30 12:14:31 -07001067bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
1068 InductionInfo* info2) {
1069 // Test structural equality only, without accounting for simplifications.
1070 if (info1 != nullptr && info2 != nullptr) {
1071 return
1072 info1->induction_class == info2->induction_class &&
1073 info1->operation == info2->operation &&
1074 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -07001075 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -07001076 InductionEqual(info1->op_a, info2->op_a) &&
1077 InductionEqual(info1->op_b, info2->op_b);
1078 }
1079 // Otherwise only two nullptrs are considered equal.
1080 return info1 == info2;
1081}
1082
Aart Bikc071a012016-12-01 10:22:31 -08001083std::string HInductionVarAnalysis::FetchToString(HInstruction* fetch) {
1084 DCHECK(fetch != nullptr);
1085 if (fetch->IsIntConstant()) {
1086 return std::to_string(fetch->AsIntConstant()->GetValue());
1087 } else if (fetch->IsLongConstant()) {
1088 return std::to_string(fetch->AsLongConstant()->GetValue());
1089 }
1090 return std::to_string(fetch->GetId()) + ":" + fetch->DebugName();
1091}
1092
Aart Bik30efb4e2015-07-30 12:14:31 -07001093std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
1094 if (info != nullptr) {
1095 if (info->induction_class == kInvariant) {
1096 std::string inv = "(";
1097 inv += InductionToString(info->op_a);
1098 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -07001099 case kNop: inv += " @ "; break;
1100 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001101 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -07001102 case kNeg: inv += " - "; break;
1103 case kMul: inv += " * "; break;
1104 case kDiv: inv += " / "; break;
Aart Bik7dc96932016-10-12 10:01:05 -07001105 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -07001106 case kLT: inv += " < "; break;
1107 case kLE: inv += " <= "; break;
1108 case kGT: inv += " > "; break;
1109 case kGE: inv += " >= "; break;
Aart Bikc071a012016-12-01 10:22:31 -08001110 case kFetch: inv += FetchToString(info->fetch); break;
Aart Bik22f05872015-10-27 15:56:28 -07001111 case kTripCountInLoop: inv += " (TC-loop) "; break;
1112 case kTripCountInBody: inv += " (TC-body) "; break;
1113 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
1114 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001115 }
1116 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -07001117 inv += ")";
1118 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -07001119 } else {
Aart Bik30efb4e2015-07-30 12:14:31 -07001120 if (info->induction_class == kLinear) {
1121 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001122 InductionToString(info->op_b) + "):" +
1123 Primitive::PrettyDescriptor(info->type);
Aart Bikc071a012016-12-01 10:22:31 -08001124 } else if (info->induction_class == kPolynomial) {
1125 return "poly( sum_i(" + InductionToString(info->op_a) + ") + " +
1126 InductionToString(info->op_b) + "):" +
1127 Primitive::PrettyDescriptor(info->type);
1128 } else if (info->induction_class == kGeometric) {
1129 DCHECK(info->fetch != nullptr);
1130 if (info->operation == kNop) {
1131 return "geo(" + InductionToString(info->op_a) + " mod_i " +
1132 FetchToString(info->fetch) + " + " +
1133 InductionToString(info->op_b) + "):" +
1134 Primitive::PrettyDescriptor(info->type);
1135 } else {
1136 return "geo(" + InductionToString(info->op_a) + " * " +
1137 FetchToString(info->fetch) +
1138 (info->operation == kMul ? " ^ i + " : " ^ -i + ") +
1139 InductionToString(info->op_b) + "):" +
1140 Primitive::PrettyDescriptor(info->type);
1141 }
Aart Bik30efb4e2015-07-30 12:14:31 -07001142 } else if (info->induction_class == kWrapAround) {
1143 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001144 InductionToString(info->op_b) + "):" +
1145 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001146 } else if (info->induction_class == kPeriodic) {
1147 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001148 InductionToString(info->op_b) + "):" +
1149 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001150 }
1151 }
1152 }
1153 return "";
1154}
1155
1156} // namespace art