blob: a1e1cde9df3367ffaff1850466952ff842252838 [file] [log] [blame]
Aart Bik30efb4e2015-07-30 12:14:31 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "induction_var_analysis.h"
Aart Bik22af3be2015-09-10 12:50:58 -070018#include "induction_var_range.h"
Aart Bik30efb4e2015-07-30 12:14:31 -070019
20namespace art {
21
22/**
Aart Bik22af3be2015-09-10 12:50:58 -070023 * Since graph traversal may enter a SCC at any position, an initial representation may be rotated,
24 * along dependences, viz. any of (a, b, c, d), (d, a, b, c) (c, d, a, b), (b, c, d, a) assuming
25 * a chain of dependences (mutual independent items may occur in arbitrary order). For proper
26 * classification, the lexicographically first entry-phi is rotated to the front.
27 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
31 // Find very first entry-phi.
32 const HInstructionList& phis = loop->GetHeader()->GetPhis();
33 HInstruction* phi = nullptr;
34 size_t phi_pos = -1;
35 const size_t size = scc->size();
36 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010037 HInstruction* other = (*scc)[i];
Aart Bikf475bee2015-09-16 12:50:25 -070038 if (other->IsLoopHeaderPhi() && (phi == nullptr || phis.FoundBefore(other, phi))) {
39 phi = other;
Aart Bik22af3be2015-09-10 12:50:58 -070040 phi_pos = i;
41 }
42 }
43
44 // If found, bring that entry-phi to front.
45 if (phi != nullptr) {
46 new_scc->clear();
47 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010048 new_scc->push_back((*scc)[phi_pos]);
Aart Bik22af3be2015-09-10 12:50:58 -070049 if (++phi_pos >= size) phi_pos = 0;
50 }
51 DCHECK_EQ(size, new_scc->size());
52 scc->swap(*new_scc);
53 }
54}
55
Aart Bik30efb4e2015-07-30 12:14:31 -070056//
57// Class methods.
58//
59
60HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph)
61 : HOptimization(graph, kInductionPassName),
62 global_depth_(0),
Vladimir Marko5233f932015-09-29 19:01:15 +010063 stack_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
64 scc_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
65 map_(std::less<HInstruction*>(),
66 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
67 cycle_(std::less<HInstruction*>(),
68 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
69 induction_(std::less<HLoopInformation*>(),
70 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -070071}
72
73void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -080074 // Detects sequence variables (generalized induction variables) during an outer to inner
75 // traversal of all loops using Gerlek's algorithm. The order is important to enable
76 // range analysis on outer loop while visiting inner loops.
77 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -070078 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +000079 // Don't analyze irreducible loops.
80 // TODO(ajcbik): could/should we remove this restriction?
81 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -070082 VisitLoop(graph_block->GetLoopInformation());
83 }
84 }
85}
86
87void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
88 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
89 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
90 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -070091 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -070092 map_.clear();
93
94 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
95 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -070096 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -070097 if (loop_block->GetLoopInformation() != loop) {
98 continue; // Inner loops already visited.
99 }
100 // Visit phi-operations and instructions.
101 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
102 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700103 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700104 VisitNode(loop, instruction);
105 }
106 }
107 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
108 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700109 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700110 VisitNode(loop, instruction);
111 }
112 }
113 }
114
Aart Bike609b7c2015-08-27 13:46:58 -0700115 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700116 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700117
118 // Determine the loop's trip count.
119 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700120}
121
122void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700123 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700124 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700125 stack_.push_back(instruction);
126
127 // Visit all descendants.
128 uint32_t low = d1;
129 for (size_t i = 0, count = instruction->InputCount(); i < count; ++i) {
130 low = std::min(low, VisitDescendant(loop, instruction->InputAt(i)));
131 }
132
133 // Lower or found SCC?
134 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700135 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700136 } else {
137 scc_.clear();
138 cycle_.clear();
139
140 // Pop the stack to build the SCC for classification.
141 while (!stack_.empty()) {
142 HInstruction* x = stack_.back();
143 scc_.push_back(x);
144 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700145 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700146 if (x == instruction) {
147 break;
148 }
149 }
150
151 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700152 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700153 ClassifyTrivial(loop, scc_[0]);
154 } else {
155 ClassifyNonTrivial(loop);
156 }
157
158 scc_.clear();
159 cycle_.clear();
160 }
161}
162
163uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
164 // If the definition is either outside the loop (loop invariant entry value)
165 // or assigned in inner loop (inner exit value), the traversal stops.
166 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
167 if (otherLoop != loop) {
168 return global_depth_;
169 }
170
171 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700172 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700173 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700174 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700175 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700176 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700177 return it->second.done ? global_depth_ : it->second.depth;
178 }
179}
180
181void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
182 InductionInfo* info = nullptr;
183 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700184 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700185 } else if (instruction->IsAdd()) {
186 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
187 LookupInfo(loop, instruction->InputAt(1)), kAdd);
188 } else if (instruction->IsSub()) {
189 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
190 LookupInfo(loop, instruction->InputAt(1)), kSub);
191 } else if (instruction->IsMul()) {
192 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
193 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700194 } else if (instruction->IsShl()) {
195 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
196 LookupInfo(loop, instruction->InputAt(1)),
197 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700198 } else if (instruction->IsNeg()) {
199 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bike609b7c2015-08-27 13:46:58 -0700200 } else if (instruction->IsBoundsCheck()) {
201 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
202 } else if (instruction->IsTypeConversion()) {
203 HTypeConversion* conversion = instruction->AsTypeConversion();
204 // TODO: accept different conversion scenarios.
205 if (conversion->GetResultType() == conversion->GetInputType()) {
206 info = LookupInfo(loop, conversion->GetInput());
207 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700208 }
209
210 // Successfully classified?
211 if (info != nullptr) {
212 AssignInfo(loop, instruction, info);
213 }
214}
215
216void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
217 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700218 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700219
220 // Rotate proper entry-phi to front.
221 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100222 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700223 RotateEntryPhiFirst(loop, &scc_, &other);
224 }
225
Aart Bikf475bee2015-09-16 12:50:25 -0700226 // Analyze from entry-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700227 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700228 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700229 return;
230 }
Aart Bikf475bee2015-09-16 12:50:25 -0700231
232 // External link should be loop invariant.
233 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700234 if (initial == nullptr || initial->induction_class != kInvariant) {
235 return;
236 }
237
Aart Bikf475bee2015-09-16 12:50:25 -0700238 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700239 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700240 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700241 if (update != nullptr) {
Aart Bik471a2032015-09-04 18:22:11 -0700242 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update));
Aart Bik30efb4e2015-07-30 12:14:31 -0700243 }
244 return;
245 }
246
247 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700248 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700249 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700250 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700251 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700252 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700253 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700254 } else if (instruction->IsAdd()) {
255 update = SolveAddSub(
256 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
257 } else if (instruction->IsSub()) {
258 update = SolveAddSub(
259 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik30efb4e2015-07-30 12:14:31 -0700260 }
261 if (update == nullptr) {
262 return;
263 }
Aart Bike609b7c2015-08-27 13:46:58 -0700264 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700265 }
266
Aart Bikf475bee2015-09-16 12:50:25 -0700267 // Success if all internal links received the same temporary meaning.
268 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
269 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700270 switch (induction->induction_class) {
271 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700272 // Classify first phi and then the rest of the cycle "on-demand".
273 // Statements are scanned in order.
Aart Bik471a2032015-09-04 18:22:11 -0700274 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial));
Aart Bik22af3be2015-09-10 12:50:58 -0700275 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700276 ClassifyTrivial(loop, scc_[i]);
277 }
278 break;
279 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700280 // Classify all elements in the cycle with the found periodic induction while
281 // rotating each first element to the end. Lastly, phi is classified.
282 // Statements are scanned in reverse order.
283 for (size_t i = size - 1; i >= 1; i--) {
284 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700285 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
286 }
287 AssignInfo(loop, phi, induction);
288 break;
289 default:
290 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700291 }
292 }
293}
294
Aart Bike609b7c2015-08-27 13:46:58 -0700295HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
296 InductionInfo* induction,
297 InductionInfo* last) {
298 // Rotates a periodic induction of the form
299 // (a, b, c, d, e)
300 // into
301 // (b, c, d, e, a)
302 // in preparation of assigning this to the previous variable in the sequence.
303 if (induction->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700304 return CreateInduction(kPeriodic, induction, last);
Aart Bike609b7c2015-08-27 13:46:58 -0700305 }
Aart Bik471a2032015-09-04 18:22:11 -0700306 return CreateInduction(kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last));
Aart Bike609b7c2015-08-27 13:46:58 -0700307}
308
Aart Bikf475bee2015-09-16 12:50:25 -0700309HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
310 HInstruction* phi,
311 size_t input_index) {
312 // Match all phi inputs from input_index onwards exactly.
313 const size_t count = phi->InputCount();
314 DCHECK_LT(input_index, count);
315 InductionInfo* a = LookupInfo(loop, phi->InputAt(input_index));
316 for (size_t i = input_index + 1; i < count; i++) {
317 InductionInfo* b = LookupInfo(loop, phi->InputAt(i));
318 if (!InductionEqual(a, b)) {
319 return nullptr;
320 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700321 }
Aart Bikf475bee2015-09-16 12:50:25 -0700322 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700323}
324
325HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
326 InductionInfo* b,
327 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700328 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
329 // can be combined with an invariant to yield a similar result. Even two linear inputs can
330 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700331 if (a != nullptr && b != nullptr) {
332 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700333 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700334 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik471a2032015-09-04 18:22:11 -0700335 return CreateInduction(
Aart Bike609b7c2015-08-27 13:46:58 -0700336 kLinear, TransferAddSub(a->op_a, b->op_a, op), TransferAddSub(a->op_b, b->op_b, op));
337 } else if (a->induction_class == kInvariant) {
338 InductionInfo* new_a = b->op_a;
339 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
340 if (b->induction_class != kLinear) {
341 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
342 new_a = TransferAddSub(a, new_a, op);
343 } else if (op == kSub) { // Negation required.
344 new_a = TransferNeg(new_a);
345 }
Aart Bik471a2032015-09-04 18:22:11 -0700346 return CreateInduction(b->induction_class, new_a, new_b);
Aart Bike609b7c2015-08-27 13:46:58 -0700347 } else if (b->induction_class == kInvariant) {
348 InductionInfo* new_a = a->op_a;
349 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
350 if (a->induction_class != kLinear) {
351 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
352 new_a = TransferAddSub(new_a, b, op);
353 }
Aart Bik471a2032015-09-04 18:22:11 -0700354 return CreateInduction(a->induction_class, new_a, new_b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700355 }
356 }
357 return nullptr;
358}
359
360HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
361 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700362 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
363 // can be multiplied with an invariant to yield a similar but multiplied result.
364 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700365 if (a != nullptr && b != nullptr) {
366 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700367 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700368 } else if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700369 return CreateInduction(b->induction_class, TransferMul(a, b->op_a), TransferMul(a, b->op_b));
Aart Bike609b7c2015-08-27 13:46:58 -0700370 } else if (b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700371 return CreateInduction(a->induction_class, TransferMul(a->op_a, b), TransferMul(a->op_b, b));
Aart Bike609b7c2015-08-27 13:46:58 -0700372 }
373 }
374 return nullptr;
375}
376
377HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
378 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700379 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700380 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700381 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800382 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700383 // Obtain the constant needed for the multiplication. This yields an existing instruction
384 // if the constants is already there. Otherwise, this has a side effect on the HIR.
385 // The restriction on the shift factor avoids generating a negative constant
386 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
387 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700388 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
389 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
390 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700391 }
392 }
393 return nullptr;
394}
395
396HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700397 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
398 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700399 if (a != nullptr) {
400 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700401 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700402 }
Aart Bik471a2032015-09-04 18:22:11 -0700403 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b));
Aart Bik30efb4e2015-07-30 12:14:31 -0700404 }
405 return nullptr;
406}
407
Aart Bikf475bee2015-09-16 12:50:25 -0700408HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
409 size_t input_index) {
410 // Match all phi inputs from input_index onwards exactly.
411 const size_t count = phi->InputCount();
412 DCHECK_LT(input_index, count);
413 auto ita = cycle_.find(phi->InputAt(input_index));
Aart Bik30efb4e2015-07-30 12:14:31 -0700414 if (ita != cycle_.end()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700415 for (size_t i = input_index + 1; i < count; i++) {
416 auto itb = cycle_.find(phi->InputAt(i));
417 if (itb == cycle_.end() ||
418 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700419 return nullptr;
420 }
421 }
Aart Bikf475bee2015-09-16 12:50:25 -0700422 return ita->second;
423 }
424 return nullptr;
425}
426
427HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
428 HLoopInformation* loop,
429 HInstruction* entry_phi,
430 HInstruction* phi) {
431 // Match all phi inputs.
432 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
433 if (match != nullptr) {
434 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700435 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700436
Aart Bikf475bee2015-09-16 12:50:25 -0700437 // Otherwise, try to solve for a periodic seeded from phi onward.
438 // Only tight multi-statement cycles are considered in order to
439 // simplify rotating the periodic during the final classification.
440 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
441 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700442 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700443 if (phi->InputAt(1) == entry_phi) {
444 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik471a2032015-09-04 18:22:11 -0700445 return CreateInduction(kPeriodic, a, initial);
Aart Bike609b7c2015-08-27 13:46:58 -0700446 }
Aart Bikf475bee2015-09-16 12:50:25 -0700447 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
448 if (b != nullptr && b->induction_class == kPeriodic) {
449 return CreateInduction(kPeriodic, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700450 }
451 }
452 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700453 return nullptr;
454}
455
Aart Bike609b7c2015-08-27 13:46:58 -0700456HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700457 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700458 HInstruction* instruction,
459 HInstruction* x,
460 HInstruction* y,
461 InductionOp op,
462 bool is_first_call) {
463 // Solve within a cycle over an addition or subtraction: adding or subtracting an
464 // invariant value, seeded from phi, keeps adding to the stride of the induction.
465 InductionInfo* b = LookupInfo(loop, y);
466 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700467 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700468 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700469 }
470 auto it = cycle_.find(x);
471 if (it != cycle_.end()) {
472 InductionInfo* a = it->second;
473 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700474 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700475 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700476 }
477 }
Aart Bike609b7c2015-08-27 13:46:58 -0700478
479 // Try some alternatives before failing.
480 if (op == kAdd) {
481 // Try the other way around for an addition if considered for first time.
482 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700483 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700484 }
485 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700486 // Solve within a tight cycle that is formed by exactly two instructions,
487 // one phi and one update, for a periodic idiom of the form k = c - k;
488 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700489 InductionInfo* a = LookupInfo(loop, x);
490 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700491 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik471a2032015-09-04 18:22:11 -0700492 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial);
Aart Bike609b7c2015-08-27 13:46:58 -0700493 }
494 }
495 }
496
Aart Bik30efb4e2015-07-30 12:14:31 -0700497 return nullptr;
498}
499
Aart Bikd14c5952015-09-08 15:25:15 -0700500void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
501 HInstruction* control = loop->GetHeader()->GetLastInstruction();
502 if (control->IsIf()) {
503 HIf* ifs = control->AsIf();
504 HBasicBlock* if_true = ifs->IfTrueSuccessor();
505 HBasicBlock* if_false = ifs->IfFalseSuccessor();
506 HInstruction* if_expr = ifs->InputAt(0);
507 // Determine if loop has following structure in header.
508 // loop-header: ....
509 // if (condition) goto X
510 if (if_expr->IsCondition()) {
511 HCondition* condition = if_expr->AsCondition();
512 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
513 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
514 Primitive::Type type = condition->InputAt(0)->GetType();
515 // Determine if the loop control uses integral arithmetic and an if-exit (X outside) or an
516 // if-iterate (X inside), always expressed as if-iterate when passing into VisitCondition().
517 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
518 // Loop control is not 32/64-bit integral.
519 } else if (a == nullptr || b == nullptr) {
520 // Loop control is not a sequence.
521 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
522 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
523 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
524 VisitCondition(loop, a, b, type, condition->GetCondition());
525 }
526 }
527 }
528}
529
530void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
531 InductionInfo* a,
532 InductionInfo* b,
533 Primitive::Type type,
534 IfCondition cmp) {
535 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700536 // 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 -0700537 switch (cmp) {
538 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
539 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
540 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
541 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700542 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700543 default: break;
544 }
545 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700546 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700547 InductionInfo* lower_expr = a->op_b;
548 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800549 InductionInfo* stride_expr = a->op_a;
550 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700551 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800552 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700553 return;
554 }
Aart Bik9401f532015-09-28 16:25:56 -0700555 // Rewrite condition i != U into i < U or i > U if end condition is reached exactly.
556 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLT)) ||
557 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGT)))) {
558 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700559 }
Aart Bikf475bee2015-09-16 12:50:25 -0700560 // Normalize a linear loop control with a nonzero stride:
561 // stride > 0, either i < U or i <= U
562 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700563 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
564 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800565 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700566 }
Aart Bikd14c5952015-09-08 15:25:15 -0700567 }
568}
569
570void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700571 InductionInfo* lower_expr,
572 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800573 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700574 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700575 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700576 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700577 // Any loop of the general form:
578 //
579 // for (i = L; i <= U; i += S) // S > 0
580 // or for (i = L; i >= U; i += S) // S < 0
581 // .. i ..
582 //
583 // can be normalized into:
584 //
585 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
586 // .. L + S * n ..
587 //
Aart Bik9401f532015-09-28 16:25:56 -0700588 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700589 //
Aart Bik9401f532015-09-28 16:25:56 -0700590 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
591 // an unsigned entity, for example, as in the following loop that uses the full range:
592 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
593 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bik22f05872015-10-27 15:56:28 -0700594 // for (int i = 12; i < U; i++) // TC = 0 when U < 12
Aart Bik9401f532015-09-28 16:25:56 -0700595 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700596 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700597 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
598 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
599 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700600 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700601 // (4) For loops which early-exits, the TC forms an upper bound, as in:
602 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700603 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700604 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
605 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
606 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700607 if (!cancels) {
608 // Convert exclusive integral inequality into inclusive integral inequality,
609 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700610 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700611 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700612 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700613 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700614 }
615 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800616 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700617 }
Aart Bik97412c922016-02-19 20:14:38 -0800618 trip_count = CreateInvariantOp(
619 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700620 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700621 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700622 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700623 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700624 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700625 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700626 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700627 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700628 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700629 }
Aart Bik22f05872015-10-27 15:56:28 -0700630 InductionOp op = kNop;
631 switch (cmp) {
632 case kCondLT: op = kLT; break;
633 case kCondLE: op = kLE; break;
634 case kCondGT: op = kGT; break;
635 case kCondGE: op = kGE; break;
636 default: LOG(FATAL) << "CONDITION UNREACHABLE";
637 }
638 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
639 AssignInfo(loop,
640 loop->GetHeader()->GetLastInstruction(),
641 CreateTripCount(tcKind, trip_count, taken_test));
Aart Bik9401f532015-09-28 16:25:56 -0700642}
643
644bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
645 InductionInfo* upper_expr,
646 IfCondition cmp) {
647 int64_t lower_value;
648 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800649 switch (cmp) {
650 case kCondLT:
651 return IsAtMost(lower_expr, &lower_value)
652 && IsAtLeast(upper_expr, &upper_value)
653 && lower_value < upper_value;
654 case kCondLE:
655 return IsAtMost(lower_expr, &lower_value)
656 && IsAtLeast(upper_expr, &upper_value)
657 && lower_value <= upper_value;
658 case kCondGT:
659 return IsAtLeast(lower_expr, &lower_value)
660 && IsAtMost(upper_expr, &upper_value)
661 && lower_value > upper_value;
662 case kCondGE:
663 return IsAtLeast(lower_expr, &lower_value)
664 && IsAtMost(upper_expr, &upper_value)
665 && lower_value >= upper_value;
666 default:
667 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700668 }
669 return false; // not certain, may be untaken
670}
671
672bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
673 int64_t stride_value,
674 Primitive::Type type,
675 IfCondition cmp) {
Aart Bik97412c922016-02-19 20:14:38 -0800676 const int64_t min = type == Primitive::kPrimInt ? std::numeric_limits<int32_t>::min()
677 : std::numeric_limits<int64_t>::min();
678 const int64_t max = type == Primitive::kPrimInt ? std::numeric_limits<int32_t>::max()
679 : std::numeric_limits<int64_t>::max();
Aart Bik9401f532015-09-28 16:25:56 -0700680 // Some rules under which it is certain at compile-time that the loop is finite.
681 int64_t value;
682 switch (cmp) {
683 case kCondLT:
684 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800685 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700686 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800687 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700688 case kCondGT:
689 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800690 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700691 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800692 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700693 default:
694 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700695 }
696 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700697}
698
Aart Bik30efb4e2015-07-30 12:14:31 -0700699void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
700 HInstruction* instruction,
701 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700702 auto it = induction_.find(loop);
703 if (it == induction_.end()) {
704 it = induction_.Put(loop,
705 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100706 std::less<HInstruction*>(),
707 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700708 }
709 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700710}
711
Aart Bike609b7c2015-08-27 13:46:58 -0700712HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
713 HInstruction* instruction) {
714 auto it = induction_.find(loop);
715 if (it != induction_.end()) {
716 auto loop_it = it->second.find(instruction);
717 if (loop_it != it->second.end()) {
718 return loop_it->second;
719 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700720 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800721 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700722 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700723 AssignInfo(loop, instruction, info);
724 return info;
725 }
726 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700727}
728
Aart Bikd14c5952015-09-08 15:25:15 -0700729HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
730 Primitive::Type type) {
731 if (type == Primitive::kPrimInt) {
732 return CreateInvariantFetch(graph_->GetIntConstant(value));
733 }
734 DCHECK_EQ(type, Primitive::kPrimLong);
735 return CreateInvariantFetch(graph_->GetLongConstant(value));
736}
737
Aart Bik471a2032015-09-04 18:22:11 -0700738HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
739 InductionOp op,
740 InductionInfo* a,
741 InductionInfo* b) {
742 // Perform some light-weight simplifications during construction of a new invariant.
743 // This often safes memory and yields a more concise representation of the induction.
744 // More exhaustive simplifications are done by later phases once induction nodes are
745 // translated back into HIR code (e.g. by loop optimizations or BCE).
746 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800747 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700748 if (value == 0) {
749 // Simplify 0 + b = b, 0 * b = 0.
750 if (op == kAdd) {
751 return b;
752 } else if (op == kMul) {
753 return a;
754 }
Aart Bikd14c5952015-09-08 15:25:15 -0700755 } else if (op == kMul) {
756 // Simplify 1 * b = b, -1 * b = -b
757 if (value == 1) {
758 return b;
759 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800760 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700761 }
Aart Bik471a2032015-09-04 18:22:11 -0700762 }
763 }
Aart Bik97412c922016-02-19 20:14:38 -0800764 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700765 if (value == 0) {
Aart Bikd14c5952015-09-08 15:25:15 -0700766 // Simplify a + 0 = a, a - 0 = a, a * 0 = 0, -0 = 0.
Aart Bik471a2032015-09-04 18:22:11 -0700767 if (op == kAdd || op == kSub) {
768 return a;
769 } else if (op == kMul || op == kNeg) {
770 return b;
771 }
Aart Bikd14c5952015-09-08 15:25:15 -0700772 } else if (op == kMul || op == kDiv) {
773 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
774 if (value == 1) {
775 return a;
776 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800777 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700778 }
Aart Bik471a2032015-09-04 18:22:11 -0700779 }
780 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700781 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
782 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800783 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700784 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800785 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700786 } else if (op == kNeg) {
787 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700788 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800789 } else if (b->operation == kSub) {
790 // Simplify - (a - b) = b - a.
791 if (op == kNeg) {
792 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
793 }
Aart Bik471a2032015-09-04 18:22:11 -0700794 }
795 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr);
796}
797
Aart Bik97412c922016-02-19 20:14:38 -0800798bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
799 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
800}
801
802bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
803 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
804}
805
806bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
807 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800808}
809
Aart Bik30efb4e2015-07-30 12:14:31 -0700810bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
811 InductionInfo* info2) {
812 // Test structural equality only, without accounting for simplifications.
813 if (info1 != nullptr && info2 != nullptr) {
814 return
815 info1->induction_class == info2->induction_class &&
816 info1->operation == info2->operation &&
817 info1->fetch == info2->fetch &&
818 InductionEqual(info1->op_a, info2->op_a) &&
819 InductionEqual(info1->op_b, info2->op_b);
820 }
821 // Otherwise only two nullptrs are considered equal.
822 return info1 == info2;
823}
824
825std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
826 if (info != nullptr) {
827 if (info->induction_class == kInvariant) {
828 std::string inv = "(";
829 inv += InductionToString(info->op_a);
830 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -0700831 case kNop: inv += " @ "; break;
832 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700833 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -0700834 case kNeg: inv += " - "; break;
835 case kMul: inv += " * "; break;
836 case kDiv: inv += " / "; break;
837 case kLT: inv += " < "; break;
838 case kLE: inv += " <= "; break;
839 case kGT: inv += " > "; break;
840 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700841 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -0700842 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800843 if (info->fetch->IsIntConstant()) {
844 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
845 } else if (info->fetch->IsLongConstant()) {
846 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -0700847 } else {
848 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
849 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700850 break;
Aart Bik22f05872015-10-27 15:56:28 -0700851 case kTripCountInLoop: inv += " (TC-loop) "; break;
852 case kTripCountInBody: inv += " (TC-body) "; break;
853 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
854 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700855 }
856 inv += InductionToString(info->op_b);
857 return inv + ")";
858 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700859 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700860 if (info->induction_class == kLinear) {
861 return "(" + InductionToString(info->op_a) + " * i + " +
862 InductionToString(info->op_b) + ")";
863 } else if (info->induction_class == kWrapAround) {
864 return "wrap(" + InductionToString(info->op_a) + ", " +
865 InductionToString(info->op_b) + ")";
866 } else if (info->induction_class == kPeriodic) {
867 return "periodic(" + InductionToString(info->op_a) + ", " +
868 InductionToString(info->op_b) + ")";
869 }
870 }
871 }
872 return "";
873}
874
875} // namespace art