blob: 473057caf5a55b184d1926be551adfb5fae1b7ca [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
69#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
77#include "llvm/Support/ManagedStatic.h"
78#include "llvm/Support/MathExtras.h"
79#include "llvm/Support/Streams.h"
80#include "llvm/ADT/Statistic.h"
81#include <ostream>
82#include <algorithm>
83#include <cmath>
84using namespace llvm;
85
86STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman089efff2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Dan Gohman089efff2008-05-13 00:00:25 +0000104static RegisterPass<ScalarEvolution>
105R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106char ScalarEvolution::ID = 0;
107
108//===----------------------------------------------------------------------===//
109// SCEV class definitions
110//===----------------------------------------------------------------------===//
111
112//===----------------------------------------------------------------------===//
113// Implementation of the SCEV class.
114//
115SCEV::~SCEV() {}
116void SCEV::dump() const {
117 print(cerr);
118}
119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120uint32_t SCEV::getBitWidth() const {
121 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
122 return ITy->getBitWidth();
123 return 0;
124}
125
Dan Gohman7b560c42008-06-18 16:23:07 +0000126bool SCEV::isZero() const {
127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
128 return SC->getValue()->isZero();
129 return false;
130}
131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132
133SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
134
135bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
137 return false;
138}
139
140const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 return 0;
143}
144
145bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
150SCEVHandle SCEVCouldNotCompute::
151replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000152 const SCEVHandle &Conc,
153 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 return this;
155}
156
157void SCEVCouldNotCompute::print(std::ostream &OS) const {
158 OS << "***COULDNOTCOMPUTE***";
159}
160
161bool SCEVCouldNotCompute::classof(const SCEV *S) {
162 return S->getSCEVType() == scCouldNotCompute;
163}
164
165
166// SCEVConstants - Only allow the creation of one SCEVConstant for any
167// particular value. Don't use a SCEVHandle here, or else the object will
168// never be deleted!
169static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
170
171
172SCEVConstant::~SCEVConstant() {
173 SCEVConstants->erase(V);
174}
175
Dan Gohman89f85052007-10-22 18:31:58 +0000176SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 SCEVConstant *&R = (*SCEVConstants)[V];
178 if (R == 0) R = new SCEVConstant(V);
179 return R;
180}
181
Dan Gohman89f85052007-10-22 18:31:58 +0000182SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
183 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184}
185
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186const Type *SCEVConstant::getType() const { return V->getType(); }
187
188void SCEVConstant::print(std::ostream &OS) const {
189 WriteAsOperand(OS, V, false);
190}
191
192// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
193// particular input. Don't use a SCEVHandle here, or else the object will
194// never be deleted!
195static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
196 SCEVTruncateExpr*> > SCEVTruncates;
197
198SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
199 : SCEV(scTruncate), Op(op), Ty(ty) {
200 assert(Op->getType()->isInteger() && Ty->isInteger() &&
201 "Cannot truncate non-integer value!");
202 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
203 && "This is not a truncating conversion!");
204}
205
206SCEVTruncateExpr::~SCEVTruncateExpr() {
207 SCEVTruncates->erase(std::make_pair(Op, Ty));
208}
209
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
212}
213
214// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215// particular input. Don't use a SCEVHandle here, or else the object will never
216// be deleted!
217static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> > SCEVZeroExtends;
219
220SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
221 : SCEV(scZeroExtend), Op(op), Ty(ty) {
222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
223 "Cannot zero extend non-integer value!");
224 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
225 && "This is not an extending conversion!");
226}
227
228SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
229 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
230}
231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232void SCEVZeroExtendExpr::print(std::ostream &OS) const {
233 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
234}
235
236// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
237// particular input. Don't use a SCEVHandle here, or else the object will never
238// be deleted!
239static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
240 SCEVSignExtendExpr*> > SCEVSignExtends;
241
242SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
243 : SCEV(scSignExtend), Op(op), Ty(ty) {
244 assert(Op->getType()->isInteger() && Ty->isInteger() &&
245 "Cannot sign extend non-integer value!");
246 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
247 && "This is not an extending conversion!");
248}
249
250SCEVSignExtendExpr::~SCEVSignExtendExpr() {
251 SCEVSignExtends->erase(std::make_pair(Op, Ty));
252}
253
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254void SCEVSignExtendExpr::print(std::ostream &OS) const {
255 OS << "(signextend " << *Op << " to " << *Ty << ")";
256}
257
258// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
259// particular input. Don't use a SCEVHandle here, or else the object will never
260// be deleted!
261static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
262 SCEVCommutativeExpr*> > SCEVCommExprs;
263
264SCEVCommutativeExpr::~SCEVCommutativeExpr() {
265 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
266 std::vector<SCEV*>(Operands.begin(),
267 Operands.end())));
268}
269
270void SCEVCommutativeExpr::print(std::ostream &OS) const {
271 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
272 const char *OpStr = getOperationStr();
273 OS << "(" << *Operands[0];
274 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
275 OS << OpStr << *Operands[i];
276 OS << ")";
277}
278
279SCEVHandle SCEVCommutativeExpr::
280replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000281 const SCEVHandle &Conc,
282 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000284 SCEVHandle H =
285 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 if (H != getOperand(i)) {
287 std::vector<SCEVHandle> NewOps;
288 NewOps.reserve(getNumOperands());
289 for (unsigned j = 0; j != i; ++j)
290 NewOps.push_back(getOperand(j));
291 NewOps.push_back(H);
292 for (++i; i != e; ++i)
293 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000294 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
296 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000297 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000299 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000300 else if (isa<SCEVSMaxExpr>(this))
301 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000302 else if (isa<SCEVUMaxExpr>(this))
303 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 else
305 assert(0 && "Unknown commutative expr!");
306 }
307 }
308 return this;
309}
310
311
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000312// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313// input. Don't use a SCEVHandle here, or else the object will never be
314// deleted!
315static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000316 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000318SCEVUDivExpr::~SCEVUDivExpr() {
319 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320}
321
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000322void SCEVUDivExpr::print(std::ostream &OS) const {
323 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324}
325
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000326const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 return LHS->getType();
328}
329
330// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
331// particular input. Don't use a SCEVHandle here, or else the object will never
332// be deleted!
333static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
334 SCEVAddRecExpr*> > SCEVAddRecExprs;
335
336SCEVAddRecExpr::~SCEVAddRecExpr() {
337 SCEVAddRecExprs->erase(std::make_pair(L,
338 std::vector<SCEV*>(Operands.begin(),
339 Operands.end())));
340}
341
342SCEVHandle SCEVAddRecExpr::
343replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000344 const SCEVHandle &Conc,
345 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000347 SCEVHandle H =
348 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 if (H != getOperand(i)) {
350 std::vector<SCEVHandle> NewOps;
351 NewOps.reserve(getNumOperands());
352 for (unsigned j = 0; j != i; ++j)
353 NewOps.push_back(getOperand(j));
354 NewOps.push_back(H);
355 for (++i; i != e; ++i)
356 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000357 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358
Dan Gohman89f85052007-10-22 18:31:58 +0000359 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 }
361 }
362 return this;
363}
364
365
366bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
367 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
368 // contain L and if the start is invariant.
369 return !QueryLoop->contains(L->getHeader()) &&
370 getOperand(0)->isLoopInvariant(QueryLoop);
371}
372
373
374void SCEVAddRecExpr::print(std::ostream &OS) const {
375 OS << "{" << *Operands[0];
376 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
377 OS << ",+," << *Operands[i];
378 OS << "}<" << L->getHeader()->getName() + ">";
379}
380
381// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
382// value. Don't use a SCEVHandle here, or else the object will never be
383// deleted!
384static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
385
386SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
387
388bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
389 // All non-instruction values are loop invariant. All instructions are loop
390 // invariant if they are not contained in the specified loop.
391 if (Instruction *I = dyn_cast<Instruction>(V))
392 return !L->contains(I->getParent());
393 return true;
394}
395
396const Type *SCEVUnknown::getType() const {
397 return V->getType();
398}
399
400void SCEVUnknown::print(std::ostream &OS) const {
401 WriteAsOperand(OS, V, false);
402}
403
404//===----------------------------------------------------------------------===//
405// SCEV Utilities
406//===----------------------------------------------------------------------===//
407
408namespace {
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
411 /// expressions.
412 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000413 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return LHS->getSCEVType() < RHS->getSCEVType();
415 }
416 };
417}
418
419/// GroupByComplexity - Given a list of SCEV objects, order them by their
420/// complexity, and group objects of the same complexity together by value.
421/// When this routine is finished, we know that any duplicates in the vector are
422/// consecutive and that complexity is monotonically increasing.
423///
424/// Note that we go take special precautions to ensure that we get determinstic
425/// results from this routine. In other words, we don't want the results of
426/// this to depend on where the addresses of various SCEV objects happened to
427/// land in memory.
428///
429static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
430 if (Ops.size() < 2) return; // Noop
431 if (Ops.size() == 2) {
432 // This is the common case, which also happens to be trivially simple.
433 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000434 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 std::swap(Ops[0], Ops[1]);
436 return;
437 }
438
439 // Do the rough sort by complexity.
440 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
441
442 // Now that we are sorted by complexity, group elements of the same
443 // complexity. Note that this is, at worst, N^2, but the vector is likely to
444 // be extremely short in practice. Note that we take this approach because we
445 // do not want to depend on the addresses of the objects we are grouping.
446 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
447 SCEV *S = Ops[i];
448 unsigned Complexity = S->getSCEVType();
449
450 // If there are any objects of the same complexity and same value as this
451 // one, group them.
452 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
453 if (Ops[j] == S) { // Found a duplicate.
454 // Move it to immediately after i'th element.
455 std::swap(Ops[i+1], Ops[j]);
456 ++i; // no need to rescan it.
457 if (i == e-2) return; // Done!
458 }
459 }
460 }
461}
462
463
464
465//===----------------------------------------------------------------------===//
466// Simple SCEV method implementations
467//===----------------------------------------------------------------------===//
468
469/// getIntegerSCEV - Given an integer or FP type, create a constant for the
470/// specified signed integer value and return a SCEV for the constant.
Dan Gohman89f85052007-10-22 18:31:58 +0000471SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 Constant *C;
473 if (Val == 0)
474 C = Constant::getNullValue(Ty);
475 else if (Ty->isFloatingPoint())
Chris Lattner5e0610f2008-04-20 00:41:09 +0000476 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
477 APFloat::IEEEdouble, Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 else
479 C = ConstantInt::get(Ty, Val);
Dan Gohman89f85052007-10-22 18:31:58 +0000480 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481}
482
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
484///
Dan Gohman89f85052007-10-22 18:31:58 +0000485SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman89f85052007-10-22 18:31:58 +0000487 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488
Nick Lewycky0cf58682008-02-20 06:58:55 +0000489 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000490}
491
492/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
493SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
494 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
495 return getUnknown(ConstantExpr::getNot(VC->getValue()));
496
Nick Lewycky0cf58682008-02-20 06:58:55 +0000497 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000498 return getMinusSCEV(AllOnes, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499}
500
501/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
502///
Dan Gohman89f85052007-10-22 18:31:58 +0000503SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
504 const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 // X - Y --> X + -Y
Dan Gohman89f85052007-10-22 18:31:58 +0000506 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507}
508
509
Eli Friedman7489ec92008-08-04 23:49:06 +0000510/// BinomialCoefficient - Compute BC(It, K). The result has width W.
511// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000512static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000513 ScalarEvolution &SE,
514 const IntegerType* ResultTy) {
515 // Handle the simplest case efficiently.
516 if (K == 1)
517 return SE.getTruncateOrZeroExtend(It, ResultTy);
518
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000519 // We are using the following formula for BC(It, K):
520 //
521 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
522 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000523 // Suppose, W is the bitwidth of the return value. We must be prepared for
524 // overflow. Hence, we must assure that the result of our computation is
525 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
526 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000527 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000528 // However, this code doesn't use exactly that formula; the formula it uses
529 // is something like the following, where T is the number of factors of 2 in
530 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
531 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000532 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000533 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000534 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000535 // This formula is trivially equivalent to the previous formula. However,
536 // this formula can be implemented much more efficiently. The trick is that
537 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
538 // arithmetic. To do exact division in modular arithmetic, all we have
539 // to do is multiply by the inverse. Therefore, this step can be done at
540 // width W.
541 //
542 // The next issue is how to safely do the division by 2^T. The way this
543 // is done is by doing the multiplication step at a width of at least W + T
544 // bits. This way, the bottom W+T bits of the product are accurate. Then,
545 // when we perform the division by 2^T (which is equivalent to a right shift
546 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
547 // truncated out after the division by 2^T.
548 //
549 // In comparison to just directly using the first formula, this technique
550 // is much more efficient; using the first formula requires W * K bits,
551 // but this formula less than W + K bits. Also, the first formula requires
552 // a division step, whereas this formula only requires multiplies and shifts.
553 //
554 // It doesn't matter whether the subtraction step is done in the calculation
555 // width or the input iteration count's width; if the subtraction overflows,
556 // the result must be zero anyway. We prefer here to do it in the width of
557 // the induction variable because it helps a lot for certain cases; CodeGen
558 // isn't smart enough to ignore the overflow, which leads to much less
559 // efficient code if the width of the subtraction is wider than the native
560 // register width.
561 //
562 // (It's possible to not widen at all by pulling out factors of 2 before
563 // the multiplication; for example, K=2 can be calculated as
564 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
565 // extra arithmetic, so it's not an obvious win, and it gets
566 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000567
Eli Friedman7489ec92008-08-04 23:49:06 +0000568 // Protection from insane SCEVs; this bound is conservative,
569 // but it probably doesn't matter.
570 if (K > 1000)
571 return new SCEVCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000572
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 unsigned W = ResultTy->getBitWidth();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000574
Eli Friedman7489ec92008-08-04 23:49:06 +0000575 // Calculate K! / 2^T and T; we divide out the factors of two before
576 // multiplying for calculating K! / 2^T to avoid overflow.
577 // Other overflow doesn't matter because we only care about the bottom
578 // W bits of the result.
579 APInt OddFactorial(W, 1);
580 unsigned T = 1;
581 for (unsigned i = 3; i <= K; ++i) {
582 APInt Mult(W, i);
583 unsigned TwoFactors = Mult.countTrailingZeros();
584 T += TwoFactors;
585 Mult = Mult.lshr(TwoFactors);
586 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000587 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000588
Eli Friedman7489ec92008-08-04 23:49:06 +0000589 // We need at least W + T bits for the multiplication step
590 // FIXME: A temporary hack; we round up the bitwidths
591 // to the nearest power of 2 to be nice to the code generator.
592 unsigned CalculationBits = 1U << Log2_32_Ceil(W + T);
593 // FIXME: Temporary hack to avoid generating integers that are too wide.
594 // Although, it's not completely clear how to determine how much
595 // widening is safe; for example, on X86, we can't really widen
596 // beyond 64 because we need to be able to do multiplication
597 // that's CalculationBits wide, but on X86-64, we can safely widen up to
598 // 128 bits.
599 if (CalculationBits > 64)
600 return new SCEVCouldNotCompute();
601
602 // Calcuate 2^T, at width T+W.
603 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
604
605 // Calculate the multiplicative inverse of K! / 2^T;
606 // this multiplication factor will perform the exact division by
607 // K! / 2^T.
608 APInt Mod = APInt::getSignedMinValue(W+1);
609 APInt MultiplyFactor = OddFactorial.zext(W+1);
610 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
611 MultiplyFactor = MultiplyFactor.trunc(W);
612
613 // Calculate the product, at width T+W
614 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
615 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
616 for (unsigned i = 1; i != K; ++i) {
617 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
618 Dividend = SE.getMulExpr(Dividend,
619 SE.getTruncateOrZeroExtend(S, CalculationTy));
620 }
621
622 // Divide by 2^T
623 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
624
625 // Truncate the result, and divide by K! / 2^T.
626
627 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
628 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629}
630
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000631/// evaluateAtIteration - Return the value of this chain of recurrences at
632/// the specified iteration number. We can evaluate this recurrence by
633/// multiplying each element in the chain by the binomial coefficient
634/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
635///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000636/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000638/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639///
Dan Gohman89f85052007-10-22 18:31:58 +0000640SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
641 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000642 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000644 // The computation is correct in the face of overflow provided that the
645 // multiplication is performed _after_ the evaluation of the binomial
646 // coefficient.
Eli Friedman7489ec92008-08-04 23:49:06 +0000647 SCEVHandle Val =
648 SE.getMulExpr(getOperand(i),
649 BinomialCoefficient(It, i, SE,
650 cast<IntegerType>(getType())));
Dan Gohman89f85052007-10-22 18:31:58 +0000651 Result = SE.getAddExpr(Result, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000652 }
653 return Result;
654}
655
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656//===----------------------------------------------------------------------===//
657// SCEV Expression folder implementations
658//===----------------------------------------------------------------------===//
659
Dan Gohman89f85052007-10-22 18:31:58 +0000660SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000662 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000663 ConstantExpr::getTrunc(SC->getValue(), Ty));
664
665 // If the input value is a chrec scev made out of constants, truncate
666 // all of the constants.
667 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
668 std::vector<SCEVHandle> Operands;
669 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
670 // FIXME: This should allow truncation of other expression types!
671 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000672 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000673 else
674 break;
675 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000676 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677 }
678
Nick Lewyckyd96819f2008-10-04 11:19:07 +0000679 if (isa<SCEVCouldNotCompute>(Op))
680 return new SCEVCouldNotCompute();
681
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
683 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
684 return Result;
685}
686
Dan Gohman89f85052007-10-22 18:31:58 +0000687SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000688 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000689 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 ConstantExpr::getZExt(SC->getValue(), Ty));
691
692 // FIXME: If the input value is a chrec scev, and we can prove that the value
693 // did not overflow the old, smaller, value, we can zero extend all of the
694 // operands (often constants). This would allow analysis of something like
695 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
696
Nick Lewyckyd96819f2008-10-04 11:19:07 +0000697 if (isa<SCEVCouldNotCompute>(Op))
698 return new SCEVCouldNotCompute();
699
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
701 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
702 return Result;
703}
704
Dan Gohman89f85052007-10-22 18:31:58 +0000705SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000706 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000707 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000708 ConstantExpr::getSExt(SC->getValue(), Ty));
709
710 // FIXME: If the input value is a chrec scev, and we can prove that the value
711 // did not overflow the old, smaller, value, we can sign extend all of the
712 // operands (often constants). This would allow analysis of something like
713 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
714
Nick Lewyckyd96819f2008-10-04 11:19:07 +0000715 if (isa<SCEVCouldNotCompute>(Op))
716 return new SCEVCouldNotCompute();
717
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
719 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
720 return Result;
721}
722
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000723/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
724/// of the input value to the specified type. If the type must be
725/// extended, it is zero extended.
726SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
727 const Type *Ty) {
728 const Type *SrcTy = V->getType();
729 assert(SrcTy->isInteger() && Ty->isInteger() &&
730 "Cannot truncate or zero extend with non-integer arguments!");
731 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
732 return V; // No conversion
733 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
734 return getTruncateExpr(V, Ty);
735 return getZeroExtendExpr(V, Ty);
736}
737
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000738// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000739SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 assert(!Ops.empty() && "Cannot get empty add!");
741 if (Ops.size() == 1) return Ops[0];
742
743 // Sort by complexity, this groups all similar expression types together.
744 GroupByComplexity(Ops);
745
Nick Lewyckyd96819f2008-10-04 11:19:07 +0000746 // Could not compute plus anything equals could not compute.
747 if (isa<SCEVCouldNotCompute>(Ops.back()))
748 return new SCEVCouldNotCompute();
749
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 // If there are any constants, fold them together.
751 unsigned Idx = 0;
752 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
753 ++Idx;
754 assert(Idx < Ops.size());
755 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
756 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000757 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
758 RHSC->getValue()->getValue());
759 Ops[0] = getConstant(Fold);
760 Ops.erase(Ops.begin()+1); // Erase the folded element
761 if (Ops.size() == 1) return Ops[0];
762 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000763 }
764
765 // If we are left with a constant zero being added, strip it off.
766 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
767 Ops.erase(Ops.begin());
768 --Idx;
769 }
770 }
771
772 if (Ops.size() == 1) return Ops[0];
773
774 // Okay, check to see if the same value occurs in the operand list twice. If
775 // so, merge them together into an multiply expression. Since we sorted the
776 // list, these values are required to be adjacent.
777 const Type *Ty = Ops[0]->getType();
778 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
779 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
780 // Found a match, merge the two values into a multiply, and add any
781 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000782 SCEVHandle Two = getIntegerSCEV(2, Ty);
783 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000784 if (Ops.size() == 2)
785 return Mul;
786 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
787 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000788 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 }
790
791 // Now we know the first non-constant operand. Skip past any cast SCEVs.
792 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
793 ++Idx;
794
795 // If there are add operands they would be next.
796 if (Idx < Ops.size()) {
797 bool DeletedAdd = false;
798 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
799 // If we have an add, expand the add operands onto the end of the operands
800 // list.
801 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
802 Ops.erase(Ops.begin()+Idx);
803 DeletedAdd = true;
804 }
805
806 // If we deleted at least one add, we added operands to the end of the list,
807 // and they are not necessarily sorted. Recurse to resort and resimplify
808 // any operands we just aquired.
809 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000810 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 }
812
813 // Skip over the add expression until we get to a multiply.
814 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
815 ++Idx;
816
817 // If we are adding something to a multiply expression, make sure the
818 // something is not already an operand of the multiply. If so, merge it into
819 // the multiply.
820 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
821 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
822 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
823 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
824 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
825 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
826 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
827 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
828 if (Mul->getNumOperands() != 2) {
829 // If the multiply has more than two operands, we must get the
830 // Y*Z term.
831 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
832 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000833 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 }
Dan Gohman89f85052007-10-22 18:31:58 +0000835 SCEVHandle One = getIntegerSCEV(1, Ty);
836 SCEVHandle AddOne = getAddExpr(InnerMul, One);
837 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 if (Ops.size() == 2) return OuterMul;
839 if (AddOp < Idx) {
840 Ops.erase(Ops.begin()+AddOp);
841 Ops.erase(Ops.begin()+Idx-1);
842 } else {
843 Ops.erase(Ops.begin()+Idx);
844 Ops.erase(Ops.begin()+AddOp-1);
845 }
846 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000847 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 }
849
850 // Check this multiply against other multiplies being added together.
851 for (unsigned OtherMulIdx = Idx+1;
852 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
853 ++OtherMulIdx) {
854 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
855 // If MulOp occurs in OtherMul, we can fold the two multiplies
856 // together.
857 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
858 OMulOp != e; ++OMulOp)
859 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
860 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
861 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
862 if (Mul->getNumOperands() != 2) {
863 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
864 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000865 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 }
867 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
868 if (OtherMul->getNumOperands() != 2) {
869 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
870 OtherMul->op_end());
871 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000872 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 }
Dan Gohman89f85052007-10-22 18:31:58 +0000874 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
875 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000876 if (Ops.size() == 2) return OuterMul;
877 Ops.erase(Ops.begin()+Idx);
878 Ops.erase(Ops.begin()+OtherMulIdx-1);
879 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000880 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000881 }
882 }
883 }
884 }
885
886 // If there are any add recurrences in the operands list, see if any other
887 // added values are loop invariant. If so, we can fold them into the
888 // recurrence.
889 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
890 ++Idx;
891
892 // Scan over all recurrences, trying to fold loop invariants into them.
893 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
894 // Scan all of the other operands to this add and add them to the vector if
895 // they are loop invariant w.r.t. the recurrence.
896 std::vector<SCEVHandle> LIOps;
897 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
898 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
899 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
900 LIOps.push_back(Ops[i]);
901 Ops.erase(Ops.begin()+i);
902 --i; --e;
903 }
904
905 // If we found some loop invariants, fold them into the recurrence.
906 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +0000907 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 LIOps.push_back(AddRec->getStart());
909
910 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000911 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000912
Dan Gohman89f85052007-10-22 18:31:58 +0000913 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 // If all of the other operands were loop invariant, we are done.
915 if (Ops.size() == 1) return NewRec;
916
917 // Otherwise, add the folded AddRec by the non-liv parts.
918 for (unsigned i = 0;; ++i)
919 if (Ops[i] == AddRec) {
920 Ops[i] = NewRec;
921 break;
922 }
Dan Gohman89f85052007-10-22 18:31:58 +0000923 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000924 }
925
926 // Okay, if there weren't any loop invariants to be folded, check to see if
927 // there are multiple AddRec's with the same loop induction variable being
928 // added together. If so, we can fold them.
929 for (unsigned OtherIdx = Idx+1;
930 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
931 if (OtherIdx != Idx) {
932 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
933 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
934 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
935 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
936 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
937 if (i >= NewOps.size()) {
938 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
939 OtherAddRec->op_end());
940 break;
941 }
Dan Gohman89f85052007-10-22 18:31:58 +0000942 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 }
Dan Gohman89f85052007-10-22 18:31:58 +0000944 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000945
946 if (Ops.size() == 2) return NewAddRec;
947
948 Ops.erase(Ops.begin()+Idx);
949 Ops.erase(Ops.begin()+OtherIdx-1);
950 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000951 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 }
953 }
954
955 // Otherwise couldn't fold anything into this recurrence. Move onto the
956 // next one.
957 }
958
959 // Okay, it looks like we really DO need an add expr. Check to see if we
960 // already have one, otherwise create a new one.
961 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
962 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
963 SCEVOps)];
964 if (Result == 0) Result = new SCEVAddExpr(Ops);
965 return Result;
966}
967
968
Dan Gohman89f85052007-10-22 18:31:58 +0000969SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000970 assert(!Ops.empty() && "Cannot get empty mul!");
971
972 // Sort by complexity, this groups all similar expression types together.
973 GroupByComplexity(Ops);
974
Nick Lewyckyd96819f2008-10-04 11:19:07 +0000975 if (isa<SCEVCouldNotCompute>(Ops.back())) {
976 // CNC * 0 = 0
977 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
978 if (Ops[i]->getSCEVType() != scConstant)
979 break;
980
981 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
982 if (SC->getValue()->isMinValue(false))
983 return SC;
984 }
985
986 // Otherwise, we can't compute it.
987 return new SCEVCouldNotCompute();
988 }
989
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 // If there are any constants, fold them together.
991 unsigned Idx = 0;
992 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
993
994 // C1*(C2+V) -> C1*C2 + C1*V
995 if (Ops.size() == 2)
996 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
997 if (Add->getNumOperands() == 2 &&
998 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000999 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1000 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001
1002
1003 ++Idx;
1004 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1005 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001006 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1007 RHSC->getValue()->getValue());
1008 Ops[0] = getConstant(Fold);
1009 Ops.erase(Ops.begin()+1); // Erase the folded element
1010 if (Ops.size() == 1) return Ops[0];
1011 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 }
1013
1014 // If we are left with a constant one being multiplied, strip it off.
1015 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1016 Ops.erase(Ops.begin());
1017 --Idx;
1018 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1019 // If we have a multiply of zero, it will always be zero.
1020 return Ops[0];
1021 }
1022 }
1023
1024 // Skip over the add expression until we get to a multiply.
1025 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1026 ++Idx;
1027
1028 if (Ops.size() == 1)
1029 return Ops[0];
1030
1031 // If there are mul operands inline them all into this expression.
1032 if (Idx < Ops.size()) {
1033 bool DeletedMul = false;
1034 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
1035 // If we have an mul, expand the mul operands onto the end of the operands
1036 // list.
1037 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1038 Ops.erase(Ops.begin()+Idx);
1039 DeletedMul = true;
1040 }
1041
1042 // If we deleted at least one mul, we added operands to the end of the list,
1043 // and they are not necessarily sorted. Recurse to resort and resimplify
1044 // any operands we just aquired.
1045 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001046 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 }
1048
1049 // If there are any add recurrences in the operands list, see if any other
1050 // added values are loop invariant. If so, we can fold them into the
1051 // recurrence.
1052 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1053 ++Idx;
1054
1055 // Scan over all recurrences, trying to fold loop invariants into them.
1056 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1057 // Scan all of the other operands to this mul and add them to the vector if
1058 // they are loop invariant w.r.t. the recurrence.
1059 std::vector<SCEVHandle> LIOps;
1060 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1061 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1062 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1063 LIOps.push_back(Ops[i]);
1064 Ops.erase(Ops.begin()+i);
1065 --i; --e;
1066 }
1067
1068 // If we found some loop invariants, fold them into the recurrence.
1069 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001070 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071 std::vector<SCEVHandle> NewOps;
1072 NewOps.reserve(AddRec->getNumOperands());
1073 if (LIOps.size() == 1) {
1074 SCEV *Scale = LIOps[0];
1075 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001076 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001077 } else {
1078 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1079 std::vector<SCEVHandle> MulOps(LIOps);
1080 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001081 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001082 }
1083 }
1084
Dan Gohman89f85052007-10-22 18:31:58 +00001085 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086
1087 // If all of the other operands were loop invariant, we are done.
1088 if (Ops.size() == 1) return NewRec;
1089
1090 // Otherwise, multiply the folded AddRec by the non-liv parts.
1091 for (unsigned i = 0;; ++i)
1092 if (Ops[i] == AddRec) {
1093 Ops[i] = NewRec;
1094 break;
1095 }
Dan Gohman89f85052007-10-22 18:31:58 +00001096 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 }
1098
1099 // Okay, if there weren't any loop invariants to be folded, check to see if
1100 // there are multiple AddRec's with the same loop induction variable being
1101 // multiplied together. If so, we can fold them.
1102 for (unsigned OtherIdx = Idx+1;
1103 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1104 if (OtherIdx != Idx) {
1105 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1106 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1107 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1108 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001109 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001110 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001111 SCEVHandle B = F->getStepRecurrence(*this);
1112 SCEVHandle D = G->getStepRecurrence(*this);
1113 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1114 getMulExpr(G, B),
1115 getMulExpr(B, D));
1116 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1117 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 if (Ops.size() == 2) return NewAddRec;
1119
1120 Ops.erase(Ops.begin()+Idx);
1121 Ops.erase(Ops.begin()+OtherIdx-1);
1122 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001123 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 }
1125 }
1126
1127 // Otherwise couldn't fold anything into this recurrence. Move onto the
1128 // next one.
1129 }
1130
1131 // Okay, it looks like we really DO need an mul expr. Check to see if we
1132 // already have one, otherwise create a new one.
1133 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1134 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1135 SCEVOps)];
1136 if (Result == 0)
1137 Result = new SCEVMulExpr(Ops);
1138 return Result;
1139}
1140
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001141SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1143 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001144 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145
1146 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1147 Constant *LHSCV = LHSC->getValue();
1148 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001149 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150 }
1151 }
1152
1153 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1154
Nick Lewyckyd96819f2008-10-04 11:19:07 +00001155 if (isa<SCEVCouldNotCompute>(LHS) || isa<SCEVCouldNotCompute>(RHS))
1156 return new SCEVCouldNotCompute();
1157
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001158 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1159 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001160 return Result;
1161}
1162
1163
1164/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1165/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001166SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001167 const SCEVHandle &Step, const Loop *L) {
1168 std::vector<SCEVHandle> Operands;
1169 Operands.push_back(Start);
1170 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1171 if (StepChrec->getLoop() == L) {
1172 Operands.insert(Operands.end(), StepChrec->op_begin(),
1173 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001174 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001175 }
1176
1177 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001178 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001179}
1180
1181/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1182/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001183SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 const Loop *L) {
1185 if (Operands.size() == 1) return Operands[0];
1186
Dan Gohman7b560c42008-06-18 16:23:07 +00001187 if (Operands.back()->isZero()) {
1188 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001189 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001190 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001191
Dan Gohman42936882008-08-08 18:33:12 +00001192 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
1193 if (SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
1194 const Loop* NestedLoop = NestedAR->getLoop();
1195 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1196 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1197 NestedAR->op_end());
1198 SCEVHandle NestedARHandle(NestedAR);
1199 Operands[0] = NestedAR->getStart();
1200 NestedOperands[0] = getAddRecExpr(Operands, L);
1201 return getAddRecExpr(NestedOperands, NestedLoop);
1202 }
1203 }
1204
Nick Lewyckyd96819f2008-10-04 11:19:07 +00001205 // Refuse to build an AddRec out of SCEVCouldNotCompute.
1206 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1207 if (isa<SCEVCouldNotCompute>(Operands[i]))
1208 return new SCEVCouldNotCompute();
1209 }
1210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 SCEVAddRecExpr *&Result =
1212 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1213 Operands.end()))];
1214 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1215 return Result;
1216}
1217
Nick Lewycky711640a2007-11-25 22:41:31 +00001218SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1219 const SCEVHandle &RHS) {
1220 std::vector<SCEVHandle> Ops;
1221 Ops.push_back(LHS);
1222 Ops.push_back(RHS);
1223 return getSMaxExpr(Ops);
1224}
1225
1226SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1227 assert(!Ops.empty() && "Cannot get empty smax!");
1228 if (Ops.size() == 1) return Ops[0];
1229
1230 // Sort by complexity, this groups all similar expression types together.
1231 GroupByComplexity(Ops);
1232
Nick Lewyckyd96819f2008-10-04 11:19:07 +00001233 if (isa<SCEVCouldNotCompute>(Ops.back())) {
1234 // CNC smax +inf = +inf.
1235 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
1236 if (Ops[i]->getSCEVType() != scConstant)
1237 break;
1238
1239 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
1240 if (SC->getValue()->isMaxValue(true))
1241 return SC;
1242 }
1243
1244 // Otherwise, we can't compute it.
1245 return new SCEVCouldNotCompute();
1246 }
1247
Nick Lewycky711640a2007-11-25 22:41:31 +00001248 // If there are any constants, fold them together.
1249 unsigned Idx = 0;
1250 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1251 ++Idx;
1252 assert(Idx < Ops.size());
1253 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1254 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001255 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001256 APIntOps::smax(LHSC->getValue()->getValue(),
1257 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001258 Ops[0] = getConstant(Fold);
1259 Ops.erase(Ops.begin()+1); // Erase the folded element
1260 if (Ops.size() == 1) return Ops[0];
1261 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001262 }
1263
1264 // If we are left with a constant -inf, strip it off.
1265 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1266 Ops.erase(Ops.begin());
1267 --Idx;
1268 }
1269 }
1270
1271 if (Ops.size() == 1) return Ops[0];
1272
1273 // Find the first SMax
1274 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1275 ++Idx;
1276
1277 // Check to see if one of the operands is an SMax. If so, expand its operands
1278 // onto our operand list, and recurse to simplify.
1279 if (Idx < Ops.size()) {
1280 bool DeletedSMax = false;
1281 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1282 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1283 Ops.erase(Ops.begin()+Idx);
1284 DeletedSMax = true;
1285 }
1286
1287 if (DeletedSMax)
1288 return getSMaxExpr(Ops);
1289 }
1290
1291 // Okay, check to see if the same value occurs in the operand list twice. If
1292 // so, delete one. Since we sorted the list, these values are required to
1293 // be adjacent.
1294 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1295 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1296 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1297 --i; --e;
1298 }
1299
1300 if (Ops.size() == 1) return Ops[0];
1301
1302 assert(!Ops.empty() && "Reduced smax down to nothing!");
1303
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001304 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001305 // already have one, otherwise create a new one.
1306 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1307 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1308 SCEVOps)];
1309 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1310 return Result;
1311}
1312
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001313SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1314 const SCEVHandle &RHS) {
1315 std::vector<SCEVHandle> Ops;
1316 Ops.push_back(LHS);
1317 Ops.push_back(RHS);
1318 return getUMaxExpr(Ops);
1319}
1320
1321SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1322 assert(!Ops.empty() && "Cannot get empty umax!");
1323 if (Ops.size() == 1) return Ops[0];
1324
1325 // Sort by complexity, this groups all similar expression types together.
1326 GroupByComplexity(Ops);
1327
Nick Lewyckyd96819f2008-10-04 11:19:07 +00001328 if (isa<SCEVCouldNotCompute>(Ops[0])) {
1329 // CNC umax inf = inf.
1330 for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
1331 if (Ops[i]->getSCEVType() != scConstant)
1332 break;
1333
1334 SCEVConstant *SC = cast<SCEVConstant>(Ops[i]);
1335 if (SC->getValue()->isMaxValue(false))
1336 return SC;
1337 }
1338
1339 // Otherwise, we can't compute it.
1340 return new SCEVCouldNotCompute();
1341 }
1342
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001343 // If there are any constants, fold them together.
1344 unsigned Idx = 0;
1345 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1346 ++Idx;
1347 assert(Idx < Ops.size());
1348 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1349 // We found two constants, fold them together!
1350 ConstantInt *Fold = ConstantInt::get(
1351 APIntOps::umax(LHSC->getValue()->getValue(),
1352 RHSC->getValue()->getValue()));
1353 Ops[0] = getConstant(Fold);
1354 Ops.erase(Ops.begin()+1); // Erase the folded element
1355 if (Ops.size() == 1) return Ops[0];
1356 LHSC = cast<SCEVConstant>(Ops[0]);
1357 }
1358
1359 // If we are left with a constant zero, strip it off.
1360 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1361 Ops.erase(Ops.begin());
1362 --Idx;
1363 }
1364 }
1365
1366 if (Ops.size() == 1) return Ops[0];
1367
1368 // Find the first UMax
1369 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1370 ++Idx;
1371
1372 // Check to see if one of the operands is a UMax. If so, expand its operands
1373 // onto our operand list, and recurse to simplify.
1374 if (Idx < Ops.size()) {
1375 bool DeletedUMax = false;
1376 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1377 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1378 Ops.erase(Ops.begin()+Idx);
1379 DeletedUMax = true;
1380 }
1381
1382 if (DeletedUMax)
1383 return getUMaxExpr(Ops);
1384 }
1385
1386 // Okay, check to see if the same value occurs in the operand list twice. If
1387 // so, delete one. Since we sorted the list, these values are required to
1388 // be adjacent.
1389 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1390 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1391 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1392 --i; --e;
1393 }
1394
1395 if (Ops.size() == 1) return Ops[0];
1396
1397 assert(!Ops.empty() && "Reduced umax down to nothing!");
1398
1399 // Okay, it looks like we really DO need a umax expr. Check to see if we
1400 // already have one, otherwise create a new one.
1401 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1402 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1403 SCEVOps)];
1404 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1405 return Result;
1406}
1407
Dan Gohman89f85052007-10-22 18:31:58 +00001408SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001410 return getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1412 if (Result == 0) Result = new SCEVUnknown(V);
1413 return Result;
1414}
1415
1416
1417//===----------------------------------------------------------------------===//
1418// ScalarEvolutionsImpl Definition and Implementation
1419//===----------------------------------------------------------------------===//
1420//
1421/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1422/// evolution code.
1423///
1424namespace {
1425 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001426 /// SE - A reference to the public ScalarEvolution object.
1427 ScalarEvolution &SE;
1428
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 /// F - The function we are analyzing.
1430 ///
1431 Function &F;
1432
1433 /// LI - The loop information for the function we are currently analyzing.
1434 ///
1435 LoopInfo &LI;
1436
1437 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1438 /// things.
1439 SCEVHandle UnknownValue;
1440
1441 /// Scalars - This is a cache of the scalars we have analyzed so far.
1442 ///
1443 std::map<Value*, SCEVHandle> Scalars;
1444
1445 /// IterationCounts - Cache the iteration count of the loops for this
1446 /// function as they are computed.
1447 std::map<const Loop*, SCEVHandle> IterationCounts;
1448
1449 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1450 /// the PHI instructions that we attempt to compute constant evolutions for.
1451 /// This allows us to avoid potentially expensive recomputation of these
1452 /// properties. An instruction maps to null if we are unable to compute its
1453 /// exit value.
1454 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1455
1456 public:
Dan Gohman89f85052007-10-22 18:31:58 +00001457 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1458 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001459
1460 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1461 /// expression and create a new one.
1462 SCEVHandle getSCEV(Value *V);
1463
1464 /// hasSCEV - Return true if the SCEV for this value has already been
1465 /// computed.
1466 bool hasSCEV(Value *V) const {
1467 return Scalars.count(V);
1468 }
1469
1470 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1471 /// the specified value.
1472 void setSCEV(Value *V, const SCEVHandle &H) {
1473 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1474 assert(isNew && "This entry already existed!");
1475 }
1476
1477
1478 /// getSCEVAtScope - Compute the value of the specified expression within
1479 /// the indicated loop (which may be null to indicate in no loop). If the
1480 /// expression cannot be evaluated, return UnknownValue itself.
1481 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1482
1483
1484 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1485 /// an analyzable loop-invariant iteration count.
1486 bool hasLoopInvariantIterationCount(const Loop *L);
1487
1488 /// getIterationCount - If the specified loop has a predictable iteration
1489 /// count, return it. Note that it is not valid to call this method on a
1490 /// loop without a loop-invariant iteration count.
1491 SCEVHandle getIterationCount(const Loop *L);
1492
1493 /// deleteValueFromRecords - This method should be called by the
1494 /// client before it removes a value from the program, to make sure
1495 /// that no dangling references are left around.
1496 void deleteValueFromRecords(Value *V);
1497
1498 private:
1499 /// createSCEV - We know that there is no SCEV for the specified value.
1500 /// Analyze the expression.
1501 SCEVHandle createSCEV(Value *V);
1502
1503 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1504 /// SCEVs.
1505 SCEVHandle createNodeForPHI(PHINode *PN);
1506
1507 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1508 /// for the specified instruction and replaces any references to the
1509 /// symbolic value SymName with the specified value. This is used during
1510 /// PHI resolution.
1511 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1512 const SCEVHandle &SymName,
1513 const SCEVHandle &NewVal);
1514
1515 /// ComputeIterationCount - Compute the number of times the specified loop
1516 /// will iterate.
1517 SCEVHandle ComputeIterationCount(const Loop *L);
1518
1519 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001520 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1522 Constant *RHS,
1523 const Loop *L,
1524 ICmpInst::Predicate p);
1525
1526 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1527 /// constant number of times (the condition evolves only from constants),
1528 /// try to evaluate a few iterations of the loop until we get the exit
1529 /// condition gets a value of ExitWhen (true or false). If we cannot
1530 /// evaluate the trip count of the loop, return UnknownValue.
1531 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1532 bool ExitWhen);
1533
1534 /// HowFarToZero - Return the number of times a backedge comparing the
1535 /// specified value to zero will execute. If not computable, return
1536 /// UnknownValue.
1537 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1538
1539 /// HowFarToNonZero - Return the number of times a backedge checking the
1540 /// specified value for nonzero will execute. If not computable, return
1541 /// UnknownValue.
1542 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1543
1544 /// HowManyLessThans - Return the number of times a backedge containing the
1545 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001546 /// UnknownValue. isSigned specifies whether the less-than is signed.
1547 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1548 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001549
Dan Gohman1cddf972008-09-15 22:18:04 +00001550 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
1551 /// (which may not be an immediate predecessor) which has exactly one
1552 /// successor from which BB is reachable, or null if no such block is
1553 /// found.
1554 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
1555
Nick Lewycky1b020bf2008-07-12 07:41:32 +00001556 /// executesAtLeastOnce - Test whether entry to the loop is protected by
1557 /// a conditional between LHS and RHS.
1558 bool executesAtLeastOnce(const Loop *L, bool isSigned, SCEV *LHS, SCEV *RHS);
1559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1561 /// in the header of its containing loop, we know the loop executes a
1562 /// constant number of times, and the PHI node is just a recurrence
1563 /// involving constants, fold it.
1564 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1565 const Loop *L);
1566 };
1567}
1568
1569//===----------------------------------------------------------------------===//
1570// Basic SCEV Analysis and PHI Idiom Recognition Code
1571//
1572
1573/// deleteValueFromRecords - This method should be called by the
1574/// client before it removes an instruction from the program, to make sure
1575/// that no dangling references are left around.
1576void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1577 SmallVector<Value *, 16> Worklist;
1578
1579 if (Scalars.erase(V)) {
1580 if (PHINode *PN = dyn_cast<PHINode>(V))
1581 ConstantEvolutionLoopExitValue.erase(PN);
1582 Worklist.push_back(V);
1583 }
1584
1585 while (!Worklist.empty()) {
1586 Value *VV = Worklist.back();
1587 Worklist.pop_back();
1588
1589 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1590 UI != UE; ++UI) {
1591 Instruction *Inst = cast<Instruction>(*UI);
1592 if (Scalars.erase(Inst)) {
1593 if (PHINode *PN = dyn_cast<PHINode>(VV))
1594 ConstantEvolutionLoopExitValue.erase(PN);
1595 Worklist.push_back(Inst);
1596 }
1597 }
1598 }
1599}
1600
1601
1602/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1603/// expression and create a new one.
1604SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1605 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1606
1607 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1608 if (I != Scalars.end()) return I->second;
1609 SCEVHandle S = createSCEV(V);
1610 Scalars.insert(std::make_pair(V, S));
1611 return S;
1612}
1613
1614/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1615/// the specified instruction and replaces any references to the symbolic value
1616/// SymName with the specified value. This is used during PHI resolution.
1617void ScalarEvolutionsImpl::
1618ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1619 const SCEVHandle &NewVal) {
1620 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1621 if (SI == Scalars.end()) return;
1622
1623 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001624 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 if (NV == SI->second) return; // No change.
1626
1627 SI->second = NV; // Update the scalars map!
1628
1629 // Any instruction values that use this instruction might also need to be
1630 // updated!
1631 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1632 UI != E; ++UI)
1633 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1634}
1635
1636/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1637/// a loop header, making it a potential recurrence, or it doesn't.
1638///
1639SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1640 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1641 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1642 if (L->getHeader() == PN->getParent()) {
1643 // If it lives in the loop header, it has two incoming values, one
1644 // from outside the loop, and one from inside.
1645 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1646 unsigned BackEdge = IncomingEdge^1;
1647
1648 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001649 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001650 assert(Scalars.find(PN) == Scalars.end() &&
1651 "PHI node already processed?");
1652 Scalars.insert(std::make_pair(PN, SymbolicName));
1653
1654 // Using this symbolic name for the PHI, analyze the value coming around
1655 // the back-edge.
1656 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1657
1658 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1659 // has a special value for the first iteration of the loop.
1660
1661 // If the value coming around the backedge is an add with the symbolic
1662 // value we just inserted, then we found a simple induction variable!
1663 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1664 // If there is a single occurrence of the symbolic value, replace it
1665 // with a recurrence.
1666 unsigned FoundIndex = Add->getNumOperands();
1667 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1668 if (Add->getOperand(i) == SymbolicName)
1669 if (FoundIndex == e) {
1670 FoundIndex = i;
1671 break;
1672 }
1673
1674 if (FoundIndex != Add->getNumOperands()) {
1675 // Create an add with everything but the specified operand.
1676 std::vector<SCEVHandle> Ops;
1677 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1678 if (i != FoundIndex)
1679 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001680 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001681
1682 // This is not a valid addrec if the step amount is varying each
1683 // loop iteration, but is not itself an addrec in this loop.
1684 if (Accum->isLoopInvariant(L) ||
1685 (isa<SCEVAddRecExpr>(Accum) &&
1686 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1687 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001688 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689
1690 // Okay, for the entire analysis of this edge we assumed the PHI
1691 // to be symbolic. We now need to go back and update all of the
1692 // entries for the scalars that use the PHI (except for the PHI
1693 // itself) to use the new analyzed value instead of the "symbolic"
1694 // value.
1695 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1696 return PHISCEV;
1697 }
1698 }
1699 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1700 // Otherwise, this could be a loop like this:
1701 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1702 // In this case, j = {1,+,1} and BEValue is j.
1703 // Because the other in-value of i (0) fits the evolution of BEValue
1704 // i really is an addrec evolution.
1705 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1706 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1707
1708 // If StartVal = j.start - j.stride, we can use StartVal as the
1709 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001710 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1711 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001713 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714
1715 // Okay, for the entire analysis of this edge we assumed the PHI
1716 // to be symbolic. We now need to go back and update all of the
1717 // entries for the scalars that use the PHI (except for the PHI
1718 // itself) to use the new analyzed value instead of the "symbolic"
1719 // value.
1720 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1721 return PHISCEV;
1722 }
1723 }
1724 }
1725
1726 return SymbolicName;
1727 }
1728
1729 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001730 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731}
1732
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001733/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1734/// guaranteed to end in (at every loop iteration). It is, at the same time,
1735/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1736/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1737static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1738 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001739 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001741 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001742 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1743
1744 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1745 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1746 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1747 }
1748
1749 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1750 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1751 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1752 }
1753
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001754 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001755 // The result is the min of all operands results.
1756 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1757 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1758 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1759 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001760 }
1761
1762 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001763 // The result is the sum of all operands results.
1764 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1765 uint32_t BitWidth = M->getBitWidth();
1766 for (unsigned i = 1, e = M->getNumOperands();
1767 SumOpRes != BitWidth && i != e; ++i)
1768 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1769 BitWidth);
1770 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001771 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001773 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001774 // The result is the min of all operands results.
1775 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1776 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1777 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1778 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001780
Nick Lewycky711640a2007-11-25 22:41:31 +00001781 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1782 // The result is the min of all operands results.
1783 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1784 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1785 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1786 return MinOpRes;
1787 }
1788
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001789 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1790 // The result is the min of all operands results.
1791 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1792 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1793 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1794 return MinOpRes;
1795 }
1796
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001797 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001798 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001799}
1800
1801/// createSCEV - We know that there is no SCEV for the specified value.
1802/// Analyze the expression.
1803///
1804SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner3fff4642007-11-23 08:46:22 +00001805 if (!isa<IntegerType>(V->getType()))
1806 return SE.getUnknown(V);
1807
Dan Gohman3996f472008-06-22 19:56:46 +00001808 unsigned Opcode = Instruction::UserOp1;
1809 if (Instruction *I = dyn_cast<Instruction>(V))
1810 Opcode = I->getOpcode();
1811 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1812 Opcode = CE->getOpcode();
1813 else
1814 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001815
Dan Gohman3996f472008-06-22 19:56:46 +00001816 User *U = cast<User>(V);
1817 switch (Opcode) {
1818 case Instruction::Add:
1819 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1820 getSCEV(U->getOperand(1)));
1821 case Instruction::Mul:
1822 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1823 getSCEV(U->getOperand(1)));
1824 case Instruction::UDiv:
1825 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1826 getSCEV(U->getOperand(1)));
1827 case Instruction::Sub:
1828 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1829 getSCEV(U->getOperand(1)));
1830 case Instruction::Or:
1831 // If the RHS of the Or is a constant, we may have something like:
1832 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1833 // optimizations will transparently handle this case.
1834 //
1835 // In order for this transformation to be safe, the LHS must be of the
1836 // form X*(2^n) and the Or constant must be less than 2^n.
1837 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1838 SCEVHandle LHS = getSCEV(U->getOperand(0));
1839 const APInt &CIVal = CI->getValue();
1840 if (GetMinTrailingZeros(LHS) >=
1841 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1842 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001843 }
Dan Gohman3996f472008-06-22 19:56:46 +00001844 break;
1845 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001846 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001847 // If the RHS of the xor is a signbit, then this is just an add.
1848 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001849 if (CI->getValue().isSignBit())
1850 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1851 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001852
1853 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001854 else if (CI->isAllOnesValue())
1855 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1856 }
1857 break;
1858
1859 case Instruction::Shl:
1860 // Turn shift left of a constant amount into a multiply.
1861 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1862 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1863 Constant *X = ConstantInt::get(
1864 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1865 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1866 }
1867 break;
1868
Nick Lewycky7fd27892008-07-07 06:15:49 +00001869 case Instruction::LShr:
1870 // Turn logical shift right of a constant into a unsigned divide.
1871 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1872 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1873 Constant *X = ConstantInt::get(
1874 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1875 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1876 }
1877 break;
1878
Dan Gohman3996f472008-06-22 19:56:46 +00001879 case Instruction::Trunc:
1880 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1881
1882 case Instruction::ZExt:
1883 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1884
1885 case Instruction::SExt:
1886 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1887
1888 case Instruction::BitCast:
1889 // BitCasts are no-op casts so we just eliminate the cast.
1890 if (U->getType()->isInteger() &&
1891 U->getOperand(0)->getType()->isInteger())
1892 return getSCEV(U->getOperand(0));
1893 break;
1894
1895 case Instruction::PHI:
1896 return createNodeForPHI(cast<PHINode>(U));
1897
1898 case Instruction::Select:
1899 // This could be a smax or umax that was lowered earlier.
1900 // Try to recover it.
1901 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1902 Value *LHS = ICI->getOperand(0);
1903 Value *RHS = ICI->getOperand(1);
1904 switch (ICI->getPredicate()) {
1905 case ICmpInst::ICMP_SLT:
1906 case ICmpInst::ICMP_SLE:
1907 std::swap(LHS, RHS);
1908 // fall through
1909 case ICmpInst::ICMP_SGT:
1910 case ICmpInst::ICMP_SGE:
1911 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1912 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1913 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00001914 // ~smax(~x, ~y) == smin(x, y).
1915 return SE.getNotSCEV(SE.getSMaxExpr(
1916 SE.getNotSCEV(getSCEV(LHS)),
1917 SE.getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00001918 break;
1919 case ICmpInst::ICMP_ULT:
1920 case ICmpInst::ICMP_ULE:
1921 std::swap(LHS, RHS);
1922 // fall through
1923 case ICmpInst::ICMP_UGT:
1924 case ICmpInst::ICMP_UGE:
1925 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1926 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1927 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1928 // ~umax(~x, ~y) == umin(x, y)
1929 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1930 SE.getNotSCEV(getSCEV(RHS))));
1931 break;
1932 default:
1933 break;
1934 }
1935 }
1936
1937 default: // We cannot analyze this expression.
1938 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939 }
1940
Dan Gohman89f85052007-10-22 18:31:58 +00001941 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942}
1943
1944
1945
1946//===----------------------------------------------------------------------===//
1947// Iteration Count Computation Code
1948//
1949
1950/// getIterationCount - If the specified loop has a predictable iteration
1951/// count, return it. Note that it is not valid to call this method on a
1952/// loop without a loop-invariant iteration count.
1953SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1954 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1955 if (I == IterationCounts.end()) {
1956 SCEVHandle ItCount = ComputeIterationCount(L);
1957 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1958 if (ItCount != UnknownValue) {
1959 assert(ItCount->isLoopInvariant(L) &&
1960 "Computed trip count isn't loop invariant for loop!");
1961 ++NumTripCountsComputed;
1962 } else if (isa<PHINode>(L->getHeader()->begin())) {
1963 // Only count loops that have phi nodes as not being computable.
1964 ++NumTripCountsNotComputed;
1965 }
1966 }
1967 return I->second;
1968}
1969
1970/// ComputeIterationCount - Compute the number of times the specified loop
1971/// will iterate.
1972SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1973 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001974 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001975 L->getExitBlocks(ExitBlocks);
1976 if (ExitBlocks.size() != 1) return UnknownValue;
1977
1978 // Okay, there is one exit block. Try to find the condition that causes the
1979 // loop to be exited.
1980 BasicBlock *ExitBlock = ExitBlocks[0];
1981
1982 BasicBlock *ExitingBlock = 0;
1983 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1984 PI != E; ++PI)
1985 if (L->contains(*PI)) {
1986 if (ExitingBlock == 0)
1987 ExitingBlock = *PI;
1988 else
1989 return UnknownValue; // More than one block exiting!
1990 }
1991 assert(ExitingBlock && "No exits from loop, something is broken!");
1992
1993 // Okay, we've computed the exiting block. See what condition causes us to
1994 // exit.
1995 //
1996 // FIXME: we should be able to handle switch instructions (with a single exit)
1997 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1998 if (ExitBr == 0) return UnknownValue;
1999 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2000
2001 // At this point, we know we have a conditional branch that determines whether
2002 // the loop is exited. However, we don't know if the branch is executed each
2003 // time through the loop. If not, then the execution count of the branch will
2004 // not be equal to the trip count of the loop.
2005 //
2006 // Currently we check for this by checking to see if the Exit branch goes to
2007 // the loop header. If so, we know it will always execute the same number of
2008 // times as the loop. We also handle the case where the exit block *is* the
2009 // loop header. This is common for un-rotated loops. More extensive analysis
2010 // could be done to handle more cases here.
2011 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2012 ExitBr->getSuccessor(1) != L->getHeader() &&
2013 ExitBr->getParent() != L->getHeader())
2014 return UnknownValue;
2015
2016 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2017
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002018 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002019 // Note that ICmpInst deals with pointer comparisons too so we must check
2020 // the type of the operand.
2021 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
2022 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
2023 ExitBr->getSuccessor(0) == ExitBlock);
2024
2025 // If the condition was exit on true, convert the condition to exit on false
2026 ICmpInst::Predicate Cond;
2027 if (ExitBr->getSuccessor(1) == ExitBlock)
2028 Cond = ExitCond->getPredicate();
2029 else
2030 Cond = ExitCond->getInversePredicate();
2031
2032 // Handle common loops like: for (X = "string"; *X; ++X)
2033 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2034 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2035 SCEVHandle ItCnt =
2036 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
2037 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2038 }
2039
2040 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2041 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2042
2043 // Try to evaluate any dependencies out of the loop.
2044 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2045 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2046 Tmp = getSCEVAtScope(RHS, L);
2047 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2048
2049 // At this point, we would like to compute how many iterations of the
2050 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002051 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2052 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 std::swap(LHS, RHS);
2054 Cond = ICmpInst::getSwappedPredicate(Cond);
2055 }
2056
2057 // FIXME: think about handling pointer comparisons! i.e.:
2058 // while (P != P+100) ++P;
2059
2060 // If we have a comparison of a chrec against a constant, try to use value
2061 // ranges to answer this query.
2062 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2063 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
2064 if (AddRec->getLoop() == L) {
2065 // Form the comparison range using the constant of the correct type so
2066 // that the ConstantRange class knows to do a signed or unsigned
2067 // comparison.
2068 ConstantInt *CompVal = RHSC->getValue();
2069 const Type *RealTy = ExitCond->getOperand(0)->getType();
2070 CompVal = dyn_cast<ConstantInt>(
2071 ConstantExpr::getBitCast(CompVal, RealTy));
2072 if (CompVal) {
2073 // Form the constant range.
2074 ConstantRange CompRange(
2075 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2076
Dan Gohman89f85052007-10-22 18:31:58 +00002077 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002078 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2079 }
2080 }
2081
2082 switch (Cond) {
2083 case ICmpInst::ICMP_NE: { // while (X != Y)
2084 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00002085 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002086 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2087 break;
2088 }
2089 case ICmpInst::ICMP_EQ: {
2090 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00002091 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2093 break;
2094 }
2095 case ICmpInst::ICMP_SLT: {
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002096 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002097 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2098 break;
2099 }
2100 case ICmpInst::ICMP_SGT: {
Eli Friedman0dcd4ed2008-07-30 00:04:08 +00002101 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
2102 SE.getNotSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002103 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2104 break;
2105 }
2106 case ICmpInst::ICMP_ULT: {
2107 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
2108 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2109 break;
2110 }
2111 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00002112 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky347e4222008-05-06 04:03:18 +00002113 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002114 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2115 break;
2116 }
2117 default:
2118#if 0
2119 cerr << "ComputeIterationCount ";
2120 if (ExitCond->getOperand(0)->getType()->isUnsigned())
2121 cerr << "[unsigned] ";
2122 cerr << *LHS << " "
2123 << Instruction::getOpcodeName(Instruction::ICmp)
2124 << " " << *RHS << "\n";
2125#endif
2126 break;
2127 }
2128 return ComputeIterationCountExhaustively(L, ExitCond,
2129 ExitBr->getSuccessor(0) == ExitBlock);
2130}
2131
2132static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002133EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2134 ScalarEvolution &SE) {
2135 SCEVHandle InVal = SE.getConstant(C);
2136 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 assert(isa<SCEVConstant>(Val) &&
2138 "Evaluation of SCEV at constant didn't fold correctly?");
2139 return cast<SCEVConstant>(Val)->getValue();
2140}
2141
2142/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2143/// and a GEP expression (missing the pointer index) indexing into it, return
2144/// the addressed element of the initializer or null if the index expression is
2145/// invalid.
2146static Constant *
2147GetAddressedElementFromGlobal(GlobalVariable *GV,
2148 const std::vector<ConstantInt*> &Indices) {
2149 Constant *Init = GV->getInitializer();
2150 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2151 uint64_t Idx = Indices[i]->getZExtValue();
2152 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2153 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2154 Init = cast<Constant>(CS->getOperand(Idx));
2155 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2156 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2157 Init = cast<Constant>(CA->getOperand(Idx));
2158 } else if (isa<ConstantAggregateZero>(Init)) {
2159 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2160 assert(Idx < STy->getNumElements() && "Bad struct index!");
2161 Init = Constant::getNullValue(STy->getElementType(Idx));
2162 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2163 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2164 Init = Constant::getNullValue(ATy->getElementType());
2165 } else {
2166 assert(0 && "Unknown constant aggregate type!");
2167 }
2168 return 0;
2169 } else {
2170 return 0; // Unknown initializer type
2171 }
2172 }
2173 return Init;
2174}
2175
2176/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky347e4222008-05-06 04:03:18 +00002177/// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002178SCEVHandle ScalarEvolutionsImpl::
2179ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2180 const Loop *L,
2181 ICmpInst::Predicate predicate) {
2182 if (LI->isVolatile()) return UnknownValue;
2183
2184 // Check to see if the loaded pointer is a getelementptr of a global.
2185 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2186 if (!GEP) return UnknownValue;
2187
2188 // Make sure that it is really a constant global we are gepping, with an
2189 // initializer, and make sure the first IDX is really 0.
2190 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2191 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2192 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2193 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2194 return UnknownValue;
2195
2196 // Okay, we allow one non-constant index into the GEP instruction.
2197 Value *VarIdx = 0;
2198 std::vector<ConstantInt*> Indexes;
2199 unsigned VarIdxNum = 0;
2200 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2201 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2202 Indexes.push_back(CI);
2203 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2204 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2205 VarIdx = GEP->getOperand(i);
2206 VarIdxNum = i-2;
2207 Indexes.push_back(0);
2208 }
2209
2210 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2211 // Check to see if X is a loop variant variable value now.
2212 SCEVHandle Idx = getSCEV(VarIdx);
2213 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2214 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2215
2216 // We can only recognize very limited forms of loop index expressions, in
2217 // particular, only affine AddRec's like {C1,+,C2}.
2218 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2219 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2220 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2221 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2222 return UnknownValue;
2223
2224 unsigned MaxSteps = MaxBruteForceIterations;
2225 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2226 ConstantInt *ItCst =
2227 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002228 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002229
2230 // Form the GEP offset.
2231 Indexes[VarIdxNum] = Val;
2232
2233 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2234 if (Result == 0) break; // Cannot compute!
2235
2236 // Evaluate the condition for this iteration.
2237 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2238 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2239 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2240#if 0
2241 cerr << "\n***\n*** Computed loop count " << *ItCst
2242 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2243 << "***\n";
2244#endif
2245 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002246 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002247 }
2248 }
2249 return UnknownValue;
2250}
2251
2252
2253/// CanConstantFold - Return true if we can constant fold an instruction of the
2254/// specified type, assuming that all operands were constants.
2255static bool CanConstantFold(const Instruction *I) {
2256 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2257 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2258 return true;
2259
2260 if (const CallInst *CI = dyn_cast<CallInst>(I))
2261 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002262 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002263 return false;
2264}
2265
2266/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2267/// in the loop that V is derived from. We allow arbitrary operations along the
2268/// way, but the operands of an operation must either be constants or a value
2269/// derived from a constant PHI. If this expression does not fit with these
2270/// constraints, return null.
2271static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2272 // If this is not an instruction, or if this is an instruction outside of the
2273 // loop, it can't be derived from a loop PHI.
2274 Instruction *I = dyn_cast<Instruction>(V);
2275 if (I == 0 || !L->contains(I->getParent())) return 0;
2276
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002277 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002278 if (L->getHeader() == I->getParent())
2279 return PN;
2280 else
2281 // We don't currently keep track of the control flow needed to evaluate
2282 // PHIs, so we cannot handle PHIs inside of loops.
2283 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002284 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002285
2286 // If we won't be able to constant fold this expression even if the operands
2287 // are constants, return early.
2288 if (!CanConstantFold(I)) return 0;
2289
2290 // Otherwise, we can evaluate this instruction if all of its operands are
2291 // constant or derived from a PHI node themselves.
2292 PHINode *PHI = 0;
2293 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2294 if (!(isa<Constant>(I->getOperand(Op)) ||
2295 isa<GlobalValue>(I->getOperand(Op)))) {
2296 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2297 if (P == 0) return 0; // Not evolving from PHI
2298 if (PHI == 0)
2299 PHI = P;
2300 else if (PHI != P)
2301 return 0; // Evolving from multiple different PHIs.
2302 }
2303
2304 // This is a expression evolving from a constant PHI!
2305 return PHI;
2306}
2307
2308/// EvaluateExpression - Given an expression that passes the
2309/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2310/// in the loop has the value PHIVal. If we can't fold this expression for some
2311/// reason, return null.
2312static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2313 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 if (Constant *C = dyn_cast<Constant>(V)) return C;
2315 Instruction *I = cast<Instruction>(V);
2316
2317 std::vector<Constant*> Operands;
2318 Operands.resize(I->getNumOperands());
2319
2320 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2321 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2322 if (Operands[i] == 0) return 0;
2323 }
2324
Chris Lattnerd6e56912007-12-10 22:53:04 +00002325 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2326 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2327 &Operands[0], Operands.size());
2328 else
2329 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2330 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331}
2332
2333/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2334/// in the header of its containing loop, we know the loop executes a
2335/// constant number of times, and the PHI node is just a recurrence
2336/// involving constants, fold it.
2337Constant *ScalarEvolutionsImpl::
2338getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2339 std::map<PHINode*, Constant*>::iterator I =
2340 ConstantEvolutionLoopExitValue.find(PN);
2341 if (I != ConstantEvolutionLoopExitValue.end())
2342 return I->second;
2343
2344 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2345 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2346
2347 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2348
2349 // Since the loop is canonicalized, the PHI node must have two entries. One
2350 // entry must be a constant (coming in from outside of the loop), and the
2351 // second must be derived from the same PHI.
2352 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2353 Constant *StartCST =
2354 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2355 if (StartCST == 0)
2356 return RetVal = 0; // Must be a constant.
2357
2358 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2359 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2360 if (PN2 != PN)
2361 return RetVal = 0; // Not derived from same PHI.
2362
2363 // Execute the loop symbolically to determine the exit value.
2364 if (Its.getActiveBits() >= 32)
2365 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2366
2367 unsigned NumIterations = Its.getZExtValue(); // must be in range
2368 unsigned IterationNum = 0;
2369 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2370 if (IterationNum == NumIterations)
2371 return RetVal = PHIVal; // Got exit value!
2372
2373 // Compute the value of the PHI node for the next iteration.
2374 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2375 if (NextPHI == PHIVal)
2376 return RetVal = NextPHI; // Stopped evolving!
2377 if (NextPHI == 0)
2378 return 0; // Couldn't evaluate!
2379 PHIVal = NextPHI;
2380 }
2381}
2382
2383/// ComputeIterationCountExhaustively - If the trip is known to execute a
2384/// constant number of times (the condition evolves only from constants),
2385/// try to evaluate a few iterations of the loop until we get the exit
2386/// condition gets a value of ExitWhen (true or false). If we cannot
2387/// evaluate the trip count of the loop, return UnknownValue.
2388SCEVHandle ScalarEvolutionsImpl::
2389ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2390 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2391 if (PN == 0) return UnknownValue;
2392
2393 // Since the loop is canonicalized, the PHI node must have two entries. One
2394 // entry must be a constant (coming in from outside of the loop), and the
2395 // second must be derived from the same PHI.
2396 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2397 Constant *StartCST =
2398 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2399 if (StartCST == 0) return UnknownValue; // Must be a constant.
2400
2401 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2402 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2403 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2404
2405 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2406 // the loop symbolically to determine when the condition gets a value of
2407 // "ExitWhen".
2408 unsigned IterationNum = 0;
2409 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2410 for (Constant *PHIVal = StartCST;
2411 IterationNum != MaxIterations; ++IterationNum) {
2412 ConstantInt *CondVal =
2413 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2414
2415 // Couldn't symbolically evaluate.
2416 if (!CondVal) return UnknownValue;
2417
2418 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2419 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2420 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002421 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002422 }
2423
2424 // Compute the value of the PHI node for the next iteration.
2425 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2426 if (NextPHI == 0 || NextPHI == PHIVal)
2427 return UnknownValue; // Couldn't evaluate or not making progress...
2428 PHIVal = NextPHI;
2429 }
2430
2431 // Too many iterations were needed to evaluate.
2432 return UnknownValue;
2433}
2434
2435/// getSCEVAtScope - Compute the value of the specified expression within the
2436/// indicated loop (which may be null to indicate in no loop). If the
2437/// expression cannot be evaluated, return UnknownValue.
2438SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2439 // FIXME: this should be turned into a virtual method on SCEV!
2440
2441 if (isa<SCEVConstant>(V)) return V;
2442
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002443 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444 // exit value from the loop without using SCEVs.
2445 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2446 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2447 const Loop *LI = this->LI[I->getParent()];
2448 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2449 if (PHINode *PN = dyn_cast<PHINode>(I))
2450 if (PN->getParent() == LI->getHeader()) {
2451 // Okay, there is no closed form solution for the PHI node. Check
2452 // to see if the loop that contains it has a known iteration count.
2453 // If so, we may be able to force computation of the exit value.
2454 SCEVHandle IterationCount = getIterationCount(LI);
2455 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2456 // Okay, we know how many times the containing loop executes. If
2457 // this is a constant evolving PHI node, get the final value at
2458 // the specified iteration number.
2459 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2460 ICC->getValue()->getValue(),
2461 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002462 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002463 }
2464 }
2465
2466 // Okay, this is an expression that we cannot symbolically evaluate
2467 // into a SCEV. Check to see if it's possible to symbolically evaluate
2468 // the arguments into constants, and if so, try to constant propagate the
2469 // result. This is particularly useful for computing loop exit values.
2470 if (CanConstantFold(I)) {
2471 std::vector<Constant*> Operands;
2472 Operands.reserve(I->getNumOperands());
2473 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2474 Value *Op = I->getOperand(i);
2475 if (Constant *C = dyn_cast<Constant>(Op)) {
2476 Operands.push_back(C);
2477 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002478 // If any of the operands is non-constant and if they are
2479 // non-integer, don't even try to analyze them with scev techniques.
2480 if (!isa<IntegerType>(Op->getType()))
2481 return V;
2482
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002483 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2484 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2485 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2486 Op->getType(),
2487 false));
2488 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2489 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2490 Operands.push_back(ConstantExpr::getIntegerCast(C,
2491 Op->getType(),
2492 false));
2493 else
2494 return V;
2495 } else {
2496 return V;
2497 }
2498 }
2499 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002500
2501 Constant *C;
2502 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2503 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2504 &Operands[0], Operands.size());
2505 else
2506 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2507 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002508 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002509 }
2510 }
2511
2512 // This is some other type of SCEVUnknown, just return it.
2513 return V;
2514 }
2515
2516 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2517 // Avoid performing the look-up in the common case where the specified
2518 // expression has no loop-variant portions.
2519 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2520 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2521 if (OpAtScope != Comm->getOperand(i)) {
2522 if (OpAtScope == UnknownValue) return UnknownValue;
2523 // Okay, at least one of these operands is loop variant but might be
2524 // foldable. Build a new instance of the folded commutative expression.
2525 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2526 NewOps.push_back(OpAtScope);
2527
2528 for (++i; i != e; ++i) {
2529 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2530 if (OpAtScope == UnknownValue) return UnknownValue;
2531 NewOps.push_back(OpAtScope);
2532 }
2533 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002534 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002535 if (isa<SCEVMulExpr>(Comm))
2536 return SE.getMulExpr(NewOps);
2537 if (isa<SCEVSMaxExpr>(Comm))
2538 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002539 if (isa<SCEVUMaxExpr>(Comm))
2540 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002541 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002542 }
2543 }
2544 // If we got here, all operands are loop invariant.
2545 return Comm;
2546 }
2547
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002548 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2550 if (LHS == UnknownValue) return LHS;
2551 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2552 if (RHS == UnknownValue) return RHS;
2553 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2554 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002555 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 }
2557
2558 // If this is a loop recurrence for a loop that does not contain L, then we
2559 // are dealing with the final value computed by the loop.
2560 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2561 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2562 // To evaluate this recurrence, we need to know how many times the AddRec
2563 // loop iterates. Compute this now.
2564 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2565 if (IterationCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002566
Eli Friedman7489ec92008-08-04 23:49:06 +00002567 // Then, evaluate the AddRec.
Dan Gohman89f85052007-10-22 18:31:58 +00002568 return AddRec->evaluateAtIteration(IterationCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002569 }
2570 return UnknownValue;
2571 }
2572
2573 //assert(0 && "Unknown SCEV type!");
2574 return UnknownValue;
2575}
2576
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002577/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2578/// following equation:
2579///
2580/// A * X = B (mod N)
2581///
2582/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2583/// A and B isn't important.
2584///
2585/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2586static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2587 ScalarEvolution &SE) {
2588 uint32_t BW = A.getBitWidth();
2589 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2590 assert(A != 0 && "A must be non-zero.");
2591
2592 // 1. D = gcd(A, N)
2593 //
2594 // The gcd of A and N may have only one prime factor: 2. The number of
2595 // trailing zeros in A is its multiplicity
2596 uint32_t Mult2 = A.countTrailingZeros();
2597 // D = 2^Mult2
2598
2599 // 2. Check if B is divisible by D.
2600 //
2601 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2602 // is not less than multiplicity of this prime factor for D.
2603 if (B.countTrailingZeros() < Mult2)
2604 return new SCEVCouldNotCompute();
2605
2606 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2607 // modulo (N / D).
2608 //
2609 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2610 // bit width during computations.
2611 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2612 APInt Mod(BW + 1, 0);
2613 Mod.set(BW - Mult2); // Mod = N / D
2614 APInt I = AD.multiplicativeInverse(Mod);
2615
2616 // 4. Compute the minimum unsigned root of the equation:
2617 // I * (B / D) mod (N / D)
2618 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2619
2620 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2621 // bits.
2622 return SE.getConstant(Result.trunc(BW));
2623}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002624
2625/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2626/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2627/// might be the same) or two SCEVCouldNotCompute objects.
2628///
2629static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002630SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2632 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2633 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2634 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2635
2636 // We currently can only solve this if the coefficients are constants.
2637 if (!LC || !MC || !NC) {
2638 SCEV *CNC = new SCEVCouldNotCompute();
2639 return std::make_pair(CNC, CNC);
2640 }
2641
2642 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2643 const APInt &L = LC->getValue()->getValue();
2644 const APInt &M = MC->getValue()->getValue();
2645 const APInt &N = NC->getValue()->getValue();
2646 APInt Two(BitWidth, 2);
2647 APInt Four(BitWidth, 4);
2648
2649 {
2650 using namespace APIntOps;
2651 const APInt& C = L;
2652 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2653 // The B coefficient is M-N/2
2654 APInt B(M);
2655 B -= sdiv(N,Two);
2656
2657 // The A coefficient is N/2
2658 APInt A(N.sdiv(Two));
2659
2660 // Compute the B^2-4ac term.
2661 APInt SqrtTerm(B);
2662 SqrtTerm *= B;
2663 SqrtTerm -= Four * (A * C);
2664
2665 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2666 // integer value or else APInt::sqrt() will assert.
2667 APInt SqrtVal(SqrtTerm.sqrt());
2668
2669 // Compute the two solutions for the quadratic formula.
2670 // The divisions must be performed as signed divisions.
2671 APInt NegB(-B);
2672 APInt TwoA( A << 1 );
2673 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2674 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2675
Dan Gohman89f85052007-10-22 18:31:58 +00002676 return std::make_pair(SE.getConstant(Solution1),
2677 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 } // end APIntOps namespace
2679}
2680
2681/// HowFarToZero - Return the number of times a backedge comparing the specified
2682/// value to zero will execute. If not computable, return UnknownValue
2683SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2684 // If the value is a constant
2685 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2686 // If the value is already zero, the branch will execute zero times.
2687 if (C->getValue()->isZero()) return C;
2688 return UnknownValue; // Otherwise it will loop infinitely.
2689 }
2690
2691 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2692 if (!AddRec || AddRec->getLoop() != L)
2693 return UnknownValue;
2694
2695 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002696 // If this is an affine expression, the execution count of this branch is
2697 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002698 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002699 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002700 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002701 // equivalent to:
2702 //
2703 // Step*N = -Start (mod 2^BW)
2704 //
2705 // where BW is the common bit width of Start and Step.
2706
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 // Get the initial value for the loop.
2708 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2709 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002710
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002711 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002713 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002714 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002715
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002716 // First, handle unitary steps.
2717 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
2718 return SE.getNegativeSCEV(Start); // N = -Start (as unsigned)
2719 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2720 return Start; // N = Start (as unsigned)
2721
2722 // Then, try to solve the above equation provided that Start is constant.
2723 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
2724 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
2725 -StartC->getValue()->getValue(),SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002726 }
2727 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2728 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2729 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002730 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2732 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2733 if (R1) {
2734#if 0
2735 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2736 << " sol#2: " << *R2 << "\n";
2737#endif
2738 // Pick the smallest positive root value.
2739 if (ConstantInt *CB =
2740 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2741 R1->getValue(), R2->getValue()))) {
2742 if (CB->getZExtValue() == false)
2743 std::swap(R1, R2); // R1 is the minimum root now.
2744
2745 // We can only use this value if the chrec ends up with an exact zero
2746 // value at this index. When solving for "X*X != 5", for example, we
2747 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002748 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002749 if (Val->isZero())
2750 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002751 }
2752 }
2753 }
2754
2755 return UnknownValue;
2756}
2757
2758/// HowFarToNonZero - Return the number of times a backedge checking the
2759/// specified value for nonzero will execute. If not computable, return
2760/// UnknownValue
2761SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2762 // Loops that look like: while (X == 0) are very strange indeed. We don't
2763 // handle them yet except for the trivial case. This could be expanded in the
2764 // future as needed.
2765
2766 // If the value is a constant, check to see if it is known to be non-zero
2767 // already. If so, the backedge will execute zero times.
2768 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002769 if (!C->getValue()->isNullValue())
2770 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771 return UnknownValue; // Otherwise it will loop infinitely.
2772 }
2773
2774 // We could implement others, but I really doubt anyone writes loops like
2775 // this, and if they did, they would already be constant folded.
2776 return UnknownValue;
2777}
2778
Dan Gohman1cddf972008-09-15 22:18:04 +00002779/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
2780/// (which may not be an immediate predecessor) which has exactly one
2781/// successor from which BB is reachable, or null if no such block is
2782/// found.
2783///
2784BasicBlock *
2785ScalarEvolutionsImpl::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
2786 // If the block has a unique predecessor, the predecessor must have
2787 // no other successors from which BB is reachable.
2788 if (BasicBlock *Pred = BB->getSinglePredecessor())
2789 return Pred;
2790
2791 // A loop's header is defined to be a block that dominates the loop.
2792 // If the loop has a preheader, it must be a block that has exactly
2793 // one successor that can reach BB. This is slightly more strict
2794 // than necessary, but works if critical edges are split.
2795 if (Loop *L = LI.getLoopFor(BB))
2796 return L->getLoopPreheader();
2797
2798 return 0;
2799}
2800
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002801/// executesAtLeastOnce - Test whether entry to the loop is protected by
2802/// a conditional between LHS and RHS.
2803bool ScalarEvolutionsImpl::executesAtLeastOnce(const Loop *L, bool isSigned,
2804 SCEV *LHS, SCEV *RHS) {
2805 BasicBlock *Preheader = L->getLoopPreheader();
2806 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002807
Dan Gohmanab678fb2008-08-12 20:17:31 +00002808 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00002809 // there are predecessors that can be found that have unique successors
2810 // leading to the original header.
2811 for (; Preheader;
2812 PreheaderDest = Preheader,
2813 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00002814
2815 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002816 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00002817 if (!LoopEntryPredicate ||
2818 LoopEntryPredicate->isUnconditional())
2819 continue;
2820
2821 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
2822 if (!ICI) continue;
2823
2824 // Now that we found a conditional branch that dominates the loop, check to
2825 // see if it is the comparison we are looking for.
2826 Value *PreCondLHS = ICI->getOperand(0);
2827 Value *PreCondRHS = ICI->getOperand(1);
2828 ICmpInst::Predicate Cond;
2829 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2830 Cond = ICI->getPredicate();
2831 else
2832 Cond = ICI->getInversePredicate();
2833
2834 switch (Cond) {
2835 case ICmpInst::ICMP_UGT:
2836 if (isSigned) continue;
2837 std::swap(PreCondLHS, PreCondRHS);
2838 Cond = ICmpInst::ICMP_ULT;
2839 break;
2840 case ICmpInst::ICMP_SGT:
2841 if (!isSigned) continue;
2842 std::swap(PreCondLHS, PreCondRHS);
2843 Cond = ICmpInst::ICMP_SLT;
2844 break;
2845 case ICmpInst::ICMP_ULT:
2846 if (isSigned) continue;
2847 break;
2848 case ICmpInst::ICMP_SLT:
2849 if (!isSigned) continue;
2850 break;
2851 default:
2852 continue;
2853 }
2854
2855 if (!PreCondLHS->getType()->isInteger()) continue;
2856
2857 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
2858 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
2859 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
2860 (LHS == SE.getNotSCEV(PreCondRHSSCEV) &&
2861 RHS == SE.getNotSCEV(PreCondLHSSCEV)))
2862 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002863 }
2864
Dan Gohmanab678fb2008-08-12 20:17:31 +00002865 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002866}
2867
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868/// HowManyLessThans - Return the number of times a backedge containing the
2869/// specified less-than comparison will execute. If not computable, return
2870/// UnknownValue.
2871SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002872HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 // Only handle: "ADDREC < LoopInvariant".
2874 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2875
2876 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2877 if (!AddRec || AddRec->getLoop() != L)
2878 return UnknownValue;
2879
2880 if (AddRec->isAffine()) {
2881 // FORNOW: We only support unit strides.
Dan Gohman89f85052007-10-22 18:31:58 +00002882 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002883 if (AddRec->getOperand(1) != One)
2884 return UnknownValue;
2885
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002886 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2887 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2888 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002889 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002890
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002891 // First, we get the value of the LHS in the first iteration: n
2892 SCEVHandle Start = AddRec->getOperand(0);
2893
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002894 if (executesAtLeastOnce(L, isSigned,
Nick Lewyckya50aa4a2008-07-15 03:40:27 +00002895 SE.getMinusSCEV(AddRec->getOperand(0), One), RHS)) {
2896 // Since we know that the condition is true in order to enter the loop,
2897 // we know that it will run exactly m-n times.
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002898 return SE.getMinusSCEV(RHS, Start);
Nick Lewyckya50aa4a2008-07-15 03:40:27 +00002899 } else {
2900 // Then, we get the value of the LHS in the first iteration in which the
2901 // above condition doesn't hold. This equals to max(m,n).
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002902 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2903 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002904
Nick Lewycky1b020bf2008-07-12 07:41:32 +00002905 // Finally, we subtract these two values to get the number of times the
2906 // backedge is executed: max(m,n)-n.
2907 return SE.getMinusSCEV(End, Start);
2908 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002909 }
2910
2911 return UnknownValue;
2912}
2913
2914/// getNumIterationsInRange - Return the number of iterations of this loop that
2915/// produce values in the specified constant range. Another way of looking at
2916/// this is that it returns the first iteration number where the value is not in
2917/// the condition, thus computing the exit count. If the iteration count can't
2918/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002919SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2920 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 if (Range.isFullSet()) // Infinite loop.
2922 return new SCEVCouldNotCompute();
2923
2924 // If the start is a non-zero constant, shift the range to simplify things.
2925 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2926 if (!SC->getValue()->isZero()) {
2927 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002928 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2929 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002930 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2931 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002932 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002933 // This is strange and shouldn't happen.
2934 return new SCEVCouldNotCompute();
2935 }
2936
2937 // The only time we can solve this is when we have all constant indices.
2938 // Otherwise, we cannot determine the overflow conditions.
2939 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2940 if (!isa<SCEVConstant>(getOperand(i)))
2941 return new SCEVCouldNotCompute();
2942
2943
2944 // Okay at this point we know that all elements of the chrec are constants and
2945 // that the start element is zero.
2946
2947 // First check to see if the range contains zero. If not, the first
2948 // iteration exits.
2949 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman89f85052007-10-22 18:31:58 +00002950 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002951
2952 if (isAffine()) {
2953 // If this is an affine expression then we have this situation:
2954 // Solve {0,+,A} in Range === Ax in Range
2955
2956 // We know that zero is in the range. If A is positive then we know that
2957 // the upper value of the range must be the first possible exit value.
2958 // If A is negative then the lower of the range is the last possible loop
2959 // value. Also note that we already checked for a full range.
2960 APInt One(getBitWidth(),1);
2961 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2962 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2963
2964 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00002965 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002966 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2967
2968 // Evaluate at the exit value. If we really did fall out of the valid
2969 // range, then we computed our trip count, otherwise wrap around or other
2970 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00002971 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002972 if (Range.contains(Val->getValue()))
2973 return new SCEVCouldNotCompute(); // Something strange happened
2974
2975 // Ensure that the previous value is in the range. This is a sanity check.
2976 assert(Range.contains(
2977 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002978 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00002980 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981 } else if (isQuadratic()) {
2982 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2983 // quadratic equation to solve it. To do this, we must frame our problem in
2984 // terms of figuring out when zero is crossed, instead of when
2985 // Range.getUpper() is crossed.
2986 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002987 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2988 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002989
2990 // Next, solve the constructed addrec
2991 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00002992 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002993 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2994 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2995 if (R1) {
2996 // Pick the smallest positive root value.
2997 if (ConstantInt *CB =
2998 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2999 R1->getValue(), R2->getValue()))) {
3000 if (CB->getZExtValue() == false)
3001 std::swap(R1, R2); // R1 is the minimum root now.
3002
3003 // Make sure the root is not off by one. The returned iteration should
3004 // not be in the range, but the previous one should be. When solving
3005 // for "X*X < 5", for example, we should not return a root of 2.
3006 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003007 R1->getValue(),
3008 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003009 if (Range.contains(R1Val->getValue())) {
3010 // The next iteration must be out of the range...
3011 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3012
Dan Gohman89f85052007-10-22 18:31:58 +00003013 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003014 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003015 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016 return new SCEVCouldNotCompute(); // Something strange happened
3017 }
3018
3019 // If R1 was not in the range, then it is a good return value. Make
3020 // sure that R1-1 WAS in the range though, just in case.
3021 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003022 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003023 if (Range.contains(R1Val->getValue()))
3024 return R1;
3025 return new SCEVCouldNotCompute(); // Something strange happened
3026 }
3027 }
3028 }
3029
3030 // Fallback, if this is a general polynomial, figure out the progression
3031 // through brute force: evaluate until we find an iteration that fails the
3032 // test. This is likely to be slow, but getting an accurate trip count is
3033 // incredibly important, we will be able to simplify the exit test a lot, and
3034 // we are almost guaranteed to get a trip count in this case.
3035 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
3036 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
3037 do {
3038 ++NumBruteForceEvaluations;
Dan Gohman89f85052007-10-22 18:31:58 +00003039 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
3041 return new SCEVCouldNotCompute();
3042
3043 // Check to see if we found the value!
3044 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003045 return SE.getConstant(TestVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003046
3047 // Increment to test the next index.
3048 TestVal = ConstantInt::get(TestVal->getValue()+1);
3049 } while (TestVal != EndVal);
3050
3051 return new SCEVCouldNotCompute();
3052}
3053
3054
3055
3056//===----------------------------------------------------------------------===//
3057// ScalarEvolution Class Implementation
3058//===----------------------------------------------------------------------===//
3059
3060bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman89f85052007-10-22 18:31:58 +00003061 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003062 return false;
3063}
3064
3065void ScalarEvolution::releaseMemory() {
3066 delete (ScalarEvolutionsImpl*)Impl;
3067 Impl = 0;
3068}
3069
3070void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3071 AU.setPreservesAll();
3072 AU.addRequiredTransitive<LoopInfo>();
3073}
3074
3075SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
3076 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
3077}
3078
3079/// hasSCEV - Return true if the SCEV for this value has already been
3080/// computed.
3081bool ScalarEvolution::hasSCEV(Value *V) const {
3082 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
3083}
3084
3085
3086/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
3087/// the specified value.
3088void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
3089 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
3090}
3091
3092
3093SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
3094 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
3095}
3096
3097bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
3098 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
3099}
3100
3101SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
3102 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
3103}
3104
3105void ScalarEvolution::deleteValueFromRecords(Value *V) const {
3106 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
3107}
3108
3109static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
3110 const Loop *L) {
3111 // Print all inner loops first
3112 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3113 PrintLoopInfo(OS, SE, *I);
3114
Nick Lewyckye5da1912008-01-02 02:49:20 +00003115 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003116
Devang Patel02451fa2007-08-21 00:31:24 +00003117 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003118 L->getExitBlocks(ExitBlocks);
3119 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003120 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121
3122 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckye5da1912008-01-02 02:49:20 +00003123 OS << *SE->getIterationCount(L) << " iterations! ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003124 } else {
Nick Lewyckye5da1912008-01-02 02:49:20 +00003125 OS << "Unpredictable iteration count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003126 }
3127
Nick Lewyckye5da1912008-01-02 02:49:20 +00003128 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003129}
3130
3131void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
3132 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
3133 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
3134
3135 OS << "Classifying expressions for: " << F.getName() << "\n";
3136 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
3137 if (I->getType()->isInteger()) {
3138 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003139 OS << " --> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 SCEVHandle SV = getSCEV(&*I);
3141 SV->print(OS);
3142 OS << "\t\t";
3143
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
3145 OS << "Exits: ";
3146 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
3147 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3148 OS << "<<Unknown>>";
3149 } else {
3150 OS << *ExitValue;
3151 }
3152 }
3153
3154
3155 OS << "\n";
3156 }
3157
3158 OS << "Determining loop execution counts for: " << F.getName() << "\n";
3159 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
3160 PrintLoopInfo(OS, this, *I);
3161}