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