Home | History | Annotate | Download | only in Analysis
      1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // The ScalarEvolution class is an LLVM pass which can be used to analyze and
     11 // categorize 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.
     15 //
     16 // This analysis is primarily useful for induction variable substitution and
     17 // strength reduction.
     18 //
     19 //===----------------------------------------------------------------------===//
     20 
     21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
     22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
     23 
     24 #include "llvm/ADT/DenseSet.h"
     25 #include "llvm/ADT/FoldingSet.h"
     26 #include "llvm/IR/Function.h"
     27 #include "llvm/IR/Instructions.h"
     28 #include "llvm/IR/Operator.h"
     29 #include "llvm/Pass.h"
     30 #include "llvm/Support/Allocator.h"
     31 #include "llvm/Support/ConstantRange.h"
     32 #include "llvm/Support/DataTypes.h"
     33 #include "llvm/Support/ValueHandle.h"
     34 #include <map>
     35 
     36 namespace llvm {
     37   class APInt;
     38   class Constant;
     39   class ConstantInt;
     40   class DominatorTree;
     41   class Type;
     42   class ScalarEvolution;
     43   class DataLayout;
     44   class TargetLibraryInfo;
     45   class LLVMContext;
     46   class Loop;
     47   class LoopInfo;
     48   class Operator;
     49   class SCEVUnknown;
     50   class SCEV;
     51   template<> struct FoldingSetTrait<SCEV>;
     52 
     53   /// SCEV - This class represents an analyzed expression in the program.  These
     54   /// are opaque objects that the client is not allowed to do much with
     55   /// directly.
     56   ///
     57   class SCEV : public FoldingSetNode {
     58     friend struct FoldingSetTrait<SCEV>;
     59 
     60     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
     61     /// The ScalarEvolution's BumpPtrAllocator holds the data.
     62     FoldingSetNodeIDRef FastID;
     63 
     64     // The SCEV baseclass this node corresponds to
     65     const unsigned short SCEVType;
     66 
     67   protected:
     68     /// SubclassData - This field is initialized to zero and may be used in
     69     /// subclasses to store miscellaneous information.
     70     unsigned short SubclassData;
     71 
     72   private:
     73     SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
     74     void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
     75 
     76   public:
     77     /// NoWrapFlags are bitfield indices into SubclassData.
     78     ///
     79     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
     80     /// no-signed-wrap <NSW> properties, which are derived from the IR
     81     /// operator. NSW is a misnomer that we use to mean no signed overflow or
     82     /// underflow.
     83     ///
     84     /// AddRec expression may have a no-self-wraparound <NW> property if the
     85     /// result can never reach the start value. This property is independent of
     86     /// the actual start value and step direction. Self-wraparound is defined
     87     /// purely in terms of the recurrence's loop, step size, and
     88     /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
     89     /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
     90     ///
     91     /// Note that NUW and NSW are also valid properties of a recurrence, and
     92     /// either implies NW. For convenience, NW will be set for a recurrence
     93     /// whenever either NUW or NSW are set.
     94     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
     95                        FlagNW      = (1 << 0),   // No self-wrap.
     96                        FlagNUW     = (1 << 1),   // No unsigned wrap.
     97                        FlagNSW     = (1 << 2),   // No signed wrap.
     98                        NoWrapMask  = (1 << 3) -1 };
     99 
    100     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
    101       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
    102 
    103     unsigned getSCEVType() const { return SCEVType; }
    104 
    105     /// getType - Return the LLVM type of this SCEV expression.
    106     ///
    107     Type *getType() const;
    108 
    109     /// isZero - Return true if the expression is a constant zero.
    110     ///
    111     bool isZero() const;
    112 
    113     /// isOne - Return true if the expression is a constant one.
    114     ///
    115     bool isOne() const;
    116 
    117     /// isAllOnesValue - Return true if the expression is a constant
    118     /// all-ones value.
    119     ///
    120     bool isAllOnesValue() const;
    121 
    122     /// isNonConstantNegative - Return true if the specified scev is negated,
    123     /// but not a constant.
    124     bool isNonConstantNegative() const;
    125 
    126     /// print - Print out the internal representation of this scalar to the
    127     /// specified stream.  This should really only be used for debugging
    128     /// purposes.
    129     void print(raw_ostream &OS) const;
    130 
    131     /// dump - This method is used for debugging.
    132     ///
    133     void dump() const;
    134   };
    135 
    136   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
    137   // temporary FoldingSetNodeID values.
    138   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
    139     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
    140       ID = X.FastID;
    141     }
    142     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
    143                        unsigned IDHash, FoldingSetNodeID &TempID) {
    144       return ID == X.FastID;
    145     }
    146     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
    147       return X.FastID.ComputeHash();
    148     }
    149   };
    150 
    151   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
    152     S.print(OS);
    153     return OS;
    154   }
    155 
    156   /// SCEVCouldNotCompute - An object of this class is returned by queries that
    157   /// could not be answered.  For example, if you ask for the number of
    158   /// iterations of a linked-list traversal loop, you will get one of these.
    159   /// None of the standard SCEV operations are valid on this class, it is just a
    160   /// marker.
    161   struct SCEVCouldNotCompute : public SCEV {
    162     SCEVCouldNotCompute();
    163 
    164     /// Methods for support type inquiry through isa, cast, and dyn_cast:
    165     static bool classof(const SCEV *S);
    166   };
    167 
    168   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
    169   /// client code (intentionally) can't do much with the SCEV objects directly,
    170   /// they must ask this class for services.
    171   ///
    172   class ScalarEvolution : public FunctionPass {
    173   public:
    174     /// LoopDisposition - An enum describing the relationship between a
    175     /// SCEV and a loop.
    176     enum LoopDisposition {
    177       LoopVariant,    ///< The SCEV is loop-variant (unknown).
    178       LoopInvariant,  ///< The SCEV is loop-invariant.
    179       LoopComputable  ///< The SCEV varies predictably with the loop.
    180     };
    181 
    182     /// BlockDisposition - An enum describing the relationship between a
    183     /// SCEV and a basic block.
    184     enum BlockDisposition {
    185       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
    186       DominatesBlock,        ///< The SCEV dominates the block.
    187       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
    188     };
    189 
    190     /// Convenient NoWrapFlags manipulation that hides enum casts and is
    191     /// visible in the ScalarEvolution name space.
    192     static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
    193       return (SCEV::NoWrapFlags)(Flags & Mask);
    194     }
    195     static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
    196                                       SCEV::NoWrapFlags OnFlags) {
    197       return (SCEV::NoWrapFlags)(Flags | OnFlags);
    198     }
    199     static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
    200                                         SCEV::NoWrapFlags OffFlags) {
    201       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
    202     }
    203 
    204   private:
    205     /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
    206     /// notified whenever a Value is deleted.
    207     class SCEVCallbackVH : public CallbackVH {
    208       ScalarEvolution *SE;
    209       virtual void deleted();
    210       virtual void allUsesReplacedWith(Value *New);
    211     public:
    212       SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
    213     };
    214 
    215     friend class SCEVCallbackVH;
    216     friend class SCEVExpander;
    217     friend class SCEVUnknown;
    218 
    219     /// F - The function we are analyzing.
    220     ///
    221     Function *F;
    222 
    223     /// LI - The loop information for the function we are currently analyzing.
    224     ///
    225     LoopInfo *LI;
    226 
    227     /// TD - The target data information for the target we are targeting.
    228     ///
    229     DataLayout *TD;
    230 
    231     /// TLI - The target library information for the target we are targeting.
    232     ///
    233     TargetLibraryInfo *TLI;
    234 
    235     /// DT - The dominator tree.
    236     ///
    237     DominatorTree *DT;
    238 
    239     /// CouldNotCompute - This SCEV is used to represent unknown trip
    240     /// counts and things.
    241     SCEVCouldNotCompute CouldNotCompute;
    242 
    243     /// ValueExprMapType - The typedef for ValueExprMap.
    244     ///
    245     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
    246       ValueExprMapType;
    247 
    248     /// ValueExprMap - This is a cache of the values we have analyzed so far.
    249     ///
    250     ValueExprMapType ValueExprMap;
    251 
    252     /// Mark predicate values currently being processed by isImpliedCond.
    253     DenseSet<Value*> PendingLoopPredicates;
    254 
    255     /// ExitLimit - Information about the number of loop iterations for
    256     /// which a loop exit's branch condition evaluates to the not-taken path.
    257     /// This is a temporary pair of exact and max expressions that are
    258     /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
    259     struct ExitLimit {
    260       const SCEV *Exact;
    261       const SCEV *Max;
    262 
    263       /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
    264 
    265       ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
    266 
    267       /// hasAnyInfo - Test whether this ExitLimit contains any computed
    268       /// information, or whether it's all SCEVCouldNotCompute values.
    269       bool hasAnyInfo() const {
    270         return !isa<SCEVCouldNotCompute>(Exact) ||
    271           !isa<SCEVCouldNotCompute>(Max);
    272       }
    273     };
    274 
    275     /// ExitNotTakenInfo - Information about the number of times a particular
    276     /// loop exit may be reached before exiting the loop.
    277     struct ExitNotTakenInfo {
    278       AssertingVH<BasicBlock> ExitingBlock;
    279       const SCEV *ExactNotTaken;
    280       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
    281 
    282       ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
    283 
    284       /// isCompleteList - Return true if all loop exits are computable.
    285       bool isCompleteList() const {
    286         return NextExit.getInt() == 0;
    287       }
    288 
    289       void setIncomplete() { NextExit.setInt(1); }
    290 
    291       /// getNextExit - Return a pointer to the next exit's not-taken info.
    292       ExitNotTakenInfo *getNextExit() const {
    293         return NextExit.getPointer();
    294       }
    295 
    296       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
    297     };
    298 
    299     /// BackedgeTakenInfo - Information about the backedge-taken count
    300     /// of a loop. This currently includes an exact count and a maximum count.
    301     ///
    302     class BackedgeTakenInfo {
    303       /// ExitNotTaken - A list of computable exits and their not-taken counts.
    304       /// Loops almost never have more than one computable exit.
    305       ExitNotTakenInfo ExitNotTaken;
    306 
    307       /// Max - An expression indicating the least maximum backedge-taken
    308       /// count of the loop that is known, or a SCEVCouldNotCompute.
    309       const SCEV *Max;
    310 
    311     public:
    312       BackedgeTakenInfo() : Max(0) {}
    313 
    314       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
    315       BackedgeTakenInfo(
    316         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
    317         bool Complete, const SCEV *MaxCount);
    318 
    319       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
    320       /// computed information, or whether it's all SCEVCouldNotCompute
    321       /// values.
    322       bool hasAnyInfo() const {
    323         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
    324       }
    325 
    326       /// getExact - Return an expression indicating the exact backedge-taken
    327       /// count of the loop if it is known, or SCEVCouldNotCompute
    328       /// otherwise. This is the number of times the loop header can be
    329       /// guaranteed to execute, minus one.
    330       const SCEV *getExact(ScalarEvolution *SE) const;
    331 
    332       /// getExact - Return the number of times this loop exit may fall through
    333       /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
    334       /// to exit via this block before this number of iterations, but may exit
    335       /// via another block.
    336       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
    337 
    338       /// getMax - Get the max backedge taken count for the loop.
    339       const SCEV *getMax(ScalarEvolution *SE) const;
    340 
    341       /// Return true if any backedge taken count expressions refer to the given
    342       /// subexpression.
    343       bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
    344 
    345       /// clear - Invalidate this result and free associated memory.
    346       void clear();
    347     };
    348 
    349     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
    350     /// this function as they are computed.
    351     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
    352 
    353     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
    354     /// the PHI instructions that we attempt to compute constant evolutions for.
    355     /// This allows us to avoid potentially expensive recomputation of these
    356     /// properties.  An instruction maps to null if we are unable to compute its
    357     /// exit value.
    358     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
    359 
    360     /// ValuesAtScopes - This map contains entries for all the expressions
    361     /// that we attempt to compute getSCEVAtScope information for, which can
    362     /// be expensive in extreme cases.
    363     DenseMap<const SCEV *,
    364              std::map<const Loop *, const SCEV *> > ValuesAtScopes;
    365 
    366     /// LoopDispositions - Memoized computeLoopDisposition results.
    367     DenseMap<const SCEV *,
    368              std::map<const Loop *, LoopDisposition> > LoopDispositions;
    369 
    370     /// computeLoopDisposition - Compute a LoopDisposition value.
    371     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
    372 
    373     /// BlockDispositions - Memoized computeBlockDisposition results.
    374     DenseMap<const SCEV *,
    375              std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
    376 
    377     /// computeBlockDisposition - Compute a BlockDisposition value.
    378     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
    379 
    380     /// UnsignedRanges - Memoized results from getUnsignedRange
    381     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
    382 
    383     /// SignedRanges - Memoized results from getSignedRange
    384     DenseMap<const SCEV *, ConstantRange> SignedRanges;
    385 
    386     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
    387     const ConstantRange &setUnsignedRange(const SCEV *S,
    388                                           const ConstantRange &CR) {
    389       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
    390         UnsignedRanges.insert(std::make_pair(S, CR));
    391       if (!Pair.second)
    392         Pair.first->second = CR;
    393       return Pair.first->second;
    394     }
    395 
    396     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
    397     const ConstantRange &setSignedRange(const SCEV *S,
    398                                         const ConstantRange &CR) {
    399       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
    400         SignedRanges.insert(std::make_pair(S, CR));
    401       if (!Pair.second)
    402         Pair.first->second = CR;
    403       return Pair.first->second;
    404     }
    405 
    406     /// createSCEV - We know that there is no SCEV for the specified value.
    407     /// Analyze the expression.
    408     const SCEV *createSCEV(Value *V);
    409 
    410     /// createNodeForPHI - Provide the special handling we need to analyze PHI
    411     /// SCEVs.
    412     const SCEV *createNodeForPHI(PHINode *PN);
    413 
    414     /// createNodeForGEP - Provide the special handling we need to analyze GEP
    415     /// SCEVs.
    416     const SCEV *createNodeForGEP(GEPOperator *GEP);
    417 
    418     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
    419     /// at most once for each SCEV+Loop pair.
    420     ///
    421     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
    422 
    423     /// ForgetSymbolicValue - This looks up computed SCEV values for all
    424     /// instructions that depend on the given instruction and removes them from
    425     /// the ValueExprMap map if they reference SymName. This is used during PHI
    426     /// resolution.
    427     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
    428 
    429     /// getBECount - Subtract the end and start values and divide by the step,
    430     /// rounding up, to get the number of times the backedge is executed. Return
    431     /// CouldNotCompute if an intermediate computation overflows.
    432     const SCEV *getBECount(const SCEV *Start,
    433                            const SCEV *End,
    434                            const SCEV *Step,
    435                            bool NoWrap);
    436 
    437     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
    438     /// loop, lazily computing new values if the loop hasn't been analyzed
    439     /// yet.
    440     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
    441 
    442     /// ComputeBackedgeTakenCount - Compute the number of times the specified
    443     /// loop will iterate.
    444     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
    445 
    446     /// ComputeExitLimit - Compute the number of times the backedge of the
    447     /// specified loop will execute if it exits via the specified block.
    448     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
    449 
    450     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
    451     /// the specified loop will execute if its exit condition were a conditional
    452     /// branch of ExitCond, TBB, and FBB.
    453     ExitLimit ComputeExitLimitFromCond(const Loop *L,
    454                                        Value *ExitCond,
    455                                        BasicBlock *TBB,
    456                                        BasicBlock *FBB,
    457                                        bool IsSubExpr);
    458 
    459     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
    460     /// the specified loop will execute if its exit condition were a conditional
    461     /// branch of the ICmpInst ExitCond, TBB, and FBB.
    462     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
    463                                        ICmpInst *ExitCond,
    464                                        BasicBlock *TBB,
    465                                        BasicBlock *FBB,
    466                                        bool IsSubExpr);
    467 
    468     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
    469     /// of 'icmp op load X, cst', try to see if we can compute the
    470     /// backedge-taken count.
    471     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
    472                                                   Constant *RHS,
    473                                                   const Loop *L,
    474                                                   ICmpInst::Predicate p);
    475 
    476     /// ComputeExitCountExhaustively - If the loop is known to execute a
    477     /// constant number of times (the condition evolves only from constants),
    478     /// try to evaluate a few iterations of the loop until we get the exit
    479     /// condition gets a value of ExitWhen (true or false).  If we cannot
    480     /// evaluate the exit count of the loop, return CouldNotCompute.
    481     const SCEV *ComputeExitCountExhaustively(const Loop *L,
    482                                              Value *Cond,
    483                                              bool ExitWhen);
    484 
    485     /// HowFarToZero - Return the number of times an exit condition comparing
    486     /// the specified value to zero will execute.  If not computable, return
    487     /// CouldNotCompute.
    488     ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
    489 
    490     /// HowFarToNonZero - Return the number of times an exit condition checking
    491     /// the specified value for nonzero will execute.  If not computable, return
    492     /// CouldNotCompute.
    493     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
    494 
    495     /// HowManyLessThans - Return the number of times an exit condition
    496     /// containing the specified less-than comparison will execute.  If not
    497     /// computable, return CouldNotCompute. isSigned specifies whether the
    498     /// less-than is signed.
    499     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
    500                                const Loop *L, bool isSigned, bool IsSubExpr);
    501 
    502     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
    503     /// (which may not be an immediate predecessor) which has exactly one
    504     /// successor from which BB is reachable, or null if no such block is
    505     /// found.
    506     std::pair<BasicBlock *, BasicBlock *>
    507     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
    508 
    509     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
    510     /// RHS is true whenever the given FoundCondValue value evaluates to true.
    511     bool isImpliedCond(ICmpInst::Predicate Pred,
    512                        const SCEV *LHS, const SCEV *RHS,
    513                        Value *FoundCondValue,
    514                        bool Inverse);
    515 
    516     /// isImpliedCondOperands - Test whether the condition described by Pred,
    517     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
    518     /// and FoundRHS is true.
    519     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
    520                                const SCEV *LHS, const SCEV *RHS,
    521                                const SCEV *FoundLHS, const SCEV *FoundRHS);
    522 
    523     /// isImpliedCondOperandsHelper - Test whether the condition described by
    524     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
    525     /// FoundLHS, and FoundRHS is true.
    526     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
    527                                      const SCEV *LHS, const SCEV *RHS,
    528                                      const SCEV *FoundLHS,
    529                                      const SCEV *FoundRHS);
    530 
    531     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
    532     /// in the header of its containing loop, we know the loop executes a
    533     /// constant number of times, and the PHI node is just a recurrence
    534     /// involving constants, fold it.
    535     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
    536                                                 const Loop *L);
    537 
    538     /// isKnownPredicateWithRanges - Test if the given expression is known to
    539     /// satisfy the condition described by Pred and the known constant ranges
    540     /// of LHS and RHS.
    541     ///
    542     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
    543                                     const SCEV *LHS, const SCEV *RHS);
    544 
    545     /// forgetMemoizedResults - Drop memoized information computed for S.
    546     void forgetMemoizedResults(const SCEV *S);
    547 
    548     /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
    549     /// pointer.
    550     bool checkValidity(const SCEV *S) const;
    551 
    552   public:
    553     static char ID; // Pass identification, replacement for typeid
    554     ScalarEvolution();
    555 
    556     LLVMContext &getContext() const { return F->getContext(); }
    557 
    558     /// isSCEVable - Test if values of the given type are analyzable within
    559     /// the SCEV framework. This primarily includes integer types, and it
    560     /// can optionally include pointer types if the ScalarEvolution class
    561     /// has access to target-specific information.
    562     bool isSCEVable(Type *Ty) const;
    563 
    564     /// getTypeSizeInBits - Return the size in bits of the specified type,
    565     /// for which isSCEVable must return true.
    566     uint64_t getTypeSizeInBits(Type *Ty) const;
    567 
    568     /// getEffectiveSCEVType - Return a type with the same bitwidth as
    569     /// the given type and which represents how SCEV will treat the given
    570     /// type, for which isSCEVable must return true. For pointer types,
    571     /// this is the pointer-sized integer type.
    572     Type *getEffectiveSCEVType(Type *Ty) const;
    573 
    574     /// getSCEV - Return a SCEV expression for the full generality of the
    575     /// specified expression.
    576     const SCEV *getSCEV(Value *V);
    577 
    578     const SCEV *getConstant(ConstantInt *V);
    579     const SCEV *getConstant(const APInt& Val);
    580     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
    581     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
    582     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
    583     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
    584     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
    585     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
    586                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    587     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
    588                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
    589       SmallVector<const SCEV *, 2> Ops;
    590       Ops.push_back(LHS);
    591       Ops.push_back(RHS);
    592       return getAddExpr(Ops, Flags);
    593     }
    594     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
    595                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
    596       SmallVector<const SCEV *, 3> Ops;
    597       Ops.push_back(Op0);
    598       Ops.push_back(Op1);
    599       Ops.push_back(Op2);
    600       return getAddExpr(Ops, Flags);
    601     }
    602     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
    603                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    604     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
    605                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
    606     {
    607       SmallVector<const SCEV *, 2> Ops;
    608       Ops.push_back(LHS);
    609       Ops.push_back(RHS);
    610       return getMulExpr(Ops, Flags);
    611     }
    612     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
    613                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
    614       SmallVector<const SCEV *, 3> Ops;
    615       Ops.push_back(Op0);
    616       Ops.push_back(Op1);
    617       Ops.push_back(Op2);
    618       return getMulExpr(Ops, Flags);
    619     }
    620     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
    621     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
    622                               const Loop *L, SCEV::NoWrapFlags Flags);
    623     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
    624                               const Loop *L, SCEV::NoWrapFlags Flags);
    625     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
    626                               const Loop *L, SCEV::NoWrapFlags Flags) {
    627       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
    628       return getAddRecExpr(NewOp, L, Flags);
    629     }
    630     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
    631     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
    632     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
    633     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
    634     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
    635     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
    636     const SCEV *getUnknown(Value *V);
    637     const SCEV *getCouldNotCompute();
    638 
    639     /// getSizeOfExpr - Return an expression for sizeof on the given type.
    640     ///
    641     const SCEV *getSizeOfExpr(Type *AllocTy);
    642 
    643     /// getAlignOfExpr - Return an expression for alignof on the given type.
    644     ///
    645     const SCEV *getAlignOfExpr(Type *AllocTy);
    646 
    647     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
    648     ///
    649     const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
    650 
    651     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
    652     ///
    653     const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
    654 
    655     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
    656     ///
    657     const SCEV *getNegativeSCEV(const SCEV *V);
    658 
    659     /// getNotSCEV - Return the SCEV object corresponding to ~V.
    660     ///
    661     const SCEV *getNotSCEV(const SCEV *V);
    662 
    663     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
    664     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
    665                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
    666 
    667     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
    668     /// of the input value to the specified type.  If the type must be
    669     /// extended, it is zero extended.
    670     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
    671 
    672     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
    673     /// of the input value to the specified type.  If the type must be
    674     /// extended, it is sign extended.
    675     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
    676 
    677     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
    678     /// the input value to the specified type.  If the type must be extended,
    679     /// it is zero extended.  The conversion must not be narrowing.
    680     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
    681 
    682     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
    683     /// the input value to the specified type.  If the type must be extended,
    684     /// it is sign extended.  The conversion must not be narrowing.
    685     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
    686 
    687     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
    688     /// the input value to the specified type. If the type must be extended,
    689     /// it is extended with unspecified bits. The conversion must not be
    690     /// narrowing.
    691     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
    692 
    693     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
    694     /// input value to the specified type.  The conversion must not be
    695     /// widening.
    696     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
    697 
    698     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
    699     /// the types using zero-extension, and then perform a umax operation
    700     /// with them.
    701     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
    702                                            const SCEV *RHS);
    703 
    704     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
    705     /// the types using zero-extension, and then perform a umin operation
    706     /// with them.
    707     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
    708                                            const SCEV *RHS);
    709 
    710     /// getPointerBase - Transitively follow the chain of pointer-type operands
    711     /// until reaching a SCEV that does not have a single pointer operand. This
    712     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
    713     /// but corner cases do exist.
    714     const SCEV *getPointerBase(const SCEV *V);
    715 
    716     /// getSCEVAtScope - Return a SCEV expression for the specified value
    717     /// at the specified scope in the program.  The L value specifies a loop
    718     /// nest to evaluate the expression at, where null is the top-level or a
    719     /// specified loop is immediately inside of the loop.
    720     ///
    721     /// This method can be used to compute the exit value for a variable defined
    722     /// in a loop by querying what the value will hold in the parent loop.
    723     ///
    724     /// In the case that a relevant loop exit value cannot be computed, the
    725     /// original value V is returned.
    726     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
    727 
    728     /// getSCEVAtScope - This is a convenience function which does
    729     /// getSCEVAtScope(getSCEV(V), L).
    730     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
    731 
    732     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
    733     /// by a conditional between LHS and RHS.  This is used to help avoid max
    734     /// expressions in loop trip counts, and to eliminate casts.
    735     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
    736                                   const SCEV *LHS, const SCEV *RHS);
    737 
    738     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
    739     /// protected by a conditional between LHS and RHS.  This is used to
    740     /// to eliminate casts.
    741     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
    742                                      const SCEV *LHS, const SCEV *RHS);
    743 
    744     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
    745     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
    746     /// not constant. This "trip count" assumes that control exits via
    747     /// ExitingBlock. More precisely, it is the number of times that control may
    748     /// reach ExitingBlock before taking the branch. For loops with multiple
    749     /// exits, it may not be the number times that the loop header executes if
    750     /// the loop exits prematurely via another branch.
    751     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
    752 
    753     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
    754     /// the trip count of this loop as a normal unsigned value, if
    755     /// possible. This means that the actual trip count is always a multiple of
    756     /// the returned value (don't forget the trip count could very well be zero
    757     /// as well!). As explained in the comments for getSmallConstantTripCount,
    758     /// this assumes that control exits the loop via ExitingBlock.
    759     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
    760 
    761     // getExitCount - Get the expression for the number of loop iterations for
    762     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
    763     // return SCEVCouldNotCompute.
    764     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
    765 
    766     /// getBackedgeTakenCount - If the specified loop has a predictable
    767     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
    768     /// object. The backedge-taken count is the number of times the loop header
    769     /// will be branched to from within the loop. This is one less than the
    770     /// trip count of the loop, since it doesn't count the first iteration,
    771     /// when the header is branched to from outside the loop.
    772     ///
    773     /// Note that it is not valid to call this method on a loop without a
    774     /// loop-invariant backedge-taken count (see
    775     /// hasLoopInvariantBackedgeTakenCount).
    776     ///
    777     const SCEV *getBackedgeTakenCount(const Loop *L);
    778 
    779     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
    780     /// return the least SCEV value that is known never to be less than the
    781     /// actual backedge taken count.
    782     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
    783 
    784     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
    785     /// has an analyzable loop-invariant backedge-taken count.
    786     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
    787 
    788     /// forgetLoop - This method should be called by the client when it has
    789     /// changed a loop in a way that may effect ScalarEvolution's ability to
    790     /// compute a trip count, or if the loop is deleted.
    791     void forgetLoop(const Loop *L);
    792 
    793     /// forgetValue - This method should be called by the client when it has
    794     /// changed a value in a way that may effect its value, or which may
    795     /// disconnect it from a def-use chain linking it to a loop.
    796     void forgetValue(Value *V);
    797 
    798     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
    799     /// is guaranteed to end in (at every loop iteration).  It is, at the same
    800     /// time, the minimum number of times S is divisible by 2.  For example,
    801     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
    802     /// bitwidth of S.
    803     uint32_t GetMinTrailingZeros(const SCEV *S);
    804 
    805     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
    806     ///
    807     ConstantRange getUnsignedRange(const SCEV *S);
    808 
    809     /// getSignedRange - Determine the signed range for a particular SCEV.
    810     ///
    811     ConstantRange getSignedRange(const SCEV *S);
    812 
    813     /// isKnownNegative - Test if the given expression is known to be negative.
    814     ///
    815     bool isKnownNegative(const SCEV *S);
    816 
    817     /// isKnownPositive - Test if the given expression is known to be positive.
    818     ///
    819     bool isKnownPositive(const SCEV *S);
    820 
    821     /// isKnownNonNegative - Test if the given expression is known to be
    822     /// non-negative.
    823     ///
    824     bool isKnownNonNegative(const SCEV *S);
    825 
    826     /// isKnownNonPositive - Test if the given expression is known to be
    827     /// non-positive.
    828     ///
    829     bool isKnownNonPositive(const SCEV *S);
    830 
    831     /// isKnownNonZero - Test if the given expression is known to be
    832     /// non-zero.
    833     ///
    834     bool isKnownNonZero(const SCEV *S);
    835 
    836     /// isKnownPredicate - Test if the given expression is known to satisfy
    837     /// the condition described by Pred, LHS, and RHS.
    838     ///
    839     bool isKnownPredicate(ICmpInst::Predicate Pred,
    840                           const SCEV *LHS, const SCEV *RHS);
    841 
    842     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
    843     /// predicate Pred. Return true iff any changes were made. If the
    844     /// operands are provably equal or unequal, LHS and RHS are set to
    845     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
    846     ///
    847     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
    848                               const SCEV *&LHS,
    849                               const SCEV *&RHS,
    850                               unsigned Depth = 0);
    851 
    852     /// getLoopDisposition - Return the "disposition" of the given SCEV with
    853     /// respect to the given loop.
    854     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
    855 
    856     /// isLoopInvariant - Return true if the value of the given SCEV is
    857     /// unchanging in the specified loop.
    858     bool isLoopInvariant(const SCEV *S, const Loop *L);
    859 
    860     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
    861     /// in a known way in the specified loop.  This property being true implies
    862     /// that the value is variant in the loop AND that we can emit an expression
    863     /// to compute the value of the expression at any particular loop iteration.
    864     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
    865 
    866     /// getLoopDisposition - Return the "disposition" of the given SCEV with
    867     /// respect to the given block.
    868     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
    869 
    870     /// dominates - Return true if elements that makes up the given SCEV
    871     /// dominate the specified basic block.
    872     bool dominates(const SCEV *S, const BasicBlock *BB);
    873 
    874     /// properlyDominates - Return true if elements that makes up the given SCEV
    875     /// properly dominate the specified basic block.
    876     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
    877 
    878     /// hasOperand - Test whether the given SCEV has Op as a direct or
    879     /// indirect operand.
    880     bool hasOperand(const SCEV *S, const SCEV *Op) const;
    881 
    882     virtual bool runOnFunction(Function &F);
    883     virtual void releaseMemory();
    884     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
    885     virtual void print(raw_ostream &OS, const Module* = 0) const;
    886     virtual void verifyAnalysis() const;
    887 
    888   private:
    889     FoldingSet<SCEV> UniqueSCEVs;
    890     BumpPtrAllocator SCEVAllocator;
    891 
    892     /// FirstUnknown - The head of a linked list of all SCEVUnknown
    893     /// values that have been allocated. This is used by releaseMemory
    894     /// to locate them all and call their destructors.
    895     SCEVUnknown *FirstUnknown;
    896   };
    897 }
    898 
    899 #endif
    900