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"
27 #include "llvm/Support/ValueHandle.h"
28 #include "llvm/Support/Allocator.h"
29 #include "llvm/ADT/FoldingSet.h"
30 #include "llvm/ADT/DenseMap.h"
37 class ScalarEvolution;
41 /// SCEV - This class represents an analyzed expression in the program. These
42 /// are opaque objects that the client is not allowed to do much with
45 class SCEV : public FoldingSetNode {
46 const unsigned SCEVType; // The SCEV baseclass this node corresponds to
48 SCEV(const SCEV &); // DO NOT IMPLEMENT
49 void operator=(const SCEV &); // DO NOT IMPLEMENT
53 explicit SCEV(unsigned SCEVTy) :
56 virtual void Profile(FoldingSetNodeID &ID) const = 0;
58 unsigned getSCEVType() const { return SCEVType; }
60 /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
61 /// the specified loop.
62 virtual bool isLoopInvariant(const Loop *L) const = 0;
64 /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
65 /// known way in the specified loop. This property being true implies that
66 /// the value is variant in the loop AND that we can emit an expression to
67 /// compute the value of the expression at any particular loop iteration.
68 virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
70 /// getType - Return the LLVM type of this SCEV expression.
72 virtual const Type *getType() const = 0;
74 /// isZero - Return true if the expression is a constant zero.
78 /// isOne - Return true if the expression is a constant one.
82 /// isAllOnesValue - Return true if the expression is a constant
85 bool isAllOnesValue() const;
87 /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
88 /// the symbolic value "Sym", construct and return a new SCEV that produces
89 /// the same value, but which uses the concrete value Conc instead of the
90 /// symbolic value. If this SCEV does not use the symbolic value, it
93 replaceSymbolicValuesWithConcrete(const SCEV* Sym,
95 ScalarEvolution &SE) const = 0;
97 /// dominates - Return true if elements that makes up this SCEV dominates
98 /// the specified basic block.
99 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
101 /// print - Print out the internal representation of this scalar to the
102 /// specified stream. This should really only be used for debugging
104 virtual void print(raw_ostream &OS) const = 0;
105 void print(std::ostream &OS) const;
106 void print(std::ostream *OS) const { if (OS) print(*OS); }
108 /// dump - This method is used for debugging.
113 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
118 inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
123 /// SCEVCouldNotCompute - An object of this class is returned by queries that
124 /// could not be answered. For example, if you ask for the number of
125 /// iterations of a linked-list traversal loop, you will get one of these.
126 /// None of the standard SCEV operations are valid on this class, it is just a
128 struct SCEVCouldNotCompute : public SCEV {
129 SCEVCouldNotCompute();
131 // None of these methods are valid for this object.
132 virtual void Profile(FoldingSetNodeID &ID) const;
133 virtual bool isLoopInvariant(const Loop *L) const;
134 virtual const Type *getType() const;
135 virtual bool hasComputableLoopEvolution(const Loop *L) const;
136 virtual void print(raw_ostream &OS) const;
138 replaceSymbolicValuesWithConcrete(const SCEV* Sym,
140 ScalarEvolution &SE) const;
142 virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
146 /// Methods for support type inquiry through isa, cast, and dyn_cast:
147 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
148 static bool classof(const SCEV *S);
151 /// ScalarEvolution - This class is the main scalar evolution driver. Because
152 /// client code (intentionally) can't do much with the SCEV objects directly,
153 /// they must ask this class for services.
155 class ScalarEvolution : public FunctionPass {
156 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
157 /// notified whenever a Value is deleted.
158 class SCEVCallbackVH : public CallbackVH {
160 virtual void deleted();
161 virtual void allUsesReplacedWith(Value *New);
163 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
166 friend class SCEVCallbackVH;
167 friend class SCEVExpander;
169 /// F - The function we are analyzing.
173 /// LI - The loop information for the function we are currently analyzing.
177 /// TD - The target data information for the target we are targetting.
181 /// CouldNotCompute - This SCEV is used to represent unknown trip
182 /// counts and things.
183 SCEVCouldNotCompute CouldNotCompute;
185 /// Scalars - This is a cache of the scalars we have analyzed so far.
187 std::map<SCEVCallbackVH, const SCEV*> Scalars;
189 /// BackedgeTakenInfo - Information about the backedge-taken count
190 /// of a loop. This currently inclues an exact count and a maximum count.
192 struct BackedgeTakenInfo {
193 /// Exact - An expression indicating the exact backedge-taken count of
194 /// the loop if it is known, or a SCEVCouldNotCompute otherwise.
197 /// Exact - An expression indicating the least maximum backedge-taken
198 /// count of the loop that is known, or a SCEVCouldNotCompute.
201 /*implicit*/ BackedgeTakenInfo(const SCEV* exact) :
202 Exact(exact), Max(exact) {}
204 BackedgeTakenInfo(const SCEV* exact, const SCEV* max) :
205 Exact(exact), Max(max) {}
207 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
208 /// computed information, or whether it's all SCEVCouldNotCompute
210 bool hasAnyInfo() const {
211 return !isa<SCEVCouldNotCompute>(Exact) ||
212 !isa<SCEVCouldNotCompute>(Max);
216 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
217 /// this function as they are computed.
218 std::map<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
220 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
221 /// the PHI instructions that we attempt to compute constant evolutions for.
222 /// This allows us to avoid potentially expensive recomputation of these
223 /// properties. An instruction maps to null if we are unable to compute its
225 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
227 /// ValuesAtScopes - This map contains entries for all the instructions
228 /// that we attempt to compute getSCEVAtScope information for without
229 /// using SCEV techniques, which can be expensive.
230 std::map<Instruction *, std::map<const Loop *, Constant *> > ValuesAtScopes;
232 /// createSCEV - We know that there is no SCEV for the specified value.
233 /// Analyze the expression.
234 const SCEV* createSCEV(Value *V);
236 /// createNodeForPHI - Provide the special handling we need to analyze PHI
238 const SCEV* createNodeForPHI(PHINode *PN);
240 /// createNodeForGEP - Provide the special handling we need to analyze GEP
242 const SCEV* createNodeForGEP(User *GEP);
244 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
245 /// for the specified instruction and replaces any references to the
246 /// symbolic value SymName with the specified value. This is used during
248 void ReplaceSymbolicValueWithConcrete(Instruction *I,
252 /// getBECount - Subtract the end and start values and divide by the step,
253 /// rounding up, to get the number of times the backedge is executed. Return
254 /// CouldNotCompute if an intermediate computation overflows.
255 const SCEV* getBECount(const SCEV* Start,
259 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
260 /// loop, lazily computing new values if the loop hasn't been analyzed
262 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
264 /// ComputeBackedgeTakenCount - Compute the number of times the specified
265 /// loop will iterate.
266 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
268 /// ComputeBackedgeTakenCountFromExit - Compute the number of times the
269 /// backedge of the specified loop will execute if it exits via the
271 BackedgeTakenInfo ComputeBackedgeTakenCountFromExit(const Loop *L,
272 BasicBlock *ExitingBlock);
274 /// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
275 /// backedge of the specified loop will execute if its exit condition
276 /// were a conditional branch of ExitCond, TBB, and FBB.
278 ComputeBackedgeTakenCountFromExitCond(const Loop *L,
283 /// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of
284 /// times the backedge of the specified loop will execute if its exit
285 /// condition were a conditional branch of the ICmpInst ExitCond, TBB,
288 ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
293 /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
294 /// of 'icmp op load X, cst', try to see if we can compute the trip count.
296 ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
299 ICmpInst::Predicate p);
301 /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
302 /// a constant number of times (the condition evolves only from constants),
303 /// try to evaluate a few iterations of the loop until we get the exit
304 /// condition gets a value of ExitWhen (true or false). If we cannot
305 /// evaluate the trip count of the loop, return CouldNotCompute.
306 const SCEV* ComputeBackedgeTakenCountExhaustively(const Loop *L,
310 /// HowFarToZero - Return the number of times a backedge comparing the
311 /// specified value to zero will execute. If not computable, return
313 const SCEV* HowFarToZero(const SCEV *V, const Loop *L);
315 /// HowFarToNonZero - Return the number of times a backedge checking the
316 /// specified value for nonzero will execute. If not computable, return
318 const SCEV* HowFarToNonZero(const SCEV *V, const Loop *L);
320 /// HowManyLessThans - Return the number of times a backedge containing the
321 /// specified less-than comparison will execute. If not computable, return
322 /// CouldNotCompute. isSigned specifies whether the less-than is signed.
323 BackedgeTakenInfo HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
324 const Loop *L, bool isSigned);
326 /// getLoopPredecessor - If the given loop's header has exactly one unique
327 /// predecessor outside the loop, return it. Otherwise return null.
328 BasicBlock *getLoopPredecessor(const Loop *L);
330 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
331 /// (which may not be an immediate predecessor) which has exactly one
332 /// successor from which BB is reachable, or null if no such block is
334 BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
336 /// isNecessaryCond - Test whether the given CondValue value is a condition
337 /// which is at least as strict as the one described by Pred, LHS, and RHS.
338 bool isNecessaryCond(Value *Cond, ICmpInst::Predicate Pred,
339 const SCEV *LHS, const SCEV *RHS,
342 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
343 /// in the header of its containing loop, we know the loop executes a
344 /// constant number of times, and the PHI node is just a recurrence
345 /// involving constants, fold it.
346 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
349 /// forgetLoopPHIs - Delete the memoized SCEVs associated with the
350 /// PHI nodes in the given loop. This is used when the trip count of
351 /// the loop may have changed.
352 void forgetLoopPHIs(const Loop *L);
355 static char ID; // Pass identification, replacement for typeid
358 LLVMContext* getContext() const { return Context; }
360 /// isSCEVable - Test if values of the given type are analyzable within
361 /// the SCEV framework. This primarily includes integer types, and it
362 /// can optionally include pointer types if the ScalarEvolution class
363 /// has access to target-specific information.
364 bool isSCEVable(const Type *Ty) const;
366 /// getTypeSizeInBits - Return the size in bits of the specified type,
367 /// for which isSCEVable must return true.
368 uint64_t getTypeSizeInBits(const Type *Ty) const;
370 /// getEffectiveSCEVType - Return a type with the same bitwidth as
371 /// the given type and which represents how SCEV will treat the given
372 /// type, for which isSCEVable must return true. For pointer types,
373 /// this is the pointer-sized integer type.
374 const Type *getEffectiveSCEVType(const Type *Ty) const;
376 /// getSCEV - Return a SCEV expression handle for the full generality of the
377 /// specified expression.
378 const SCEV* getSCEV(Value *V);
380 const SCEV* getConstant(ConstantInt *V);
381 const SCEV* getConstant(const APInt& Val);
382 const SCEV* getConstant(const Type *Ty, uint64_t V, bool isSigned = false);
383 const SCEV* getTruncateExpr(const SCEV* Op, const Type *Ty);
384 const SCEV* getZeroExtendExpr(const SCEV* Op, const Type *Ty);
385 const SCEV* getSignExtendExpr(const SCEV* Op, const Type *Ty);
386 const SCEV* getAnyExtendExpr(const SCEV* Op, const Type *Ty);
387 const SCEV* getAddExpr(SmallVectorImpl<const SCEV*> &Ops);
388 const SCEV* getAddExpr(const SCEV* LHS, const SCEV* RHS) {
389 SmallVector<const SCEV*, 2> Ops;
392 return getAddExpr(Ops);
394 const SCEV* getAddExpr(const SCEV* Op0, const SCEV* Op1,
396 SmallVector<const SCEV*, 3> Ops;
400 return getAddExpr(Ops);
402 const SCEV* getMulExpr(SmallVectorImpl<const SCEV*> &Ops);
403 const SCEV* getMulExpr(const SCEV* LHS, const SCEV* RHS) {
404 SmallVector<const SCEV*, 2> Ops;
407 return getMulExpr(Ops);
409 const SCEV* getUDivExpr(const SCEV* LHS, const SCEV* RHS);
410 const SCEV* getAddRecExpr(const SCEV* Start, const SCEV* Step,
412 const SCEV* getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
414 const SCEV* getAddRecExpr(const SmallVectorImpl<const SCEV*> &Operands,
416 SmallVector<const SCEV*, 4> NewOp(Operands.begin(), Operands.end());
417 return getAddRecExpr(NewOp, L);
419 const SCEV* getSMaxExpr(const SCEV* LHS, const SCEV* RHS);
420 const SCEV* getSMaxExpr(SmallVectorImpl<const SCEV*> &Operands);
421 const SCEV* getUMaxExpr(const SCEV* LHS, const SCEV* RHS);
422 const SCEV* getUMaxExpr(SmallVectorImpl<const SCEV*> &Operands);
423 const SCEV* getSMinExpr(const SCEV* LHS, const SCEV* RHS);
424 const SCEV* getUMinExpr(const SCEV* LHS, const SCEV* RHS);
425 const SCEV* getUnknown(Value *V);
426 const SCEV* getCouldNotCompute();
428 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
430 const SCEV* getNegativeSCEV(const SCEV* V);
432 /// getNotSCEV - Return the SCEV object corresponding to ~V.
434 const SCEV* getNotSCEV(const SCEV* V);
436 /// getMinusSCEV - Return LHS-RHS.
438 const SCEV* getMinusSCEV(const SCEV* LHS,
441 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
442 /// of the input value to the specified type. If the type must be
443 /// extended, it is zero extended.
444 const SCEV* getTruncateOrZeroExtend(const SCEV* V, const Type *Ty);
446 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
447 /// of the input value to the specified type. If the type must be
448 /// extended, it is sign extended.
449 const SCEV* getTruncateOrSignExtend(const SCEV* V, const Type *Ty);
451 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
452 /// the input value to the specified type. If the type must be extended,
453 /// it is zero extended. The conversion must not be narrowing.
454 const SCEV* getNoopOrZeroExtend(const SCEV* V, const Type *Ty);
456 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
457 /// the input value to the specified type. If the type must be extended,
458 /// it is sign extended. The conversion must not be narrowing.
459 const SCEV* getNoopOrSignExtend(const SCEV* V, const Type *Ty);
461 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
462 /// the input value to the specified type. If the type must be extended,
463 /// it is extended with unspecified bits. The conversion must not be
465 const SCEV* getNoopOrAnyExtend(const SCEV* V, const Type *Ty);
467 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
468 /// input value to the specified type. The conversion must not be
470 const SCEV* getTruncateOrNoop(const SCEV* V, const Type *Ty);
472 /// getIntegerSCEV - Given a SCEVable type, create a constant for the
473 /// specified signed integer value and return a SCEV for the constant.
474 const SCEV* getIntegerSCEV(int Val, const Type *Ty);
476 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
477 /// the types using zero-extension, and then perform a umax operation
479 const SCEV* getUMaxFromMismatchedTypes(const SCEV* LHS,
482 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
483 /// the types using zero-extension, and then perform a umin operation
485 const SCEV* getUMinFromMismatchedTypes(const SCEV* LHS,
488 /// hasSCEV - Return true if the SCEV for this value has already been
490 bool hasSCEV(Value *V) const;
492 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
493 /// the specified value.
494 void setSCEV(Value *V, const SCEV* H);
496 /// getSCEVAtScope - Return a SCEV expression handle for the specified value
497 /// at the specified scope in the program. The L value specifies a loop
498 /// nest to evaluate the expression at, where null is the top-level or a
499 /// specified loop is immediately inside of the loop.
501 /// This method can be used to compute the exit value for a variable defined
502 /// in a loop by querying what the value will hold in the parent loop.
504 /// In the case that a relevant loop exit value cannot be computed, the
505 /// original value V is returned.
506 const SCEV* getSCEVAtScope(const SCEV *S, const Loop *L);
508 /// getSCEVAtScope - This is a convenience function which does
509 /// getSCEVAtScope(getSCEV(V), L).
510 const SCEV* getSCEVAtScope(Value *V, const Loop *L);
512 /// isLoopGuardedByCond - Test whether entry to the loop is protected by
513 /// a conditional between LHS and RHS. This is used to help avoid max
514 /// expressions in loop trip counts.
515 bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
516 const SCEV *LHS, const SCEV *RHS);
518 /// getBackedgeTakenCount - If the specified loop has a predictable
519 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
520 /// object. The backedge-taken count is the number of times the loop header
521 /// will be branched to from within the loop. This is one less than the
522 /// trip count of the loop, since it doesn't count the first iteration,
523 /// when the header is branched to from outside the loop.
525 /// Note that it is not valid to call this method on a loop without a
526 /// loop-invariant backedge-taken count (see
527 /// hasLoopInvariantBackedgeTakenCount).
529 const SCEV* getBackedgeTakenCount(const Loop *L);
531 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
532 /// return the least SCEV value that is known never to be less than the
533 /// actual backedge taken count.
534 const SCEV* getMaxBackedgeTakenCount(const Loop *L);
536 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
537 /// has an analyzable loop-invariant backedge-taken count.
538 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
540 /// forgetLoopBackedgeTakenCount - This method should be called by the
541 /// client when it has changed a loop in a way that may effect
542 /// ScalarEvolution's ability to compute a trip count, or if the loop
544 void forgetLoopBackedgeTakenCount(const Loop *L);
546 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
547 /// is guaranteed to end in (at every loop iteration). It is, at the same
548 /// time, the minimum number of times S is divisible by 2. For example,
549 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
551 uint32_t GetMinTrailingZeros(const SCEV* S);
553 /// GetMinLeadingZeros - Determine the minimum number of zero bits that S is
554 /// guaranteed to begin with (at every loop iteration).
555 uint32_t GetMinLeadingZeros(const SCEV* S);
557 /// GetMinSignBits - Determine the minimum number of sign bits that S is
558 /// guaranteed to begin with.
559 uint32_t GetMinSignBits(const SCEV* S);
561 virtual bool runOnFunction(Function &F);
562 virtual void releaseMemory();
563 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
564 void print(raw_ostream &OS, const Module* = 0) const;
565 virtual void print(std::ostream &OS, const Module* = 0) const;
566 void print(std::ostream *OS, const Module* M = 0) const {
567 if (OS) print(*OS, M);
571 FoldingSet<SCEV> UniqueSCEVs;
572 BumpPtrAllocator SCEVAllocator;