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