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 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
221 /// this function as they are computed.
222 std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
224 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
225 /// the PHI instructions that we attempt to compute constant evolutions for.
226 /// This allows us to avoid potentially expensive recomputation of these
227 /// properties. An instruction maps to null if we are unable to compute its
229 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
231 /// createSCEV - We know that there is no SCEV for the specified value.
232 /// Analyze the expression.
233 SCEVHandle createSCEV(Value *V);
235 /// createNodeForPHI - Provide the special handling we need to analyze PHI
237 SCEVHandle createNodeForPHI(PHINode *PN);
239 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
240 /// for the specified instruction and replaces any references to the
241 /// symbolic value SymName with the specified value. This is used during
243 void ReplaceSymbolicValueWithConcrete(Instruction *I,
244 const SCEVHandle &SymName,
245 const SCEVHandle &NewVal);
247 /// ComputeBackedgeTakenCount - Compute the number of times the specified
248 /// loop will iterate.
249 SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
251 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
252 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
254 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
257 ICmpInst::Predicate p);
259 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
260 /// a constant number of times (the condition evolves only from constants),
261 /// try to evaluate a few iterations of the loop until we get the exit
262 /// condition gets a value of ExitWhen (true or false). If we cannot
263 /// evaluate the trip count of the loop, return UnknownValue.
264 SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
267 /// HowFarToZero - Return the number of times a backedge comparing the
268 /// specified value to zero will execute. If not computable, return
270 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
272 /// HowFarToNonZero - Return the number of times a backedge checking the
273 /// specified value for nonzero will execute. If not computable, return
275 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
277 /// HowManyLessThans - Return the number of times a backedge containing the
278 /// specified less-than comparison will execute. If not computable, return
279 /// UnknownValue. isSigned specifies whether the less-than is signed.
280 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
283 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
284 /// (which may not be an immediate predecessor) which has exactly one
285 /// successor from which BB is reachable, or null if no such block is
287 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
289 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
290 /// in the header of its containing loop, we know the loop executes a
291 /// constant number of times, and the PHI node is just a recurrence
292 /// involving constants, fold it.
293 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
296 /// getSCEVAtScope - Compute the value of the specified expression within
297 /// the indicated loop (which may be null to indicate in no loop). If the
298 /// expression cannot be evaluated, return UnknownValue itself.
299 SCEVHandle getSCEVAtScope(SCEV *S, const Loop *L);
302 static char ID; // Pass identification, replacement for typeid
305 /// isSCEVable - Test if values of the given type are analyzable within
306 /// the SCEV framework. This primarily includes integer types, and it
307 /// can optionally include pointer types if the ScalarEvolution class
308 /// has access to target-specific information.
309 bool isSCEVable(const Type *Ty) const;
311 /// getTypeSizeInBits - Return the size in bits of the specified type,
312 /// for which isSCEVable must return true.
313 uint64_t getTypeSizeInBits(const Type *Ty) const;
315 /// getEffectiveSCEVType - Return a type with the same bitwidth as
316 /// the given type and which represents how SCEV will treat the given
317 /// type, for which isSCEVable must return true. For pointer types,
318 /// this is the pointer-sized integer type.
319 const Type *getEffectiveSCEVType(const Type *Ty) const;
321 /// getSCEV - Return a SCEV expression handle for the full generality of the
322 /// specified expression.
323 SCEVHandle getSCEV(Value *V);
325 SCEVHandle getConstant(ConstantInt *V);
326 SCEVHandle getConstant(const APInt& Val);
327 SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
328 SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
329 SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
330 SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
331 SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
332 std::vector<SCEVHandle> Ops;
335 return getAddExpr(Ops);
337 SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
338 const SCEVHandle &Op2) {
339 std::vector<SCEVHandle> Ops;
343 return getAddExpr(Ops);
345 SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
346 SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
347 std::vector<SCEVHandle> Ops;
350 return getMulExpr(Ops);
352 SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
353 SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
355 SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
357 SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
359 std::vector<SCEVHandle> NewOp(Operands);
360 return getAddRecExpr(NewOp, L);
362 SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
363 SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
364 SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
365 SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
366 SCEVHandle getUnknown(Value *V);
367 SCEVHandle getCouldNotCompute();
369 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
371 SCEVHandle getNegativeSCEV(const SCEVHandle &V);
373 /// getNotSCEV - Return the SCEV object corresponding to ~V.
375 SCEVHandle getNotSCEV(const SCEVHandle &V);
377 /// getMinusSCEV - Return LHS-RHS.
379 SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
380 const SCEVHandle &RHS);
382 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
383 /// of the input value to the specified type. If the type must be
384 /// extended, it is zero extended.
385 SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
387 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
388 /// of the input value to the specified type. If the type must be
389 /// extended, it is sign extended.
390 SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
392 /// getIntegerSCEV - Given an integer or FP type, create a constant for the
393 /// specified signed integer value and return a SCEV for the constant.
394 SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
396 /// hasSCEV - Return true if the SCEV for this value has already been
398 bool hasSCEV(Value *V) const;
400 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
401 /// the specified value.
402 void setSCEV(Value *V, const SCEVHandle &H);
404 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
405 /// at the specified scope in the program. The L value specifies a loop
406 /// nest to evaluate the expression at, where null is the top-level or a
407 /// specified loop is immediately inside of the loop.
409 /// This method can be used to compute the exit value for a variable defined
410 /// in a loop by querying what the value will hold in the parent loop.
412 /// If this value is not computable at this scope, a SCEVCouldNotCompute
413 /// object is returned.
414 SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
416 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
417 /// a conditional between LHS and RHS.
418 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
419 SCEV *LHS, SCEV *RHS);
421 /// getBackedgeTakenCount - If the specified loop has a predictable
422 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
423 /// object. The backedge-taken count is the number of times the loop header
424 /// will be branched to from within the loop. This is one less than the
425 /// trip count of the loop, since it doesn't count the first iteration,
426 /// when the header is branched to from outside the loop.
428 /// Note that it is not valid to call this method on a loop without a
429 /// loop-invariant backedge-taken count (see
430 /// hasLoopInvariantBackedgeTakenCount).
432 SCEVHandle getBackedgeTakenCount(const Loop *L);
434 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
435 /// has an analyzable loop-invariant backedge-taken count.
436 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
438 /// forgetLoopBackedgeTakenCount - This method should be called by the
439 /// client when it has changed a loop in a way that may effect
440 /// ScalarEvolution's ability to compute a trip count, or if the loop
442 void forgetLoopBackedgeTakenCount(const Loop *L);
444 /// deleteValueFromRecords - This method should be called by the
445 /// client before it removes a Value from the program, to make sure
446 /// that no dangling references are left around.
447 void deleteValueFromRecords(Value *V);
449 virtual bool runOnFunction(Function &F);
450 virtual void releaseMemory();
451 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
452 void print(raw_ostream &OS, const Module* = 0) const;
453 virtual void print(std::ostream &OS, const Module* = 0) const;
454 void print(std::ostream *OS, const Module* M = 0) const {
455 if (OS) print(*OS, M);