1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
11 // catagorize scalar expressions in loops. It specializes in recognizing
12 // general induction variables, representing them with the abstract and opaque
13 // SCEV class. Given this analysis, trip counts of loops and other important
14 // properties can be obtained.
16 // This analysis is primarily useful for induction variable substitution and
17 // strength reduction.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/Support/DataTypes.h"
34 class ScalarEvolution;
37 /// SCEV - This class represent an analyzed expression in the program. These
38 /// are reference counted opaque objects that the client is not allowed to
39 /// do much with directly.
42 const unsigned SCEVType; // The SCEV baseclass this node corresponds to
43 mutable unsigned RefCount;
45 friend class SCEVHandle;
46 void addRef() const { ++RefCount; }
47 void dropRef() const {
52 SCEV(const SCEV &); // DO NOT IMPLEMENT
53 void operator=(const SCEV &); // DO NOT IMPLEMENT
57 explicit SCEV(unsigned SCEVTy) : SCEVType(SCEVTy), RefCount(0) {}
59 unsigned getSCEVType() const { return SCEVType; }
61 /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
62 /// the specified loop.
63 virtual bool isLoopInvariant(const Loop *L) const = 0;
65 /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
66 /// known way in the specified loop. This property being true implies that
67 /// the value is variant in the loop AND that we can emit an expression to
68 /// compute the value of the expression at any particular loop iteration.
69 virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
71 /// getType - Return the LLVM type of this SCEV expression.
73 virtual const Type *getType() const = 0;
75 /// isZero - Return true if the expression is a constant zero.
79 /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
80 /// the symbolic value "Sym", construct and return a new SCEV that produces
81 /// the same value, but which uses the concrete value Conc instead of the
82 /// symbolic value. If this SCEV does not use the symbolic value, it
85 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
86 const SCEVHandle &Conc,
87 ScalarEvolution &SE) const = 0;
89 /// dominates - Return true if elements that makes up this SCEV dominates
90 /// the specified basic block.
91 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
93 /// print - Print out the internal representation of this scalar to the
94 /// specified stream. This should really only be used for debugging
96 virtual void print(raw_ostream &OS) const = 0;
97 void print(std::ostream &OS) const;
98 void print(std::ostream *OS) const { if (OS) print(*OS); }
100 /// dump - This method is used for debugging.
105 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
110 inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
115 /// SCEVCouldNotCompute - An object of this class is returned by queries that
116 /// could not be answered. For example, if you ask for the number of
117 /// iterations of a linked-list traversal loop, you will get one of these.
118 /// None of the standard SCEV operations are valid on this class, it is just a
120 struct SCEVCouldNotCompute : public SCEV {
121 SCEVCouldNotCompute();
122 ~SCEVCouldNotCompute();
124 // None of these methods are valid for this object.
125 virtual bool isLoopInvariant(const Loop *L) const;
126 virtual const Type *getType() const;
127 virtual bool hasComputableLoopEvolution(const Loop *L) const;
128 virtual void print(raw_ostream &OS) const;
130 replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
131 const SCEVHandle &Conc,
132 ScalarEvolution &SE) const;
134 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
138 /// Methods for support type inquiry through isa, cast, and dyn_cast:
139 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
140 static bool classof(const SCEV *S);
143 /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
144 /// freeing the objects when the last reference is dropped.
147 SCEVHandle(); // DO NOT IMPLEMENT
149 SCEVHandle(const SCEV *s) : S(const_cast<SCEV*>(s)) {
150 assert(S && "Cannot create a handle to a null SCEV!");
153 SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
156 ~SCEVHandle() { S->dropRef(); }
158 operator SCEV*() const { return S; }
160 SCEV &operator*() const { return *S; }
161 SCEV *operator->() const { return S; }
163 bool operator==(SCEV *RHS) const { return S == RHS; }
164 bool operator!=(SCEV *RHS) const { return S != RHS; }
166 const SCEVHandle &operator=(SCEV *RHS) {
175 const SCEVHandle &operator=(const SCEVHandle &RHS) {
185 template<typename From> struct simplify_type;
186 template<> struct simplify_type<const SCEVHandle> {
187 typedef SCEV* SimpleType;
188 static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
192 template<> struct simplify_type<SCEVHandle>
193 : public simplify_type<const SCEVHandle> {};
195 /// ScalarEvolution - This class is the main scalar evolution driver. Because
196 /// client code (intentionally) can't do much with the SCEV objects directly,
197 /// they must ask this class for services.
199 class ScalarEvolution : public FunctionPass {
200 /// F - The function we are analyzing.
204 /// LI - The loop information for the function we are currently analyzing.
208 /// TD - The target data information for the target we are targetting.
212 /// UnknownValue - This SCEV is used to represent unknown trip counts and
214 SCEVHandle UnknownValue;
216 /// Scalars - This is a cache of the scalars we have analyzed so far.
218 std::map<Value*, SCEVHandle> Scalars;
220 /// BackedgeTakenInfo - Information about the backedge-taken count
221 /// of a loop. This currently inclues an exact count and a maximum count.
223 struct BackedgeTakenInfo {
224 /// Exact - An expression indicating the exact backedge-taken count of
225 /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
228 /// Exact - An expression indicating the least maximum backedge-taken
229 /// count of the loop that is known, or a SCEVCouldNotCompute.
232 /*implicit*/ BackedgeTakenInfo(SCEVHandle exact) :
233 Exact(exact), Max(exact) {}
235 /*implicit*/ BackedgeTakenInfo(SCEV *exact) :
236 Exact(exact), Max(exact) {}
238 BackedgeTakenInfo(SCEVHandle exact, SCEVHandle max) :
239 Exact(exact), Max(max) {}
241 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
242 /// computed information, or whether it's all SCEVCouldNotCompute
244 bool hasAnyInfo() const {
245 return !isa<SCEVCouldNotCompute>(Exact) ||
246 !isa<SCEVCouldNotCompute>(Max);
250 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
251 /// this function as they are computed.
252 std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
254 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
255 /// the PHI instructions that we attempt to compute constant evolutions for.
256 /// This allows us to avoid potentially expensive recomputation of these
257 /// properties. An instruction maps to null if we are unable to compute its
259 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
261 /// createSCEV - We know that there is no SCEV for the specified value.
262 /// Analyze the expression.
263 SCEVHandle createSCEV(Value *V);
265 /// createNodeForPHI - Provide the special handling we need to analyze PHI
267 SCEVHandle createNodeForPHI(PHINode *PN);
269 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
270 /// for the specified instruction and replaces any references to the
271 /// symbolic value SymName with the specified value. This is used during
273 void ReplaceSymbolicValueWithConcrete(Instruction *I,
274 const SCEVHandle &SymName,
275 const SCEVHandle &NewVal);
277 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
278 /// loop, lazily computing new values if the loop hasn't been analyzed
280 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
282 /// ComputeBackedgeTakenCount - Compute the number of times the specified
283 /// loop will iterate.
284 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
286 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
287 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
289 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
292 ICmpInst::Predicate p);
294 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
295 /// a constant number of times (the condition evolves only from constants),
296 /// try to evaluate a few iterations of the loop until we get the exit
297 /// condition gets a value of ExitWhen (true or false). If we cannot
298 /// evaluate the trip count of the loop, return UnknownValue.
299 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
302 /// HowFarToZero - Return the number of times a backedge comparing the
303 /// specified value to zero will execute. If not computable, return
305 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
307 /// HowFarToNonZero - Return the number of times a backedge checking the
308 /// specified value for nonzero will execute. If not computable, return
310 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
312 /// HowManyLessThans - Return the number of times a backedge containing the
313 /// specified less-than comparison will execute. If not computable, return
314 /// UnknownValue. isSigned specifies whether the less-than is signed.
315 BackedgeTakenInfo HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
318 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
319 /// (which may not be an immediate predecessor) which has exactly one
320 /// successor from which BB is reachable, or null if no such block is
322 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
324 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
325 /// in the header of its containing loop, we know the loop executes a
326 /// constant number of times, and the PHI node is just a recurrence
327 /// involving constants, fold it.
328 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
331 /// getSCEVAtScope - Compute the value of the specified expression within
332 /// the indicated loop (which may be null to indicate in no loop). If the
333 /// expression cannot be evaluated, return UnknownValue itself.
334 SCEVHandle getSCEVAtScope(SCEV *S, const Loop *L);
337 static char ID; // Pass identification, replacement for typeid
340 /// isSCEVable - Test if values of the given type are analyzable within
341 /// the SCEV framework. This primarily includes integer types, and it
342 /// can optionally include pointer types if the ScalarEvolution class
343 /// has access to target-specific information.
344 bool isSCEVable(const Type *Ty) const;
346 /// getTypeSizeInBits - Return the size in bits of the specified type,
347 /// for which isSCEVable must return true.
348 uint64_t getTypeSizeInBits(const Type *Ty) const;
350 /// getEffectiveSCEVType - Return a type with the same bitwidth as
351 /// the given type and which represents how SCEV will treat the given
352 /// type, for which isSCEVable must return true. For pointer types,
353 /// this is the pointer-sized integer type.
354 const Type *getEffectiveSCEVType(const Type *Ty) const;
356 /// getSCEV - Return a SCEV expression handle for the full generality of the
357 /// specified expression.
358 SCEVHandle getSCEV(Value *V);
360 SCEVHandle getConstant(ConstantInt *V);
361 SCEVHandle getConstant(const APInt& Val);
362 SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
363 SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
364 SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
365 SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
366 SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
367 std::vector<SCEVHandle> Ops;
370 return getAddExpr(Ops);
372 SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
373 const SCEVHandle &Op2) {
374 std::vector<SCEVHandle> Ops;
378 return getAddExpr(Ops);
380 SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
381 SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
382 std::vector<SCEVHandle> Ops;
385 return getMulExpr(Ops);
387 SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
388 SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
390 SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
392 SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
394 std::vector<SCEVHandle> NewOp(Operands);
395 return getAddRecExpr(NewOp, L);
397 SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
398 SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
399 SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
400 SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
401 SCEVHandle getUnknown(Value *V);
402 SCEVHandle getCouldNotCompute();
404 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
406 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
408 /// getNotSCEV - Return the SCEV object corresponding to ~V.
410 SCEVHandle getNotSCEV(const SCEVHandle &V);
412 /// getMinusSCEV - Return LHS-RHS.
414 SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
415 const SCEVHandle &RHS);
417 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
418 /// of the input value to the specified type. If the type must be
419 /// extended, it is zero extended.
420 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
422 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
423 /// of the input value to the specified type. If the type must be
424 /// extended, it is sign extended.
425 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
427 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
428 /// specified signed integer value and return a SCEV for the constant.
429 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
431 /// hasSCEV - Return true if the SCEV for this value has already been
433 bool hasSCEV(Value *V) const;
435 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
436 /// the specified value.
437 void setSCEV(Value *V, const SCEVHandle &H);
439 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
440 /// at the specified scope in the program. The L value specifies a loop
441 /// nest to evaluate the expression at, where null is the top-level or a
442 /// specified loop is immediately inside of the loop.
444 /// This method can be used to compute the exit value for a variable defined
445 /// in a loop by querying what the value will hold in the parent loop.
447 /// If this value is not computable at this scope, a SCEVCouldNotCompute
448 /// object is returned.
449 SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
451 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
452 /// a conditional between LHS and RHS.
453 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
454 SCEV *LHS, SCEV *RHS);
456 /// getBackedgeTakenCount - If the specified loop has a predictable
457 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
458 /// object. The backedge-taken count is the number of times the loop header
459 /// will be branched to from within the loop. This is one less than the
460 /// trip count of the loop, since it doesn't count the first iteration,
461 /// when the header is branched to from outside the loop.
463 /// Note that it is not valid to call this method on a loop without a
464 /// loop-invariant backedge-taken count (see
465 /// hasLoopInvariantBackedgeTakenCount).
467 SCEVHandle getBackedgeTakenCount(const Loop *L);
469 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
470 /// return the least SCEV value that is known never to be less than the
471 /// actual backedge taken count.
472 SCEVHandle getMaxBackedgeTakenCount(const Loop *L);
474 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
475 /// has an analyzable loop-invariant backedge-taken count.
476 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
478 /// forgetLoopBackedgeTakenCount - This method should be called by the
479 /// client when it has changed a loop in a way that may effect
480 /// ScalarEvolution's ability to compute a trip count, or if the loop
482 void forgetLoopBackedgeTakenCount(const Loop *L);
484 /// deleteValueFromRecords - This method should be called by the
485 /// client before it removes a Value from the program, to make sure
486 /// that no dangling references are left around.
487 void deleteValueFromRecords(Value *V);
489 virtual bool runOnFunction(Function &F);
490 virtual void releaseMemory();
491 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
492 void print(raw_ostream &OS, const Module* = 0) const;
493 virtual void print(std::ostream &OS, const Module* = 0) const;
494 void print(std::ostream *OS, const Module* M = 0) const {
495 if (OS) print(*OS, M);