ScalarEvolution.h revision fcb4356dee96563def584fe38eeafb3eb63c5cd8
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      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, const SCEV *FoundRHS);
511
512    /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
513    /// in the header of its containing loop, we know the loop executes a
514    /// constant number of times, and the PHI node is just a recurrence
515    /// involving constants, fold it.
516    Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
517                                                const Loop *L);
518
519    /// isKnownPredicateWithRanges - Test if the given expression is known to
520    /// satisfy the condition described by Pred and the known constant ranges
521    /// of LHS and RHS.
522    ///
523    bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
524                                    const SCEV *LHS, const SCEV *RHS);
525
526    /// forgetMemoizedResults - Drop memoized information computed for S.
527    void forgetMemoizedResults(const SCEV *S);
528
529  public:
530    static char ID; // Pass identification, replacement for typeid
531    ScalarEvolution();
532
533    LLVMContext &getContext() const { return F->getContext(); }
534
535    /// isSCEVable - Test if values of the given type are analyzable within
536    /// the SCEV framework. This primarily includes integer types, and it
537    /// can optionally include pointer types if the ScalarEvolution class
538    /// has access to target-specific information.
539    bool isSCEVable(Type *Ty) const;
540
541    /// getTypeSizeInBits - Return the size in bits of the specified type,
542    /// for which isSCEVable must return true.
543    uint64_t getTypeSizeInBits(Type *Ty) const;
544
545    /// getEffectiveSCEVType - Return a type with the same bitwidth as
546    /// the given type and which represents how SCEV will treat the given
547    /// type, for which isSCEVable must return true. For pointer types,
548    /// this is the pointer-sized integer type.
549    Type *getEffectiveSCEVType(Type *Ty) const;
550
551    /// getSCEV - Return a SCEV expression for the full generality of the
552    /// specified expression.
553    const SCEV *getSCEV(Value *V);
554
555    const SCEV *getConstant(ConstantInt *V);
556    const SCEV *getConstant(const APInt& Val);
557    const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
558    const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
559    const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
560    const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
561    const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
562    const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
563                           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
564    const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
565                           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
566      SmallVector<const SCEV *, 2> Ops;
567      Ops.push_back(LHS);
568      Ops.push_back(RHS);
569      return getAddExpr(Ops, Flags);
570    }
571    const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
572                           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
573      SmallVector<const SCEV *, 3> Ops;
574      Ops.push_back(Op0);
575      Ops.push_back(Op1);
576      Ops.push_back(Op2);
577      return getAddExpr(Ops, Flags);
578    }
579    const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
580                           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
581    const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
582                           SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
583    {
584      SmallVector<const SCEV *, 2> Ops;
585      Ops.push_back(LHS);
586      Ops.push_back(RHS);
587      return getMulExpr(Ops, Flags);
588    }
589    const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
590    const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
591                              const Loop *L, SCEV::NoWrapFlags Flags);
592    const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
593                              const Loop *L, SCEV::NoWrapFlags Flags);
594    const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
595                              const Loop *L, SCEV::NoWrapFlags Flags) {
596      SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
597      return getAddRecExpr(NewOp, L, Flags);
598    }
599    const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
600    const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
601    const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
602    const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
603    const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
604    const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
605    const SCEV *getUnknown(Value *V);
606    const SCEV *getCouldNotCompute();
607
608    /// getSizeOfExpr - Return an expression for sizeof on the given type.
609    ///
610    const SCEV *getSizeOfExpr(Type *AllocTy);
611
612    /// getAlignOfExpr - Return an expression for alignof on the given type.
613    ///
614    const SCEV *getAlignOfExpr(Type *AllocTy);
615
616    /// getOffsetOfExpr - Return an expression for offsetof on the given field.
617    ///
618    const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
619
620    /// getOffsetOfExpr - Return an expression for offsetof on the given field.
621    ///
622    const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
623
624    /// getNegativeSCEV - Return the SCEV object corresponding to -V.
625    ///
626    const SCEV *getNegativeSCEV(const SCEV *V);
627
628    /// getNotSCEV - Return the SCEV object corresponding to ~V.
629    ///
630    const SCEV *getNotSCEV(const SCEV *V);
631
632    /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
633    const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
634                             SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
635
636    /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
637    /// of the input value to the specified type.  If the type must be
638    /// extended, it is zero extended.
639    const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
640
641    /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
642    /// of the input value to the specified type.  If the type must be
643    /// extended, it is sign extended.
644    const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
645
646    /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
647    /// the input value to the specified type.  If the type must be extended,
648    /// it is zero extended.  The conversion must not be narrowing.
649    const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
650
651    /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
652    /// the input value to the specified type.  If the type must be extended,
653    /// it is sign extended.  The conversion must not be narrowing.
654    const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
655
656    /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
657    /// the input value to the specified type. If the type must be extended,
658    /// it is extended with unspecified bits. The conversion must not be
659    /// narrowing.
660    const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
661
662    /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
663    /// input value to the specified type.  The conversion must not be
664    /// widening.
665    const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
666
667    /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
668    /// the types using zero-extension, and then perform a umax operation
669    /// with them.
670    const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
671                                           const SCEV *RHS);
672
673    /// getUMinFromMismatchedTypes - Promote the operands to the wider of
674    /// the types using zero-extension, and then perform a umin operation
675    /// with them.
676    const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
677                                           const SCEV *RHS);
678
679    /// getPointerBase - Transitively follow the chain of pointer-type operands
680    /// until reaching a SCEV that does not have a single pointer operand. This
681    /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
682    /// but corner cases do exist.
683    const SCEV *getPointerBase(const SCEV *V);
684
685    /// getSCEVAtScope - Return a SCEV expression for the specified value
686    /// at the specified scope in the program.  The L value specifies a loop
687    /// nest to evaluate the expression at, where null is the top-level or a
688    /// specified loop is immediately inside of the loop.
689    ///
690    /// This method can be used to compute the exit value for a variable defined
691    /// in a loop by querying what the value will hold in the parent loop.
692    ///
693    /// In the case that a relevant loop exit value cannot be computed, the
694    /// original value V is returned.
695    const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
696
697    /// getSCEVAtScope - This is a convenience function which does
698    /// getSCEVAtScope(getSCEV(V), L).
699    const SCEV *getSCEVAtScope(Value *V, const Loop *L);
700
701    /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
702    /// by a conditional between LHS and RHS.  This is used to help avoid max
703    /// expressions in loop trip counts, and to eliminate casts.
704    bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
705                                  const SCEV *LHS, const SCEV *RHS);
706
707    /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
708    /// protected by a conditional between LHS and RHS.  This is used to
709    /// to eliminate casts.
710    bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
711                                     const SCEV *LHS, const SCEV *RHS);
712
713    // getExitCount - Get the expression for the number of loop iterations for
714    // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
715    // return SCEVCouldNotCompute.
716    const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
717
718    /// getBackedgeTakenCount - If the specified loop has a predictable
719    /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
720    /// object. The backedge-taken count is the number of times the loop header
721    /// will be branched to from within the loop. This is one less than the
722    /// trip count of the loop, since it doesn't count the first iteration,
723    /// when the header is branched to from outside the loop.
724    ///
725    /// Note that it is not valid to call this method on a loop without a
726    /// loop-invariant backedge-taken count (see
727    /// hasLoopInvariantBackedgeTakenCount).
728    ///
729    const SCEV *getBackedgeTakenCount(const Loop *L);
730
731    /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
732    /// return the least SCEV value that is known never to be less than the
733    /// actual backedge taken count.
734    const SCEV *getMaxBackedgeTakenCount(const Loop *L);
735
736    /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
737    /// has an analyzable loop-invariant backedge-taken count.
738    bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
739
740    /// forgetLoop - This method should be called by the client when it has
741    /// changed a loop in a way that may effect ScalarEvolution's ability to
742    /// compute a trip count, or if the loop is deleted.
743    void forgetLoop(const Loop *L);
744
745    /// forgetValue - This method should be called by the client when it has
746    /// changed a value in a way that may effect its value, or which may
747    /// disconnect it from a def-use chain linking it to a loop.
748    void forgetValue(Value *V);
749
750    /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
751    /// is guaranteed to end in (at every loop iteration).  It is, at the same
752    /// time, the minimum number of times S is divisible by 2.  For example,
753    /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
754    /// bitwidth of S.
755    uint32_t GetMinTrailingZeros(const SCEV *S);
756
757    /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
758    ///
759    ConstantRange getUnsignedRange(const SCEV *S);
760
761    /// getSignedRange - Determine the signed range for a particular SCEV.
762    ///
763    ConstantRange getSignedRange(const SCEV *S);
764
765    /// isKnownNegative - Test if the given expression is known to be negative.
766    ///
767    bool isKnownNegative(const SCEV *S);
768
769    /// isKnownPositive - Test if the given expression is known to be positive.
770    ///
771    bool isKnownPositive(const SCEV *S);
772
773    /// isKnownNonNegative - Test if the given expression is known to be
774    /// non-negative.
775    ///
776    bool isKnownNonNegative(const SCEV *S);
777
778    /// isKnownNonPositive - Test if the given expression is known to be
779    /// non-positive.
780    ///
781    bool isKnownNonPositive(const SCEV *S);
782
783    /// isKnownNonZero - Test if the given expression is known to be
784    /// non-zero.
785    ///
786    bool isKnownNonZero(const SCEV *S);
787
788    /// isKnownPredicate - Test if the given expression is known to satisfy
789    /// the condition described by Pred, LHS, and RHS.
790    ///
791    bool isKnownPredicate(ICmpInst::Predicate Pred,
792                          const SCEV *LHS, const SCEV *RHS);
793
794    /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
795    /// predicate Pred. Return true iff any changes were made. If the
796    /// operands are provably equal or inequal, LHS and RHS are set to
797    /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
798    ///
799    bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
800                              const SCEV *&LHS,
801                              const SCEV *&RHS);
802
803    /// getLoopDisposition - Return the "disposition" of the given SCEV with
804    /// respect to the given loop.
805    LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
806
807    /// isLoopInvariant - Return true if the value of the given SCEV is
808    /// unchanging in the specified loop.
809    bool isLoopInvariant(const SCEV *S, const Loop *L);
810
811    /// hasComputableLoopEvolution - Return true if the given SCEV changes value
812    /// in a known way in the specified loop.  This property being true implies
813    /// that the value is variant in the loop AND that we can emit an expression
814    /// to compute the value of the expression at any particular loop iteration.
815    bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
816
817    /// getLoopDisposition - Return the "disposition" of the given SCEV with
818    /// respect to the given block.
819    BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
820
821    /// dominates - Return true if elements that makes up the given SCEV
822    /// dominate the specified basic block.
823    bool dominates(const SCEV *S, const BasicBlock *BB);
824
825    /// properlyDominates - Return true if elements that makes up the given SCEV
826    /// properly dominate the specified basic block.
827    bool properlyDominates(const SCEV *S, const BasicBlock *BB);
828
829    /// hasOperand - Test whether the given SCEV has Op as a direct or
830    /// indirect operand.
831    bool hasOperand(const SCEV *S, const SCEV *Op) const;
832
833    virtual bool runOnFunction(Function &F);
834    virtual void releaseMemory();
835    virtual void getAnalysisUsage(AnalysisUsage &AU) const;
836    virtual void print(raw_ostream &OS, const Module* = 0) const;
837
838  private:
839    FoldingSet<SCEV> UniqueSCEVs;
840    BumpPtrAllocator SCEVAllocator;
841
842    /// FirstUnknown - The head of a linked list of all SCEVUnknown
843    /// values that have been allocated. This is used by releaseMemory
844    /// to locate them all and call their destructors.
845    SCEVUnknown *FirstUnknown;
846  };
847}
848
849#endif
850