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