blob: 2356412b5ac5f969de6276d6e371414c0c7b0ae9 [file] [log] [blame]
Chris Lattnerd934c702004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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//
Chris Lattnerd934c702004-04-02 20:23:17 +000036// 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
Chris Lattnerb4f681b2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
65#include "llvm/Instructions.h"
66#include "llvm/Type.h"
67#include "llvm/Value.h"
68#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
Chris Lattner4021d1a2004-04-17 18:36:24 +000071#include "llvm/Transforms/Utils/Local.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000072#include "llvm/Support/CFG.h"
73#include "llvm/Support/ConstantRange.h"
74#include "llvm/Support/InstIterator.h"
Chris Lattner4021d1a2004-04-17 18:36:24 +000075#include "Support/CommandLine.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000076#include "Support/Statistic.h"
Brian Gaeke174633b2004-04-16 15:57:32 +000077#include <cmath>
Chris Lattnerd934c702004-04-02 20:23:17 +000078using namespace llvm;
79
80namespace {
81 RegisterAnalysis<ScalarEvolution>
Chris Lattner663ebc32004-04-19 03:42:32 +000082 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattnerd934c702004-04-02 20:23:17 +000083
84 Statistic<>
85 NumBruteForceEvaluations("scalar-evolution",
86 "Number of brute force evaluations needed to calculate high-order polynomial exit values");
87 Statistic<>
88 NumTripCountsComputed("scalar-evolution",
89 "Number of loops with predictable loop counts");
90 Statistic<>
91 NumTripCountsNotComputed("scalar-evolution",
92 "Number of loops without predictable loop counts");
Chris Lattner4021d1a2004-04-17 18:36:24 +000093 Statistic<>
94 NumBruteForceTripCountsComputed("scalar-evolution",
95 "Number of loops with trip counts computed by force");
96
97 cl::opt<unsigned>
98 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
99 cl::desc("Maximum number of iterations SCEV will symbolically execute a constant derived loop"),
100 cl::init(100));
Chris Lattnerd934c702004-04-02 20:23:17 +0000101}
102
103//===----------------------------------------------------------------------===//
104// SCEV class definitions
105//===----------------------------------------------------------------------===//
106
107//===----------------------------------------------------------------------===//
108// Implementation of the SCEV class.
109//
Chris Lattnerd934c702004-04-02 20:23:17 +0000110SCEV::~SCEV() {}
111void SCEV::dump() const {
112 print(std::cerr);
113}
114
115/// getValueRange - Return the tightest constant bounds that this value is
116/// known to have. This method is only valid on integer SCEV objects.
117ConstantRange SCEV::getValueRange() const {
118 const Type *Ty = getType();
119 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
120 Ty = Ty->getUnsignedVersion();
121 // Default to a full range if no better information is available.
122 return ConstantRange(getType());
123}
124
125
126SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
127
128bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
129 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000130 return false;
Chris Lattnerd934c702004-04-02 20:23:17 +0000131}
132
133const Type *SCEVCouldNotCompute::getType() const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukman5ebc25c2004-04-05 19:00:46 +0000135 return 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000136}
137
138bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return false;
141}
142
Chris Lattnerd934c702004-04-02 20:23:17 +0000143void SCEVCouldNotCompute::print(std::ostream &OS) const {
144 OS << "***COULDNOTCOMPUTE***";
145}
146
147bool SCEVCouldNotCompute::classof(const SCEV *S) {
148 return S->getSCEVType() == scCouldNotCompute;
149}
150
151
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000152// SCEVConstants - Only allow the creation of one SCEVConstant for any
153// particular value. Don't use a SCEVHandle here, or else the object will
154// never be deleted!
155static std::map<ConstantInt*, SCEVConstant*> SCEVConstants;
156
Chris Lattnerd934c702004-04-02 20:23:17 +0000157
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000158SCEVConstant::~SCEVConstant() {
159 SCEVConstants.erase(V);
160}
Chris Lattnerd934c702004-04-02 20:23:17 +0000161
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000162SCEVHandle SCEVConstant::get(ConstantInt *V) {
163 // Make sure that SCEVConstant instances are all unsigned.
164 if (V->getType()->isSigned()) {
165 const Type *NewTy = V->getType()->getUnsignedVersion();
166 V = cast<ConstantUInt>(ConstantExpr::getCast(V, NewTy));
167 }
168
169 SCEVConstant *&R = SCEVConstants[V];
170 if (R == 0) R = new SCEVConstant(V);
171 return R;
172}
Chris Lattnerd934c702004-04-02 20:23:17 +0000173
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000174ConstantRange SCEVConstant::getValueRange() const {
175 return ConstantRange(V);
176}
Chris Lattnerd934c702004-04-02 20:23:17 +0000177
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000178const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000179
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000180void SCEVConstant::print(std::ostream &OS) const {
181 WriteAsOperand(OS, V, false);
182}
Chris Lattnerd934c702004-04-02 20:23:17 +0000183
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000184// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
185// particular input. Don't use a SCEVHandle here, or else the object will
186// never be deleted!
187static std::map<std::pair<SCEV*, const Type*>, SCEVTruncateExpr*> SCEVTruncates;
Chris Lattnerd934c702004-04-02 20:23:17 +0000188
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000189SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
190 : SCEV(scTruncate), Op(op), Ty(ty) {
191 assert(Op->getType()->isInteger() && Ty->isInteger() &&
192 Ty->isUnsigned() &&
193 "Cannot truncate non-integer value!");
194 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
195 "This is not a truncating conversion!");
196}
Chris Lattnerd934c702004-04-02 20:23:17 +0000197
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000198SCEVTruncateExpr::~SCEVTruncateExpr() {
199 SCEVTruncates.erase(std::make_pair(Op, Ty));
200}
Chris Lattnerd934c702004-04-02 20:23:17 +0000201
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000202ConstantRange SCEVTruncateExpr::getValueRange() const {
203 return getOperand()->getValueRange().truncate(getType());
204}
Chris Lattnerd934c702004-04-02 20:23:17 +0000205
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000206void SCEVTruncateExpr::print(std::ostream &OS) const {
207 OS << "(truncate " << *Op << " to " << *Ty << ")";
208}
209
210// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
211// particular input. Don't use a SCEVHandle here, or else the object will never
212// be deleted!
213static std::map<std::pair<SCEV*, const Type*>,
214 SCEVZeroExtendExpr*> SCEVZeroExtends;
215
216SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
217 : SCEV(scTruncate), Op(Op), Ty(ty) {
218 assert(Op->getType()->isInteger() && Ty->isInteger() &&
219 Ty->isUnsigned() &&
220 "Cannot zero extend non-integer value!");
221 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
222 "This is not an extending conversion!");
223}
224
225SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
226 SCEVZeroExtends.erase(std::make_pair(Op, Ty));
227}
228
229ConstantRange SCEVZeroExtendExpr::getValueRange() const {
230 return getOperand()->getValueRange().zeroExtend(getType());
231}
232
233void SCEVZeroExtendExpr::print(std::ostream &OS) const {
234 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
235}
236
237// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
238// particular input. Don't use a SCEVHandle here, or else the object will never
239// be deleted!
240static std::map<std::pair<unsigned, std::vector<SCEV*> >,
241 SCEVCommutativeExpr*> SCEVCommExprs;
242
243SCEVCommutativeExpr::~SCEVCommutativeExpr() {
244 SCEVCommExprs.erase(std::make_pair(getSCEVType(),
245 std::vector<SCEV*>(Operands.begin(),
246 Operands.end())));
247}
248
249void SCEVCommutativeExpr::print(std::ostream &OS) const {
250 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
251 const char *OpStr = getOperationStr();
252 OS << "(" << *Operands[0];
253 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
254 OS << OpStr << *Operands[i];
255 OS << ")";
256}
257
258// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
259// input. Don't use a SCEVHandle here, or else the object will never be
260// deleted!
261static std::map<std::pair<SCEV*, SCEV*>, SCEVUDivExpr*> SCEVUDivs;
262
263SCEVUDivExpr::~SCEVUDivExpr() {
264 SCEVUDivs.erase(std::make_pair(LHS, RHS));
265}
266
267void SCEVUDivExpr::print(std::ostream &OS) const {
268 OS << "(" << *LHS << " /u " << *RHS << ")";
269}
270
271const Type *SCEVUDivExpr::getType() const {
272 const Type *Ty = LHS->getType();
273 if (Ty->isSigned()) Ty = Ty->getUnsignedVersion();
274 return Ty;
275}
276
277// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
278// particular input. Don't use a SCEVHandle here, or else the object will never
279// be deleted!
280static std::map<std::pair<const Loop *, std::vector<SCEV*> >,
281 SCEVAddRecExpr*> SCEVAddRecExprs;
282
283SCEVAddRecExpr::~SCEVAddRecExpr() {
284 SCEVAddRecExprs.erase(std::make_pair(L,
285 std::vector<SCEV*>(Operands.begin(),
286 Operands.end())));
287}
288
289bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
290 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
291 // contain L.
292 return !QueryLoop->contains(L->getHeader());
Chris Lattnerd934c702004-04-02 20:23:17 +0000293}
294
295
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000296void SCEVAddRecExpr::print(std::ostream &OS) const {
297 OS << "{" << *Operands[0];
298 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
299 OS << ",+," << *Operands[i];
300 OS << "}<" << L->getHeader()->getName() + ">";
301}
Chris Lattnerd934c702004-04-02 20:23:17 +0000302
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000303// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
304// value. Don't use a SCEVHandle here, or else the object will never be
305// deleted!
306static std::map<Value*, SCEVUnknown*> SCEVUnknowns;
Chris Lattnerd934c702004-04-02 20:23:17 +0000307
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000308SCEVUnknown::~SCEVUnknown() { SCEVUnknowns.erase(V); }
Chris Lattnerd934c702004-04-02 20:23:17 +0000309
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000310bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
311 // All non-instruction values are loop invariant. All instructions are loop
312 // invariant if they are not contained in the specified loop.
313 if (Instruction *I = dyn_cast<Instruction>(V))
314 return !L->contains(I->getParent());
315 return true;
316}
Chris Lattnerd934c702004-04-02 20:23:17 +0000317
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000318const Type *SCEVUnknown::getType() const {
319 return V->getType();
320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000322void SCEVUnknown::print(std::ostream &OS) const {
323 WriteAsOperand(OS, V, false);
Chris Lattnerd934c702004-04-02 20:23:17 +0000324}
325
Chris Lattnereb3e8402004-06-20 06:23:15 +0000326//===----------------------------------------------------------------------===//
327// SCEV Utilities
328//===----------------------------------------------------------------------===//
329
330namespace {
331 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
332 /// than the complexity of the RHS. This comparator is used to canonicalize
333 /// expressions.
334 struct SCEVComplexityCompare {
335 bool operator()(SCEV *LHS, SCEV *RHS) {
336 return LHS->getSCEVType() < RHS->getSCEVType();
337 }
338 };
339}
340
341/// GroupByComplexity - Given a list of SCEV objects, order them by their
342/// complexity, and group objects of the same complexity together by value.
343/// When this routine is finished, we know that any duplicates in the vector are
344/// consecutive and that complexity is monotonically increasing.
345///
346/// Note that we go take special precautions to ensure that we get determinstic
347/// results from this routine. In other words, we don't want the results of
348/// this to depend on where the addresses of various SCEV objects happened to
349/// land in memory.
350///
351static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
352 if (Ops.size() < 2) return; // Noop
353 if (Ops.size() == 2) {
354 // This is the common case, which also happens to be trivially simple.
355 // Special case it.
356 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
357 std::swap(Ops[0], Ops[1]);
358 return;
359 }
360
361 // Do the rough sort by complexity.
362 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
363
364 // Now that we are sorted by complexity, group elements of the same
365 // complexity. Note that this is, at worst, N^2, but the vector is likely to
366 // be extremely short in practice. Note that we take this approach because we
367 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner6bfca8f2004-06-20 17:01:44 +0000368 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000369 SCEV *S = Ops[i];
370 unsigned Complexity = S->getSCEVType();
371
372 // If there are any objects of the same complexity and same value as this
373 // one, group them.
374 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
375 if (Ops[j] == S) { // Found a duplicate.
376 // Move it to immediately after i'th element.
377 std::swap(Ops[i+1], Ops[j]);
378 ++i; // no need to rescan it.
379 }
380 }
381 }
382}
383
Chris Lattnerd934c702004-04-02 20:23:17 +0000384
Chris Lattnerd934c702004-04-02 20:23:17 +0000385
386//===----------------------------------------------------------------------===//
387// Simple SCEV method implementations
388//===----------------------------------------------------------------------===//
389
390/// getIntegerSCEV - Given an integer or FP type, create a constant for the
391/// specified signed integer value and return a SCEV for the constant.
Chris Lattner05ef97f2004-04-23 21:29:03 +0000392SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattnerd934c702004-04-02 20:23:17 +0000393 Constant *C;
394 if (Val == 0)
395 C = Constant::getNullValue(Ty);
396 else if (Ty->isFloatingPoint())
397 C = ConstantFP::get(Ty, Val);
398 else if (Ty->isSigned())
399 C = ConstantSInt::get(Ty, Val);
400 else {
401 C = ConstantSInt::get(Ty->getSignedVersion(), Val);
402 C = ConstantExpr::getCast(C, Ty);
403 }
404 return SCEVUnknown::get(C);
405}
406
407/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
408/// input value to the specified type. If the type must be extended, it is zero
409/// extended.
410static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
411 const Type *SrcTy = V->getType();
412 assert(SrcTy->isInteger() && Ty->isInteger() &&
413 "Cannot truncate or zero extend with non-integer arguments!");
414 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
415 return V; // No conversion
416 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
417 return SCEVTruncateExpr::get(V, Ty);
418 return SCEVZeroExtendExpr::get(V, Ty);
419}
420
421/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
422///
423static SCEVHandle getNegativeSCEV(const SCEVHandle &V) {
424 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
425 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
426
Chris Lattner05ef97f2004-04-23 21:29:03 +0000427 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattnerd934c702004-04-02 20:23:17 +0000428}
429
430/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
431///
432static SCEVHandle getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
433 // X - Y --> X + -Y
434 return SCEVAddExpr::get(LHS, getNegativeSCEV(RHS));
435}
436
437
438/// Binomial - Evaluate N!/((N-M)!*M!) . Note that N is often large and M is
439/// often very small, so we try to reduce the number of N! terms we need to
440/// evaluate by evaluating this as (N!/(N-M)!)/M!
441static ConstantInt *Binomial(ConstantInt *N, unsigned M) {
442 uint64_t NVal = N->getRawValue();
443 uint64_t FirstTerm = 1;
444 for (unsigned i = 0; i != M; ++i)
445 FirstTerm *= NVal-i;
446
447 unsigned MFactorial = 1;
448 for (; M; --M)
449 MFactorial *= M;
450
451 Constant *Result = ConstantUInt::get(Type::ULongTy, FirstTerm/MFactorial);
452 Result = ConstantExpr::getCast(Result, N->getType());
453 assert(isa<ConstantInt>(Result) && "Cast of integer not folded??");
454 return cast<ConstantInt>(Result);
455}
456
457/// PartialFact - Compute V!/(V-NumSteps)!
458static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
459 // Handle this case efficiently, it is common to have constant iteration
460 // counts while computing loop exit values.
461 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
462 uint64_t Val = SC->getValue()->getRawValue();
463 uint64_t Result = 1;
464 for (; NumSteps; --NumSteps)
465 Result *= Val-(NumSteps-1);
466 Constant *Res = ConstantUInt::get(Type::ULongTy, Result);
467 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
468 }
469
470 const Type *Ty = V->getType();
471 if (NumSteps == 0)
Chris Lattner05ef97f2004-04-23 21:29:03 +0000472 return SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattnerd934c702004-04-02 20:23:17 +0000473
474 SCEVHandle Result = V;
475 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattner05ef97f2004-04-23 21:29:03 +0000476 Result = SCEVMulExpr::get(Result, getMinusSCEV(V,
477 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +0000478 return Result;
479}
480
481
482/// evaluateAtIteration - Return the value of this chain of recurrences at
483/// the specified iteration number. We can evaluate this recurrence by
484/// multiplying each element in the chain by the binomial coefficient
485/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
486///
487/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
488///
489/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
490/// Is the binomial equation safe using modular arithmetic??
491///
492SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
493 SCEVHandle Result = getStart();
494 int Divisor = 1;
495 const Type *Ty = It->getType();
496 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
497 SCEVHandle BC = PartialFact(It, i);
498 Divisor *= i;
499 SCEVHandle Val = SCEVUDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattner05ef97f2004-04-23 21:29:03 +0000500 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattnerd934c702004-04-02 20:23:17 +0000501 Result = SCEVAddExpr::get(Result, Val);
502 }
503 return Result;
504}
505
506
507//===----------------------------------------------------------------------===//
508// SCEV Expression folder implementations
509//===----------------------------------------------------------------------===//
510
511SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
512 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
513 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
514
515 // If the input value is a chrec scev made out of constants, truncate
516 // all of the constants.
517 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
518 std::vector<SCEVHandle> Operands;
519 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
520 // FIXME: This should allow truncation of other expression types!
521 if (isa<SCEVConstant>(AddRec->getOperand(i)))
522 Operands.push_back(get(AddRec->getOperand(i), Ty));
523 else
524 break;
525 if (Operands.size() == AddRec->getNumOperands())
526 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
527 }
528
529 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
530 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
531 return Result;
532}
533
534SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
535 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
536 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
537
538 // FIXME: If the input value is a chrec scev, and we can prove that the value
539 // did not overflow the old, smaller, value, we can zero extend all of the
540 // operands (often constants). This would allow analysis of something like
541 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
542
543 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
544 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
545 return Result;
546}
547
548// get - Get a canonical add expression, or something simpler if possible.
549SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
550 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +0000551 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000552
553 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000554 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000555
556 // If there are any constants, fold them together.
557 unsigned Idx = 0;
558 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
559 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +0000560 assert(Idx < Ops.size());
Chris Lattnerd934c702004-04-02 20:23:17 +0000561 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
562 // We found two constants, fold them together!
563 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
564 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
565 Ops[0] = SCEVConstant::get(CI);
566 Ops.erase(Ops.begin()+1); // Erase the folded element
567 if (Ops.size() == 1) return Ops[0];
568 } else {
569 // If we couldn't fold the expression, move to the next constant. Note
570 // that this is impossible to happen in practice because we always
571 // constant fold constant ints to constant ints.
572 ++Idx;
573 }
574 }
575
576 // If we are left with a constant zero being added, strip it off.
577 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
578 Ops.erase(Ops.begin());
579 --Idx;
580 }
581 }
582
Chris Lattner74498e12004-04-07 16:16:11 +0000583 if (Ops.size() == 1) return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +0000584
585 // Okay, check to see if the same value occurs in the operand list twice. If
586 // so, merge them together into an multiply expression. Since we sorted the
587 // list, these values are required to be adjacent.
588 const Type *Ty = Ops[0]->getType();
589 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
590 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
591 // Found a match, merge the two values into a multiply, and add any
592 // remaining values to the result.
Chris Lattner05ef97f2004-04-23 21:29:03 +0000593 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattnerd934c702004-04-02 20:23:17 +0000594 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
595 if (Ops.size() == 2)
596 return Mul;
597 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
598 Ops.push_back(Mul);
599 return SCEVAddExpr::get(Ops);
600 }
601
602 // Okay, now we know the first non-constant operand. If there are add
603 // operands they would be next.
604 if (Idx < Ops.size()) {
605 bool DeletedAdd = false;
606 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
607 // If we have an add, expand the add operands onto the end of the operands
608 // list.
609 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
610 Ops.erase(Ops.begin()+Idx);
611 DeletedAdd = true;
612 }
613
614 // If we deleted at least one add, we added operands to the end of the list,
615 // and they are not necessarily sorted. Recurse to resort and resimplify
616 // any operands we just aquired.
617 if (DeletedAdd)
618 return get(Ops);
619 }
620
621 // Skip over the add expression until we get to a multiply.
622 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
623 ++Idx;
624
625 // If we are adding something to a multiply expression, make sure the
626 // something is not already an operand of the multiply. If so, merge it into
627 // the multiply.
628 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
629 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
630 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
631 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
632 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
633 if (MulOpSCEV == Ops[AddOp] &&
634 (Mul->getNumOperands() != 2 || !isa<SCEVConstant>(MulOpSCEV))) {
635 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
636 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
637 if (Mul->getNumOperands() != 2) {
638 // If the multiply has more than two operands, we must get the
639 // Y*Z term.
640 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
641 MulOps.erase(MulOps.begin()+MulOp);
642 InnerMul = SCEVMulExpr::get(MulOps);
643 }
Chris Lattner05ef97f2004-04-23 21:29:03 +0000644 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattnerd934c702004-04-02 20:23:17 +0000645 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
646 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
647 if (Ops.size() == 2) return OuterMul;
648 if (AddOp < Idx) {
649 Ops.erase(Ops.begin()+AddOp);
650 Ops.erase(Ops.begin()+Idx-1);
651 } else {
652 Ops.erase(Ops.begin()+Idx);
653 Ops.erase(Ops.begin()+AddOp-1);
654 }
655 Ops.push_back(OuterMul);
656 return SCEVAddExpr::get(Ops);
657 }
658
659 // Check this multiply against other multiplies being added together.
660 for (unsigned OtherMulIdx = Idx+1;
661 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
662 ++OtherMulIdx) {
663 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
664 // If MulOp occurs in OtherMul, we can fold the two multiplies
665 // together.
666 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
667 OMulOp != e; ++OMulOp)
668 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
669 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
670 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
671 if (Mul->getNumOperands() != 2) {
672 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
673 MulOps.erase(MulOps.begin()+MulOp);
674 InnerMul1 = SCEVMulExpr::get(MulOps);
675 }
676 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
677 if (OtherMul->getNumOperands() != 2) {
678 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
679 OtherMul->op_end());
680 MulOps.erase(MulOps.begin()+OMulOp);
681 InnerMul2 = SCEVMulExpr::get(MulOps);
682 }
683 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
684 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
685 if (Ops.size() == 2) return OuterMul;
686 Ops.erase(Ops.begin()+Idx);
687 Ops.erase(Ops.begin()+OtherMulIdx-1);
688 Ops.push_back(OuterMul);
689 return SCEVAddExpr::get(Ops);
690 }
691 }
692 }
693 }
694
695 // If there are any add recurrences in the operands list, see if any other
696 // added values are loop invariant. If so, we can fold them into the
697 // recurrence.
698 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
699 ++Idx;
700
701 // Scan over all recurrences, trying to fold loop invariants into them.
702 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
703 // Scan all of the other operands to this add and add them to the vector if
704 // they are loop invariant w.r.t. the recurrence.
705 std::vector<SCEVHandle> LIOps;
706 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
707 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
708 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
709 LIOps.push_back(Ops[i]);
710 Ops.erase(Ops.begin()+i);
711 --i; --e;
712 }
713
714 // If we found some loop invariants, fold them into the recurrence.
715 if (!LIOps.empty()) {
716 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
717 LIOps.push_back(AddRec->getStart());
718
719 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
720 AddRecOps[0] = SCEVAddExpr::get(LIOps);
721
722 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
723 // If all of the other operands were loop invariant, we are done.
724 if (Ops.size() == 1) return NewRec;
725
726 // Otherwise, add the folded AddRec by the non-liv parts.
727 for (unsigned i = 0;; ++i)
728 if (Ops[i] == AddRec) {
729 Ops[i] = NewRec;
730 break;
731 }
732 return SCEVAddExpr::get(Ops);
733 }
734
735 // Okay, if there weren't any loop invariants to be folded, check to see if
736 // there are multiple AddRec's with the same loop induction variable being
737 // added together. If so, we can fold them.
738 for (unsigned OtherIdx = Idx+1;
739 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
740 if (OtherIdx != Idx) {
741 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
742 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
743 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
744 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
745 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
746 if (i >= NewOps.size()) {
747 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
748 OtherAddRec->op_end());
749 break;
750 }
751 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
752 }
753 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
754
755 if (Ops.size() == 2) return NewAddRec;
756
757 Ops.erase(Ops.begin()+Idx);
758 Ops.erase(Ops.begin()+OtherIdx-1);
759 Ops.push_back(NewAddRec);
760 return SCEVAddExpr::get(Ops);
761 }
762 }
763
764 // Otherwise couldn't fold anything into this recurrence. Move onto the
765 // next one.
766 }
767
768 // Okay, it looks like we really DO need an add expr. Check to see if we
769 // already have one, otherwise create a new one.
770 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
771 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
772 SCEVOps)];
773 if (Result == 0) Result = new SCEVAddExpr(Ops);
774 return Result;
775}
776
777
778SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
779 assert(!Ops.empty() && "Cannot get empty mul!");
780
781 // Sort by complexity, this groups all similar expression types together.
Chris Lattnereb3e8402004-06-20 06:23:15 +0000782 GroupByComplexity(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +0000783
784 // If there are any constants, fold them together.
785 unsigned Idx = 0;
786 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
787
788 // C1*(C2+V) -> C1*C2 + C1*V
789 if (Ops.size() == 2)
790 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
791 if (Add->getNumOperands() == 2 &&
792 isa<SCEVConstant>(Add->getOperand(0)))
793 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
794 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
795
796
797 ++Idx;
798 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
799 // We found two constants, fold them together!
800 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
801 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
802 Ops[0] = SCEVConstant::get(CI);
803 Ops.erase(Ops.begin()+1); // Erase the folded element
804 if (Ops.size() == 1) return Ops[0];
805 } else {
806 // If we couldn't fold the expression, move to the next constant. Note
807 // that this is impossible to happen in practice because we always
808 // constant fold constant ints to constant ints.
809 ++Idx;
810 }
811 }
812
813 // If we are left with a constant one being multiplied, strip it off.
814 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
815 Ops.erase(Ops.begin());
816 --Idx;
817 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
818 // If we have a multiply of zero, it will always be zero.
819 return Ops[0];
820 }
821 }
822
823 // Skip over the add expression until we get to a multiply.
824 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
825 ++Idx;
826
827 if (Ops.size() == 1)
828 return Ops[0];
829
830 // If there are mul operands inline them all into this expression.
831 if (Idx < Ops.size()) {
832 bool DeletedMul = false;
833 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
834 // If we have an mul, expand the mul operands onto the end of the operands
835 // list.
836 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
837 Ops.erase(Ops.begin()+Idx);
838 DeletedMul = true;
839 }
840
841 // If we deleted at least one mul, we added operands to the end of the list,
842 // and they are not necessarily sorted. Recurse to resort and resimplify
843 // any operands we just aquired.
844 if (DeletedMul)
845 return get(Ops);
846 }
847
848 // If there are any add recurrences in the operands list, see if any other
849 // added values are loop invariant. If so, we can fold them into the
850 // recurrence.
851 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
852 ++Idx;
853
854 // Scan over all recurrences, trying to fold loop invariants into them.
855 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
856 // Scan all of the other operands to this mul and add them to the vector if
857 // they are loop invariant w.r.t. the recurrence.
858 std::vector<SCEVHandle> LIOps;
859 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
860 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
861 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
862 LIOps.push_back(Ops[i]);
863 Ops.erase(Ops.begin()+i);
864 --i; --e;
865 }
866
867 // If we found some loop invariants, fold them into the recurrence.
868 if (!LIOps.empty()) {
869 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
870 std::vector<SCEVHandle> NewOps;
871 NewOps.reserve(AddRec->getNumOperands());
872 if (LIOps.size() == 1) {
873 SCEV *Scale = LIOps[0];
874 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
875 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
876 } else {
877 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
878 std::vector<SCEVHandle> MulOps(LIOps);
879 MulOps.push_back(AddRec->getOperand(i));
880 NewOps.push_back(SCEVMulExpr::get(MulOps));
881 }
882 }
883
884 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
885
886 // If all of the other operands were loop invariant, we are done.
887 if (Ops.size() == 1) return NewRec;
888
889 // Otherwise, multiply the folded AddRec by the non-liv parts.
890 for (unsigned i = 0;; ++i)
891 if (Ops[i] == AddRec) {
892 Ops[i] = NewRec;
893 break;
894 }
895 return SCEVMulExpr::get(Ops);
896 }
897
898 // Okay, if there weren't any loop invariants to be folded, check to see if
899 // there are multiple AddRec's with the same loop induction variable being
900 // multiplied together. If so, we can fold them.
901 for (unsigned OtherIdx = Idx+1;
902 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
903 if (OtherIdx != Idx) {
904 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
905 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
906 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
907 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
908 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
909 G->getStart());
910 SCEVHandle B = F->getStepRecurrence();
911 SCEVHandle D = G->getStepRecurrence();
912 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
913 SCEVMulExpr::get(G, B),
914 SCEVMulExpr::get(B, D));
915 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
916 F->getLoop());
917 if (Ops.size() == 2) return NewAddRec;
918
919 Ops.erase(Ops.begin()+Idx);
920 Ops.erase(Ops.begin()+OtherIdx-1);
921 Ops.push_back(NewAddRec);
922 return SCEVMulExpr::get(Ops);
923 }
924 }
925
926 // Otherwise couldn't fold anything into this recurrence. Move onto the
927 // next one.
928 }
929
930 // Okay, it looks like we really DO need an mul expr. Check to see if we
931 // already have one, otherwise create a new one.
932 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
933 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
934 SCEVOps)];
935 if (Result == 0) Result = new SCEVMulExpr(Ops);
936 return Result;
937}
938
939SCEVHandle SCEVUDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
940 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
941 if (RHSC->getValue()->equalsInt(1))
942 return LHS; // X /u 1 --> x
943 if (RHSC->getValue()->isAllOnesValue())
944 return getNegativeSCEV(LHS); // X /u -1 --> -x
945
946 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
947 Constant *LHSCV = LHSC->getValue();
948 Constant *RHSCV = RHSC->getValue();
949 if (LHSCV->getType()->isSigned())
950 LHSCV = ConstantExpr::getCast(LHSCV,
951 LHSCV->getType()->getUnsignedVersion());
952 if (RHSCV->getType()->isSigned())
953 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
954 return SCEVUnknown::get(ConstantExpr::getDiv(LHSCV, RHSCV));
955 }
956 }
957
958 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
959
960 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
961 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
962 return Result;
963}
964
965
966/// SCEVAddRecExpr::get - Get a add recurrence expression for the
967/// specified loop. Simplify the expression as much as possible.
968SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
969 const SCEVHandle &Step, const Loop *L) {
970 std::vector<SCEVHandle> Operands;
971 Operands.push_back(Start);
972 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
973 if (StepChrec->getLoop() == L) {
974 Operands.insert(Operands.end(), StepChrec->op_begin(),
975 StepChrec->op_end());
976 return get(Operands, L);
977 }
978
979 Operands.push_back(Step);
980 return get(Operands, L);
981}
982
983/// SCEVAddRecExpr::get - Get a add recurrence expression for the
984/// specified loop. Simplify the expression as much as possible.
985SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
986 const Loop *L) {
987 if (Operands.size() == 1) return Operands[0];
988
989 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
990 if (StepC->getValue()->isNullValue()) {
991 Operands.pop_back();
992 return get(Operands, L); // { X,+,0 } --> X
993 }
994
995 SCEVAddRecExpr *&Result =
996 SCEVAddRecExprs[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
997 Operands.end()))];
998 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
999 return Result;
1000}
1001
Chris Lattnerb4f681b2004-04-15 15:07:24 +00001002SCEVHandle SCEVUnknown::get(Value *V) {
1003 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1004 return SCEVConstant::get(CI);
1005 SCEVUnknown *&Result = SCEVUnknowns[V];
1006 if (Result == 0) Result = new SCEVUnknown(V);
1007 return Result;
1008}
1009
Chris Lattnerd934c702004-04-02 20:23:17 +00001010
1011//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00001012// ScalarEvolutionsImpl Definition and Implementation
1013//===----------------------------------------------------------------------===//
1014//
1015/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1016/// evolution code.
1017///
1018namespace {
1019 struct ScalarEvolutionsImpl {
1020 /// F - The function we are analyzing.
1021 ///
1022 Function &F;
1023
1024 /// LI - The loop information for the function we are currently analyzing.
1025 ///
1026 LoopInfo &LI;
1027
1028 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1029 /// things.
1030 SCEVHandle UnknownValue;
1031
1032 /// Scalars - This is a cache of the scalars we have analyzed so far.
1033 ///
1034 std::map<Value*, SCEVHandle> Scalars;
1035
1036 /// IterationCounts - Cache the iteration count of the loops for this
1037 /// function as they are computed.
1038 std::map<const Loop*, SCEVHandle> IterationCounts;
1039
Chris Lattnerdd730472004-04-17 22:58:41 +00001040 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1041 /// the PHI instructions that we attempt to compute constant evolutions for.
1042 /// This allows us to avoid potentially expensive recomputation of these
1043 /// properties. An instruction maps to null if we are unable to compute its
1044 /// exit value.
1045 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1046
Chris Lattnerd934c702004-04-02 20:23:17 +00001047 public:
1048 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1049 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1050
1051 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1052 /// expression and create a new one.
1053 SCEVHandle getSCEV(Value *V);
1054
1055 /// getSCEVAtScope - Compute the value of the specified expression within
1056 /// the indicated loop (which may be null to indicate in no loop). If the
1057 /// expression cannot be evaluated, return UnknownValue itself.
1058 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1059
1060
1061 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1062 /// an analyzable loop-invariant iteration count.
1063 bool hasLoopInvariantIterationCount(const Loop *L);
1064
1065 /// getIterationCount - If the specified loop has a predictable iteration
1066 /// count, return it. Note that it is not valid to call this method on a
1067 /// loop without a loop-invariant iteration count.
1068 SCEVHandle getIterationCount(const Loop *L);
1069
1070 /// deleteInstructionFromRecords - This method should be called by the
1071 /// client before it removes an instruction from the program, to make sure
1072 /// that no dangling references are left around.
1073 void deleteInstructionFromRecords(Instruction *I);
1074
1075 private:
1076 /// createSCEV - We know that there is no SCEV for the specified value.
1077 /// Analyze the expression.
1078 SCEVHandle createSCEV(Value *V);
1079 SCEVHandle createNodeForCast(CastInst *CI);
1080
1081 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1082 /// SCEVs.
1083 SCEVHandle createNodeForPHI(PHINode *PN);
1084 void UpdatePHIUserScalarEntries(Instruction *I, PHINode *PN,
1085 std::set<Instruction*> &UpdatedInsts);
1086
1087 /// ComputeIterationCount - Compute the number of times the specified loop
1088 /// will iterate.
1089 SCEVHandle ComputeIterationCount(const Loop *L);
1090
Chris Lattner4021d1a2004-04-17 18:36:24 +00001091 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1092 /// constant number of times (the condition evolves only from constants),
1093 /// try to evaluate a few iterations of the loop until we get the exit
1094 /// condition gets a value of ExitWhen (true or false). If we cannot
1095 /// evaluate the trip count of the loop, return UnknownValue.
1096 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1097 bool ExitWhen);
1098
Chris Lattnerd934c702004-04-02 20:23:17 +00001099 /// HowFarToZero - Return the number of times a backedge comparing the
1100 /// specified value to zero will execute. If not computable, return
1101 /// UnknownValue
1102 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1103
1104 /// HowFarToNonZero - Return the number of times a backedge checking the
1105 /// specified value for nonzero will execute. If not computable, return
1106 /// UnknownValue
1107 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattnerdd730472004-04-17 22:58:41 +00001108
1109 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1110 /// in the header of its containing loop, we know the loop executes a
1111 /// constant number of times, and the PHI node is just a recurrence
1112 /// involving constants, fold it.
1113 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1114 const Loop *L);
Chris Lattnerd934c702004-04-02 20:23:17 +00001115 };
1116}
1117
1118//===----------------------------------------------------------------------===//
1119// Basic SCEV Analysis and PHI Idiom Recognition Code
1120//
1121
1122/// deleteInstructionFromRecords - This method should be called by the
1123/// client before it removes an instruction from the program, to make sure
1124/// that no dangling references are left around.
1125void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1126 Scalars.erase(I);
Chris Lattnerdd730472004-04-17 22:58:41 +00001127 if (PHINode *PN = dyn_cast<PHINode>(I))
1128 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00001129}
1130
1131
1132/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1133/// expression and create a new one.
1134SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1135 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1136
1137 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1138 if (I != Scalars.end()) return I->second;
1139 SCEVHandle S = createSCEV(V);
1140 Scalars.insert(std::make_pair(V, S));
1141 return S;
1142}
1143
1144
1145/// UpdatePHIUserScalarEntries - After PHI node analysis, we have a bunch of
1146/// entries in the scalar map that refer to the "symbolic" PHI value instead of
1147/// the recurrence value. After we resolve the PHI we must loop over all of the
1148/// using instructions that have scalar map entries and update them.
1149void ScalarEvolutionsImpl::UpdatePHIUserScalarEntries(Instruction *I,
1150 PHINode *PN,
1151 std::set<Instruction*> &UpdatedInsts) {
1152 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1153 if (SI == Scalars.end()) return; // This scalar wasn't previous processed.
1154 if (UpdatedInsts.insert(I).second) {
1155 Scalars.erase(SI); // Remove the old entry
1156 getSCEV(I); // Calculate the new entry
1157
1158 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1159 UI != E; ++UI)
1160 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN, UpdatedInsts);
1161 }
1162}
1163
1164
1165/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1166/// a loop header, making it a potential recurrence, or it doesn't.
1167///
1168SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1169 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1170 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1171 if (L->getHeader() == PN->getParent()) {
1172 // If it lives in the loop header, it has two incoming values, one
1173 // from outside the loop, and one from inside.
1174 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1175 unsigned BackEdge = IncomingEdge^1;
1176
1177 // While we are analyzing this PHI node, handle its value symbolically.
1178 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1179 assert(Scalars.find(PN) == Scalars.end() &&
1180 "PHI node already processed?");
1181 Scalars.insert(std::make_pair(PN, SymbolicName));
1182
1183 // Using this symbolic name for the PHI, analyze the value coming around
1184 // the back-edge.
1185 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1186
1187 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1188 // has a special value for the first iteration of the loop.
1189
1190 // If the value coming around the backedge is an add with the symbolic
1191 // value we just inserted, then we found a simple induction variable!
1192 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1193 // If there is a single occurrence of the symbolic value, replace it
1194 // with a recurrence.
1195 unsigned FoundIndex = Add->getNumOperands();
1196 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1197 if (Add->getOperand(i) == SymbolicName)
1198 if (FoundIndex == e) {
1199 FoundIndex = i;
1200 break;
1201 }
1202
1203 if (FoundIndex != Add->getNumOperands()) {
1204 // Create an add with everything but the specified operand.
1205 std::vector<SCEVHandle> Ops;
1206 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1207 if (i != FoundIndex)
1208 Ops.push_back(Add->getOperand(i));
1209 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1210
1211 // This is not a valid addrec if the step amount is varying each
1212 // loop iteration, but is not itself an addrec in this loop.
1213 if (Accum->isLoopInvariant(L) ||
1214 (isa<SCEVAddRecExpr>(Accum) &&
1215 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1216 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1217 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1218
1219 // Okay, for the entire analysis of this edge we assumed the PHI
1220 // to be symbolic. We now need to go back and update all of the
1221 // entries for the scalars that use the PHI (except for the PHI
1222 // itself) to use the new analyzed value instead of the "symbolic"
1223 // value.
1224 Scalars.find(PN)->second = PHISCEV; // Update the PHI value
1225 std::set<Instruction*> UpdatedInsts;
1226 UpdatedInsts.insert(PN);
1227 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
1228 UI != E; ++UI)
1229 UpdatePHIUserScalarEntries(cast<Instruction>(*UI), PN,
1230 UpdatedInsts);
1231 return PHISCEV;
1232 }
1233 }
1234 }
1235
1236 return SymbolicName;
1237 }
1238
1239 // If it's not a loop phi, we can't handle it yet.
1240 return SCEVUnknown::get(PN);
1241}
1242
1243/// createNodeForCast - Handle the various forms of casts that we support.
1244///
1245SCEVHandle ScalarEvolutionsImpl::createNodeForCast(CastInst *CI) {
1246 const Type *SrcTy = CI->getOperand(0)->getType();
1247 const Type *DestTy = CI->getType();
1248
1249 // If this is a noop cast (ie, conversion from int to uint), ignore it.
1250 if (SrcTy->isLosslesslyConvertibleTo(DestTy))
1251 return getSCEV(CI->getOperand(0));
1252
1253 if (SrcTy->isInteger() && DestTy->isInteger()) {
1254 // Otherwise, if this is a truncating integer cast, we can represent this
1255 // cast.
1256 if (SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1257 return SCEVTruncateExpr::get(getSCEV(CI->getOperand(0)),
1258 CI->getType()->getUnsignedVersion());
1259 if (SrcTy->isUnsigned() &&
1260 SrcTy->getPrimitiveSize() > DestTy->getPrimitiveSize())
1261 return SCEVZeroExtendExpr::get(getSCEV(CI->getOperand(0)),
1262 CI->getType()->getUnsignedVersion());
1263 }
1264
1265 // If this is an sign or zero extending cast and we can prove that the value
1266 // will never overflow, we could do similar transformations.
1267
1268 // Otherwise, we can't handle this cast!
1269 return SCEVUnknown::get(CI);
1270}
1271
1272
1273/// createSCEV - We know that there is no SCEV for the specified value.
1274/// Analyze the expression.
1275///
1276SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1277 if (Instruction *I = dyn_cast<Instruction>(V)) {
1278 switch (I->getOpcode()) {
1279 case Instruction::Add:
1280 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1281 getSCEV(I->getOperand(1)));
1282 case Instruction::Mul:
1283 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1284 getSCEV(I->getOperand(1)));
1285 case Instruction::Div:
1286 if (V->getType()->isInteger() && V->getType()->isUnsigned())
1287 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)),
1288 getSCEV(I->getOperand(1)));
1289 break;
1290
1291 case Instruction::Sub:
1292 return getMinusSCEV(getSCEV(I->getOperand(0)), getSCEV(I->getOperand(1)));
1293
1294 case Instruction::Shl:
1295 // Turn shift left of a constant amount into a multiply.
1296 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1297 Constant *X = ConstantInt::get(V->getType(), 1);
1298 X = ConstantExpr::getShl(X, SA);
1299 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1300 }
1301 break;
1302
1303 case Instruction::Shr:
1304 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
1305 if (V->getType()->isUnsigned()) {
1306 Constant *X = ConstantInt::get(V->getType(), 1);
1307 X = ConstantExpr::getShl(X, SA);
1308 return SCEVUDivExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1309 }
1310 break;
1311
1312 case Instruction::Cast:
1313 return createNodeForCast(cast<CastInst>(I));
1314
1315 case Instruction::PHI:
1316 return createNodeForPHI(cast<PHINode>(I));
1317
1318 default: // We cannot analyze this expression.
1319 break;
1320 }
1321 }
1322
1323 return SCEVUnknown::get(V);
1324}
1325
1326
1327
1328//===----------------------------------------------------------------------===//
1329// Iteration Count Computation Code
1330//
1331
1332/// getIterationCount - If the specified loop has a predictable iteration
1333/// count, return it. Note that it is not valid to call this method on a
1334/// loop without a loop-invariant iteration count.
1335SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1336 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1337 if (I == IterationCounts.end()) {
1338 SCEVHandle ItCount = ComputeIterationCount(L);
1339 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1340 if (ItCount != UnknownValue) {
1341 assert(ItCount->isLoopInvariant(L) &&
1342 "Computed trip count isn't loop invariant for loop!");
1343 ++NumTripCountsComputed;
1344 } else if (isa<PHINode>(L->getHeader()->begin())) {
1345 // Only count loops that have phi nodes as not being computable.
1346 ++NumTripCountsNotComputed;
1347 }
1348 }
1349 return I->second;
1350}
1351
1352/// ComputeIterationCount - Compute the number of times the specified loop
1353/// will iterate.
1354SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1355 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001356 std::vector<BasicBlock*> ExitBlocks;
1357 L->getExitBlocks(ExitBlocks);
1358 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattnerd934c702004-04-02 20:23:17 +00001359
1360 // Okay, there is one exit block. Try to find the condition that causes the
1361 // loop to be exited.
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00001362 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00001363
1364 BasicBlock *ExitingBlock = 0;
1365 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1366 PI != E; ++PI)
1367 if (L->contains(*PI)) {
1368 if (ExitingBlock == 0)
1369 ExitingBlock = *PI;
1370 else
1371 return UnknownValue; // More than one block exiting!
1372 }
1373 assert(ExitingBlock && "No exits from loop, something is broken!");
1374
1375 // Okay, we've computed the exiting block. See what condition causes us to
1376 // exit.
1377 //
1378 // FIXME: we should be able to handle switch instructions (with a single exit)
1379 // FIXME: We should handle cast of int to bool as well
1380 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1381 if (ExitBr == 0) return UnknownValue;
1382 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1383 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner4021d1a2004-04-17 18:36:24 +00001384 if (ExitCond == 0) // Not a setcc
1385 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1386 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattnerd934c702004-04-02 20:23:17 +00001387
1388 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1389 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1390
1391 // Try to evaluate any dependencies out of the loop.
1392 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1393 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1394 Tmp = getSCEVAtScope(RHS, L);
1395 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1396
1397 // If the condition was exit on true, convert the condition to exit on false.
1398 Instruction::BinaryOps Cond;
1399 if (ExitBr->getSuccessor(1) == ExitBlock)
1400 Cond = ExitCond->getOpcode();
1401 else
1402 Cond = ExitCond->getInverseCondition();
1403
1404 // At this point, we would like to compute how many iterations of the loop the
1405 // predicate will return true for these inputs.
1406 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1407 // If there is a constant, force it into the RHS.
1408 std::swap(LHS, RHS);
1409 Cond = SetCondInst::getSwappedCondition(Cond);
1410 }
1411
1412 // FIXME: think about handling pointer comparisons! i.e.:
1413 // while (P != P+100) ++P;
1414
1415 // If we have a comparison of a chrec against a constant, try to use value
1416 // ranges to answer this query.
1417 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1418 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1419 if (AddRec->getLoop() == L) {
1420 // Form the comparison range using the constant of the correct type so
1421 // that the ConstantRange class knows to do a signed or unsigned
1422 // comparison.
1423 ConstantInt *CompVal = RHSC->getValue();
1424 const Type *RealTy = ExitCond->getOperand(0)->getType();
1425 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1426 if (CompVal) {
1427 // Form the constant range.
1428 ConstantRange CompRange(Cond, CompVal);
1429
1430 // Now that we have it, if it's signed, convert it to an unsigned
1431 // range.
1432 if (CompRange.getLower()->getType()->isSigned()) {
1433 const Type *NewTy = RHSC->getValue()->getType();
1434 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1435 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1436 CompRange = ConstantRange(NewL, NewU);
1437 }
1438
1439 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1440 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1441 }
1442 }
1443
1444 switch (Cond) {
1445 case Instruction::SetNE: // while (X != Y)
1446 // Convert to: while (X-Y != 0)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001447 if (LHS->getType()->isInteger()) {
1448 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
1449 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1450 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001451 break;
1452 case Instruction::SetEQ:
1453 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001454 if (LHS->getType()->isInteger()) {
1455 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
1456 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1457 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001458 break;
1459 default:
Chris Lattner09169212004-04-02 20:26:46 +00001460#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00001461 std::cerr << "ComputeIterationCount ";
1462 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1463 std::cerr << "[unsigned] ";
1464 std::cerr << *LHS << " "
1465 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00001466#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00001467 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00001468 }
Chris Lattner4021d1a2004-04-17 18:36:24 +00001469
1470 return ComputeIterationCountExhaustively(L, ExitCond,
1471 ExitBr->getSuccessor(0) == ExitBlock);
1472}
1473
Chris Lattnerdd730472004-04-17 22:58:41 +00001474/// CanConstantFold - Return true if we can constant fold an instruction of the
1475/// specified type, assuming that all operands were constants.
1476static bool CanConstantFold(const Instruction *I) {
1477 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1478 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1479 return true;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001480
Chris Lattnerdd730472004-04-17 22:58:41 +00001481 if (const CallInst *CI = dyn_cast<CallInst>(I))
1482 if (const Function *F = CI->getCalledFunction())
1483 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1484 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001485}
1486
Chris Lattnerdd730472004-04-17 22:58:41 +00001487/// ConstantFold - Constant fold an instruction of the specified type with the
1488/// specified constant operands. This function may modify the operands vector.
1489static Constant *ConstantFold(const Instruction *I,
1490 std::vector<Constant*> &Operands) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00001491 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1492 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1493
1494 switch (I->getOpcode()) {
1495 case Instruction::Cast:
1496 return ConstantExpr::getCast(Operands[0], I->getType());
1497 case Instruction::Select:
1498 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1499 case Instruction::Call:
1500 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Operands[0])) {
1501 Operands.erase(Operands.begin());
1502 return ConstantFoldCall(cast<Function>(CPR->getValue()), Operands);
1503 }
1504
1505 return 0;
1506 case Instruction::GetElementPtr:
1507 Constant *Base = Operands[0];
1508 Operands.erase(Operands.begin());
1509 return ConstantExpr::getGetElementPtr(Base, Operands);
1510 }
1511 return 0;
1512}
1513
1514
Chris Lattnerdd730472004-04-17 22:58:41 +00001515/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1516/// in the loop that V is derived from. We allow arbitrary operations along the
1517/// way, but the operands of an operation must either be constants or a value
1518/// derived from a constant PHI. If this expression does not fit with these
1519/// constraints, return null.
1520static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1521 // If this is not an instruction, or if this is an instruction outside of the
1522 // loop, it can't be derived from a loop PHI.
1523 Instruction *I = dyn_cast<Instruction>(V);
1524 if (I == 0 || !L->contains(I->getParent())) return 0;
1525
1526 if (PHINode *PN = dyn_cast<PHINode>(I))
1527 if (L->getHeader() == I->getParent())
1528 return PN;
1529 else
1530 // We don't currently keep track of the control flow needed to evaluate
1531 // PHIs, so we cannot handle PHIs inside of loops.
1532 return 0;
1533
1534 // If we won't be able to constant fold this expression even if the operands
1535 // are constants, return early.
1536 if (!CanConstantFold(I)) return 0;
1537
1538 // Otherwise, we can evaluate this instruction if all of its operands are
1539 // constant or derived from a PHI node themselves.
1540 PHINode *PHI = 0;
1541 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1542 if (!(isa<Constant>(I->getOperand(Op)) ||
1543 isa<GlobalValue>(I->getOperand(Op)))) {
1544 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1545 if (P == 0) return 0; // Not evolving from PHI
1546 if (PHI == 0)
1547 PHI = P;
1548 else if (PHI != P)
1549 return 0; // Evolving from multiple different PHIs.
1550 }
1551
1552 // This is a expression evolving from a constant PHI!
1553 return PHI;
1554}
1555
1556/// EvaluateExpression - Given an expression that passes the
1557/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1558/// in the loop has the value PHIVal. If we can't fold this expression for some
1559/// reason, return null.
1560static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1561 if (isa<PHINode>(V)) return PHIVal;
1562 if (Constant *C = dyn_cast<Constant>(V)) return C;
1563 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
1564 return ConstantPointerRef::get(GV);
1565 Instruction *I = cast<Instruction>(V);
1566
1567 std::vector<Constant*> Operands;
1568 Operands.resize(I->getNumOperands());
1569
1570 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1571 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1572 if (Operands[i] == 0) return 0;
1573 }
1574
1575 return ConstantFold(I, Operands);
1576}
1577
1578/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1579/// in the header of its containing loop, we know the loop executes a
1580/// constant number of times, and the PHI node is just a recurrence
1581/// involving constants, fold it.
1582Constant *ScalarEvolutionsImpl::
1583getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1584 std::map<PHINode*, Constant*>::iterator I =
1585 ConstantEvolutionLoopExitValue.find(PN);
1586 if (I != ConstantEvolutionLoopExitValue.end())
1587 return I->second;
1588
1589 if (Its > MaxBruteForceIterations)
1590 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1591
1592 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1593
1594 // Since the loop is canonicalized, the PHI node must have two entries. One
1595 // entry must be a constant (coming in from outside of the loop), and the
1596 // second must be derived from the same PHI.
1597 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1598 Constant *StartCST =
1599 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1600 if (StartCST == 0)
1601 return RetVal = 0; // Must be a constant.
1602
1603 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1604 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1605 if (PN2 != PN)
1606 return RetVal = 0; // Not derived from same PHI.
1607
1608 // Execute the loop symbolically to determine the exit value.
1609 unsigned IterationNum = 0;
1610 unsigned NumIterations = Its;
1611 if (NumIterations != Its)
1612 return RetVal = 0; // More than 2^32 iterations??
1613
1614 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1615 if (IterationNum == NumIterations)
1616 return RetVal = PHIVal; // Got exit value!
1617
1618 // Compute the value of the PHI node for the next iteration.
1619 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1620 if (NextPHI == PHIVal)
1621 return RetVal = NextPHI; // Stopped evolving!
1622 if (NextPHI == 0)
1623 return 0; // Couldn't evaluate!
1624 PHIVal = NextPHI;
1625 }
1626}
1627
Chris Lattner4021d1a2004-04-17 18:36:24 +00001628/// ComputeIterationCountExhaustively - If the trip is known to execute a
1629/// constant number of times (the condition evolves only from constants),
1630/// try to evaluate a few iterations of the loop until we get the exit
1631/// condition gets a value of ExitWhen (true or false). If we cannot
1632/// evaluate the trip count of the loop, return UnknownValue.
1633SCEVHandle ScalarEvolutionsImpl::
1634ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1635 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1636 if (PN == 0) return UnknownValue;
1637
1638 // Since the loop is canonicalized, the PHI node must have two entries. One
1639 // entry must be a constant (coming in from outside of the loop), and the
1640 // second must be derived from the same PHI.
1641 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1642 Constant *StartCST =
1643 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1644 if (StartCST == 0) return UnknownValue; // Must be a constant.
1645
1646 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1647 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1648 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1649
1650 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1651 // the loop symbolically to determine when the condition gets a value of
1652 // "ExitWhen".
1653 unsigned IterationNum = 0;
1654 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1655 for (Constant *PHIVal = StartCST;
1656 IterationNum != MaxIterations; ++IterationNum) {
1657 ConstantBool *CondVal =
1658 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1659 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattnerdd730472004-04-17 22:58:41 +00001660
Chris Lattner4021d1a2004-04-17 18:36:24 +00001661 if (CondVal->getValue() == ExitWhen) {
Chris Lattnerdd730472004-04-17 22:58:41 +00001662 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001663 ++NumBruteForceTripCountsComputed;
1664 return SCEVConstant::get(ConstantUInt::get(Type::UIntTy, IterationNum));
1665 }
1666
Chris Lattnerdd730472004-04-17 22:58:41 +00001667 // Compute the value of the PHI node for the next iteration.
1668 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1669 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner4021d1a2004-04-17 18:36:24 +00001670 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattnerdd730472004-04-17 22:58:41 +00001671 PHIVal = NextPHI;
Chris Lattner4021d1a2004-04-17 18:36:24 +00001672 }
1673
1674 // Too many iterations were needed to evaluate.
Chris Lattnerd934c702004-04-02 20:23:17 +00001675 return UnknownValue;
1676}
1677
1678/// getSCEVAtScope - Compute the value of the specified expression within the
1679/// indicated loop (which may be null to indicate in no loop). If the
1680/// expression cannot be evaluated, return UnknownValue.
1681SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1682 // FIXME: this should be turned into a virtual method on SCEV!
1683
Chris Lattnerdd730472004-04-17 22:58:41 +00001684 if (isa<SCEVConstant>(V)) return V;
1685
1686 // If this instruction is evolves from a constant-evolving PHI, compute the
1687 // exit value from the loop without using SCEVs.
1688 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1689 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1690 const Loop *LI = this->LI[I->getParent()];
1691 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1692 if (PHINode *PN = dyn_cast<PHINode>(I))
1693 if (PN->getParent() == LI->getHeader()) {
1694 // Okay, there is no closed form solution for the PHI node. Check
1695 // to see if the loop that contains it has a known iteration count.
1696 // If so, we may be able to force computation of the exit value.
1697 SCEVHandle IterationCount = getIterationCount(LI);
1698 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1699 // Okay, we know how many times the containing loop executes. If
1700 // this is a constant evolving PHI node, get the final value at
1701 // the specified iteration number.
1702 Constant *RV = getConstantEvolutionLoopExitValue(PN,
1703 ICC->getValue()->getRawValue(),
1704 LI);
1705 if (RV) return SCEVUnknown::get(RV);
1706 }
1707 }
1708
1709 // Okay, this is a some expression that we cannot symbolically evaluate
1710 // into a SCEV. Check to see if it's possible to symbolically evaluate
1711 // the arguments into constants, and if see, try to constant propagate the
1712 // result. This is particularly useful for computing loop exit values.
1713 if (CanConstantFold(I)) {
1714 std::vector<Constant*> Operands;
1715 Operands.reserve(I->getNumOperands());
1716 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1717 Value *Op = I->getOperand(i);
1718 if (Constant *C = dyn_cast<Constant>(Op)) {
1719 Operands.push_back(C);
1720 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Op)) {
1721 Operands.push_back(ConstantPointerRef::get(GV));
1722 } else {
1723 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1724 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1725 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1726 Op->getType()));
1727 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1728 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1729 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1730 else
1731 return V;
1732 } else {
1733 return V;
1734 }
1735 }
1736 }
1737 return SCEVUnknown::get(ConstantFold(I, Operands));
1738 }
1739 }
1740
1741 // This is some other type of SCEVUnknown, just return it.
1742 return V;
1743 }
1744
Chris Lattnerd934c702004-04-02 20:23:17 +00001745 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1746 // Avoid performing the look-up in the common case where the specified
1747 // expression has no loop-variant portions.
1748 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1749 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1750 if (OpAtScope != Comm->getOperand(i)) {
1751 if (OpAtScope == UnknownValue) return UnknownValue;
1752 // Okay, at least one of these operands is loop variant but might be
1753 // foldable. Build a new instance of the folded commutative expression.
Chris Lattnerdd730472004-04-17 22:58:41 +00001754 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00001755 NewOps.push_back(OpAtScope);
1756
1757 for (++i; i != e; ++i) {
1758 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1759 if (OpAtScope == UnknownValue) return UnknownValue;
1760 NewOps.push_back(OpAtScope);
1761 }
1762 if (isa<SCEVAddExpr>(Comm))
1763 return SCEVAddExpr::get(NewOps);
1764 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1765 return SCEVMulExpr::get(NewOps);
1766 }
1767 }
1768 // If we got here, all operands are loop invariant.
1769 return Comm;
1770 }
1771
1772 if (SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(V)) {
1773 SCEVHandle LHS = getSCEVAtScope(UDiv->getLHS(), L);
1774 if (LHS == UnknownValue) return LHS;
1775 SCEVHandle RHS = getSCEVAtScope(UDiv->getRHS(), L);
1776 if (RHS == UnknownValue) return RHS;
1777 if (LHS == UDiv->getLHS() && RHS == UDiv->getRHS())
1778 return UDiv; // must be loop invariant
1779 return SCEVUDivExpr::get(LHS, RHS);
1780 }
1781
1782 // If this is a loop recurrence for a loop that does not contain L, then we
1783 // are dealing with the final value computed by the loop.
1784 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1785 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1786 // To evaluate this recurrence, we need to know how many times the AddRec
1787 // loop iterates. Compute this now.
1788 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
1789 if (IterationCount == UnknownValue) return UnknownValue;
1790 IterationCount = getTruncateOrZeroExtend(IterationCount,
1791 AddRec->getType());
1792
1793 // If the value is affine, simplify the expression evaluation to just
1794 // Start + Step*IterationCount.
1795 if (AddRec->isAffine())
1796 return SCEVAddExpr::get(AddRec->getStart(),
1797 SCEVMulExpr::get(IterationCount,
1798 AddRec->getOperand(1)));
1799
1800 // Otherwise, evaluate it the hard way.
1801 return AddRec->evaluateAtIteration(IterationCount);
1802 }
1803 return UnknownValue;
1804 }
1805
1806 //assert(0 && "Unknown SCEV type!");
1807 return UnknownValue;
1808}
1809
1810
1811/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
1812/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
1813/// might be the same) or two SCEVCouldNotCompute objects.
1814///
1815static std::pair<SCEVHandle,SCEVHandle>
1816SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
1817 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
1818 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
1819 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
1820 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
1821
1822 // We currently can only solve this if the coefficients are constants.
1823 if (!L || !M || !N) {
1824 SCEV *CNC = new SCEVCouldNotCompute();
1825 return std::make_pair(CNC, CNC);
1826 }
1827
1828 Constant *Two = ConstantInt::get(L->getValue()->getType(), 2);
1829
1830 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
1831 Constant *C = L->getValue();
1832 // The B coefficient is M-N/2
1833 Constant *B = ConstantExpr::getSub(M->getValue(),
1834 ConstantExpr::getDiv(N->getValue(),
1835 Two));
1836 // The A coefficient is N/2
1837 Constant *A = ConstantExpr::getDiv(N->getValue(), Two);
1838
1839 // Compute the B^2-4ac term.
1840 Constant *SqrtTerm =
1841 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
1842 ConstantExpr::getMul(A, C));
1843 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
1844
1845 // Compute floor(sqrt(B^2-4ac))
1846 ConstantUInt *SqrtVal =
1847 cast<ConstantUInt>(ConstantExpr::getCast(SqrtTerm,
1848 SqrtTerm->getType()->getUnsignedVersion()));
1849 uint64_t SqrtValV = SqrtVal->getValue();
Chris Lattnerd4f78f22004-04-05 19:05:15 +00001850 uint64_t SqrtValV2 = (uint64_t)sqrt(SqrtValV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001851 // The square root might not be precise for arbitrary 64-bit integer
1852 // values. Do some sanity checks to ensure it's correct.
1853 if (SqrtValV2*SqrtValV2 > SqrtValV ||
1854 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
1855 SCEV *CNC = new SCEVCouldNotCompute();
1856 return std::make_pair(CNC, CNC);
1857 }
1858
1859 SqrtVal = ConstantUInt::get(Type::ULongTy, SqrtValV2);
1860 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
1861
1862 Constant *NegB = ConstantExpr::getNeg(B);
1863 Constant *TwoA = ConstantExpr::getMul(A, Two);
1864
1865 // The divisions must be performed as signed divisions.
1866 const Type *SignedTy = NegB->getType()->getSignedVersion();
1867 NegB = ConstantExpr::getCast(NegB, SignedTy);
1868 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
1869 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
1870
1871 Constant *Solution1 =
1872 ConstantExpr::getDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
1873 Constant *Solution2 =
1874 ConstantExpr::getDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
1875 return std::make_pair(SCEVUnknown::get(Solution1),
1876 SCEVUnknown::get(Solution2));
1877}
1878
1879/// HowFarToZero - Return the number of times a backedge comparing the specified
1880/// value to zero will execute. If not computable, return UnknownValue
1881SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
1882 // If the value is a constant
1883 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1884 // If the value is already zero, the branch will execute zero times.
1885 if (C->getValue()->isNullValue()) return C;
1886 return UnknownValue; // Otherwise it will loop infinitely.
1887 }
1888
1889 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
1890 if (!AddRec || AddRec->getLoop() != L)
1891 return UnknownValue;
1892
1893 if (AddRec->isAffine()) {
1894 // If this is an affine expression the execution count of this branch is
1895 // equal to:
1896 //
1897 // (0 - Start/Step) iff Start % Step == 0
1898 //
1899 // Get the initial value for the loop.
1900 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
1901 SCEVHandle Step = AddRec->getOperand(1);
1902
1903 Step = getSCEVAtScope(Step, L->getParentLoop());
1904
1905 // Figure out if Start % Step == 0.
1906 // FIXME: We should add DivExpr and RemExpr operations to our AST.
1907 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
1908 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
1909 return getNegativeSCEV(Start); // 0 - Start/1 == -Start
1910 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
1911 return Start; // 0 - Start/-1 == Start
1912
1913 // Check to see if Start is divisible by SC with no remainder.
1914 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
1915 ConstantInt *StartCC = StartC->getValue();
1916 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
1917 Constant *Rem = ConstantExpr::getRem(StartNegC, StepC->getValue());
1918 if (Rem->isNullValue()) {
1919 Constant *Result =ConstantExpr::getDiv(StartNegC,StepC->getValue());
1920 return SCEVUnknown::get(Result);
1921 }
1922 }
1923 }
1924 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
1925 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
1926 // the quadratic equation to solve it.
1927 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
1928 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
1929 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
1930 if (R1) {
Chris Lattner09169212004-04-02 20:26:46 +00001931#if 0
Chris Lattnerd934c702004-04-02 20:23:17 +00001932 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
1933 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00001934#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00001935 // Pick the smallest positive root value.
1936 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
1937 if (ConstantBool *CB =
1938 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
1939 R2->getValue()))) {
1940 if (CB != ConstantBool::True)
1941 std::swap(R1, R2); // R1 is the minimum root now.
1942
1943 // We can only use this value if the chrec ends up with an exact zero
1944 // value at this index. When solving for "X*X != 5", for example, we
1945 // should not accept a root of 2.
1946 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
1947 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
1948 if (EvalVal->getValue()->isNullValue())
1949 return R1; // We found a quadratic root!
1950 }
1951 }
1952 }
1953
1954 return UnknownValue;
1955}
1956
1957/// HowFarToNonZero - Return the number of times a backedge checking the
1958/// specified value for nonzero will execute. If not computable, return
1959/// UnknownValue
1960SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
1961 // Loops that look like: while (X == 0) are very strange indeed. We don't
1962 // handle them yet except for the trivial case. This could be expanded in the
1963 // future as needed.
1964
1965 // If the value is a constant, check to see if it is known to be non-zero
1966 // already. If so, the backedge will execute zero times.
1967 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
1968 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
1969 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
1970 if (NonZero == ConstantBool::True)
1971 return getSCEV(Zero);
1972 return UnknownValue; // Otherwise it will loop infinitely.
1973 }
1974
1975 // We could implement others, but I really doubt anyone writes loops like
1976 // this, and if they did, they would already be constant folded.
1977 return UnknownValue;
1978}
1979
1980static ConstantInt *
1981EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1982 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1983 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1984 assert(isa<SCEVConstant>(Val) &&
1985 "Evaluation of SCEV at constant didn't fold correctly?");
1986 return cast<SCEVConstant>(Val)->getValue();
1987}
1988
1989
1990/// getNumIterationsInRange - Return the number of iterations of this loop that
1991/// produce values in the specified constant range. Another way of looking at
1992/// this is that it returns the first iteration number where the value is not in
1993/// the condition, thus computing the exit count. If the iteration count can't
1994/// be computed, an instance of SCEVCouldNotCompute is returned.
1995SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
1996 if (Range.isFullSet()) // Infinite loop.
1997 return new SCEVCouldNotCompute();
1998
1999 // If the start is a non-zero constant, shift the range to simplify things.
2000 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2001 if (!SC->getValue()->isNullValue()) {
2002 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattner05ef97f2004-04-23 21:29:03 +00002003 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattnerd934c702004-04-02 20:23:17 +00002004 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2005 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2006 return ShiftedAddRec->getNumIterationsInRange(
2007 Range.subtract(SC->getValue()));
2008 // This is strange and shouldn't happen.
2009 return new SCEVCouldNotCompute();
2010 }
2011
2012 // The only time we can solve this is when we have all constant indices.
2013 // Otherwise, we cannot determine the overflow conditions.
2014 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2015 if (!isa<SCEVConstant>(getOperand(i)))
2016 return new SCEVCouldNotCompute();
2017
2018
2019 // Okay at this point we know that all elements of the chrec are constants and
2020 // that the start element is zero.
2021
2022 // First check to see if the range contains zero. If not, the first
2023 // iteration exits.
2024 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2025 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
2026
2027 if (isAffine()) {
2028 // If this is an affine expression then we have this situation:
2029 // Solve {0,+,A} in Range === Ax in Range
2030
2031 // Since we know that zero is in the range, we know that the upper value of
2032 // the range must be the first possible exit value. Also note that we
2033 // already checked for a full range.
2034 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2035 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2036 ConstantInt *One = ConstantInt::get(getType(), 1);
2037
2038 // The exit value should be (Upper+A-1)/A.
2039 Constant *ExitValue = Upper;
2040 if (A != One) {
2041 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
2042 ExitValue = ConstantExpr::getDiv(ExitValue, A);
2043 }
2044 assert(isa<ConstantInt>(ExitValue) &&
2045 "Constant folding of integers not implemented?");
2046
2047 // Evaluate at the exit value. If we really did fall out of the valid
2048 // range, then we computed our trip count, otherwise wrap around or other
2049 // things must have happened.
2050 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2051 if (Range.contains(Val))
2052 return new SCEVCouldNotCompute(); // Something strange happened
2053
2054 // Ensure that the previous value is in the range. This is a sanity check.
2055 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2056 ConstantExpr::getSub(ExitValue, One))) &&
2057 "Linear scev computation is off in a bad way!");
2058 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2059 } else if (isQuadratic()) {
2060 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2061 // quadratic equation to solve it. To do this, we must frame our problem in
2062 // terms of figuring out when zero is crossed, instead of when
2063 // Range.getUpper() is crossed.
2064 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
2065 NewOps[0] = getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
2066 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2067
2068 // Next, solve the constructed addrec
2069 std::pair<SCEVHandle,SCEVHandle> Roots =
2070 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2071 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2072 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2073 if (R1) {
2074 // Pick the smallest positive root value.
2075 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2076 if (ConstantBool *CB =
2077 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2078 R2->getValue()))) {
2079 if (CB != ConstantBool::True)
2080 std::swap(R1, R2); // R1 is the minimum root now.
2081
2082 // Make sure the root is not off by one. The returned iteration should
2083 // not be in the range, but the previous one should be. When solving
2084 // for "X*X < 5", for example, we should not return a root of 2.
2085 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2086 R1->getValue());
2087 if (Range.contains(R1Val)) {
2088 // The next iteration must be out of the range...
2089 Constant *NextVal =
2090 ConstantExpr::getAdd(R1->getValue(),
2091 ConstantInt::get(R1->getType(), 1));
2092
2093 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2094 if (!Range.contains(R1Val))
2095 return SCEVUnknown::get(NextVal);
2096 return new SCEVCouldNotCompute(); // Something strange happened
2097 }
2098
2099 // If R1 was not in the range, then it is a good return value. Make
2100 // sure that R1-1 WAS in the range though, just in case.
2101 Constant *NextVal =
2102 ConstantExpr::getSub(R1->getValue(),
2103 ConstantInt::get(R1->getType(), 1));
2104 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2105 if (Range.contains(R1Val))
2106 return R1;
2107 return new SCEVCouldNotCompute(); // Something strange happened
2108 }
2109 }
2110 }
2111
2112 // Fallback, if this is a general polynomial, figure out the progression
2113 // through brute force: evaluate until we find an iteration that fails the
2114 // test. This is likely to be slow, but getting an accurate trip count is
2115 // incredibly important, we will be able to simplify the exit test a lot, and
2116 // we are almost guaranteed to get a trip count in this case.
2117 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2118 ConstantInt *One = ConstantInt::get(getType(), 1);
2119 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2120 do {
2121 ++NumBruteForceEvaluations;
2122 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2123 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2124 return new SCEVCouldNotCompute();
2125
2126 // Check to see if we found the value!
2127 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2128 return SCEVConstant::get(TestVal);
2129
2130 // Increment to test the next index.
2131 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2132 } while (TestVal != EndVal);
2133
2134 return new SCEVCouldNotCompute();
2135}
2136
2137
2138
2139//===----------------------------------------------------------------------===//
2140// ScalarEvolution Class Implementation
2141//===----------------------------------------------------------------------===//
2142
2143bool ScalarEvolution::runOnFunction(Function &F) {
2144 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2145 return false;
2146}
2147
2148void ScalarEvolution::releaseMemory() {
2149 delete (ScalarEvolutionsImpl*)Impl;
2150 Impl = 0;
2151}
2152
2153void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2154 AU.setPreservesAll();
2155 AU.addRequiredID(LoopSimplifyID);
2156 AU.addRequiredTransitive<LoopInfo>();
2157}
2158
2159SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2160 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2161}
2162
2163SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2164 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2165}
2166
2167bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2168 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2169}
2170
2171SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2172 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2173}
2174
2175void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2176 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2177}
2178
2179
2180/// shouldSubstituteIndVar - Return true if we should perform induction variable
2181/// substitution for this variable. This is a hack because we don't have a
2182/// strength reduction pass yet. When we do we will promote all vars, because
2183/// we can strength reduce them later as desired.
2184bool ScalarEvolution::shouldSubstituteIndVar(const SCEV *S) const {
2185 // Don't substitute high degree polynomials.
2186 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S))
2187 if (AddRec->getNumOperands() > 3) return false;
2188 return true;
2189}
2190
2191
2192static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2193 const Loop *L) {
2194 // Print all inner loops first
2195 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2196 PrintLoopInfo(OS, SE, *I);
2197
2198 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00002199
2200 std::vector<BasicBlock*> ExitBlocks;
2201 L->getExitBlocks(ExitBlocks);
2202 if (ExitBlocks.size() != 1)
Chris Lattnerd934c702004-04-02 20:23:17 +00002203 std::cerr << "<multiple exits> ";
2204
2205 if (SE->hasLoopInvariantIterationCount(L)) {
2206 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2207 } else {
2208 std::cerr << "Unpredictable iteration count. ";
2209 }
2210
2211 std::cerr << "\n";
2212}
2213
2214void ScalarEvolution::print(std::ostream &OS) const {
2215 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2216 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2217
2218 OS << "Classifying expressions for: " << F.getName() << "\n";
2219 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002220 if (I->getType()->isInteger()) {
2221 OS << *I;
Chris Lattnerd934c702004-04-02 20:23:17 +00002222 OS << " --> ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002223 SCEVHandle SV = getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00002224 SV->print(OS);
2225 OS << "\t\t";
2226
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002227 if ((*I).getType()->isIntegral()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002228 ConstantRange Bounds = SV->getValueRange();
2229 if (!Bounds.isFullSet())
2230 OS << "Bounds: " << Bounds << " ";
2231 }
2232
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002233 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002234 OS << "Exits: ";
Chris Lattner2d3a7a62004-04-27 15:13:33 +00002235 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattnerd934c702004-04-02 20:23:17 +00002236 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2237 OS << "<<Unknown>>";
2238 } else {
2239 OS << *ExitValue;
2240 }
2241 }
2242
2243
2244 OS << "\n";
2245 }
2246
2247 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2248 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2249 PrintLoopInfo(OS, this, *I);
2250}
2251