]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/include/llvm/Analysis/ScalarEvolution.h
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / contrib / llvm / include / llvm / Analysis / ScalarEvolution.h
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
36 namespace 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, or SCEVCouldNotCompute. The loop is guaranteed not
323       /// to exit via this block before this number of iterations, but may exit
324       /// via another block.
325       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
326
327       /// getMax - Get the max backedge taken count for the loop.
328       const SCEV *getMax(ScalarEvolution *SE) const;
329
330       /// clear - Invalidate this result and free associated memory.
331       void clear();
332     };
333
334     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
335     /// this function as they are computed.
336     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
337
338     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
339     /// the PHI instructions that we attempt to compute constant evolutions for.
340     /// This allows us to avoid potentially expensive recomputation of these
341     /// properties.  An instruction maps to null if we are unable to compute its
342     /// exit value.
343     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
344
345     /// ValuesAtScopes - This map contains entries for all the expressions
346     /// that we attempt to compute getSCEVAtScope information for, which can
347     /// be expensive in extreme cases.
348     DenseMap<const SCEV *,
349              std::map<const Loop *, const SCEV *> > ValuesAtScopes;
350
351     /// LoopDispositions - Memoized computeLoopDisposition results.
352     DenseMap<const SCEV *,
353              std::map<const Loop *, LoopDisposition> > LoopDispositions;
354
355     /// computeLoopDisposition - Compute a LoopDisposition value.
356     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
357
358     /// BlockDispositions - Memoized computeBlockDisposition results.
359     DenseMap<const SCEV *,
360              std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
361
362     /// computeBlockDisposition - Compute a BlockDisposition value.
363     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
364
365     /// UnsignedRanges - Memoized results from getUnsignedRange
366     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
367
368     /// SignedRanges - Memoized results from getSignedRange
369     DenseMap<const SCEV *, ConstantRange> SignedRanges;
370
371     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
372     const ConstantRange &setUnsignedRange(const SCEV *S,
373                                           const ConstantRange &CR) {
374       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
375         UnsignedRanges.insert(std::make_pair(S, CR));
376       if (!Pair.second)
377         Pair.first->second = CR;
378       return Pair.first->second;
379     }
380
381     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
382     const ConstantRange &setSignedRange(const SCEV *S,
383                                         const ConstantRange &CR) {
384       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
385         SignedRanges.insert(std::make_pair(S, CR));
386       if (!Pair.second)
387         Pair.first->second = CR;
388       return Pair.first->second;
389     }
390
391     /// createSCEV - We know that there is no SCEV for the specified value.
392     /// Analyze the expression.
393     const SCEV *createSCEV(Value *V);
394
395     /// createNodeForPHI - Provide the special handling we need to analyze PHI
396     /// SCEVs.
397     const SCEV *createNodeForPHI(PHINode *PN);
398
399     /// createNodeForGEP - Provide the special handling we need to analyze GEP
400     /// SCEVs.
401     const SCEV *createNodeForGEP(GEPOperator *GEP);
402
403     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
404     /// at most once for each SCEV+Loop pair.
405     ///
406     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
407
408     /// ForgetSymbolicValue - This looks up computed SCEV values for all
409     /// instructions that depend on the given instruction and removes them from
410     /// the ValueExprMap map if they reference SymName. This is used during PHI
411     /// resolution.
412     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
413
414     /// getBECount - Subtract the end and start values and divide by the step,
415     /// rounding up, to get the number of times the backedge is executed. Return
416     /// CouldNotCompute if an intermediate computation overflows.
417     const SCEV *getBECount(const SCEV *Start,
418                            const SCEV *End,
419                            const SCEV *Step,
420                            bool NoWrap);
421
422     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
423     /// loop, lazily computing new values if the loop hasn't been analyzed
424     /// yet.
425     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
426
427     /// ComputeBackedgeTakenCount - Compute the number of times the specified
428     /// loop will iterate.
429     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
430
431     /// ComputeExitLimit - Compute the number of times the backedge of the
432     /// specified loop will execute if it exits via the specified block.
433     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
434
435     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
436     /// the specified loop will execute if its exit condition were a conditional
437     /// branch of ExitCond, TBB, and FBB.
438     ExitLimit ComputeExitLimitFromCond(const Loop *L,
439                                        Value *ExitCond,
440                                        BasicBlock *TBB,
441                                        BasicBlock *FBB);
442
443     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
444     /// the specified loop will execute if its exit condition were a conditional
445     /// branch of the ICmpInst ExitCond, TBB, and FBB.
446     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
447                                        ICmpInst *ExitCond,
448                                        BasicBlock *TBB,
449                                        BasicBlock *FBB);
450
451     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
452     /// of 'icmp op load X, cst', try to see if we can compute the
453     /// backedge-taken count.
454     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
455                                                   Constant *RHS,
456                                                   const Loop *L,
457                                                   ICmpInst::Predicate p);
458
459     /// ComputeExitCountExhaustively - If the loop is known to execute a
460     /// constant number of times (the condition evolves only from constants),
461     /// try to evaluate a few iterations of the loop until we get the exit
462     /// condition gets a value of ExitWhen (true or false).  If we cannot
463     /// evaluate the exit count of the loop, return CouldNotCompute.
464     const SCEV *ComputeExitCountExhaustively(const Loop *L,
465                                              Value *Cond,
466                                              bool ExitWhen);
467
468     /// HowFarToZero - Return the number of times an exit condition comparing
469     /// the specified value to zero will execute.  If not computable, return
470     /// CouldNotCompute.
471     ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
472
473     /// HowFarToNonZero - Return the number of times an exit condition checking
474     /// the specified value for nonzero will execute.  If not computable, return
475     /// CouldNotCompute.
476     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
477
478     /// HowManyLessThans - Return the number of times an exit condition
479     /// containing the specified less-than comparison will execute.  If not
480     /// computable, return CouldNotCompute. isSigned specifies whether the
481     /// less-than is signed.
482     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
483                                const Loop *L, bool isSigned);
484
485     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
486     /// (which may not be an immediate predecessor) which has exactly one
487     /// successor from which BB is reachable, or null if no such block is
488     /// found.
489     std::pair<BasicBlock *, BasicBlock *>
490     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
491
492     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
493     /// RHS is true whenever the given FoundCondValue value evaluates to true.
494     bool isImpliedCond(ICmpInst::Predicate Pred,
495                        const SCEV *LHS, const SCEV *RHS,
496                        Value *FoundCondValue,
497                        bool Inverse);
498
499     /// isImpliedCondOperands - Test whether the condition described by Pred,
500     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
501     /// and FoundRHS is true.
502     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
503                                const SCEV *LHS, const SCEV *RHS,
504                                const SCEV *FoundLHS, const SCEV *FoundRHS);
505
506     /// isImpliedCondOperandsHelper - Test whether the condition described by
507     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
508     /// FoundLHS, and FoundRHS is true.
509     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
510                                      const SCEV *LHS, const SCEV *RHS,
511                                      const SCEV *FoundLHS,
512                                      const SCEV *FoundRHS);
513
514     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
515     /// in the header of its containing loop, we know the loop executes a
516     /// constant number of times, and the PHI node is just a recurrence
517     /// involving constants, fold it.
518     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
519                                                 const Loop *L);
520
521     /// isKnownPredicateWithRanges - Test if the given expression is known to
522     /// satisfy the condition described by Pred and the known constant ranges
523     /// of LHS and RHS.
524     ///
525     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
526                                     const SCEV *LHS, const SCEV *RHS);
527
528     /// forgetMemoizedResults - Drop memoized information computed for S.
529     void forgetMemoizedResults(const SCEV *S);
530
531   public:
532     static char ID; // Pass identification, replacement for typeid
533     ScalarEvolution();
534
535     LLVMContext &getContext() const { return F->getContext(); }
536
537     /// isSCEVable - Test if values of the given type are analyzable within
538     /// the SCEV framework. This primarily includes integer types, and it
539     /// can optionally include pointer types if the ScalarEvolution class
540     /// has access to target-specific information.
541     bool isSCEVable(Type *Ty) const;
542
543     /// getTypeSizeInBits - Return the size in bits of the specified type,
544     /// for which isSCEVable must return true.
545     uint64_t getTypeSizeInBits(Type *Ty) const;
546
547     /// getEffectiveSCEVType - Return a type with the same bitwidth as
548     /// the given type and which represents how SCEV will treat the given
549     /// type, for which isSCEVable must return true. For pointer types,
550     /// this is the pointer-sized integer type.
551     Type *getEffectiveSCEVType(Type *Ty) const;
552
553     /// getSCEV - Return a SCEV expression for the full generality of the
554     /// specified expression.
555     const SCEV *getSCEV(Value *V);
556
557     const SCEV *getConstant(ConstantInt *V);
558     const SCEV *getConstant(const APInt& Val);
559     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
560     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
561     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
562     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
563     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
564     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
565                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
566     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
567                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
568       SmallVector<const SCEV *, 2> Ops;
569       Ops.push_back(LHS);
570       Ops.push_back(RHS);
571       return getAddExpr(Ops, Flags);
572     }
573     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
574                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
575       SmallVector<const SCEV *, 3> Ops;
576       Ops.push_back(Op0);
577       Ops.push_back(Op1);
578       Ops.push_back(Op2);
579       return getAddExpr(Ops, Flags);
580     }
581     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
582                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
583     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
584                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
585     {
586       SmallVector<const SCEV *, 2> Ops;
587       Ops.push_back(LHS);
588       Ops.push_back(RHS);
589       return getMulExpr(Ops, Flags);
590     }
591     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
592                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
593       SmallVector<const SCEV *, 3> Ops;
594       Ops.push_back(Op0);
595       Ops.push_back(Op1);
596       Ops.push_back(Op2);
597       return getMulExpr(Ops, Flags);
598     }
599     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
600     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
601                               const Loop *L, SCEV::NoWrapFlags Flags);
602     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
603                               const Loop *L, SCEV::NoWrapFlags Flags);
604     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
605                               const Loop *L, SCEV::NoWrapFlags Flags) {
606       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
607       return getAddRecExpr(NewOp, L, Flags);
608     }
609     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
610     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
611     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
612     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
613     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
614     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
615     const SCEV *getUnknown(Value *V);
616     const SCEV *getCouldNotCompute();
617
618     /// getSizeOfExpr - Return an expression for sizeof on the given type.
619     ///
620     const SCEV *getSizeOfExpr(Type *AllocTy);
621
622     /// getAlignOfExpr - Return an expression for alignof on the given type.
623     ///
624     const SCEV *getAlignOfExpr(Type *AllocTy);
625
626     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
627     ///
628     const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
629
630     /// getOffsetOfExpr - Return an expression for offsetof on the given field.
631     ///
632     const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
633
634     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
635     ///
636     const SCEV *getNegativeSCEV(const SCEV *V);
637
638     /// getNotSCEV - Return the SCEV object corresponding to ~V.
639     ///
640     const SCEV *getNotSCEV(const SCEV *V);
641
642     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
643     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
644                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
645
646     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
647     /// of the input value to the specified type.  If the type must be
648     /// extended, it is zero extended.
649     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
650
651     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
652     /// of the input value to the specified type.  If the type must be
653     /// extended, it is sign extended.
654     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
655
656     /// getNoopOrZeroExtend - 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 zero extended.  The conversion must not be narrowing.
659     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
660
661     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
662     /// the input value to the specified type.  If the type must be extended,
663     /// it is sign extended.  The conversion must not be narrowing.
664     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
665
666     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
667     /// the input value to the specified type. If the type must be extended,
668     /// it is extended with unspecified bits. The conversion must not be
669     /// narrowing.
670     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
671
672     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
673     /// input value to the specified type.  The conversion must not be
674     /// widening.
675     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
676
677     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
678     /// the types using zero-extension, and then perform a umax operation
679     /// with them.
680     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
681                                            const SCEV *RHS);
682
683     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
684     /// the types using zero-extension, and then perform a umin operation
685     /// with them.
686     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
687                                            const SCEV *RHS);
688
689     /// getPointerBase - Transitively follow the chain of pointer-type operands
690     /// until reaching a SCEV that does not have a single pointer operand. This
691     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
692     /// but corner cases do exist.
693     const SCEV *getPointerBase(const SCEV *V);
694
695     /// getSCEVAtScope - Return a SCEV expression for the specified value
696     /// at the specified scope in the program.  The L value specifies a loop
697     /// nest to evaluate the expression at, where null is the top-level or a
698     /// specified loop is immediately inside of the loop.
699     ///
700     /// This method can be used to compute the exit value for a variable defined
701     /// in a loop by querying what the value will hold in the parent loop.
702     ///
703     /// In the case that a relevant loop exit value cannot be computed, the
704     /// original value V is returned.
705     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
706
707     /// getSCEVAtScope - This is a convenience function which does
708     /// getSCEVAtScope(getSCEV(V), L).
709     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
710
711     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
712     /// by a conditional between LHS and RHS.  This is used to help avoid max
713     /// expressions in loop trip counts, and to eliminate casts.
714     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
715                                   const SCEV *LHS, const SCEV *RHS);
716
717     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
718     /// protected by a conditional between LHS and RHS.  This is used to
719     /// to eliminate casts.
720     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
721                                      const SCEV *LHS, const SCEV *RHS);
722
723     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
724     /// as a normal unsigned value, if possible. Returns 0 if the trip count is
725     /// unknown or not constant.
726     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitBlock);
727
728     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
729     /// the trip count of this loop as a normal unsigned value, if
730     /// possible. This means that the actual trip count is always a multiple of
731     /// the returned value (don't forget the trip count could very well be zero
732     /// as well!).
733     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitBlock);
734
735     // getExitCount - Get the expression for the number of loop iterations for
736     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
737     // return SCEVCouldNotCompute.
738     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
739
740     /// getBackedgeTakenCount - If the specified loop has a predictable
741     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
742     /// object. The backedge-taken count is the number of times the loop header
743     /// will be branched to from within the loop. This is one less than the
744     /// trip count of the loop, since it doesn't count the first iteration,
745     /// when the header is branched to from outside the loop.
746     ///
747     /// Note that it is not valid to call this method on a loop without a
748     /// loop-invariant backedge-taken count (see
749     /// hasLoopInvariantBackedgeTakenCount).
750     ///
751     const SCEV *getBackedgeTakenCount(const Loop *L);
752
753     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
754     /// return the least SCEV value that is known never to be less than the
755     /// actual backedge taken count.
756     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
757
758     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
759     /// has an analyzable loop-invariant backedge-taken count.
760     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
761
762     /// forgetLoop - This method should be called by the client when it has
763     /// changed a loop in a way that may effect ScalarEvolution's ability to
764     /// compute a trip count, or if the loop is deleted.
765     void forgetLoop(const Loop *L);
766
767     /// forgetValue - This method should be called by the client when it has
768     /// changed a value in a way that may effect its value, or which may
769     /// disconnect it from a def-use chain linking it to a loop.
770     void forgetValue(Value *V);
771
772     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
773     /// is guaranteed to end in (at every loop iteration).  It is, at the same
774     /// time, the minimum number of times S is divisible by 2.  For example,
775     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
776     /// bitwidth of S.
777     uint32_t GetMinTrailingZeros(const SCEV *S);
778
779     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
780     ///
781     ConstantRange getUnsignedRange(const SCEV *S);
782
783     /// getSignedRange - Determine the signed range for a particular SCEV.
784     ///
785     ConstantRange getSignedRange(const SCEV *S);
786
787     /// isKnownNegative - Test if the given expression is known to be negative.
788     ///
789     bool isKnownNegative(const SCEV *S);
790
791     /// isKnownPositive - Test if the given expression is known to be positive.
792     ///
793     bool isKnownPositive(const SCEV *S);
794
795     /// isKnownNonNegative - Test if the given expression is known to be
796     /// non-negative.
797     ///
798     bool isKnownNonNegative(const SCEV *S);
799
800     /// isKnownNonPositive - Test if the given expression is known to be
801     /// non-positive.
802     ///
803     bool isKnownNonPositive(const SCEV *S);
804
805     /// isKnownNonZero - Test if the given expression is known to be
806     /// non-zero.
807     ///
808     bool isKnownNonZero(const SCEV *S);
809
810     /// isKnownPredicate - Test if the given expression is known to satisfy
811     /// the condition described by Pred, LHS, and RHS.
812     ///
813     bool isKnownPredicate(ICmpInst::Predicate Pred,
814                           const SCEV *LHS, const SCEV *RHS);
815
816     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
817     /// predicate Pred. Return true iff any changes were made. If the
818     /// operands are provably equal or inequal, LHS and RHS are set to
819     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
820     ///
821     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
822                               const SCEV *&LHS,
823                               const SCEV *&RHS);
824
825     /// getLoopDisposition - Return the "disposition" of the given SCEV with
826     /// respect to the given loop.
827     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
828
829     /// isLoopInvariant - Return true if the value of the given SCEV is
830     /// unchanging in the specified loop.
831     bool isLoopInvariant(const SCEV *S, const Loop *L);
832
833     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
834     /// in a known way in the specified loop.  This property being true implies
835     /// that the value is variant in the loop AND that we can emit an expression
836     /// to compute the value of the expression at any particular loop iteration.
837     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
838
839     /// getLoopDisposition - Return the "disposition" of the given SCEV with
840     /// respect to the given block.
841     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
842
843     /// dominates - Return true if elements that makes up the given SCEV
844     /// dominate the specified basic block.
845     bool dominates(const SCEV *S, const BasicBlock *BB);
846
847     /// properlyDominates - Return true if elements that makes up the given SCEV
848     /// properly dominate the specified basic block.
849     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
850
851     /// hasOperand - Test whether the given SCEV has Op as a direct or
852     /// indirect operand.
853     bool hasOperand(const SCEV *S, const SCEV *Op) const;
854
855     virtual bool runOnFunction(Function &F);
856     virtual void releaseMemory();
857     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
858     virtual void print(raw_ostream &OS, const Module* = 0) const;
859
860   private:
861     FoldingSet<SCEV> UniqueSCEVs;
862     BumpPtrAllocator SCEVAllocator;
863
864     /// FirstUnknown - The head of a linked list of all SCEVUnknown
865     /// values that have been allocated. This is used by releaseMemory
866     /// to locate them all and call their destructors.
867     SCEVUnknown *FirstUnknown;
868   };
869 }
870
871 #endif