0786b51f53532991f2374863aec08186d8fd29b1
[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 // catagorize 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/Analysis/LoopInfo.h"
26 #include "llvm/Support/DataTypes.h"
27 #include <iosfwd>
28
29 namespace llvm {
30   class APInt;
31   class ConstantInt;
32   class Type;
33   class SCEVHandle;
34   class ScalarEvolution;
35
36   /// SCEV - This class represent an analyzed expression in the program.  These
37   /// are reference counted opaque objects that the client is not allowed to
38   /// do much with directly.
39   ///
40   class SCEV {
41     const unsigned SCEVType;      // The SCEV baseclass this node corresponds to
42     mutable unsigned RefCount;
43
44     friend class SCEVHandle;
45     void addRef() const { ++RefCount; }
46     void dropRef() const {
47       if (--RefCount == 0)
48         delete this;
49     }
50
51     SCEV(const SCEV &);            // DO NOT IMPLEMENT
52     void operator=(const SCEV &);  // DO NOT IMPLEMENT
53   protected:
54     virtual ~SCEV();
55   public:
56     explicit SCEV(unsigned SCEVTy) : SCEVType(SCEVTy), RefCount(0) {}
57
58     unsigned getSCEVType() const { return SCEVType; }
59
60     /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
61     /// the specified loop.
62     virtual bool isLoopInvariant(const Loop *L) const = 0;
63
64     /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
65     /// known way in the specified loop.  This property being true implies that
66     /// the value is variant in the loop AND that we can emit an expression to
67     /// compute the value of the expression at any particular loop iteration.
68     virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
69
70     /// getType - Return the LLVM type of this SCEV expression.
71     ///
72     virtual const Type *getType() const = 0;
73
74     /// getBitWidth - Get the bit width of the type, if it has one, 0 otherwise.
75     /// 
76     uint32_t getBitWidth() const;
77
78     /// isZero - Return true if the expression is a constant zero.
79     ///
80     bool isZero() const;
81
82     /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
83     /// the symbolic value "Sym", construct and return a new SCEV that produces
84     /// the same value, but which uses the concrete value Conc instead of the
85     /// symbolic value.  If this SCEV does not use the symbolic value, it
86     /// returns itself.
87     virtual SCEVHandle
88     replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
89                                       const SCEVHandle &Conc,
90                                       ScalarEvolution &SE) const = 0;
91
92     /// print - Print out the internal representation of this scalar to the
93     /// specified stream.  This should really only be used for debugging
94     /// purposes.
95     virtual void print(std::ostream &OS) const = 0;
96     void print(std::ostream *OS) const { if (OS) print(*OS); }
97
98     /// dump - This method is used for debugging.
99     ///
100     void dump() const;
101   };
102
103   inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
104     S.print(OS);
105     return OS;
106   }
107
108   /// SCEVCouldNotCompute - An object of this class is returned by queries that
109   /// could not be answered.  For example, if you ask for the number of
110   /// iterations of a linked-list traversal loop, you will get one of these.
111   /// None of the standard SCEV operations are valid on this class, it is just a
112   /// marker.
113   struct SCEVCouldNotCompute : public SCEV {
114     SCEVCouldNotCompute();
115
116     // None of these methods are valid for this object.
117     virtual bool isLoopInvariant(const Loop *L) const;
118     virtual const Type *getType() const;
119     virtual bool hasComputableLoopEvolution(const Loop *L) const;
120     virtual void print(std::ostream &OS) const;
121     void print(std::ostream *OS) const { if (OS) print(*OS); }
122     virtual SCEVHandle
123     replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
124                                       const SCEVHandle &Conc,
125                                       ScalarEvolution &SE) const;
126
127     /// Methods for support type inquiry through isa, cast, and dyn_cast:
128     static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
129     static bool classof(const SCEV *S);
130   };
131
132   /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
133   /// freeing the objects when the last reference is dropped.
134   class SCEVHandle {
135     SCEV *S;
136     SCEVHandle();  // DO NOT IMPLEMENT
137   public:
138     SCEVHandle(const SCEV *s) : S(const_cast<SCEV*>(s)) {
139       assert(S && "Cannot create a handle to a null SCEV!");
140       S->addRef();
141     }
142     SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
143       S->addRef();
144     }
145     ~SCEVHandle() { S->dropRef(); }
146
147     operator SCEV*() const { return S; }
148
149     SCEV &operator*() const { return *S; }
150     SCEV *operator->() const { return S; }
151
152     bool operator==(SCEV *RHS) const { return S == RHS; }
153     bool operator!=(SCEV *RHS) const { return S != RHS; }
154
155     const SCEVHandle &operator=(SCEV *RHS) {
156       if (S != RHS) {
157         S->dropRef();
158         S = RHS;
159         S->addRef();
160       }
161       return *this;
162     }
163
164     const SCEVHandle &operator=(const SCEVHandle &RHS) {
165       if (S != RHS.S) {
166         S->dropRef();
167         S = RHS.S;
168         S->addRef();
169       }
170       return *this;
171     }
172   };
173
174   template<typename From> struct simplify_type;
175   template<> struct simplify_type<const SCEVHandle> {
176     typedef SCEV* SimpleType;
177     static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
178       return Node;
179     }
180   };
181   template<> struct simplify_type<SCEVHandle>
182     : public simplify_type<const SCEVHandle> {};
183
184   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
185   /// client code (intentionally) can't do much with the SCEV objects directly,
186   /// they must ask this class for services.
187   ///
188   class ScalarEvolution : public FunctionPass {
189     void *Impl;    // ScalarEvolution uses the pimpl pattern
190   public:
191     static char ID; // Pass identification, replacement for typeid
192     ScalarEvolution() : FunctionPass(&ID), Impl(0) {}
193
194     /// getSCEV - Return a SCEV expression handle for the full generality of the
195     /// specified expression.
196     SCEVHandle getSCEV(Value *V) const;
197
198     SCEVHandle getConstant(ConstantInt *V);
199     SCEVHandle getConstant(const APInt& Val);
200     SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
201     SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
202     SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
203     SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
204     SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
205       std::vector<SCEVHandle> Ops;
206       Ops.push_back(LHS);
207       Ops.push_back(RHS);
208       return getAddExpr(Ops);
209     }
210     SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
211                           const SCEVHandle &Op2) {
212       std::vector<SCEVHandle> Ops;
213       Ops.push_back(Op0);
214       Ops.push_back(Op1);
215       Ops.push_back(Op2);
216       return getAddExpr(Ops);
217     }
218     SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
219     SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
220       std::vector<SCEVHandle> Ops;
221       Ops.push_back(LHS);
222       Ops.push_back(RHS);
223       return getMulExpr(Ops);
224     }
225     SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
226     SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
227                              const Loop *L);
228     SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
229                              const Loop *L);
230     SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
231                              const Loop *L) {
232       std::vector<SCEVHandle> NewOp(Operands);
233       return getAddRecExpr(NewOp, L);
234     }
235     SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
236     SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
237     SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
238     SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
239     SCEVHandle getUnknown(Value *V);
240
241     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
242     ///
243     SCEVHandle getNegativeSCEV(const SCEVHandle &V);
244
245     /// getNotSCEV - Return the SCEV object corresponding to ~V.
246     ///
247     SCEVHandle getNotSCEV(const SCEVHandle &V);
248
249     /// getMinusSCEV - Return LHS-RHS.
250     ///
251     SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
252                             const SCEVHandle &RHS);
253
254     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
255     /// of the input value to the specified type.  If the type must be
256     /// extended, it is zero extended.
257     SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
258
259     /// getIntegerSCEV - Given an integer or FP type, create a constant for the
260     /// specified signed integer value and return a SCEV for the constant.
261     SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
262
263     /// hasSCEV - Return true if the SCEV for this value has already been
264     /// computed.
265     bool hasSCEV(Value *V) const;
266
267     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
268     /// the specified value.
269     void setSCEV(Value *V, const SCEVHandle &H);
270
271     /// getSCEVAtScope - Return a SCEV expression handle for the specified value
272     /// at the specified scope in the program.  The L value specifies a loop
273     /// nest to evaluate the expression at, where null is the top-level or a
274     /// specified loop is immediately inside of the loop.
275     ///
276     /// This method can be used to compute the exit value for a variable defined
277     /// in a loop by querying what the value will hold in the parent loop.
278     ///
279     /// If this value is not computable at this scope, a SCEVCouldNotCompute
280     /// object is returned.
281     SCEVHandle getSCEVAtScope(Value *V, const Loop *L) const;
282
283     /// isLoopGuardedByCond - Test whether entry to the loop is protected by
284     /// a conditional between LHS and RHS.
285     bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
286                              SCEV *LHS, SCEV *RHS);
287
288     /// getIterationCount - If the specified loop has a predictable iteration
289     /// count, return it, otherwise return a SCEVCouldNotCompute object.
290     SCEVHandle getIterationCount(const Loop *L) const;
291
292     /// hasLoopInvariantIterationCount - Return true if the specified loop has
293     /// an analyzable loop-invariant iteration count.
294     bool hasLoopInvariantIterationCount(const Loop *L) const;
295
296     /// deleteValueFromRecords - This method should be called by the
297     /// client before it removes a Value from the program, to make sure
298     /// that no dangling references are left around.
299     void deleteValueFromRecords(Value *V) const;
300
301     virtual bool runOnFunction(Function &F);
302     virtual void releaseMemory();
303     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
304     virtual void print(std::ostream &OS, const Module* = 0) const;
305     void print(std::ostream *OS, const Module* M = 0) const {
306       if (OS) print(*OS, M);
307     }
308   };
309 }
310
311 #endif