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