blob: d270c6a28e23deb4626cecf63734de02514a9b88 [file] [log] [blame]
Aart Bik30efb4e2015-07-30 12:14:31 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "induction_var_analysis.h"
Aart Bik22af3be2015-09-10 12:50:58 -070018#include "induction_var_range.h"
Aart Bik30efb4e2015-07-30 12:14:31 -070019
20namespace art {
21
22/**
Aart Bik22af3be2015-09-10 12:50:58 -070023 * Since graph traversal may enter a SCC at any position, an initial representation may be rotated,
24 * along dependences, viz. any of (a, b, c, d), (d, a, b, c) (c, d, a, b), (b, c, d, a) assuming
25 * a chain of dependences (mutual independent items may occur in arbitrary order). For proper
Aart Bikcc42be02016-10-20 16:14:16 -070026 * classification, the lexicographically first loop-phi is rotated to the front.
Aart Bik22af3be2015-09-10 12:50:58 -070027 */
28static void RotateEntryPhiFirst(HLoopInformation* loop,
29 ArenaVector<HInstruction*>* scc,
30 ArenaVector<HInstruction*>* new_scc) {
Aart Bikcc42be02016-10-20 16:14:16 -070031 // Find very first loop-phi.
Aart Bik22af3be2015-09-10 12:50:58 -070032 const HInstructionList& phis = loop->GetHeader()->GetPhis();
33 HInstruction* phi = nullptr;
34 size_t phi_pos = -1;
35 const size_t size = scc->size();
36 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010037 HInstruction* other = (*scc)[i];
Aart Bikf475bee2015-09-16 12:50:25 -070038 if (other->IsLoopHeaderPhi() && (phi == nullptr || phis.FoundBefore(other, phi))) {
39 phi = other;
Aart Bik22af3be2015-09-10 12:50:58 -070040 phi_pos = i;
41 }
42 }
43
Aart Bikcc42be02016-10-20 16:14:16 -070044 // If found, bring that loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -070045 if (phi != nullptr) {
46 new_scc->clear();
47 for (size_t i = 0; i < size; i++) {
Vladimir Markoec7802a2015-10-01 20:57:57 +010048 new_scc->push_back((*scc)[phi_pos]);
Aart Bik22af3be2015-09-10 12:50:58 -070049 if (++phi_pos >= size) phi_pos = 0;
50 }
51 DCHECK_EQ(size, new_scc->size());
52 scc->swap(*new_scc);
53 }
54}
55
Aart Bik0d345cf2016-03-16 10:49:38 -070056/**
57 * Returns true if the from/to types denote a narrowing, integral conversion (precision loss).
58 */
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010059static bool IsNarrowingIntegralConversion(DataType::Type from, DataType::Type to) {
Aart Bik0d345cf2016-03-16 10:49:38 -070060 switch (from) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010061 case DataType::Type::kInt64:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010062 return to == DataType::Type::kUint8 ||
63 to == DataType::Type::kInt8 ||
64 to == DataType::Type::kUint16 ||
65 to == DataType::Type::kInt16 ||
66 to == DataType::Type::kInt32;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010067 case DataType::Type::kInt32:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010068 return to == DataType::Type::kUint8 ||
69 to == DataType::Type::kInt8 ||
70 to == DataType::Type::kUint16 ||
71 to == DataType::Type::kInt16;
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010072 case DataType::Type::kUint16:
73 case DataType::Type::kInt16:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010074 return to == DataType::Type::kUint8 || to == DataType::Type::kInt8;
Aart Bik0d345cf2016-03-16 10:49:38 -070075 default:
76 return false;
77 }
78}
79
80/**
Aart Bike6bd0272016-12-16 13:57:52 -080081 * Returns result of implicit widening type conversion done in HIR.
Aart Bik0d345cf2016-03-16 10:49:38 -070082 */
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010083static DataType::Type ImplicitConversion(DataType::Type type) {
Aart Bike6bd0272016-12-16 13:57:52 -080084 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010085 case DataType::Type::kBool:
Vladimir Markod5d2f2c2017-09-26 12:37:26 +010086 case DataType::Type::kUint8:
87 case DataType::Type::kInt8:
88 case DataType::Type::kUint16:
89 case DataType::Type::kInt16:
Vladimir Marko0ebe0d82017-09-21 22:50:39 +010090 return DataType::Type::kInt32;
Aart Bike6bd0272016-12-16 13:57:52 -080091 default:
92 return type;
93 }
Aart Bik0d345cf2016-03-16 10:49:38 -070094}
95
Aart Bikceb06932017-11-13 10:31:17 -080096/**
97 * Returns true if loop is guarded by "a cmp b" on entry.
98 */
99static bool IsGuardedBy(HLoopInformation* loop,
100 IfCondition cmp,
101 HInstruction* a,
102 HInstruction* b) {
103 // Chase back through straightline code to the first potential
104 // block that has a control dependence.
105 // guard: if (x) bypass
106 // |
107 // entry: straightline code
108 // |
109 // preheader
110 // |
111 // header
112 HBasicBlock* guard = loop->GetPreHeader();
113 HBasicBlock* entry = loop->GetHeader();
114 while (guard->GetPredecessors().size() == 1 &&
115 guard->GetSuccessors().size() == 1) {
116 entry = guard;
117 guard = guard->GetSinglePredecessor();
118 }
119 // Find guard.
120 HInstruction* control = guard->GetLastInstruction();
121 if (!control->IsIf()) {
122 return false;
123 }
124 HIf* ifs = control->AsIf();
125 HInstruction* if_expr = ifs->InputAt(0);
126 if (if_expr->IsCondition()) {
127 IfCondition other_cmp = ifs->IfTrueSuccessor() == entry
128 ? if_expr->AsCondition()->GetCondition()
129 : if_expr->AsCondition()->GetOppositeCondition();
130 if (if_expr->InputAt(0) == a && if_expr->InputAt(1) == b) {
131 return cmp == other_cmp;
132 } else if (if_expr->InputAt(1) == a && if_expr->InputAt(0) == b) {
133 switch (cmp) {
134 case kCondLT: return other_cmp == kCondGT;
135 case kCondLE: return other_cmp == kCondGE;
136 case kCondGT: return other_cmp == kCondLT;
137 case kCondGE: return other_cmp == kCondLE;
138 default: LOG(FATAL) << "unexpected cmp: " << cmp;
139 }
140 }
141 }
142 return false;
143}
144
145/* Finds first loop header phi use. */
146HInstruction* FindFirstLoopHeaderPhiUse(HLoopInformation* loop, HInstruction* instruction) {
147 for (const HUseListNode<HInstruction*>& use : instruction->GetUses()) {
148 if (use.GetUser()->GetBlock() == loop->GetHeader() &&
149 use.GetUser()->IsPhi() &&
150 use.GetUser()->InputAt(1) == instruction) {
151 return use.GetUser();
152 }
153 }
154 return nullptr;
155}
156
157/**
158 * Relinks the Phi structure after break-loop rewriting.
159 */
160bool FixOutsideUse(HLoopInformation* loop,
161 HInstruction* instruction,
162 HInstruction* replacement,
163 bool rewrite) {
164 // Deal with regular uses.
165 const HUseList<HInstruction*>& uses = instruction->GetUses();
166 for (auto it = uses.begin(), end = uses.end(); it != end; ) {
167 HInstruction* user = it->GetUser();
168 size_t index = it->GetIndex();
169 ++it; // increment prior to potential removal
170 if (user->GetBlock()->GetLoopInformation() != loop) {
171 if (replacement == nullptr) {
172 return false;
173 } else if (rewrite) {
174 user->ReplaceInput(replacement, index);
175 }
176 }
177 }
178 // Deal with environment uses.
179 const HUseList<HEnvironment*>& env_uses = instruction->GetEnvUses();
180 for (auto it = env_uses.begin(), end = env_uses.end(); it != end;) {
181 HEnvironment* user = it->GetUser();
182 size_t index = it->GetIndex();
183 ++it; // increment prior to potential removal
184 if (user->GetHolder()->GetBlock()->GetLoopInformation() != loop) {
185 if (replacement == nullptr) {
186 return false;
187 } else if (rewrite) {
188 user->RemoveAsUserOfInput(index);
189 user->SetRawEnvAt(index, replacement);
190 replacement->AddEnvUseAt(user, index);
191 }
192 }
193 }
194 return true;
195}
196
197/**
198 * Test and rewrite the loop body of a break-loop. Returns true on success.
199 */
200bool RewriteBreakLoopBody(HLoopInformation* loop,
201 HBasicBlock* body,
202 HInstruction* cond,
203 HInstruction* index,
204 HInstruction* upper,
205 bool rewrite) {
206 // Deal with Phis. Outside use prohibited, except for index (which gets exit value).
207 for (HInstructionIterator it(loop->GetHeader()->GetPhis()); !it.Done(); it.Advance()) {
208 HInstruction* exit_value = it.Current() == index ? upper : nullptr;
209 if (!FixOutsideUse(loop, it.Current(), exit_value, rewrite)) {
210 return false;
211 }
212 }
213 // Deal with other statements in header.
214 for (HInstruction* m = cond->GetPrevious(), *p = nullptr; m && !m->IsSuspendCheck(); m = p) {
215 p = m->GetPrevious();
216 if (rewrite) {
217 m->MoveBefore(body->GetFirstInstruction(), false);
218 }
219 if (!FixOutsideUse(loop, m, FindFirstLoopHeaderPhiUse(loop, m), rewrite)) {
220 return false;
221 }
222 }
223 return true;
224}
225
Aart Bik30efb4e2015-07-30 12:14:31 -0700226//
227// Class methods.
228//
229
Aart Bik2ca10eb2017-11-15 15:17:53 -0800230HInductionVarAnalysis::HInductionVarAnalysis(HGraph* graph, const char* name)
231 : HOptimization(graph, name),
Aart Bik30efb4e2015-07-30 12:14:31 -0700232 global_depth_(0),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100233 stack_(graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko5233f932015-09-29 19:01:15 +0100234 map_(std::less<HInstruction*>(),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100235 graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)),
236 scc_(graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko5233f932015-09-29 19:01:15 +0100237 cycle_(std::less<HInstruction*>(),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100238 graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)),
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100239 type_(DataType::Type::kVoid),
Vladimir Marko5233f932015-09-29 19:01:15 +0100240 induction_(std::less<HLoopInformation*>(),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100241 graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)),
Aart Bikcc42be02016-10-20 16:14:16 -0700242 cycles_(std::less<HPhi*>(),
Vladimir Markoca6fff82017-10-03 14:49:14 +0100243 graph->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700244}
245
246void HInductionVarAnalysis::Run() {
Aart Bik7d57d7f2015-12-09 14:39:48 -0800247 // Detects sequence variables (generalized induction variables) during an outer to inner
248 // traversal of all loops using Gerlek's algorithm. The order is important to enable
249 // range analysis on outer loop while visiting inner loops.
Vladimir Marko2c45bc92016-10-25 16:54:12 +0100250 for (HBasicBlock* graph_block : graph_->GetReversePostOrder()) {
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000251 // Don't analyze irreducible loops.
Nicolas Geoffray15bd2282016-01-05 15:55:41 +0000252 if (graph_block->IsLoopHeader() && !graph_block->GetLoopInformation()->IsIrreducible()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700253 VisitLoop(graph_block->GetLoopInformation());
254 }
255 }
256}
257
258void HInductionVarAnalysis::VisitLoop(HLoopInformation* loop) {
259 // Find strongly connected components (SSCs) in the SSA graph of this loop using Tarjan's
260 // algorithm. Due to the descendant-first nature, classification happens "on-demand".
261 global_depth_ = 0;
Aart Bike609b7c2015-08-27 13:46:58 -0700262 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700263 map_.clear();
264
265 for (HBlocksInLoopIterator it_loop(*loop); !it_loop.Done(); it_loop.Advance()) {
266 HBasicBlock* loop_block = it_loop.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700267 DCHECK(loop_block->IsInLoop());
Aart Bik30efb4e2015-07-30 12:14:31 -0700268 if (loop_block->GetLoopInformation() != loop) {
Aart Bik7dc96932016-10-12 10:01:05 -0700269 continue; // Inner loops visited later.
Aart Bik30efb4e2015-07-30 12:14:31 -0700270 }
271 // Visit phi-operations and instructions.
272 for (HInstructionIterator it(loop_block->GetPhis()); !it.Done(); it.Advance()) {
273 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700274 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700275 VisitNode(loop, instruction);
276 }
277 }
278 for (HInstructionIterator it(loop_block->GetInstructions()); !it.Done(); it.Advance()) {
279 HInstruction* instruction = it.Current();
Aart Bike609b7c2015-08-27 13:46:58 -0700280 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700281 VisitNode(loop, instruction);
282 }
283 }
284 }
285
Aart Bike609b7c2015-08-27 13:46:58 -0700286 DCHECK(stack_.empty());
Aart Bik30efb4e2015-07-30 12:14:31 -0700287 map_.clear();
Aart Bikd14c5952015-09-08 15:25:15 -0700288
Aart Bik78296912016-03-25 13:14:53 -0700289 // Determine the loop's trip-count.
Aart Bikd14c5952015-09-08 15:25:15 -0700290 VisitControl(loop);
Aart Bik30efb4e2015-07-30 12:14:31 -0700291}
292
293void HInductionVarAnalysis::VisitNode(HLoopInformation* loop, HInstruction* instruction) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700294 const uint32_t d1 = ++global_depth_;
Aart Bike609b7c2015-08-27 13:46:58 -0700295 map_.Put(instruction, NodeInfo(d1));
Aart Bik30efb4e2015-07-30 12:14:31 -0700296 stack_.push_back(instruction);
297
298 // Visit all descendants.
299 uint32_t low = d1;
Vladimir Marko372f10e2016-05-17 16:30:10 +0100300 for (HInstruction* input : instruction->GetInputs()) {
301 low = std::min(low, VisitDescendant(loop, input));
Aart Bik30efb4e2015-07-30 12:14:31 -0700302 }
303
304 // Lower or found SCC?
305 if (low < d1) {
Aart Bike609b7c2015-08-27 13:46:58 -0700306 map_.find(instruction)->second.depth = low;
Aart Bik30efb4e2015-07-30 12:14:31 -0700307 } else {
308 scc_.clear();
309 cycle_.clear();
310
311 // Pop the stack to build the SCC for classification.
312 while (!stack_.empty()) {
313 HInstruction* x = stack_.back();
314 scc_.push_back(x);
315 stack_.pop_back();
Aart Bike609b7c2015-08-27 13:46:58 -0700316 map_.find(x)->second.done = true;
Aart Bik30efb4e2015-07-30 12:14:31 -0700317 if (x == instruction) {
318 break;
319 }
320 }
321
Aart Bik0d345cf2016-03-16 10:49:38 -0700322 // Type of induction.
323 type_ = scc_[0]->GetType();
324
Aart Bik30efb4e2015-07-30 12:14:31 -0700325 // Classify the SCC.
Aart Bikf475bee2015-09-16 12:50:25 -0700326 if (scc_.size() == 1 && !scc_[0]->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700327 ClassifyTrivial(loop, scc_[0]);
328 } else {
329 ClassifyNonTrivial(loop);
330 }
331
332 scc_.clear();
333 cycle_.clear();
334 }
335}
336
337uint32_t HInductionVarAnalysis::VisitDescendant(HLoopInformation* loop, HInstruction* instruction) {
338 // If the definition is either outside the loop (loop invariant entry value)
339 // or assigned in inner loop (inner exit value), the traversal stops.
340 HLoopInformation* otherLoop = instruction->GetBlock()->GetLoopInformation();
341 if (otherLoop != loop) {
342 return global_depth_;
343 }
344
345 // Inspect descendant node.
Aart Bike609b7c2015-08-27 13:46:58 -0700346 if (!IsVisitedNode(instruction)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700347 VisitNode(loop, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700348 return map_.find(instruction)->second.depth;
Aart Bik30efb4e2015-07-30 12:14:31 -0700349 } else {
Aart Bike609b7c2015-08-27 13:46:58 -0700350 auto it = map_.find(instruction);
Aart Bik30efb4e2015-07-30 12:14:31 -0700351 return it->second.done ? global_depth_ : it->second.depth;
352 }
353}
354
355void HInductionVarAnalysis::ClassifyTrivial(HLoopInformation* loop, HInstruction* instruction) {
356 InductionInfo* info = nullptr;
357 if (instruction->IsPhi()) {
Aart Bikd0a022d2016-12-13 11:22:31 -0800358 info = TransferPhi(loop, instruction, /*input_index*/ 0, /*adjust_input_size*/ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700359 } else if (instruction->IsAdd()) {
360 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
361 LookupInfo(loop, instruction->InputAt(1)), kAdd);
362 } else if (instruction->IsSub()) {
363 info = TransferAddSub(LookupInfo(loop, instruction->InputAt(0)),
364 LookupInfo(loop, instruction->InputAt(1)), kSub);
Aart Bikc071a012016-12-01 10:22:31 -0800365 } else if (instruction->IsNeg()) {
366 info = TransferNeg(LookupInfo(loop, instruction->InputAt(0)));
Aart Bik30efb4e2015-07-30 12:14:31 -0700367 } else if (instruction->IsMul()) {
368 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
369 LookupInfo(loop, instruction->InputAt(1)));
Aart Bike609b7c2015-08-27 13:46:58 -0700370 } else if (instruction->IsShl()) {
Aart Bikd0a022d2016-12-13 11:22:31 -0800371 HInstruction* mulc = GetShiftConstant(loop, instruction, /*initial*/ nullptr);
Aart Bikc071a012016-12-01 10:22:31 -0800372 if (mulc != nullptr) {
373 info = TransferMul(LookupInfo(loop, instruction->InputAt(0)),
374 LookupInfo(loop, mulc));
375 }
Aart Bikd0a022d2016-12-13 11:22:31 -0800376 } else if (instruction->IsSelect()) {
377 info = TransferPhi(loop, instruction, /*input_index*/ 0, /*adjust_input_size*/ 1);
Aart Bik0d345cf2016-03-16 10:49:38 -0700378 } else if (instruction->IsTypeConversion()) {
Aart Bike6bd0272016-12-16 13:57:52 -0800379 info = TransferConversion(LookupInfo(loop, instruction->InputAt(0)),
380 instruction->AsTypeConversion()->GetInputType(),
381 instruction->AsTypeConversion()->GetResultType());
Aart Bike609b7c2015-08-27 13:46:58 -0700382 } else if (instruction->IsBoundsCheck()) {
383 info = LookupInfo(loop, instruction->InputAt(0)); // Pass-through.
Aart Bik30efb4e2015-07-30 12:14:31 -0700384 }
385
386 // Successfully classified?
387 if (info != nullptr) {
388 AssignInfo(loop, instruction, info);
389 }
390}
391
392void HInductionVarAnalysis::ClassifyNonTrivial(HLoopInformation* loop) {
393 const size_t size = scc_.size();
Aart Bike609b7c2015-08-27 13:46:58 -0700394 DCHECK_GE(size, 1u);
Aart Bik22af3be2015-09-10 12:50:58 -0700395
Aart Bikcc42be02016-10-20 16:14:16 -0700396 // Rotate proper loop-phi to front.
Aart Bik22af3be2015-09-10 12:50:58 -0700397 if (size > 1) {
Vladimir Markoca6fff82017-10-03 14:49:14 +0100398 ArenaVector<HInstruction*> other(
399 graph_->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis));
Aart Bik22af3be2015-09-10 12:50:58 -0700400 RotateEntryPhiFirst(loop, &scc_, &other);
401 }
402
Aart Bikcc42be02016-10-20 16:14:16 -0700403 // Analyze from loop-phi onwards.
Aart Bik22af3be2015-09-10 12:50:58 -0700404 HInstruction* phi = scc_[0];
Aart Bikf475bee2015-09-16 12:50:25 -0700405 if (!phi->IsLoopHeaderPhi()) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700406 return;
407 }
Aart Bikf475bee2015-09-16 12:50:25 -0700408
409 // External link should be loop invariant.
410 InductionInfo* initial = LookupInfo(loop, phi->InputAt(0));
Aart Bik30efb4e2015-07-30 12:14:31 -0700411 if (initial == nullptr || initial->induction_class != kInvariant) {
412 return;
413 }
414
Aart Bike6bd0272016-12-16 13:57:52 -0800415 // Store interesting cycle in each loop phi.
416 for (size_t i = 0; i < size; i++) {
417 if (scc_[i]->IsLoopHeaderPhi()) {
418 AssignCycle(scc_[i]->AsPhi());
419 }
420 }
Aart Bikcc42be02016-10-20 16:14:16 -0700421
Aart Bikf475bee2015-09-16 12:50:25 -0700422 // Singleton is wrap-around induction if all internal links have the same meaning.
Aart Bik30efb4e2015-07-30 12:14:31 -0700423 if (size == 1) {
Aart Bikd0a022d2016-12-13 11:22:31 -0800424 InductionInfo* update = TransferPhi(loop, phi, /*input_index*/ 1, /*adjust_input_size*/ 0);
Aart Bik30efb4e2015-07-30 12:14:31 -0700425 if (update != nullptr) {
Aart Bikc071a012016-12-01 10:22:31 -0800426 AssignInfo(loop, phi, CreateInduction(kWrapAround,
427 kNop,
428 initial,
429 update,
430 /*fetch*/ nullptr,
431 type_));
Aart Bik30efb4e2015-07-30 12:14:31 -0700432 }
433 return;
434 }
435
436 // Inspect remainder of the cycle that resides in scc_. The cycle_ mapping assigns
Aart Bike609b7c2015-08-27 13:46:58 -0700437 // temporary meaning to its nodes, seeded from the phi instruction and back.
Aart Bik22af3be2015-09-10 12:50:58 -0700438 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700439 HInstruction* instruction = scc_[i];
Aart Bik30efb4e2015-07-30 12:14:31 -0700440 InductionInfo* update = nullptr;
Aart Bike609b7c2015-08-27 13:46:58 -0700441 if (instruction->IsPhi()) {
Aart Bikf475bee2015-09-16 12:50:25 -0700442 update = SolvePhiAllInputs(loop, phi, instruction);
Aart Bike609b7c2015-08-27 13:46:58 -0700443 } else if (instruction->IsAdd()) {
444 update = SolveAddSub(
445 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kAdd, true);
446 } else if (instruction->IsSub()) {
447 update = SolveAddSub(
448 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kSub, true);
Aart Bikc071a012016-12-01 10:22:31 -0800449 } else if (instruction->IsMul()) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800450 update = SolveOp(
Aart Bikc071a012016-12-01 10:22:31 -0800451 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kMul);
452 } else if (instruction->IsDiv()) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800453 update = SolveOp(
Aart Bikc071a012016-12-01 10:22:31 -0800454 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kDiv);
455 } else if (instruction->IsRem()) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800456 update = SolveOp(
457 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kRem);
Aart Bikc071a012016-12-01 10:22:31 -0800458 } else if (instruction->IsShl()) {
Aart Bikd0a022d2016-12-13 11:22:31 -0800459 HInstruction* mulc = GetShiftConstant(loop, instruction, /*initial*/ nullptr);
Aart Bikc071a012016-12-01 10:22:31 -0800460 if (mulc != nullptr) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800461 update = SolveOp(loop, phi, instruction, instruction->InputAt(0), mulc, kMul);
Aart Bikc071a012016-12-01 10:22:31 -0800462 }
Aart Bikd0a022d2016-12-13 11:22:31 -0800463 } else if (instruction->IsShr() || instruction->IsUShr()) {
464 HInstruction* divc = GetShiftConstant(loop, instruction, initial);
465 if (divc != nullptr) {
466 update = SolveOp(loop, phi, instruction, instruction->InputAt(0), divc, kDiv);
467 }
Aart Bik7dc96932016-10-12 10:01:05 -0700468 } else if (instruction->IsXor()) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800469 update = SolveOp(
470 loop, phi, instruction, instruction->InputAt(0), instruction->InputAt(1), kXor);
Aart Bik639cc8c2016-10-18 13:03:31 -0700471 } else if (instruction->IsEqual()) {
472 update = SolveTest(loop, phi, instruction, 0);
473 } else if (instruction->IsNotEqual()) {
474 update = SolveTest(loop, phi, instruction, 1);
Aart Bikd0a022d2016-12-13 11:22:31 -0800475 } else if (instruction->IsSelect()) {
476 update = SolvePhi(instruction, /*input_index*/ 0, /*adjust_input_size*/ 1); // acts like Phi
Aart Bik0d345cf2016-03-16 10:49:38 -0700477 } else if (instruction->IsTypeConversion()) {
Aart Bike6bd0272016-12-16 13:57:52 -0800478 update = SolveConversion(loop, phi, instruction->AsTypeConversion());
Aart Bik30efb4e2015-07-30 12:14:31 -0700479 }
480 if (update == nullptr) {
481 return;
482 }
Aart Bike609b7c2015-08-27 13:46:58 -0700483 cycle_.Put(instruction, update);
Aart Bik30efb4e2015-07-30 12:14:31 -0700484 }
485
Aart Bikf475bee2015-09-16 12:50:25 -0700486 // Success if all internal links received the same temporary meaning.
Aart Bikd0a022d2016-12-13 11:22:31 -0800487 InductionInfo* induction = SolvePhi(phi, /*input_index*/ 1, /*adjust_input_size*/ 0);
Aart Bikf475bee2015-09-16 12:50:25 -0700488 if (induction != nullptr) {
Aart Bike609b7c2015-08-27 13:46:58 -0700489 switch (induction->induction_class) {
490 case kInvariant:
Aart Bikc071a012016-12-01 10:22:31 -0800491 // Construct combined stride of the linear induction.
492 induction = CreateInduction(kLinear, kNop, induction, initial, /*fetch*/ nullptr, type_);
493 FALLTHROUGH_INTENDED;
494 case kPolynomial:
495 case kGeometric:
Aart Bikdf7822e2016-12-06 10:05:30 -0800496 case kWrapAround:
Aart Bik22af3be2015-09-10 12:50:58 -0700497 // Classify first phi and then the rest of the cycle "on-demand".
498 // Statements are scanned in order.
Aart Bikc071a012016-12-01 10:22:31 -0800499 AssignInfo(loop, phi, induction);
Aart Bik22af3be2015-09-10 12:50:58 -0700500 for (size_t i = 1; i < size; i++) {
Aart Bike609b7c2015-08-27 13:46:58 -0700501 ClassifyTrivial(loop, scc_[i]);
502 }
503 break;
504 case kPeriodic:
Aart Bik22af3be2015-09-10 12:50:58 -0700505 // Classify all elements in the cycle with the found periodic induction while
506 // rotating each first element to the end. Lastly, phi is classified.
507 // Statements are scanned in reverse order.
508 for (size_t i = size - 1; i >= 1; i--) {
509 AssignInfo(loop, scc_[i], induction);
Aart Bike609b7c2015-08-27 13:46:58 -0700510 induction = RotatePeriodicInduction(induction->op_b, induction->op_a);
511 }
512 AssignInfo(loop, phi, induction);
513 break;
514 default:
515 break;
Aart Bik30efb4e2015-07-30 12:14:31 -0700516 }
517 }
518}
519
Aart Bike609b7c2015-08-27 13:46:58 -0700520HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::RotatePeriodicInduction(
521 InductionInfo* induction,
522 InductionInfo* last) {
523 // Rotates a periodic induction of the form
524 // (a, b, c, d, e)
525 // into
526 // (b, c, d, e, a)
527 // in preparation of assigning this to the previous variable in the sequence.
528 if (induction->induction_class == kInvariant) {
Aart Bikc071a012016-12-01 10:22:31 -0800529 return CreateInduction(kPeriodic,
530 kNop,
531 induction,
532 last,
533 /*fetch*/ nullptr,
534 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700535 }
Aart Bikc071a012016-12-01 10:22:31 -0800536 return CreateInduction(kPeriodic,
537 kNop,
538 induction->op_a,
539 RotatePeriodicInduction(induction->op_b, last),
540 /*fetch*/ nullptr,
541 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700542}
543
Aart Bikf475bee2015-09-16 12:50:25 -0700544HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferPhi(HLoopInformation* loop,
545 HInstruction* phi,
Aart Bikd0a022d2016-12-13 11:22:31 -0800546 size_t input_index,
547 size_t adjust_input_size) {
Aart Bikf475bee2015-09-16 12:50:25 -0700548 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100549 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100550 DCHECK_LT(input_index, inputs.size());
551 InductionInfo* a = LookupInfo(loop, inputs[input_index]);
Aart Bikd0a022d2016-12-13 11:22:31 -0800552 for (size_t i = input_index + 1, n = inputs.size() - adjust_input_size; i < n; i++) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100553 InductionInfo* b = LookupInfo(loop, inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700554 if (!InductionEqual(a, b)) {
555 return nullptr;
556 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700557 }
Aart Bikf475bee2015-09-16 12:50:25 -0700558 return a;
Aart Bik30efb4e2015-07-30 12:14:31 -0700559}
560
561HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferAddSub(InductionInfo* a,
562 InductionInfo* b,
563 InductionOp op) {
Aart Bikc071a012016-12-01 10:22:31 -0800564 // Transfer over an addition or subtraction: any invariant, linear, polynomial, geometric,
565 // wrap-around, or periodic can be combined with an invariant to yield a similar result.
Aart Bikdf7822e2016-12-06 10:05:30 -0800566 // Two linear or two polynomial inputs can be combined too. Other combinations fail.
Aart Bik30efb4e2015-07-30 12:14:31 -0700567 if (a != nullptr && b != nullptr) {
Aart Bike6bd0272016-12-16 13:57:52 -0800568 if (IsNarrowingLinear(a) || IsNarrowingLinear(b)) {
569 return nullptr; // no transfer
570 } else if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik74da5292016-12-20 11:13:03 -0800571 return CreateInvariantOp(op, a, b); // direct invariant
Aart Bikdf7822e2016-12-06 10:05:30 -0800572 } else if ((a->induction_class == kLinear && b->induction_class == kLinear) ||
573 (a->induction_class == kPolynomial && b->induction_class == kPolynomial)) {
Aart Bik74da5292016-12-20 11:13:03 -0800574 // Rule induc(a, b) + induc(a', b') -> induc(a + a', b + b').
575 InductionInfo* new_a = TransferAddSub(a->op_a, b->op_a, op);
576 InductionInfo* new_b = TransferAddSub(a->op_b, b->op_b, op);
577 if (new_a != nullptr && new_b != nullptr) {
578 return CreateInduction(a->induction_class, a->operation, new_a, new_b, a->fetch, type_);
579 }
Aart Bike609b7c2015-08-27 13:46:58 -0700580 } else if (a->induction_class == kInvariant) {
Aart Bik74da5292016-12-20 11:13:03 -0800581 // Rule a + induc(a', b') -> induc(a', a + b') or induc(a + a', a + b').
Aart Bike609b7c2015-08-27 13:46:58 -0700582 InductionInfo* new_a = b->op_a;
583 InductionInfo* new_b = TransferAddSub(a, b->op_b, op);
Aart Bikc071a012016-12-01 10:22:31 -0800584 if (b->induction_class == kWrapAround || b->induction_class == kPeriodic) {
Aart Bike609b7c2015-08-27 13:46:58 -0700585 new_a = TransferAddSub(a, new_a, op);
586 } else if (op == kSub) { // Negation required.
587 new_a = TransferNeg(new_a);
588 }
Aart Bik74da5292016-12-20 11:13:03 -0800589 if (new_a != nullptr && new_b != nullptr) {
590 return CreateInduction(b->induction_class, b->operation, new_a, new_b, b->fetch, type_);
591 }
Aart Bike609b7c2015-08-27 13:46:58 -0700592 } else if (b->induction_class == kInvariant) {
Aart Bik74da5292016-12-20 11:13:03 -0800593 // Rule induc(a, b) + b' -> induc(a, b + b') or induc(a + b', b + b').
Aart Bike609b7c2015-08-27 13:46:58 -0700594 InductionInfo* new_a = a->op_a;
595 InductionInfo* new_b = TransferAddSub(a->op_b, b, op);
Aart Bikc071a012016-12-01 10:22:31 -0800596 if (a->induction_class == kWrapAround || a->induction_class == kPeriodic) {
Aart Bike609b7c2015-08-27 13:46:58 -0700597 new_a = TransferAddSub(new_a, b, op);
598 }
Aart Bik74da5292016-12-20 11:13:03 -0800599 if (new_a != nullptr && new_b != nullptr) {
600 return CreateInduction(a->induction_class, a->operation, new_a, new_b, a->fetch, type_);
601 }
Aart Bikc071a012016-12-01 10:22:31 -0800602 }
603 }
604 return nullptr;
605}
606
607HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferNeg(InductionInfo* a) {
608 // Transfer over a unary negation: an invariant, linear, polynomial, geometric (mul),
609 // wrap-around, or periodic input yields a similar but negated induction as result.
610 if (a != nullptr) {
Aart Bike6bd0272016-12-16 13:57:52 -0800611 if (IsNarrowingLinear(a)) {
612 return nullptr; // no transfer
613 } else if (a->induction_class == kInvariant) {
Aart Bik74da5292016-12-20 11:13:03 -0800614 return CreateInvariantOp(kNeg, nullptr, a); // direct invariant
Aart Bikc071a012016-12-01 10:22:31 -0800615 } else if (a->induction_class != kGeometric || a->operation == kMul) {
Aart Bik74da5292016-12-20 11:13:03 -0800616 // Rule - induc(a, b) -> induc(-a, -b).
617 InductionInfo* new_a = TransferNeg(a->op_a);
618 InductionInfo* new_b = TransferNeg(a->op_b);
619 if (new_a != nullptr && new_b != nullptr) {
620 return CreateInduction(a->induction_class, a->operation, new_a, new_b, a->fetch, type_);
621 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700622 }
623 }
624 return nullptr;
625}
626
627HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferMul(InductionInfo* a,
628 InductionInfo* b) {
Aart Bikc071a012016-12-01 10:22:31 -0800629 // Transfer over a multiplication: any invariant, linear, polynomial, geometric (mul),
630 // wrap-around, or periodic can be multiplied with an invariant to yield a similar
631 // but multiplied result. Two non-invariant inputs cannot be multiplied, however.
Aart Bik30efb4e2015-07-30 12:14:31 -0700632 if (a != nullptr && b != nullptr) {
Aart Bike6bd0272016-12-16 13:57:52 -0800633 if (IsNarrowingLinear(a) || IsNarrowingLinear(b)) {
634 return nullptr; // no transfer
635 } else if (a->induction_class == kInvariant && b->induction_class == kInvariant) {
Aart Bik74da5292016-12-20 11:13:03 -0800636 return CreateInvariantOp(kMul, a, b); // direct invariant
Aart Bikc071a012016-12-01 10:22:31 -0800637 } else if (a->induction_class == kInvariant && (b->induction_class != kGeometric ||
638 b->operation == kMul)) {
Aart Bik74da5292016-12-20 11:13:03 -0800639 // Rule a * induc(a', b') -> induc(a * a', b * b').
640 InductionInfo* new_a = TransferMul(a, b->op_a);
641 InductionInfo* new_b = TransferMul(a, b->op_b);
642 if (new_a != nullptr && new_b != nullptr) {
643 return CreateInduction(b->induction_class, b->operation, new_a, new_b, b->fetch, type_);
644 }
Aart Bikc071a012016-12-01 10:22:31 -0800645 } else if (b->induction_class == kInvariant && (a->induction_class != kGeometric ||
646 a->operation == kMul)) {
Aart Bik74da5292016-12-20 11:13:03 -0800647 // Rule induc(a, b) * b' -> induc(a * b', b * b').
648 InductionInfo* new_a = TransferMul(a->op_a, b);
649 InductionInfo* new_b = TransferMul(a->op_b, b);
650 if (new_a != nullptr && new_b != nullptr) {
651 return CreateInduction(a->induction_class, a->operation, new_a, new_b, a->fetch, type_);
652 }
Aart Bike609b7c2015-08-27 13:46:58 -0700653 }
654 }
655 return nullptr;
656}
657
Aart Bike6bd0272016-12-16 13:57:52 -0800658HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::TransferConversion(
659 InductionInfo* a,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100660 DataType::Type from,
661 DataType::Type to) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700662 if (a != nullptr) {
Aart Bike6bd0272016-12-16 13:57:52 -0800663 // Allow narrowing conversion on linear induction in certain cases:
664 // induction is already at narrow type, or can be made narrower.
665 if (IsNarrowingIntegralConversion(from, to) &&
666 a->induction_class == kLinear &&
667 (a->type == to || IsNarrowingIntegralConversion(a->type, to))) {
Aart Bik74da5292016-12-20 11:13:03 -0800668 return CreateInduction(kLinear, kNop, a->op_a, a->op_b, a->fetch, to);
Aart Bik0d345cf2016-03-16 10:49:38 -0700669 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700670 }
671 return nullptr;
672}
673
Aart Bikf475bee2015-09-16 12:50:25 -0700674HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhi(HInstruction* phi,
Aart Bikd0a022d2016-12-13 11:22:31 -0800675 size_t input_index,
676 size_t adjust_input_size) {
Aart Bikf475bee2015-09-16 12:50:25 -0700677 // Match all phi inputs from input_index onwards exactly.
Vladimir Markoe9004912016-06-16 16:50:52 +0100678 HInputsRef inputs = phi->GetInputs();
Vladimir Marko372f10e2016-05-17 16:30:10 +0100679 DCHECK_LT(input_index, inputs.size());
680 auto ita = cycle_.find(inputs[input_index]);
Aart Bik30efb4e2015-07-30 12:14:31 -0700681 if (ita != cycle_.end()) {
Aart Bikd0a022d2016-12-13 11:22:31 -0800682 for (size_t i = input_index + 1, n = inputs.size() - adjust_input_size; i < n; i++) {
Vladimir Marko372f10e2016-05-17 16:30:10 +0100683 auto itb = cycle_.find(inputs[i]);
Aart Bikf475bee2015-09-16 12:50:25 -0700684 if (itb == cycle_.end() ||
685 !HInductionVarAnalysis::InductionEqual(ita->second, itb->second)) {
Aart Bik30efb4e2015-07-30 12:14:31 -0700686 return nullptr;
687 }
688 }
Aart Bikf475bee2015-09-16 12:50:25 -0700689 return ita->second;
690 }
691 return nullptr;
692}
693
694HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolvePhiAllInputs(
695 HLoopInformation* loop,
696 HInstruction* entry_phi,
697 HInstruction* phi) {
698 // Match all phi inputs.
Aart Bikd0a022d2016-12-13 11:22:31 -0800699 InductionInfo* match = SolvePhi(phi, /*input_index*/ 0, /*adjust_input_size*/ 0);
Aart Bikf475bee2015-09-16 12:50:25 -0700700 if (match != nullptr) {
701 return match;
Aart Bik30efb4e2015-07-30 12:14:31 -0700702 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700703
Aart Bikf475bee2015-09-16 12:50:25 -0700704 // Otherwise, try to solve for a periodic seeded from phi onward.
705 // Only tight multi-statement cycles are considered in order to
706 // simplify rotating the periodic during the final classification.
707 if (phi->IsLoopHeaderPhi() && phi->InputCount() == 2) {
708 InductionInfo* a = LookupInfo(loop, phi->InputAt(0));
Aart Bike609b7c2015-08-27 13:46:58 -0700709 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700710 if (phi->InputAt(1) == entry_phi) {
711 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bikc071a012016-12-01 10:22:31 -0800712 return CreateInduction(kPeriodic, kNop, a, initial, /*fetch*/ nullptr, type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700713 }
Aart Bikd0a022d2016-12-13 11:22:31 -0800714 InductionInfo* b = SolvePhi(phi, /*input_index*/ 1, /*adjust_input_size*/ 0);
Aart Bikf475bee2015-09-16 12:50:25 -0700715 if (b != nullptr && b->induction_class == kPeriodic) {
Aart Bikc071a012016-12-01 10:22:31 -0800716 return CreateInduction(kPeriodic, kNop, a, b, /*fetch*/ nullptr, type_);
Aart Bik30efb4e2015-07-30 12:14:31 -0700717 }
718 }
719 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700720 return nullptr;
721}
722
Aart Bike609b7c2015-08-27 13:46:58 -0700723HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveAddSub(HLoopInformation* loop,
Aart Bikf475bee2015-09-16 12:50:25 -0700724 HInstruction* entry_phi,
Aart Bike609b7c2015-08-27 13:46:58 -0700725 HInstruction* instruction,
726 HInstruction* x,
727 HInstruction* y,
728 InductionOp op,
729 bool is_first_call) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800730 // Solve within a cycle over an addition or subtraction.
Aart Bike609b7c2015-08-27 13:46:58 -0700731 InductionInfo* b = LookupInfo(loop, y);
Aart Bikdf7822e2016-12-06 10:05:30 -0800732 if (b != nullptr) {
733 if (b->induction_class == kInvariant) {
734 // Adding or subtracting an invariant value, seeded from phi,
735 // keeps adding to the stride of the linear induction.
736 if (x == entry_phi) {
737 return (op == kAdd) ? b : CreateInvariantOp(kNeg, nullptr, b);
738 }
739 auto it = cycle_.find(x);
740 if (it != cycle_.end()) {
741 InductionInfo* a = it->second;
742 if (a->induction_class == kInvariant) {
743 return CreateInvariantOp(op, a, b);
744 }
745 }
Aart Bik74da5292016-12-20 11:13:03 -0800746 } else if (b->induction_class == kLinear && b->type == type_) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800747 // Solve within a tight cycle that adds a term that is already classified as a linear
748 // induction for a polynomial induction k = k + i (represented as sum over linear terms).
749 if (x == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
750 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bik74da5292016-12-20 11:13:03 -0800751 InductionInfo* new_a = op == kAdd ? b : TransferNeg(b);
752 if (new_a != nullptr) {
753 return CreateInduction(kPolynomial, kNop, new_a, initial, /*fetch*/ nullptr, type_);
754 }
Aart Bike609b7c2015-08-27 13:46:58 -0700755 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700756 }
757 }
Aart Bike609b7c2015-08-27 13:46:58 -0700758
759 // Try some alternatives before failing.
760 if (op == kAdd) {
761 // Try the other way around for an addition if considered for first time.
762 if (is_first_call) {
Aart Bikf475bee2015-09-16 12:50:25 -0700763 return SolveAddSub(loop, entry_phi, instruction, y, x, op, false);
Aart Bike609b7c2015-08-27 13:46:58 -0700764 }
765 } else if (op == kSub) {
Aart Bikf475bee2015-09-16 12:50:25 -0700766 // Solve within a tight cycle that is formed by exactly two instructions,
Aart Bikc071a012016-12-01 10:22:31 -0800767 // one phi and one update, for a periodic idiom of the form k = c - k.
Aart Bikf475bee2015-09-16 12:50:25 -0700768 if (y == entry_phi && entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bike609b7c2015-08-27 13:46:58 -0700769 InductionInfo* a = LookupInfo(loop, x);
770 if (a != nullptr && a->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700771 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
Aart Bikc071a012016-12-01 10:22:31 -0800772 return CreateInduction(kPeriodic,
773 kNop,
774 CreateInvariantOp(kSub, a, initial),
775 initial,
776 /*fetch*/ nullptr,
777 type_);
Aart Bike609b7c2015-08-27 13:46:58 -0700778 }
779 }
780 }
Aart Bik30efb4e2015-07-30 12:14:31 -0700781 return nullptr;
782}
783
Aart Bikdf7822e2016-12-06 10:05:30 -0800784HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveOp(HLoopInformation* loop,
Aart Bikc071a012016-12-01 10:22:31 -0800785 HInstruction* entry_phi,
786 HInstruction* instruction,
787 HInstruction* x,
788 HInstruction* y,
789 InductionOp op) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800790 // Solve within a tight cycle for a binary operation k = k op c or, for some op, k = c op k.
Aart Bik639cc8c2016-10-18 13:03:31 -0700791 if (entry_phi->InputCount() == 2 && instruction == entry_phi->InputAt(1)) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800792 InductionInfo* c = nullptr;
Aart Bik639cc8c2016-10-18 13:03:31 -0700793 InductionInfo* b = LookupInfo(loop, y);
794 if (b != nullptr && b->induction_class == kInvariant && entry_phi == x) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800795 c = b;
796 } else if (op != kDiv && op != kRem) {
797 InductionInfo* a = LookupInfo(loop, x);
798 if (a != nullptr && a->induction_class == kInvariant && entry_phi == y) {
799 c = a;
800 }
801 }
802 // Found suitable operand left or right?
803 if (c != nullptr) {
804 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
805 switch (op) {
806 case kMul:
807 case kDiv:
808 // Restrict base of geometric induction to direct fetch.
809 if (c->operation == kFetch) {
810 return CreateInduction(kGeometric,
811 op,
812 initial,
813 CreateConstant(0, type_),
814 c->fetch,
815 type_);
Igor Murashkin2ffb7032017-11-08 13:35:21 -0800816 }
Aart Bikdf7822e2016-12-06 10:05:30 -0800817 break;
818 case kRem:
819 // Idiomatic MOD wrap-around induction.
820 return CreateInduction(kWrapAround,
821 kNop,
822 initial,
823 CreateInvariantOp(kRem, initial, c),
824 /*fetch*/ nullptr,
825 type_);
826 case kXor:
827 // Idiomatic XOR periodic induction.
828 return CreateInduction(kPeriodic,
829 kNop,
830 CreateInvariantOp(kXor, initial, c),
831 initial,
832 /*fetch*/ nullptr,
833 type_);
834 default:
Andreas Gampef45d61c2017-06-07 10:29:33 -0700835 LOG(FATAL) << op;
836 UNREACHABLE();
Aart Bikdf7822e2016-12-06 10:05:30 -0800837 }
Aart Bik7dc96932016-10-12 10:01:05 -0700838 }
839 }
Aart Bik639cc8c2016-10-18 13:03:31 -0700840 return nullptr;
841}
842
843HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveTest(HLoopInformation* loop,
844 HInstruction* entry_phi,
845 HInstruction* instruction,
846 int64_t opposite_value) {
Aart Bikc071a012016-12-01 10:22:31 -0800847 // Detect hidden XOR construction in x = (x == false) or x = (x != true).
Aart Bik639cc8c2016-10-18 13:03:31 -0700848 int64_t value = -1;
849 HInstruction* x = instruction->InputAt(0);
850 HInstruction* y = instruction->InputAt(1);
851 if (IsExact(LookupInfo(loop, x), &value) && value == opposite_value) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800852 return SolveOp(loop, entry_phi, instruction, graph_->GetIntConstant(1), y, kXor);
Aart Bik639cc8c2016-10-18 13:03:31 -0700853 } else if (IsExact(LookupInfo(loop, y), &value) && value == opposite_value) {
Aart Bikdf7822e2016-12-06 10:05:30 -0800854 return SolveOp(loop, entry_phi, instruction, x, graph_->GetIntConstant(1), kXor);
Aart Bik7dc96932016-10-12 10:01:05 -0700855 }
856 return nullptr;
857}
858
Aart Bike6bd0272016-12-16 13:57:52 -0800859HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::SolveConversion(
860 HLoopInformation* loop,
861 HInstruction* entry_phi,
862 HTypeConversion* conversion) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100863 DataType::Type from = conversion->GetInputType();
864 DataType::Type to = conversion->GetResultType();
Aart Bike6bd0272016-12-16 13:57:52 -0800865 // A narrowing conversion is allowed as *last* operation of the cycle of a linear induction
866 // with an initial value that fits the type, provided that the narrowest encountered type is
867 // recorded with the induction to account for the precision loss. The narrower induction does
868 // *not* transfer to any wider operations, however, since these may yield out-of-type values
869 if (entry_phi->InputCount() == 2 && conversion == entry_phi->InputAt(1)) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100870 int64_t min = DataType::MinValueOfIntegralType(to);
871 int64_t max = DataType::MaxValueOfIntegralType(to);
Aart Bike6bd0272016-12-16 13:57:52 -0800872 int64_t value = 0;
873 InductionInfo* initial = LookupInfo(loop, entry_phi->InputAt(0));
874 if (IsNarrowingIntegralConversion(from, to) &&
875 IsAtLeast(initial, &value) && value >= min &&
876 IsAtMost(initial, &value) && value <= max) {
877 auto it = cycle_.find(conversion->GetInput());
878 if (it != cycle_.end() && it->second->induction_class == kInvariant) {
879 type_ = to;
880 return it->second;
881 }
Aart Bik0d345cf2016-03-16 10:49:38 -0700882 }
883 }
884 return nullptr;
885}
886
Aart Bikceb06932017-11-13 10:31:17 -0800887//
888// Loop trip count analysis methods.
889//
890
Aart Bikd14c5952015-09-08 15:25:15 -0700891void HInductionVarAnalysis::VisitControl(HLoopInformation* loop) {
892 HInstruction* control = loop->GetHeader()->GetLastInstruction();
893 if (control->IsIf()) {
894 HIf* ifs = control->AsIf();
895 HBasicBlock* if_true = ifs->IfTrueSuccessor();
896 HBasicBlock* if_false = ifs->IfFalseSuccessor();
897 HInstruction* if_expr = ifs->InputAt(0);
898 // Determine if loop has following structure in header.
899 // loop-header: ....
900 // if (condition) goto X
901 if (if_expr->IsCondition()) {
902 HCondition* condition = if_expr->AsCondition();
903 InductionInfo* a = LookupInfo(loop, condition->InputAt(0));
904 InductionInfo* b = LookupInfo(loop, condition->InputAt(1));
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100905 DataType::Type type = ImplicitConversion(condition->InputAt(0)->GetType());
Aart Bik0d345cf2016-03-16 10:49:38 -0700906 // Determine if the loop control uses a known sequence on an if-exit (X outside) or on
907 // an if-iterate (X inside), expressed as if-iterate when passed into VisitCondition().
908 if (a == nullptr || b == nullptr) {
909 return; // Loop control is not a sequence.
Aart Bikd14c5952015-09-08 15:25:15 -0700910 } else if (if_true->GetLoopInformation() != loop && if_false->GetLoopInformation() == loop) {
Aart Bikceb06932017-11-13 10:31:17 -0800911 VisitCondition(loop, if_false, a, b, type, condition->GetOppositeCondition());
Aart Bikd14c5952015-09-08 15:25:15 -0700912 } else if (if_true->GetLoopInformation() == loop && if_false->GetLoopInformation() != loop) {
Aart Bikceb06932017-11-13 10:31:17 -0800913 VisitCondition(loop, if_true, a, b, type, condition->GetCondition());
Aart Bikd14c5952015-09-08 15:25:15 -0700914 }
915 }
916 }
917}
918
919void HInductionVarAnalysis::VisitCondition(HLoopInformation* loop,
Aart Bikceb06932017-11-13 10:31:17 -0800920 HBasicBlock* body,
Aart Bikd14c5952015-09-08 15:25:15 -0700921 InductionInfo* a,
922 InductionInfo* b,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100923 DataType::Type type,
Aart Bikd14c5952015-09-08 15:25:15 -0700924 IfCondition cmp) {
925 if (a->induction_class == kInvariant && b->induction_class == kLinear) {
Aart Bikf475bee2015-09-16 12:50:25 -0700926 // 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 -0700927 switch (cmp) {
Aart Bikceb06932017-11-13 10:31:17 -0800928 case kCondLT: VisitCondition(loop, body, b, a, type, kCondGT); break;
929 case kCondLE: VisitCondition(loop, body, b, a, type, kCondGE); break;
930 case kCondGT: VisitCondition(loop, body, b, a, type, kCondLT); break;
931 case kCondGE: VisitCondition(loop, body, b, a, type, kCondLE); break;
932 case kCondNE: VisitCondition(loop, body, b, a, type, kCondNE); break;
Aart Bikd14c5952015-09-08 15:25:15 -0700933 default: break;
934 }
935 } else if (a->induction_class == kLinear && b->induction_class == kInvariant) {
Aart Bikf475bee2015-09-16 12:50:25 -0700936 // Analyze condition with induction at left-hand-side (e.g. i < U).
Aart Bik9401f532015-09-28 16:25:56 -0700937 InductionInfo* lower_expr = a->op_b;
938 InductionInfo* upper_expr = b;
Aart Bik97412c922016-02-19 20:14:38 -0800939 InductionInfo* stride_expr = a->op_a;
Aart Bikceb06932017-11-13 10:31:17 -0800940 // Test for constant stride and integral condition.
Aart Bik9401f532015-09-28 16:25:56 -0700941 int64_t stride_value = 0;
Aart Bik97412c922016-02-19 20:14:38 -0800942 if (!IsExact(stride_expr, &stride_value)) {
Aart Bikceb06932017-11-13 10:31:17 -0800943 return; // unknown stride
944 } else if (type != DataType::Type::kInt32 && type != DataType::Type::kInt64) {
945 return; // not integral
Aart Bikf475bee2015-09-16 12:50:25 -0700946 }
Aart Bikceb06932017-11-13 10:31:17 -0800947 // Since loops with a i != U condition will not be normalized by the method below, first
948 // try to rewrite a break-loop with terminating condition i != U into an equivalent loop
949 // with non-strict end condition i <= U or i >= U if such a rewriting is possible and safe.
950 if (cmp == kCondNE && RewriteBreakLoop(loop, body, stride_value, type)) {
951 cmp = stride_value > 0 ? kCondLE : kCondGE;
952 }
953 // If this rewriting failed, try to rewrite condition i != U into strict end condition i < U
954 // or i > U if this end condition is reached exactly (tested by verifying if the loop has a
955 // unit stride and the non-strict condition would be always taken).
Aart Bik358af832016-02-24 14:17:53 -0800956 if (cmp == kCondNE && ((stride_value == +1 && IsTaken(lower_expr, upper_expr, kCondLE)) ||
957 (stride_value == -1 && IsTaken(lower_expr, upper_expr, kCondGE)))) {
Aart Bik9401f532015-09-28 16:25:56 -0700958 cmp = stride_value > 0 ? kCondLT : kCondGT;
Aart Bikd14c5952015-09-08 15:25:15 -0700959 }
Aart Bikceb06932017-11-13 10:31:17 -0800960 // A mismatch between the type of condition and the induction is only allowed if the,
961 // necessarily narrower, induction range fits the narrower control.
962 if (type != a->type &&
963 !FitsNarrowerControl(lower_expr, upper_expr, stride_value, a->type, cmp)) {
Aart Bik0d345cf2016-03-16 10:49:38 -0700964 return; // mismatched type
965 }
Aart Bikf475bee2015-09-16 12:50:25 -0700966 // Normalize a linear loop control with a nonzero stride:
967 // stride > 0, either i < U or i <= U
968 // stride < 0, either i > U or i >= U
Aart Bikf475bee2015-09-16 12:50:25 -0700969 if ((stride_value > 0 && (cmp == kCondLT || cmp == kCondLE)) ||
970 (stride_value < 0 && (cmp == kCondGT || cmp == kCondGE))) {
Aart Bik97412c922016-02-19 20:14:38 -0800971 VisitTripCount(loop, lower_expr, upper_expr, stride_expr, stride_value, type, cmp);
Aart Bikf475bee2015-09-16 12:50:25 -0700972 }
Aart Bikd14c5952015-09-08 15:25:15 -0700973 }
974}
975
976void HInductionVarAnalysis::VisitTripCount(HLoopInformation* loop,
Aart Bik9401f532015-09-28 16:25:56 -0700977 InductionInfo* lower_expr,
978 InductionInfo* upper_expr,
Aart Bik97412c922016-02-19 20:14:38 -0800979 InductionInfo* stride_expr,
Aart Bik9401f532015-09-28 16:25:56 -0700980 int64_t stride_value,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +0100981 DataType::Type type,
Aart Bikf475bee2015-09-16 12:50:25 -0700982 IfCondition cmp) {
Aart Bikd14c5952015-09-08 15:25:15 -0700983 // Any loop of the general form:
984 //
985 // for (i = L; i <= U; i += S) // S > 0
986 // or for (i = L; i >= U; i += S) // S < 0
987 // .. i ..
988 //
989 // can be normalized into:
990 //
991 // for (n = 0; n < TC; n++) // where TC = (U + S - L) / S
992 // .. L + S * n ..
993 //
Aart Bik9401f532015-09-28 16:25:56 -0700994 // taking the following into consideration:
Aart Bikd14c5952015-09-08 15:25:15 -0700995 //
Aart Bik9401f532015-09-28 16:25:56 -0700996 // (1) Using the same precision, the TC (trip-count) expression should be interpreted as
997 // an unsigned entity, for example, as in the following loop that uses the full range:
998 // for (int i = INT_MIN; i < INT_MAX; i++) // TC = UINT_MAX
999 // (2) The TC is only valid if the loop is taken, otherwise TC = 0, as in:
Aart Bikd5cc6832016-06-22 16:34:46 -07001000 // for (int i = 12; i < U; i++) // TC = 0 when U <= 12
Aart Bik9401f532015-09-28 16:25:56 -07001001 // If this cannot be determined at compile-time, the TC is only valid within the
Aart Bik22f05872015-10-27 15:56:28 -07001002 // loop-body proper, not the loop-header unless enforced with an explicit taken-test.
Aart Bik9401f532015-09-28 16:25:56 -07001003 // (3) The TC is only valid if the loop is finite, otherwise TC has no value, as in:
1004 // for (int i = 0; i <= U; i++) // TC = Inf when U = INT_MAX
1005 // If this cannot be determined at compile-time, the TC is only valid when enforced
Aart Bik22f05872015-10-27 15:56:28 -07001006 // with an explicit finite-test.
Aart Bik9401f532015-09-28 16:25:56 -07001007 // (4) For loops which early-exits, the TC forms an upper bound, as in:
1008 // for (int i = 0; i < 10 && ....; i++) // TC <= 10
Aart Bik22f05872015-10-27 15:56:28 -07001009 InductionInfo* trip_count = upper_expr;
Aart Bik9401f532015-09-28 16:25:56 -07001010 const bool is_taken = IsTaken(lower_expr, upper_expr, cmp);
1011 const bool is_finite = IsFinite(upper_expr, stride_value, type, cmp);
1012 const bool cancels = (cmp == kCondLT || cmp == kCondGT) && std::abs(stride_value) == 1;
Aart Bikd14c5952015-09-08 15:25:15 -07001013 if (!cancels) {
1014 // Convert exclusive integral inequality into inclusive integral inequality,
1015 // viz. condition i < U is i <= U - 1 and condition i > U is i >= U + 1.
Aart Bikf475bee2015-09-16 12:50:25 -07001016 if (cmp == kCondLT) {
Aart Bik22f05872015-10-27 15:56:28 -07001017 trip_count = CreateInvariantOp(kSub, trip_count, CreateConstant(1, type));
Aart Bikf475bee2015-09-16 12:50:25 -07001018 } else if (cmp == kCondGT) {
Aart Bik22f05872015-10-27 15:56:28 -07001019 trip_count = CreateInvariantOp(kAdd, trip_count, CreateConstant(1, type));
Aart Bikd14c5952015-09-08 15:25:15 -07001020 }
1021 // Compensate for stride.
Aart Bik97412c922016-02-19 20:14:38 -08001022 trip_count = CreateInvariantOp(kAdd, trip_count, stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -07001023 }
Aart Bik97412c922016-02-19 20:14:38 -08001024 trip_count = CreateInvariantOp(
1025 kDiv, CreateInvariantOp(kSub, trip_count, lower_expr), stride_expr);
Aart Bikd14c5952015-09-08 15:25:15 -07001026 // Assign the trip-count expression to the loop control. Clients that use the information
Aart Bik9401f532015-09-28 16:25:56 -07001027 // should be aware that the expression is only valid under the conditions listed above.
Aart Bik22f05872015-10-27 15:56:28 -07001028 InductionOp tcKind = kTripCountInBodyUnsafe; // needs both tests
Aart Bik9401f532015-09-28 16:25:56 -07001029 if (is_taken && is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -07001030 tcKind = kTripCountInLoop; // needs neither test
Aart Bik9401f532015-09-28 16:25:56 -07001031 } else if (is_finite) {
Aart Bik22f05872015-10-27 15:56:28 -07001032 tcKind = kTripCountInBody; // needs taken-test
Aart Bik9401f532015-09-28 16:25:56 -07001033 } else if (is_taken) {
Aart Bik22f05872015-10-27 15:56:28 -07001034 tcKind = kTripCountInLoopUnsafe; // needs finite-test
Aart Bik9401f532015-09-28 16:25:56 -07001035 }
Aart Bik22f05872015-10-27 15:56:28 -07001036 InductionOp op = kNop;
1037 switch (cmp) {
1038 case kCondLT: op = kLT; break;
1039 case kCondLE: op = kLE; break;
1040 case kCondGT: op = kGT; break;
1041 case kCondGE: op = kGE; break;
1042 default: LOG(FATAL) << "CONDITION UNREACHABLE";
1043 }
Aart Bik009cace2016-09-16 10:15:19 -07001044 // Associate trip count with control instruction, rather than the condition (even
1045 // though it's its use) since former provides a convenient use-free placeholder.
1046 HInstruction* control = loop->GetHeader()->GetLastInstruction();
Aart Bik22f05872015-10-27 15:56:28 -07001047 InductionInfo* taken_test = CreateInvariantOp(op, lower_expr, upper_expr);
Aart Bik009cace2016-09-16 10:15:19 -07001048 DCHECK(control->IsIf());
1049 AssignInfo(loop, control, CreateTripCount(tcKind, trip_count, taken_test, type));
Aart Bik9401f532015-09-28 16:25:56 -07001050}
1051
1052bool HInductionVarAnalysis::IsTaken(InductionInfo* lower_expr,
1053 InductionInfo* upper_expr,
1054 IfCondition cmp) {
1055 int64_t lower_value;
1056 int64_t upper_value;
Aart Bik97412c922016-02-19 20:14:38 -08001057 switch (cmp) {
1058 case kCondLT:
1059 return IsAtMost(lower_expr, &lower_value)
1060 && IsAtLeast(upper_expr, &upper_value)
1061 && lower_value < upper_value;
1062 case kCondLE:
1063 return IsAtMost(lower_expr, &lower_value)
1064 && IsAtLeast(upper_expr, &upper_value)
1065 && lower_value <= upper_value;
1066 case kCondGT:
1067 return IsAtLeast(lower_expr, &lower_value)
1068 && IsAtMost(upper_expr, &upper_value)
1069 && lower_value > upper_value;
1070 case kCondGE:
1071 return IsAtLeast(lower_expr, &lower_value)
1072 && IsAtMost(upper_expr, &upper_value)
1073 && lower_value >= upper_value;
1074 default:
1075 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -07001076 }
1077 return false; // not certain, may be untaken
1078}
1079
1080bool HInductionVarAnalysis::IsFinite(InductionInfo* upper_expr,
1081 int64_t stride_value,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001082 DataType::Type type,
Aart Bik9401f532015-09-28 16:25:56 -07001083 IfCondition cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001084 int64_t min = DataType::MinValueOfIntegralType(type);
1085 int64_t max = DataType::MaxValueOfIntegralType(type);
Aart Bik9401f532015-09-28 16:25:56 -07001086 // Some rules under which it is certain at compile-time that the loop is finite.
1087 int64_t value;
1088 switch (cmp) {
1089 case kCondLT:
1090 return stride_value == 1 ||
Aart Bik97412c922016-02-19 20:14:38 -08001091 (IsAtMost(upper_expr, &value) && value <= (max - stride_value + 1));
Aart Bik9401f532015-09-28 16:25:56 -07001092 case kCondLE:
Aart Bik97412c922016-02-19 20:14:38 -08001093 return (IsAtMost(upper_expr, &value) && value <= (max - stride_value));
Aart Bik9401f532015-09-28 16:25:56 -07001094 case kCondGT:
1095 return stride_value == -1 ||
Aart Bik97412c922016-02-19 20:14:38 -08001096 (IsAtLeast(upper_expr, &value) && value >= (min - stride_value - 1));
Aart Bik9401f532015-09-28 16:25:56 -07001097 case kCondGE:
Aart Bik97412c922016-02-19 20:14:38 -08001098 return (IsAtLeast(upper_expr, &value) && value >= (min - stride_value));
Aart Bike9f37602015-10-09 11:15:55 -07001099 default:
1100 LOG(FATAL) << "CONDITION UNREACHABLE";
Aart Bik9401f532015-09-28 16:25:56 -07001101 }
1102 return false; // not certain, may be infinite
Aart Bikd14c5952015-09-08 15:25:15 -07001103}
1104
Aart Bik0d345cf2016-03-16 10:49:38 -07001105bool HInductionVarAnalysis::FitsNarrowerControl(InductionInfo* lower_expr,
1106 InductionInfo* upper_expr,
1107 int64_t stride_value,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001108 DataType::Type type,
Aart Bik0d345cf2016-03-16 10:49:38 -07001109 IfCondition cmp) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001110 int64_t min = DataType::MinValueOfIntegralType(type);
1111 int64_t max = DataType::MaxValueOfIntegralType(type);
Aart Bik0d345cf2016-03-16 10:49:38 -07001112 // Inclusive test need one extra.
1113 if (stride_value != 1 && stride_value != -1) {
1114 return false; // non-unit stride
1115 } else if (cmp == kCondLE) {
1116 max--;
1117 } else if (cmp == kCondGE) {
1118 min++;
1119 }
1120 // Do both bounds fit the range?
Vladimir Marko0e2f2ff2016-03-22 12:31:54 +00001121 int64_t value = 0;
Aart Bik0d345cf2016-03-16 10:49:38 -07001122 return IsAtLeast(lower_expr, &value) && value >= min &&
1123 IsAtMost(lower_expr, &value) && value <= max &&
1124 IsAtLeast(upper_expr, &value) && value >= min &&
1125 IsAtMost(upper_expr, &value) && value <= max;
1126}
1127
Aart Bikceb06932017-11-13 10:31:17 -08001128bool HInductionVarAnalysis::RewriteBreakLoop(HLoopInformation* loop,
1129 HBasicBlock* body,
1130 int64_t stride_value,
1131 DataType::Type type) {
1132 // Only accept unit stride.
1133 if (std::abs(stride_value) != 1) {
1134 return false;
1135 }
1136 // Simple terminating i != U condition, used nowhere else.
1137 HIf* ifs = loop->GetHeader()->GetLastInstruction()->AsIf();
1138 HInstruction* cond = ifs->InputAt(0);
1139 if (ifs->GetPrevious() != cond || !cond->HasOnlyOneNonEnvironmentUse()) {
1140 return false;
1141 }
1142 int c = LookupInfo(loop, cond->InputAt(0))->induction_class == kLinear ? 0 : 1;
1143 HInstruction* index = cond->InputAt(c);
1144 HInstruction* upper = cond->InputAt(1 - c);
1145 // Safe to rewrite into i <= U?
1146 IfCondition cmp = stride_value > 0 ? kCondLE : kCondGE;
1147 if (!index->IsPhi() || !IsFinite(LookupInfo(loop, upper), stride_value, type, cmp)) {
1148 return false;
1149 }
1150 // Body consists of update to index i only, used nowhere else.
1151 if (body->GetSuccessors().size() != 1 ||
1152 body->GetSingleSuccessor() != loop->GetHeader() ||
1153 !body->GetPhis().IsEmpty() ||
1154 body->GetInstructions().IsEmpty() ||
1155 body->GetFirstInstruction() != index->InputAt(1) ||
1156 !body->GetFirstInstruction()->HasOnlyOneNonEnvironmentUse() ||
1157 !body->GetFirstInstruction()->GetNext()->IsGoto()) {
1158 return false;
1159 }
1160 // Always taken or guarded by enclosing condition.
1161 if (!IsTaken(LookupInfo(loop, index)->op_b, LookupInfo(loop, upper), cmp) &&
1162 !IsGuardedBy(loop, cmp, index->InputAt(0), upper)) {
1163 return false;
1164 }
1165 // Test if break-loop body can be written, and do so on success.
1166 if (RewriteBreakLoopBody(loop, body, cond, index, upper, /*rewrite*/ false)) {
1167 RewriteBreakLoopBody(loop, body, cond, index, upper, /*rewrite*/ true);
1168 } else {
1169 return false;
1170 }
1171 // Rewrite condition in HIR.
1172 if (ifs->IfTrueSuccessor() != body) {
1173 cmp = (cmp == kCondLE) ? kCondGT : kCondLT;
1174 }
1175 HInstruction* rep = nullptr;
1176 switch (cmp) {
1177 case kCondLT: rep = new (graph_->GetAllocator()) HLessThan(index, upper); break;
1178 case kCondGT: rep = new (graph_->GetAllocator()) HGreaterThan(index, upper); break;
1179 case kCondLE: rep = new (graph_->GetAllocator()) HLessThanOrEqual(index, upper); break;
1180 case kCondGE: rep = new (graph_->GetAllocator()) HGreaterThanOrEqual(index, upper); break;
1181 default: LOG(FATAL) << cmp; UNREACHABLE();
1182 }
1183 loop->GetHeader()->ReplaceAndRemoveInstructionWith(cond, rep);
1184 return true;
1185}
1186
1187//
1188// Helper methods.
1189//
1190
Aart Bik30efb4e2015-07-30 12:14:31 -07001191void HInductionVarAnalysis::AssignInfo(HLoopInformation* loop,
1192 HInstruction* instruction,
1193 InductionInfo* info) {
Aart Bike609b7c2015-08-27 13:46:58 -07001194 auto it = induction_.find(loop);
1195 if (it == induction_.end()) {
1196 it = induction_.Put(loop,
1197 ArenaSafeMap<HInstruction*, InductionInfo*>(
Vladimir Marko5233f932015-09-29 19:01:15 +01001198 std::less<HInstruction*>(),
Vladimir Markoca6fff82017-10-03 14:49:14 +01001199 graph_->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)));
Aart Bike609b7c2015-08-27 13:46:58 -07001200 }
1201 it->second.Put(instruction, info);
Aart Bik30efb4e2015-07-30 12:14:31 -07001202}
1203
Aart Bike609b7c2015-08-27 13:46:58 -07001204HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::LookupInfo(HLoopInformation* loop,
1205 HInstruction* instruction) {
1206 auto it = induction_.find(loop);
1207 if (it != induction_.end()) {
1208 auto loop_it = it->second.find(instruction);
1209 if (loop_it != it->second.end()) {
1210 return loop_it->second;
1211 }
Aart Bik30efb4e2015-07-30 12:14:31 -07001212 }
Mingyao Yang4b467ed2015-11-19 17:04:22 -08001213 if (loop->IsDefinedOutOfTheLoop(instruction)) {
Aart Bik471a2032015-09-04 18:22:11 -07001214 InductionInfo* info = CreateInvariantFetch(instruction);
Aart Bike609b7c2015-08-27 13:46:58 -07001215 AssignInfo(loop, instruction, info);
1216 return info;
1217 }
1218 return nullptr;
Aart Bik30efb4e2015-07-30 12:14:31 -07001219}
1220
Aart Bikd14c5952015-09-08 15:25:15 -07001221HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateConstant(int64_t value,
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001222 DataType::Type type) {
Aart Bikc071a012016-12-01 10:22:31 -08001223 HInstruction* constant;
1224 switch (type) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001225 case DataType::Type::kFloat64: constant = graph_->GetDoubleConstant(value); break;
1226 case DataType::Type::kFloat32: constant = graph_->GetFloatConstant(value); break;
1227 case DataType::Type::kInt64: constant = graph_->GetLongConstant(value); break;
1228 default: constant = graph_->GetIntConstant(value); break;
Aart Bikd14c5952015-09-08 15:25:15 -07001229 }
Aart Bikc071a012016-12-01 10:22:31 -08001230 return CreateInvariantFetch(constant);
Aart Bikd14c5952015-09-08 15:25:15 -07001231}
1232
Aart Bik471a2032015-09-04 18:22:11 -07001233HInductionVarAnalysis::InductionInfo* HInductionVarAnalysis::CreateSimplifiedInvariant(
1234 InductionOp op,
1235 InductionInfo* a,
1236 InductionInfo* b) {
1237 // Perform some light-weight simplifications during construction of a new invariant.
1238 // This often safes memory and yields a more concise representation of the induction.
1239 // More exhaustive simplifications are done by later phases once induction nodes are
1240 // translated back into HIR code (e.g. by loop optimizations or BCE).
1241 int64_t value = -1;
Aart Bik97412c922016-02-19 20:14:38 -08001242 if (IsExact(a, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -07001243 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -07001244 // Simplify 0 + b = b, 0 ^ b = b, 0 * b = 0.
1245 if (op == kAdd || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -07001246 return b;
1247 } else if (op == kMul) {
1248 return a;
1249 }
Aart Bikd14c5952015-09-08 15:25:15 -07001250 } else if (op == kMul) {
1251 // Simplify 1 * b = b, -1 * b = -b
1252 if (value == 1) {
1253 return b;
1254 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001255 return CreateSimplifiedInvariant(kNeg, nullptr, b);
Aart Bikd14c5952015-09-08 15:25:15 -07001256 }
Aart Bik471a2032015-09-04 18:22:11 -07001257 }
1258 }
Aart Bik97412c922016-02-19 20:14:38 -08001259 if (IsExact(b, &value)) {
Aart Bik471a2032015-09-04 18:22:11 -07001260 if (value == 0) {
Aart Bik7dc96932016-10-12 10:01:05 -07001261 // Simplify a + 0 = a, a - 0 = a, a ^ 0 = a, a * 0 = 0, -0 = 0.
1262 if (op == kAdd || op == kSub || op == kXor) {
Aart Bik471a2032015-09-04 18:22:11 -07001263 return a;
1264 } else if (op == kMul || op == kNeg) {
1265 return b;
1266 }
Aart Bikd14c5952015-09-08 15:25:15 -07001267 } else if (op == kMul || op == kDiv) {
1268 // Simplify a * 1 = a, a / 1 = a, a * -1 = -a, a / -1 = -a
1269 if (value == 1) {
1270 return a;
1271 } else if (value == -1) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001272 return CreateSimplifiedInvariant(kNeg, nullptr, a);
Aart Bikd14c5952015-09-08 15:25:15 -07001273 }
Aart Bik471a2032015-09-04 18:22:11 -07001274 }
1275 } else if (b->operation == kNeg) {
Aart Bikd14c5952015-09-08 15:25:15 -07001276 // Simplify a + (-b) = a - b, a - (-b) = a + b, -(-b) = b.
1277 if (op == kAdd) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001278 return CreateSimplifiedInvariant(kSub, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -07001279 } else if (op == kSub) {
Aart Bik7d57d7f2015-12-09 14:39:48 -08001280 return CreateSimplifiedInvariant(kAdd, a, b->op_b);
Aart Bikd14c5952015-09-08 15:25:15 -07001281 } else if (op == kNeg) {
1282 return b->op_b;
Aart Bik471a2032015-09-04 18:22:11 -07001283 }
Aart Bik7d57d7f2015-12-09 14:39:48 -08001284 } else if (b->operation == kSub) {
1285 // Simplify - (a - b) = b - a.
1286 if (op == kNeg) {
1287 return CreateSimplifiedInvariant(kSub, b->op_b, b->op_a);
1288 }
Aart Bik471a2032015-09-04 18:22:11 -07001289 }
Vladimir Markoca6fff82017-10-03 14:49:14 +01001290 return new (graph_->GetAllocator()) InductionInfo(
Aart Bike6bd0272016-12-16 13:57:52 -08001291 kInvariant, op, a, b, nullptr, ImplicitConversion(b->type));
Aart Bik471a2032015-09-04 18:22:11 -07001292}
1293
Aart Bikd0a022d2016-12-13 11:22:31 -08001294HInstruction* HInductionVarAnalysis::GetShiftConstant(HLoopInformation* loop,
1295 HInstruction* instruction,
1296 InductionInfo* initial) {
1297 DCHECK(instruction->IsShl() || instruction->IsShr() || instruction->IsUShr());
1298 // Shift-rights are only the same as division for non-negative initial inputs.
1299 // Otherwise we would round incorrectly.
1300 if (initial != nullptr) {
1301 int64_t value = -1;
1302 if (!IsAtLeast(initial, &value) || value < 0) {
1303 return nullptr;
1304 }
1305 }
1306 // Obtain the constant needed to treat shift as equivalent multiplication or division.
1307 // This yields an existing instruction if the constant is already there. Otherwise, this
1308 // has a side effect on the HIR. The restriction on the shift factor avoids generating a
1309 // negative constant (viz. 1 << 31 and 1L << 63 set the sign bit). The code assumes that
1310 // generalization for shift factors outside [0,32) and [0,64) ranges is done earlier.
Aart Bikc071a012016-12-01 10:22:31 -08001311 InductionInfo* b = LookupInfo(loop, instruction->InputAt(1));
1312 int64_t value = -1;
1313 if (IsExact(b, &value)) {
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001314 DataType::Type type = instruction->InputAt(0)->GetType();
1315 if (type == DataType::Type::kInt32 && 0 <= value && value < 31) {
Aart Bikc071a012016-12-01 10:22:31 -08001316 return graph_->GetIntConstant(1 << value);
1317 }
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001318 if (type == DataType::Type::kInt64 && 0 <= value && value < 63) {
Aart Bikc071a012016-12-01 10:22:31 -08001319 return graph_->GetLongConstant(1L << value);
1320 }
1321 }
1322 return nullptr;
1323}
Aart Bikcc42be02016-10-20 16:14:16 -07001324
1325void HInductionVarAnalysis::AssignCycle(HPhi* phi) {
1326 ArenaSet<HInstruction*>* set = &cycles_.Put(phi, ArenaSet<HInstruction*>(
Vladimir Markoca6fff82017-10-03 14:49:14 +01001327 graph_->GetAllocator()->Adapter(kArenaAllocInductionVarAnalysis)))->second;
Aart Bikcc42be02016-10-20 16:14:16 -07001328 for (HInstruction* i : scc_) {
1329 set->insert(i);
1330 }
1331}
1332
1333ArenaSet<HInstruction*>* HInductionVarAnalysis::LookupCycle(HPhi* phi) {
1334 auto it = cycles_.find(phi);
1335 if (it != cycles_.end()) {
1336 return &it->second;
1337 }
1338 return nullptr;
1339}
1340
Aart Bik97412c922016-02-19 20:14:38 -08001341bool HInductionVarAnalysis::IsExact(InductionInfo* info, int64_t* value) {
1342 return InductionVarRange(this).IsConstant(info, InductionVarRange::kExact, value);
1343}
1344
1345bool HInductionVarAnalysis::IsAtMost(InductionInfo* info, int64_t* value) {
1346 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtMost, value);
1347}
1348
1349bool HInductionVarAnalysis::IsAtLeast(InductionInfo* info, int64_t* value) {
1350 return InductionVarRange(this).IsConstant(info, InductionVarRange::kAtLeast, value);
Aart Bik7d57d7f2015-12-09 14:39:48 -08001351}
1352
Aart Bike6bd0272016-12-16 13:57:52 -08001353bool HInductionVarAnalysis::IsNarrowingLinear(InductionInfo* info) {
1354 return info != nullptr &&
1355 info->induction_class == kLinear &&
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001356 (info->type == DataType::Type::kUint8 ||
1357 info->type == DataType::Type::kInt8 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001358 info->type == DataType::Type::kUint16 ||
Vladimir Markod5d2f2c2017-09-26 12:37:26 +01001359 info->type == DataType::Type::kInt16 ||
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001360 (info->type == DataType::Type::kInt32 && (info->op_a->type == DataType::Type::kInt64 ||
1361 info->op_b->type == DataType::Type::kInt64)));
Aart Bike6bd0272016-12-16 13:57:52 -08001362}
1363
Aart Bik30efb4e2015-07-30 12:14:31 -07001364bool HInductionVarAnalysis::InductionEqual(InductionInfo* info1,
1365 InductionInfo* info2) {
1366 // Test structural equality only, without accounting for simplifications.
1367 if (info1 != nullptr && info2 != nullptr) {
1368 return
1369 info1->induction_class == info2->induction_class &&
1370 info1->operation == info2->operation &&
1371 info1->fetch == info2->fetch &&
Aart Bik78296912016-03-25 13:14:53 -07001372 info1->type == info2->type &&
Aart Bik30efb4e2015-07-30 12:14:31 -07001373 InductionEqual(info1->op_a, info2->op_a) &&
1374 InductionEqual(info1->op_b, info2->op_b);
1375 }
1376 // Otherwise only two nullptrs are considered equal.
1377 return info1 == info2;
1378}
1379
Aart Bikc071a012016-12-01 10:22:31 -08001380std::string HInductionVarAnalysis::FetchToString(HInstruction* fetch) {
1381 DCHECK(fetch != nullptr);
1382 if (fetch->IsIntConstant()) {
1383 return std::to_string(fetch->AsIntConstant()->GetValue());
1384 } else if (fetch->IsLongConstant()) {
1385 return std::to_string(fetch->AsLongConstant()->GetValue());
1386 }
1387 return std::to_string(fetch->GetId()) + ":" + fetch->DebugName();
1388}
1389
Aart Bik30efb4e2015-07-30 12:14:31 -07001390std::string HInductionVarAnalysis::InductionToString(InductionInfo* info) {
1391 if (info != nullptr) {
1392 if (info->induction_class == kInvariant) {
1393 std::string inv = "(";
1394 inv += InductionToString(info->op_a);
1395 switch (info->operation) {
Aart Bik22f05872015-10-27 15:56:28 -07001396 case kNop: inv += " @ "; break;
1397 case kAdd: inv += " + "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001398 case kSub:
Aart Bik22f05872015-10-27 15:56:28 -07001399 case kNeg: inv += " - "; break;
1400 case kMul: inv += " * "; break;
1401 case kDiv: inv += " / "; break;
Aart Bikdf7822e2016-12-06 10:05:30 -08001402 case kRem: inv += " % "; break;
Aart Bik7dc96932016-10-12 10:01:05 -07001403 case kXor: inv += " ^ "; break;
Aart Bik22f05872015-10-27 15:56:28 -07001404 case kLT: inv += " < "; break;
1405 case kLE: inv += " <= "; break;
1406 case kGT: inv += " > "; break;
1407 case kGE: inv += " >= "; break;
Aart Bikc071a012016-12-01 10:22:31 -08001408 case kFetch: inv += FetchToString(info->fetch); break;
Aart Bik22f05872015-10-27 15:56:28 -07001409 case kTripCountInLoop: inv += " (TC-loop) "; break;
1410 case kTripCountInBody: inv += " (TC-body) "; break;
1411 case kTripCountInLoopUnsafe: inv += " (TC-loop-unsafe) "; break;
1412 case kTripCountInBodyUnsafe: inv += " (TC-body-unsafe) "; break;
Aart Bik30efb4e2015-07-30 12:14:31 -07001413 }
1414 inv += InductionToString(info->op_b);
Aart Bik0d345cf2016-03-16 10:49:38 -07001415 inv += ")";
1416 return inv;
Aart Bik30efb4e2015-07-30 12:14:31 -07001417 } else {
Aart Bik30efb4e2015-07-30 12:14:31 -07001418 if (info->induction_class == kLinear) {
Aart Bikdf7822e2016-12-06 10:05:30 -08001419 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001420 return "(" + InductionToString(info->op_a) + " * i + " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001421 InductionToString(info->op_b) + "):" +
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001422 DataType::PrettyDescriptor(info->type);
Aart Bikc071a012016-12-01 10:22:31 -08001423 } else if (info->induction_class == kPolynomial) {
Aart Bikdf7822e2016-12-06 10:05:30 -08001424 DCHECK(info->operation == kNop);
1425 return "poly(sum_lt(" + InductionToString(info->op_a) + ") + " +
Aart Bikc071a012016-12-01 10:22:31 -08001426 InductionToString(info->op_b) + "):" +
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001427 DataType::PrettyDescriptor(info->type);
Aart Bikc071a012016-12-01 10:22:31 -08001428 } else if (info->induction_class == kGeometric) {
Aart Bikdf7822e2016-12-06 10:05:30 -08001429 DCHECK(info->operation == kMul || info->operation == kDiv);
Aart Bikc071a012016-12-01 10:22:31 -08001430 DCHECK(info->fetch != nullptr);
Aart Bikdf7822e2016-12-06 10:05:30 -08001431 return "geo(" + InductionToString(info->op_a) + " * " +
1432 FetchToString(info->fetch) +
1433 (info->operation == kMul ? " ^ i + " : " ^ -i + ") +
1434 InductionToString(info->op_b) + "):" +
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001435 DataType::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001436 } else if (info->induction_class == kWrapAround) {
Aart Bikdf7822e2016-12-06 10:05:30 -08001437 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001438 return "wrap(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001439 InductionToString(info->op_b) + "):" +
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001440 DataType::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001441 } else if (info->induction_class == kPeriodic) {
Aart Bikdf7822e2016-12-06 10:05:30 -08001442 DCHECK(info->operation == kNop);
Aart Bik30efb4e2015-07-30 12:14:31 -07001443 return "periodic(" + InductionToString(info->op_a) + ", " +
Aart Bik0d345cf2016-03-16 10:49:38 -07001444 InductionToString(info->op_b) + "):" +
Vladimir Marko0ebe0d82017-09-21 22:50:39 +01001445 DataType::PrettyDescriptor(info->type);
Aart Bik30efb4e2015-07-30 12:14:31 -07001446 }
1447 }
1448 }
1449 return "";
1450}
1451
1452} // namespace art