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