blob: 38937bf488db16b0bca6f75dbea64fd4c483738a [file] [log] [blame]
Aart Bik30efb4e2015-07-30 12:14:31 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "induction_var_analysis.h"
Aart Bik22af3be2015-09-10 12:50:58 -070018#include "induction_var_range.h"
Aart Bik30efb4e2015-07-30 12:14:31 -070019
20namespace art {
21
22/**
Aart Bik22af3be2015-09-10 12:50:58 -070023 * Since graph traversal may enter a SCC at any position, an initial representation may be rotated,
24 * along dependences, viz. any of (a, b, c, d), (d, a, b, c) (c, d, a, b), (b, c, d, a) assuming
25 * a chain of dependences (mutual independent items may occur in arbitrary order). For proper
26 * classification, the lexicographically first entry-phi is rotated to the front.
27 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
31 // Find very first entry-phi.
32 const HInstructionList& phis = loop->GetHeader()->GetPhis();
33 HInstruction* phi = nullptr;
34 size_t phi_pos = -1;
35 const size_t size = scc->size();
36 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010037 HInstruction* other = (*scc)[i];
Aart Bikf475bee2015-09-16 12:50:25 -070038 if (other->IsLoopHeaderPhi() && (phi == nullptr || phis.FoundBefore(other, phi))) {
39 phi = other;
Aart Bik22af3be2015-09-10 12:50:58 -070040 phi_pos = i;
41 }
42 }
43
44 // If found, bring that entry-phi to front.
45 if (phi != nullptr) {
46 new_scc->clear();
47 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010048 new_scc->push_back((*scc)[phi_pos]);
Aart Bik22af3be2015-09-10 12:50:58 -070049 if (++phi_pos >= size) phi_pos = 0;
50 }
51 DCHECK_EQ(size, new_scc->size());
52 scc->swap(*new_scc);
53 }
54}
55
Aart Bik0d345cf2016-03-16 10:49:38 -070056/**
57 * Returns true if the from/to types denote a narrowing, integral conversion (precision loss).
58 */
59static bool IsNarrowingIntegralConversion(Primitive::Type from, Primitive::Type to) {
60 switch (from) {
61 case Primitive::kPrimLong:
62 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
63 || to == Primitive::kPrimChar || to == Primitive::kPrimInt;
64 case Primitive::kPrimInt:
65 return to == Primitive::kPrimByte || to == Primitive::kPrimShort
66 || to == Primitive::kPrimChar;
67 case Primitive::kPrimChar:
68 case Primitive::kPrimShort:
69 return to == Primitive::kPrimByte;
70 default:
71 return false;
72 }
73}
74
75/**
76 * Returns narrowest data type.
77 */
78static Primitive::Type Narrowest(Primitive::Type type1, Primitive::Type type2) {
79 return Primitive::ComponentSize(type1) <= Primitive::ComponentSize(type2) ? type1 : type2;
80}
81
Aart Bik30efb4e2015-07-30 12:14:31 -070082//
83// Class methods.
84//
85
86HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph)
87 : HOptimization(graph, kInductionPassName),
88 global_depth_(0),
Vladimir Marko5233f932015-09-29 19:01:15 +010089 stack_(graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)),
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*>(),
97 graph->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -070098}
99
100void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800101 // Detects sequence variables (generalized induction variables) during an outer to inner
102 // traversal of all loops using Gerlek's algorithm. The order is important to enable
103 // range analysis on outer loop while visiting inner loops.
104 for (HReversePostOrderIterator it_graph(*graph_); !it_graph.Done(); it_graph.Advance()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700105 HBasicBlock* graph_block = it_graph.Current();
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000106 // Don't analyze irreducible loops.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000107 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700108 VisitLoop(graph_block->GetLoopInformation());
109 }
110 }
111}
112
113void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
114 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
115 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
116 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700117 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700118 map_.clear();
119
120 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
121 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700122 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700123 if (loop_block->GetLoopInformation() != loop) {
Aart Bik7dc96932016-10-12 10:01:05 -0700124 continue; // Inner loops visited later.
Aart Bik30efb4e2015-07-30 12:14:31 -0700125 }
126 // Visit phi-operations and instructions.
127 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
128 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700129 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700130 VisitNode(loop, instruction);
131 }
132 }
133 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
134 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700135 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700136 VisitNode(loop, instruction);
137 }
138 }
139 }
140
Aart Bike609b7c2015-08-27 13:46:58 -0700141 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700142 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700143
Aart Bik78296912016-03-25 13:14:53 -0700144 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700145 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700146}
147
148void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700149 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700150 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700151 stack_.push_back(instruction);
152
153 // Visit all descendants.
154 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100155 for (HInstruction* input : instruction->GetInputs()) {
156 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700157 }
158
159 // Lower or found SCC?
160 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700161 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700162 } else {
163 scc_.clear();
164 cycle_.clear();
165
166 // Pop the stack to build the SCC for classification.
167 while (!stack_.empty()) {
168 HInstruction* x = stack_.back();
169 scc_.push_back(x);
170 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700171 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700172 if (x == instruction) {
173 break;
174 }
175 }
176
Aart Bik0d345cf2016-03-16 10:49:38 -0700177 // Type of induction.
178 type_ = scc_[0]->GetType();
179
Aart Bik30efb4e2015-07-30 12:14:31 -0700180 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700181 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700182 ClassifyTrivial(loop, scc_[0]);
183 } else {
184 ClassifyNonTrivial(loop);
185 }
186
187 scc_.clear();
188 cycle_.clear();
189 }
190}
191
192uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
193 // If the definition is either outside the loop (loop invariant entry value)
194 // or assigned in inner loop (inner exit value), the traversal stops.
195 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
196 if (otherLoop != loop) {
197 return global_depth_;
198 }
199
200 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700201 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700202 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700203 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700204 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700205 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700206 return it->second.done ? global_depth_ : it->second.depth;
207 }
208}
209
210void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
211 InductionInfo* info = nullptr;
212 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700213 info = TransferPhi(loop, instruction, /* input_index */ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700214 } else if (instruction->IsAdd()) {
215 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
216 LookupInfo(loop, instruction->InputAt(1)), kAdd);
217 } else if (instruction->IsSub()) {
218 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
219 LookupInfo(loop, instruction->InputAt(1)), kSub);
220 } else if (instruction->IsMul()) {
221 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
222 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700223 } else if (instruction->IsShl()) {
224 info = TransferShl(LookupInfo(loop, instruction->InputAt(0)),
225 LookupInfo(loop, instruction->InputAt(1)),
226 instruction->InputAt(0)->GetType());
Aart Bik30efb4e2015-07-30 12:14:31 -0700227 } else if (instruction->IsNeg()) {
228 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik0d345cf2016-03-16 10:49:38 -0700229 } else if (instruction->IsTypeConversion()) {
230 info = TransferCnv(LookupInfo(loop, instruction->InputAt(0)),
231 instruction->AsTypeConversion()->GetInputType(),
232 instruction->AsTypeConversion()->GetResultType());
233
Aart Bike609b7c2015-08-27 13:46:58 -0700234 } else if (instruction->IsBoundsCheck()) {
235 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700236 }
237
238 // Successfully classified?
239 if (info != nullptr) {
240 AssignInfo(loop, instruction, info);
241 }
242}
243
244void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
245 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700246 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700247
248 // Rotate proper entry-phi to front.
249 if (size > 1) {
Vladimir Marko5233f932015-09-29 19:01:15 +0100250 ArenaVector<HInstruction*> other(graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700251 RotateEntryPhiFirst(loop, &scc_, &other);
252 }
253
Aart Bikf475bee2015-09-16 12:50:25 -0700254 // Analyze from entry-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700255 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700256 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700257 return;
258 }
Aart Bikf475bee2015-09-16 12:50:25 -0700259
260 // External link should be loop invariant.
261 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700262 if (initial == nullptr || initial->induction_class != kInvariant) {
263 return;
264 }
265
Aart Bikf475bee2015-09-16 12:50:25 -0700266 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700267 if (size == 1) {
Aart Bikf475bee2015-09-16 12:50:25 -0700268 InductionInfo* update = TransferPhi(loop, phi, /* input_index */ 1);
Aart Bik30efb4e2015-07-30 12:14:31 -0700269 if (update != nullptr) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700270 AssignInfo(loop, phi, CreateInduction(kWrapAround, initial, update, type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700271 }
272 return;
273 }
274
275 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700276 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700277 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700278 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700279 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700280 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700281 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700282 } else if (instruction->IsAdd()) {
283 update = SolveAddSub(
284 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
285 } else if (instruction->IsSub()) {
286 update = SolveAddSub(
287 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bik7dc96932016-10-12 10:01:05 -0700288 } else if (instruction->IsXor()) {
Aart Bik639cc8c2016-10-18 13:03:31 -0700289 update = SolveXor(loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1));
290 } else if (instruction->IsEqual()) {
291 update = SolveTest(loop, phi, instruction, 0);
292 } else if (instruction->IsNotEqual()) {
293 update = SolveTest(loop, phi, instruction, 1);
Aart Bik0d345cf2016-03-16 10:49:38 -0700294 } else if (instruction->IsTypeConversion()) {
295 update = SolveCnv(instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700296 }
297 if (update == nullptr) {
298 return;
299 }
Aart Bike609b7c2015-08-27 13:46:58 -0700300 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700301 }
302
Aart Bikf475bee2015-09-16 12:50:25 -0700303 // Success if all internal links received the same temporary meaning.
304 InductionInfo* induction = SolvePhi(phi, /* input_index */ 1);
305 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700306 switch (induction->induction_class) {
307 case kInvariant:
Aart Bik22af3be2015-09-10 12:50:58 -0700308 // Classify first phi and then the rest of the cycle "on-demand".
309 // Statements are scanned in order.
Aart Bik0d345cf2016-03-16 10:49:38 -0700310 AssignInfo(loop, phi, CreateInduction(kLinear, induction, initial, type_));
Aart Bik22af3be2015-09-10 12:50:58 -0700311 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700312 ClassifyTrivial(loop, scc_[i]);
313 }
314 break;
315 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700316 // Classify all elements in the cycle with the found periodic induction while
317 // rotating each first element to the end. Lastly, phi is classified.
318 // Statements are scanned in reverse order.
319 for (size_t i = size - 1; i >= 1; i--) {
320 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700321 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
322 }
323 AssignInfo(loop, phi, induction);
324 break;
325 default:
326 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700327 }
328 }
329}
330
Aart Bike609b7c2015-08-27 13:46:58 -0700331HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
332 InductionInfo* induction,
333 InductionInfo* last) {
334 // Rotates a periodic induction of the form
335 // (a, b, c, d, e)
336 // into
337 // (b, c, d, e, a)
338 // in preparation of assigning this to the previous variable in the sequence.
339 if (induction->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700340 return CreateInduction(kPeriodic, induction, last, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700341 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700342 return CreateInduction(
343 kPeriodic, induction->op_a, RotatePeriodicInduction(induction->op_b, last), type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700344}
345
Aart Bikf475bee2015-09-16 12:50:25 -0700346HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
347 HInstruction* phi,
348 size_t input_index) {
349 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100350 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100351 DCHECK_LT(input_index, inputs.size());
352 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
353 for (size_t i = input_index + 1; i < inputs.size(); i++) {
354 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700355 if (!InductionEqual(a, b)) {
356 return nullptr;
357 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700358 }
Aart Bikf475bee2015-09-16 12:50:25 -0700359 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700360}
361
362HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
363 InductionInfo* b,
364 InductionOp op) {
Aart Bike609b7c2015-08-27 13:46:58 -0700365 // Transfer over an addition or subtraction: any invariant, linear, wrap-around, or periodic
366 // can be combined with an invariant to yield a similar result. Even two linear inputs can
367 // be combined. All other combinations fail, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700368 if (a != nullptr && b != nullptr) {
369 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700370 return CreateInvariantOp(op, a, b);
Aart Bik30efb4e2015-07-30 12:14:31 -0700371 } else if (a->induction_class == kLinear && b->induction_class == kLinear) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700372 return CreateInduction(kLinear,
373 TransferAddSub(a->op_a, b->op_a, op),
374 TransferAddSub(a->op_b, b->op_b, op),
375 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700376 } else if (a->induction_class == kInvariant) {
377 InductionInfo* new_a = b->op_a;
378 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
379 if (b->induction_class != kLinear) {
380 DCHECK(b->induction_class == kWrapAround || b->induction_class == kPeriodic);
381 new_a = TransferAddSub(a, new_a, op);
382 } else if (op == kSub) { // Negation required.
383 new_a = TransferNeg(new_a);
384 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700385 return CreateInduction(b->induction_class, new_a, new_b, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700386 } else if (b->induction_class == kInvariant) {
387 InductionInfo* new_a = a->op_a;
388 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
389 if (a->induction_class != kLinear) {
390 DCHECK(a->induction_class == kWrapAround || a->induction_class == kPeriodic);
391 new_a = TransferAddSub(new_a, b, op);
392 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700393 return CreateInduction(a->induction_class, new_a, new_b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700394 }
395 }
396 return nullptr;
397}
398
399HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
400 InductionInfo* b) {
Aart Bike609b7c2015-08-27 13:46:58 -0700401 // Transfer over a multiplication: any invariant, linear, wrap-around, or periodic
402 // can be multiplied with an invariant to yield a similar but multiplied result.
403 // Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700404 if (a != nullptr && b != nullptr) {
405 if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700406 return CreateInvariantOp(kMul, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700407 } else if (a->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700408 return CreateInduction(b->induction_class,
409 TransferMul(a, b->op_a),
410 TransferMul(a, b->op_b),
411 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700412 } else if (b->induction_class == kInvariant) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700413 return CreateInduction(a->induction_class,
414 TransferMul(a->op_a, b),
415 TransferMul(a->op_b, b),
416 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700417 }
418 }
419 return nullptr;
420}
421
422HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferShl(InductionInfo* a,
423 InductionInfo* b,
Aart Bikd14c5952015-09-08 15:25:15 -0700424 Primitive::Type type) {
Aart Bike609b7c2015-08-27 13:46:58 -0700425 // Transfer over a shift left: treat shift by restricted constant as equivalent multiplication.
Aart Bik471a2032015-09-04 18:22:11 -0700426 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800427 if (a != nullptr && IsExact(b, &value)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700428 // Obtain the constant needed for the multiplication. This yields an existing instruction
429 // if the constants is already there. Otherwise, this has a side effect on the HIR.
430 // The restriction on the shift factor avoids generating a negative constant
431 // (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that generalization
432 // for shift factors outside [0,32) and [0,64) ranges is done by earlier simplification.
Aart Bikd14c5952015-09-08 15:25:15 -0700433 if ((type == Primitive::kPrimInt && 0 <= value && value < 31) ||
434 (type == Primitive::kPrimLong && 0 <= value && value < 63)) {
435 return TransferMul(a, CreateConstant(1 << value, type));
Aart Bik30efb4e2015-07-30 12:14:31 -0700436 }
437 }
438 return nullptr;
439}
440
441HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
Aart Bike609b7c2015-08-27 13:46:58 -0700442 // Transfer over a unary negation: an invariant, linear, wrap-around, or periodic input
443 // yields a similar but negated induction as result.
Aart Bik30efb4e2015-07-30 12:14:31 -0700444 if (a != nullptr) {
445 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700446 return CreateInvariantOp(kNeg, nullptr, a);
Aart Bik30efb4e2015-07-30 12:14:31 -0700447 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700448 return CreateInduction(a->induction_class, TransferNeg(a->op_a), TransferNeg(a->op_b), type_);
449 }
450 return nullptr;
451}
452
453HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferCnv(InductionInfo* a,
454 Primitive::Type from,
455 Primitive::Type to) {
456 if (a != nullptr) {
457 // Allow narrowing conversion in certain cases.
458 if (IsNarrowingIntegralConversion(from, to)) {
459 if (a->induction_class == kLinear) {
460 if (a->type == to || (a->type == from && IsNarrowingIntegralConversion(from, to))) {
461 return CreateInduction(kLinear, a->op_a, a->op_b, to);
462 }
463 }
464 // TODO: other cases useful too?
465 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700466 }
467 return nullptr;
468}
469
Aart Bikf475bee2015-09-16 12:50:25 -0700470HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
471 size_t input_index) {
472 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100473 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100474 DCHECK_LT(input_index, inputs.size());
475 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700476 if (ita != cycle_.end()) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100477 for (size_t i = input_index + 1; i < inputs.size(); i++) {
478 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700479 if (itb == cycle_.end() ||
480 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700481 return nullptr;
482 }
483 }
Aart Bikf475bee2015-09-16 12:50:25 -0700484 return ita->second;
485 }
486 return nullptr;
487}
488
489HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
490 HLoopInformation* loop,
491 HInstruction* entry_phi,
492 HInstruction* phi) {
493 // Match all phi inputs.
494 InductionInfo* match = SolvePhi(phi, /* input_index */ 0);
495 if (match != nullptr) {
496 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700497 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700498
Aart Bikf475bee2015-09-16 12:50:25 -0700499 // Otherwise, try to solve for a periodic seeded from phi onward.
500 // Only tight multi-statement cycles are considered in order to
501 // simplify rotating the periodic during the final classification.
502 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
503 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700504 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700505 if (phi->InputAt(1) == entry_phi) {
506 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700507 return CreateInduction(kPeriodic, a, initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700508 }
Aart Bikf475bee2015-09-16 12:50:25 -0700509 InductionInfo* b = SolvePhi(phi, /* input_index */ 1);
510 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700511 return CreateInduction(kPeriodic, a, b, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700512 }
513 }
514 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700515 return nullptr;
516}
517
Aart Bike609b7c2015-08-27 13:46:58 -0700518HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700519 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700520 HInstruction* instruction,
521 HInstruction* x,
522 HInstruction* y,
523 InductionOp op,
524 bool is_first_call) {
525 // Solve within a cycle over an addition or subtraction: adding or subtracting an
526 // invariant value, seeded from phi, keeps adding to the stride of the induction.
527 InductionInfo* b = LookupInfo(loop, y);
528 if (b != nullptr && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700529 if (x == entry_phi) {
Aart Bik471a2032015-09-04 18:22:11 -0700530 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700531 }
532 auto it = cycle_.find(x);
533 if (it != cycle_.end()) {
534 InductionInfo* a = it->second;
535 if (a->induction_class == kInvariant) {
Aart Bik471a2032015-09-04 18:22:11 -0700536 return CreateInvariantOp(op, a, b);
Aart Bike609b7c2015-08-27 13:46:58 -0700537 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700538 }
539 }
Aart Bike609b7c2015-08-27 13:46:58 -0700540
541 // Try some alternatives before failing.
542 if (op == kAdd) {
543 // Try the other way around for an addition if considered for first time.
544 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700545 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700546 }
547 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700548 // Solve within a tight cycle that is formed by exactly two instructions,
549 // one phi and one update, for a periodic idiom of the form k = c - k;
550 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700551 InductionInfo* a = LookupInfo(loop, x);
552 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700553 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik0d345cf2016-03-16 10:49:38 -0700554 return CreateInduction(kPeriodic, CreateInvariantOp(kSub, a, initial), initial, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700555 }
556 }
557 }
558
Aart Bik30efb4e2015-07-30 12:14:31 -0700559 return nullptr;
560}
561
Aart Bik7dc96932016-10-12 10:01:05 -0700562HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveXor(HLoopInformation* loop,
563 HInstruction* entry_phi,
564 HInstruction* instruction,
565 HInstruction* x,
Aart Bik639cc8c2016-10-18 13:03:31 -0700566 HInstruction* y) {
567 // Solve within a tight cycle on x = c ^ x or x = x ^ c.
568 if (entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
569 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
570 InductionInfo* a = LookupInfo(loop, x);
571 if (a != nullptr && a->induction_class == kInvariant && entry_phi == y) {
572 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, a, initial), initial, type_);
573 }
574 InductionInfo* b = LookupInfo(loop, y);
575 if (b != nullptr && b->induction_class == kInvariant && entry_phi == x) {
Aart Bik7dc96932016-10-12 10:01:05 -0700576 return CreateInduction(kPeriodic, CreateInvariantOp(kXor, initial, b), initial, type_);
577 }
578 }
Aart Bik639cc8c2016-10-18 13:03:31 -0700579 return nullptr;
580}
581
582HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveTest(HLoopInformation* loop,
583 HInstruction* entry_phi,
584 HInstruction* instruction,
585 int64_t opposite_value) {
586 // Detect hidden XOR construction in tight cycles on x = (x == 0) or x = (x != 1).
587 int64_t value = -1;
588 HInstruction* x = instruction->InputAt(0);
589 HInstruction* y = instruction->InputAt(1);
590 if (IsExact(LookupInfo(loop, x), &value) && value == opposite_value) {
591 return SolveXor(loop, entry_phi, instruction, graph_->GetIntConstant(1), y);
592 } else if (IsExact(LookupInfo(loop, y), &value) && value == opposite_value) {
593 return SolveXor(loop, entry_phi, instruction, x, graph_->GetIntConstant(1));
Aart Bik7dc96932016-10-12 10:01:05 -0700594 }
595 return nullptr;
596}
597
Aart Bik0d345cf2016-03-16 10:49:38 -0700598HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveCnv(HTypeConversion* conversion) {
599 Primitive::Type from = conversion->GetInputType();
600 Primitive::Type to = conversion->GetResultType();
601 // A narrowing conversion is allowed within the cycle of a linear induction, provided that the
602 // narrowest encountered type is recorded with the induction to account for the precision loss.
603 if (IsNarrowingIntegralConversion(from, to)) {
604 auto it = cycle_.find(conversion->GetInput());
605 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
606 type_ = Narrowest(type_, to);
607 return it->second;
608 }
609 }
610 return nullptr;
611}
612
Aart Bikd14c5952015-09-08 15:25:15 -0700613void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
614 HInstruction* control = loop->GetHeader()->GetLastInstruction();
615 if (control->IsIf()) {
616 HIf* ifs = control->AsIf();
617 HBasicBlock* if_true = ifs->IfTrueSuccessor();
618 HBasicBlock* if_false = ifs->IfFalseSuccessor();
619 HInstruction* if_expr = ifs->InputAt(0);
620 // Determine if loop has following structure in header.
621 // loop-header: ....
622 // if (condition) goto X
623 if (if_expr->IsCondition()) {
624 HCondition* condition = if_expr->AsCondition();
625 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
626 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
627 Primitive::Type type = condition->InputAt(0)->GetType();
Aart Bik0d345cf2016-03-16 10:49:38 -0700628 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
629 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
630 if (a == nullptr || b == nullptr) {
631 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700632 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
633 VisitCondition(loop, a, b, type, condition->GetOppositeCondition());
634 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
635 VisitCondition(loop, a, b, type, condition->GetCondition());
636 }
637 }
638 }
639}
640
641void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
642 InductionInfo* a,
643 InductionInfo* b,
644 Primitive::Type type,
645 IfCondition cmp) {
646 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700647 // 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 -0700648 switch (cmp) {
649 case kCondLT: VisitCondition(loop, b, a, type, kCondGT); break;
650 case kCondLE: VisitCondition(loop, b, a, type, kCondGE); break;
651 case kCondGT: VisitCondition(loop, b, a, type, kCondLT); break;
652 case kCondGE: VisitCondition(loop, b, a, type, kCondLE); break;
Aart Bikf475bee2015-09-16 12:50:25 -0700653 case kCondNE: VisitCondition(loop, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700654 default: break;
655 }
656 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700657 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700658 InductionInfo* lower_expr = a->op_b;
659 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800660 InductionInfo* stride_expr = a->op_a;
661 // Constant stride?
Aart Bik9401f532015-09-28 16:25:56 -0700662 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800663 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikf475bee2015-09-16 12:50:25 -0700664 return;
665 }
Aart Bik358af832016-02-24 14:17:53 -0800666 // Rewrite condition i != U into strict end condition i < U or i > U if this end condition
667 // is reached exactly (tested by verifying if the loop has a unit stride and the non-strict
668 // condition would be always taken).
669 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
670 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700671 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700672 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700673 // Only accept integral condition. A mismatch between the type of condition and the induction
674 // is only allowed if the, necessarily narrower, induction range fits the narrower control.
675 if (type != Primitive::kPrimInt && type != Primitive::kPrimLong) {
676 return; // not integral
677 } else if (type != a->type &&
678 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
679 return; // mismatched type
680 }
Aart Bikf475bee2015-09-16 12:50:25 -0700681 // Normalize a linear loop control with a nonzero stride:
682 // stride > 0, either i < U or i <= U
683 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700684 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
685 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800686 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700687 }
Aart Bikd14c5952015-09-08 15:25:15 -0700688 }
689}
690
691void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700692 InductionInfo* lower_expr,
693 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800694 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700695 int64_t stride_value,
Aart Bikd14c5952015-09-08 15:25:15 -0700696 Primitive::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700697 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700698 // Any loop of the general form:
699 //
700 // for (i = L; i <= U; i += S) // S > 0
701 // or for (i = L; i >= U; i += S) // S < 0
702 // .. i ..
703 //
704 // can be normalized into:
705 //
706 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
707 // .. L + S * n ..
708 //
Aart Bik9401f532015-09-28 16:25:56 -0700709 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700710 //
Aart Bik9401f532015-09-28 16:25:56 -0700711 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
712 // an unsigned entity, for example, as in the following loop that uses the full range:
713 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
714 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -0700715 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -0700716 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -0700717 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -0700718 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
719 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
720 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -0700721 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -0700722 // (4) For loops which early-exits, the TC forms an upper bound, as in:
723 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -0700724 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -0700725 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
726 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
727 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -0700728 if (!cancels) {
729 // Convert exclusive integral inequality into inclusive integral inequality,
730 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -0700731 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -0700732 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -0700733 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -0700734 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -0700735 }
736 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -0800737 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700738 }
Aart Bik97412c922016-02-19 20:14:38 -0800739 trip_count = CreateInvariantOp(
740 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -0700741 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -0700742 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -0700743 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -0700744 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700745 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -0700746 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -0700747 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -0700748 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -0700749 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -0700750 }
Aart Bik22f05872015-10-27 15:56:28 -0700751 InductionOp op = kNop;
752 switch (cmp) {
753 case kCondLT: op = kLT; break;
754 case kCondLE: op = kLE; break;
755 case kCondGT: op = kGT; break;
756 case kCondGE: op = kGE; break;
757 default: LOG(FATAL) << "CONDITION UNREACHABLE";
758 }
Aart Bik009cace2016-09-16 10:15:19 -0700759 // Associate trip count with control instruction, rather than the condition (even
760 // though it's its use) since former provides a convenient use-free placeholder.
761 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -0700762 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -0700763 DCHECK(control->IsIf());
764 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -0700765}
766
767bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
768 InductionInfo* upper_expr,
769 IfCondition cmp) {
770 int64_t lower_value;
771 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -0800772 switch (cmp) {
773 case kCondLT:
774 return IsAtMost(lower_expr, &lower_value)
775 && IsAtLeast(upper_expr, &upper_value)
776 && lower_value < upper_value;
777 case kCondLE:
778 return IsAtMost(lower_expr, &lower_value)
779 && IsAtLeast(upper_expr, &upper_value)
780 && lower_value <= upper_value;
781 case kCondGT:
782 return IsAtLeast(lower_expr, &lower_value)
783 && IsAtMost(upper_expr, &upper_value)
784 && lower_value > upper_value;
785 case kCondGE:
786 return IsAtLeast(lower_expr, &lower_value)
787 && IsAtMost(upper_expr, &upper_value)
788 && lower_value >= upper_value;
789 default:
790 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700791 }
792 return false; // not certain, may be untaken
793}
794
795bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
796 int64_t stride_value,
797 Primitive::Type type,
798 IfCondition cmp) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700799 const int64_t min = Primitive::MinValueOfIntegralType(type);
800 const int64_t max = Primitive::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -0700801 // Some rules under which it is certain at compile-time that the loop is finite.
802 int64_t value;
803 switch (cmp) {
804 case kCondLT:
805 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800806 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -0700807 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -0800808 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -0700809 case kCondGT:
810 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -0800811 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -0700812 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -0800813 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -0700814 default:
815 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -0700816 }
817 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -0700818}
819
Aart Bik0d345cf2016-03-16 10:49:38 -0700820bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
821 InductionInfo* upper_expr,
822 int64_t stride_value,
823 Primitive::Type type,
824 IfCondition cmp) {
825 int64_t min = Primitive::MinValueOfIntegralType(type);
826 int64_t max = Primitive::MaxValueOfIntegralType(type);
827 // Inclusive test need one extra.
828 if (stride_value != 1 && stride_value != -1) {
829 return false; // non-unit stride
830 } else if (cmp == kCondLE) {
831 max--;
832 } else if (cmp == kCondGE) {
833 min++;
834 }
835 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +0000836 // Note: The `value` is initialized to please valgrind - the compiler can reorder
837 // the return value check with the `value` check, b/27651442 .
838 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -0700839 return IsAtLeast(lower_expr, &value) && value >= min &&
840 IsAtMost(lower_expr, &value) && value <= max &&
841 IsAtLeast(upper_expr, &value) && value >= min &&
842 IsAtMost(upper_expr, &value) && value <= max;
843}
844
Aart Bik30efb4e2015-07-30 12:14:31 -0700845void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
846 HInstruction* instruction,
847 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -0700848 auto it = induction_.find(loop);
849 if (it == induction_.end()) {
850 it = induction_.Put(loop,
851 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +0100852 std::less<HInstruction*>(),
853 graph_->GetArena()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -0700854 }
855 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -0700856}
857
Aart Bike609b7c2015-08-27 13:46:58 -0700858HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
859 HInstruction* instruction) {
860 auto it = induction_.find(loop);
861 if (it != induction_.end()) {
862 auto loop_it = it->second.find(instruction);
863 if (loop_it != it->second.end()) {
864 return loop_it->second;
865 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700866 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -0800867 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -0700868 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700869 AssignInfo(loop, instruction, info);
870 return info;
871 }
872 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -0700873}
874
Aart Bikd14c5952015-09-08 15:25:15 -0700875HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
876 Primitive::Type type) {
877 if (type == Primitive::kPrimInt) {
878 return CreateInvariantFetch(graph_->GetIntConstant(value));
879 }
880 DCHECK_EQ(type, Primitive::kPrimLong);
881 return CreateInvariantFetch(graph_->GetLongConstant(value));
882}
883
Aart Bik471a2032015-09-04 18:22:11 -0700884HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
885 InductionOp op,
886 InductionInfo* a,
887 InductionInfo* b) {
888 // Perform some light-weight simplifications during construction of a new invariant.
889 // This often safes memory and yields a more concise representation of the induction.
890 // More exhaustive simplifications are done by later phases once induction nodes are
891 // translated back into HIR code (e.g. by loop optimizations or BCE).
892 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -0800893 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700894 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700895 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
896 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700897 return b;
898 } else if (op == kMul) {
899 return a;
900 }
Aart Bikd14c5952015-09-08 15:25:15 -0700901 } else if (op == kMul) {
902 // Simplify 1 * b = b, -1 * b = -b
903 if (value == 1) {
904 return b;
905 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800906 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -0700907 }
Aart Bik471a2032015-09-04 18:22:11 -0700908 }
909 }
Aart Bik97412c922016-02-19 20:14:38 -0800910 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -0700911 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -0700912 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
913 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -0700914 return a;
915 } else if (op == kMul || op == kNeg) {
916 return b;
917 }
Aart Bikd14c5952015-09-08 15:25:15 -0700918 } else if (op == kMul || op == kDiv) {
919 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
920 if (value == 1) {
921 return a;
922 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800923 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -0700924 }
Aart Bik471a2032015-09-04 18:22:11 -0700925 }
926 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -0700927 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
928 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800929 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700930 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800931 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -0700932 } else if (op == kNeg) {
933 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -0700934 }
Aart Bik7d57d7f2015-12-09 14:39:48 -0800935 } else if (b->operation == kSub) {
936 // Simplify - (a - b) = b - a.
937 if (op == kNeg) {
938 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
939 }
Aart Bik471a2032015-09-04 18:22:11 -0700940 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700941 return new (graph_->GetArena()) InductionInfo(kInvariant, op, a, b, nullptr, b->type);
Aart Bik471a2032015-09-04 18:22:11 -0700942}
943
Aart Bik97412c922016-02-19 20:14:38 -0800944bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
945 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
946}
947
948bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
949 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
950}
951
952bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
953 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800954}
955
Aart Bik30efb4e2015-07-30 12:14:31 -0700956bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
957 InductionInfo* info2) {
958 // Test structural equality only, without accounting for simplifications.
959 if (info1 != nullptr && info2 != nullptr) {
960 return
961 info1->induction_class == info2->induction_class &&
962 info1->operation == info2->operation &&
963 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -0700964 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -0700965 InductionEqual(info1->op_a, info2->op_a) &&
966 InductionEqual(info1->op_b, info2->op_b);
967 }
968 // Otherwise only two nullptrs are considered equal.
969 return info1 == info2;
970}
971
972std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
973 if (info != nullptr) {
974 if (info->induction_class == kInvariant) {
975 std::string inv = "(";
976 inv += InductionToString(info->op_a);
977 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -0700978 case kNop: inv += " @ "; break;
979 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700980 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -0700981 case kNeg: inv += " - "; break;
982 case kMul: inv += " * "; break;
983 case kDiv: inv += " / "; break;
Aart Bik7dc96932016-10-12 10:01:05 -0700984 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -0700985 case kLT: inv += " < "; break;
986 case kLE: inv += " <= "; break;
987 case kGT: inv += " > "; break;
988 case kGE: inv += " >= "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700989 case kFetch:
Aart Bike609b7c2015-08-27 13:46:58 -0700990 DCHECK(info->fetch);
Aart Bik7d57d7f2015-12-09 14:39:48 -0800991 if (info->fetch->IsIntConstant()) {
992 inv += std::to_string(info->fetch->AsIntConstant()->GetValue());
993 } else if (info->fetch->IsLongConstant()) {
994 inv += std::to_string(info->fetch->AsLongConstant()->GetValue());
Aart Bik471a2032015-09-04 18:22:11 -0700995 } else {
996 inv += std::to_string(info->fetch->GetId()) + ":" + info->fetch->DebugName();
997 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700998 break;
Aart Bik22f05872015-10-27 15:56:28 -0700999 case kTripCountInLoop: inv += " (TC-loop) "; break;
1000 case kTripCountInBody: inv += " (TC-body) "; break;
1001 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
1002 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001003 }
1004 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -07001005 inv += ")";
1006 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -07001007 } else {
Aart Bike609b7c2015-08-27 13:46:58 -07001008 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001009 if (info->induction_class == kLinear) {
1010 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001011 InductionToString(info->op_b) + "):" +
1012 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001013 } else if (info->induction_class == kWrapAround) {
1014 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001015 InductionToString(info->op_b) + "):" +
1016 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001017 } else if (info->induction_class == kPeriodic) {
1018 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001019 InductionToString(info->op_b) + "):" +
1020 Primitive::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001021 }
1022 }
1023 }
1024 return "";
1025}
1026
1027} // namespace art