Make SCEVExpanders private methods private, instead of protected.
[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   class TargetData;
36
37   /// SCEV - This class represent an analyzed expression in the program.  These
38   /// are reference counted opaque objects that the client is not allowed to
39   /// do much with directly.
40   ///
41   class SCEV {
42     const unsigned SCEVType;      // The SCEV baseclass this node corresponds to
43     mutable unsigned RefCount;
44
45     friend class SCEVHandle;
46     void addRef() const { ++RefCount; }
47     void dropRef() const {
48       if (--RefCount == 0)
49         delete this;
50     }
51
52     SCEV(const SCEV &);            // DO NOT IMPLEMENT
53     void operator=(const SCEV &);  // DO NOT IMPLEMENT
54   protected:
55     virtual ~SCEV();
56   public:
57     explicit SCEV(unsigned SCEVTy) : SCEVType(SCEVTy), RefCount(0) {}
58
59     unsigned getSCEVType() const { return SCEVType; }
60
61     /// isLoopInvariant - Return true if the value of this SCEV is unchanging in
62     /// the specified loop.
63     virtual bool isLoopInvariant(const Loop *L) const = 0;
64
65     /// hasComputableLoopEvolution - Return true if this SCEV changes value in a
66     /// known way in the specified loop.  This property being true implies that
67     /// the value is variant in the loop AND that we can emit an expression to
68     /// compute the value of the expression at any particular loop iteration.
69     virtual bool hasComputableLoopEvolution(const Loop *L) const = 0;
70
71     /// getType - Return the LLVM type of this SCEV expression.
72     ///
73     virtual const Type *getType() const = 0;
74
75     /// isZero - Return true if the expression is a constant zero.
76     ///
77     bool isZero() const;
78
79     /// replaceSymbolicValuesWithConcrete - If this SCEV internally references
80     /// the symbolic value "Sym", construct and return a new SCEV that produces
81     /// the same value, but which uses the concrete value Conc instead of the
82     /// symbolic value.  If this SCEV does not use the symbolic value, it
83     /// returns itself.
84     virtual SCEVHandle
85     replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
86                                       const SCEVHandle &Conc,
87                                       ScalarEvolution &SE) const = 0;
88
89     /// dominates - Return true if elements that makes up this SCEV dominates
90     /// the specified basic block.
91     virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const = 0;
92
93     /// print - Print out the internal representation of this scalar to the
94     /// specified stream.  This should really only be used for debugging
95     /// purposes.
96     virtual void print(raw_ostream &OS) const = 0;
97     void print(std::ostream &OS) const;
98     void print(std::ostream *OS) const { if (OS) print(*OS); }
99
100     /// dump - This method is used for debugging.
101     ///
102     void dump() const;
103   };
104
105   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
106     S.print(OS);
107     return OS;
108   }
109
110   inline std::ostream &operator<<(std::ostream &OS, const SCEV &S) {
111     S.print(OS);
112     return OS;
113   }
114
115   /// SCEVCouldNotCompute - An object of this class is returned by queries that
116   /// could not be answered.  For example, if you ask for the number of
117   /// iterations of a linked-list traversal loop, you will get one of these.
118   /// None of the standard SCEV operations are valid on this class, it is just a
119   /// marker.
120   struct SCEVCouldNotCompute : public SCEV {
121     SCEVCouldNotCompute();
122     ~SCEVCouldNotCompute();
123
124     // None of these methods are valid for this object.
125     virtual bool isLoopInvariant(const Loop *L) const;
126     virtual const Type *getType() const;
127     virtual bool hasComputableLoopEvolution(const Loop *L) const;
128     virtual void print(raw_ostream &OS) const;
129     virtual SCEVHandle
130     replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
131                                       const SCEVHandle &Conc,
132                                       ScalarEvolution &SE) const;
133
134     virtual bool dominates(BasicBlock *BB, DominatorTree *DT) const {
135       return true;
136     }
137
138     /// Methods for support type inquiry through isa, cast, and dyn_cast:
139     static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
140     static bool classof(const SCEV *S);
141   };
142
143   /// SCEVHandle - This class is used to maintain the SCEV object's refcounts,
144   /// freeing the objects when the last reference is dropped.
145   class SCEVHandle {
146     SCEV *S;
147     SCEVHandle();  // DO NOT IMPLEMENT
148   public:
149     SCEVHandle(const SCEV *s) : S(const_cast<SCEV*>(s)) {
150       assert(S && "Cannot create a handle to a null SCEV!");
151       S->addRef();
152     }
153     SCEVHandle(const SCEVHandle &RHS) : S(RHS.S) {
154       S->addRef();
155     }
156     ~SCEVHandle() { S->dropRef(); }
157
158     operator SCEV*() const { return S; }
159
160     SCEV &operator*() const { return *S; }
161     SCEV *operator->() const { return S; }
162
163     bool operator==(SCEV *RHS) const { return S == RHS; }
164     bool operator!=(SCEV *RHS) const { return S != RHS; }
165
166     const SCEVHandle &operator=(SCEV *RHS) {
167       if (S != RHS) {
168         S->dropRef();
169         S = RHS;
170         S->addRef();
171       }
172       return *this;
173     }
174
175     const SCEVHandle &operator=(const SCEVHandle &RHS) {
176       if (S != RHS.S) {
177         S->dropRef();
178         S = RHS.S;
179         S->addRef();
180       }
181       return *this;
182     }
183   };
184
185   template<typename From> struct simplify_type;
186   template<> struct simplify_type<const SCEVHandle> {
187     typedef SCEV* SimpleType;
188     static SimpleType getSimplifiedValue(const SCEVHandle &Node) {
189       return Node;
190     }
191   };
192   template<> struct simplify_type<SCEVHandle>
193     : public simplify_type<const SCEVHandle> {};
194
195   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
196   /// client code (intentionally) can't do much with the SCEV objects directly,
197   /// they must ask this class for services.
198   ///
199   class ScalarEvolution : public FunctionPass {
200     /// F - The function we are analyzing.
201     ///
202     Function *F;
203
204     /// LI - The loop information for the function we are currently analyzing.
205     ///
206     LoopInfo *LI;
207
208     /// TD - The target data information for the target we are targetting.
209     ///
210     TargetData *TD;
211
212     /// UnknownValue - This SCEV is used to represent unknown trip counts and
213     /// things.
214     SCEVHandle UnknownValue;
215
216     /// Scalars - This is a cache of the scalars we have analyzed so far.
217     ///
218     std::map<Value*, SCEVHandle> Scalars;
219
220     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
221     /// this function as they are computed.
222     std::map<const Loop*, SCEVHandle> BackedgeTakenCounts;
223
224     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
225     /// the PHI instructions that we attempt to compute constant evolutions for.
226     /// This allows us to avoid potentially expensive recomputation of these
227     /// properties.  An instruction maps to null if we are unable to compute its
228     /// exit value.
229     std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
230
231     /// createSCEV - We know that there is no SCEV for the specified value.
232     /// Analyze the expression.
233     SCEVHandle createSCEV(Value *V);
234
235     /// createNodeForPHI - Provide the special handling we need to analyze PHI
236     /// SCEVs.
237     SCEVHandle createNodeForPHI(PHINode *PN);
238
239     /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
240     /// for the specified instruction and replaces any references to the
241     /// symbolic value SymName with the specified value.  This is used during
242     /// PHI resolution.
243     void ReplaceSymbolicValueWithConcrete(Instruction *I,
244                                           const SCEVHandle &SymName,
245                                           const SCEVHandle &NewVal);
246
247     /// ComputeBackedgeTakenCount - Compute the number of times the specified
248     /// loop will iterate.
249     SCEVHandle ComputeBackedgeTakenCount(const Loop *L);
250
251     /// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition
252     /// of 'icmp op load X, cst', try to see if we can compute the trip count.
253     SCEVHandle
254       ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI,
255                                                    Constant *RHS,
256                                                    const Loop *L,
257                                                    ICmpInst::Predicate p);
258
259     /// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute
260     /// a constant number of times (the condition evolves only from constants),
261     /// try to evaluate a few iterations of the loop until we get the exit
262     /// condition gets a value of ExitWhen (true or false).  If we cannot
263     /// evaluate the trip count of the loop, return UnknownValue.
264     SCEVHandle ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond,
265                                                      bool ExitWhen);
266
267     /// HowFarToZero - Return the number of times a backedge comparing the
268     /// specified value to zero will execute.  If not computable, return
269     /// UnknownValue.
270     SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
271
272     /// HowFarToNonZero - Return the number of times a backedge checking the
273     /// specified value for nonzero will execute.  If not computable, return
274     /// UnknownValue.
275     SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
276
277     /// HowManyLessThans - Return the number of times a backedge containing the
278     /// specified less-than comparison will execute.  If not computable, return
279     /// UnknownValue. isSigned specifies whether the less-than is signed.
280     SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
281                                 bool isSigned);
282
283     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
284     /// (which may not be an immediate predecessor) which has exactly one
285     /// successor from which BB is reachable, or null if no such block is
286     /// found.
287     BasicBlock* getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
288
289     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
290     /// in the header of its containing loop, we know the loop executes a
291     /// constant number of times, and the PHI node is just a recurrence
292     /// involving constants, fold it.
293     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
294                                                 const Loop *L);
295
296     /// getSCEVAtScope - Compute the value of the specified expression within
297     /// the indicated loop (which may be null to indicate in no loop).  If the
298     /// expression cannot be evaluated, return UnknownValue itself.
299     SCEVHandle getSCEVAtScope(SCEV *S, const Loop *L);
300
301   public:
302     static char ID; // Pass identification, replacement for typeid
303     ScalarEvolution();
304
305     /// isSCEVable - Test if values of the given type are analyzable within
306     /// the SCEV framework. This primarily includes integer types, and it
307     /// can optionally include pointer types if the ScalarEvolution class
308     /// has access to target-specific information.
309     bool isSCEVable(const Type *Ty) const;
310
311     /// getTypeSizeInBits - Return the size in bits of the specified type,
312     /// for which isSCEVable must return true.
313     uint64_t getTypeSizeInBits(const Type *Ty) const;
314
315     /// getEffectiveSCEVType - Return a type with the same bitwidth as
316     /// the given type and which represents how SCEV will treat the given
317     /// type, for which isSCEVable must return true. For pointer types,
318     /// this is the pointer-sized integer type.
319     const Type *getEffectiveSCEVType(const Type *Ty) const;
320
321     /// getSCEV - Return a SCEV expression handle for the full generality of the
322     /// specified expression.
323     SCEVHandle getSCEV(Value *V);
324
325     SCEVHandle getConstant(ConstantInt *V);
326     SCEVHandle getConstant(const APInt& Val);
327     SCEVHandle getTruncateExpr(const SCEVHandle &Op, const Type *Ty);
328     SCEVHandle getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty);
329     SCEVHandle getSignExtendExpr(const SCEVHandle &Op, const Type *Ty);
330     SCEVHandle getAddExpr(std::vector<SCEVHandle> &Ops);
331     SCEVHandle getAddExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
332       std::vector<SCEVHandle> Ops;
333       Ops.push_back(LHS);
334       Ops.push_back(RHS);
335       return getAddExpr(Ops);
336     }
337     SCEVHandle getAddExpr(const SCEVHandle &Op0, const SCEVHandle &Op1,
338                           const SCEVHandle &Op2) {
339       std::vector<SCEVHandle> Ops;
340       Ops.push_back(Op0);
341       Ops.push_back(Op1);
342       Ops.push_back(Op2);
343       return getAddExpr(Ops);
344     }
345     SCEVHandle getMulExpr(std::vector<SCEVHandle> &Ops);
346     SCEVHandle getMulExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
347       std::vector<SCEVHandle> Ops;
348       Ops.push_back(LHS);
349       Ops.push_back(RHS);
350       return getMulExpr(Ops);
351     }
352     SCEVHandle getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
353     SCEVHandle getAddRecExpr(const SCEVHandle &Start, const SCEVHandle &Step,
354                              const Loop *L);
355     SCEVHandle getAddRecExpr(std::vector<SCEVHandle> &Operands,
356                              const Loop *L);
357     SCEVHandle getAddRecExpr(const std::vector<SCEVHandle> &Operands,
358                              const Loop *L) {
359       std::vector<SCEVHandle> NewOp(Operands);
360       return getAddRecExpr(NewOp, L);
361     }
362     SCEVHandle getSMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
363     SCEVHandle getSMaxExpr(std::vector<SCEVHandle> Operands);
364     SCEVHandle getUMaxExpr(const SCEVHandle &LHS, const SCEVHandle &RHS);
365     SCEVHandle getUMaxExpr(std::vector<SCEVHandle> Operands);
366     SCEVHandle getUnknown(Value *V);
367     SCEVHandle getCouldNotCompute();
368
369     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
370     ///
371     SCEVHandle getNegativeSCEV(const SCEVHandle &V);
372
373     /// getNotSCEV - Return the SCEV object corresponding to ~V.
374     ///
375     SCEVHandle getNotSCEV(const SCEVHandle &V);
376
377     /// getMinusSCEV - Return LHS-RHS.
378     ///
379     SCEVHandle getMinusSCEV(const SCEVHandle &LHS,
380                             const SCEVHandle &RHS);
381
382     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
383     /// of the input value to the specified type.  If the type must be
384     /// extended, it is zero extended.
385     SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty);
386
387     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
388     /// of the input value to the specified type.  If the type must be
389     /// extended, it is sign extended.
390     SCEVHandle getTruncateOrSignExtend(const SCEVHandle &V, const Type *Ty);
391
392     /// getIntegerSCEV - Given an integer or FP type, create a constant for the
393     /// specified signed integer value and return a SCEV for the constant.
394     SCEVHandle getIntegerSCEV(int Val, const Type *Ty);
395
396     /// hasSCEV - Return true if the SCEV for this value has already been
397     /// computed.
398     bool hasSCEV(Value *V) const;
399
400     /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
401     /// the specified value.
402     void setSCEV(Value *V, const SCEVHandle &H);
403
404     /// getSCEVAtScope - Return a SCEV expression handle for the specified value
405     /// at the specified scope in the program.  The L value specifies a loop
406     /// nest to evaluate the expression at, where null is the top-level or a
407     /// specified loop is immediately inside of the loop.
408     ///
409     /// This method can be used to compute the exit value for a variable defined
410     /// in a loop by querying what the value will hold in the parent loop.
411     ///
412     /// If this value is not computable at this scope, a SCEVCouldNotCompute
413     /// object is returned.
414     SCEVHandle getSCEVAtScope(Value *V, const Loop *L);
415
416     /// isLoopGuardedByCond - Test whether entry to the loop is protected by
417     /// a conditional between LHS and RHS.
418     bool isLoopGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
419                              SCEV *LHS, SCEV *RHS);
420
421     /// getBackedgeTakenCount - If the specified loop has a predictable
422     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
423     /// object. The backedge-taken count is the number of times the loop header
424     /// will be branched to from within the loop. This is one less than the
425     /// trip count of the loop, since it doesn't count the first iteration,
426     /// when the header is branched to from outside the loop.
427     ///
428     /// Note that it is not valid to call this method on a loop without a
429     /// loop-invariant backedge-taken count (see
430     /// hasLoopInvariantBackedgeTakenCount).
431     ///
432     SCEVHandle getBackedgeTakenCount(const Loop *L);
433
434     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
435     /// has an analyzable loop-invariant backedge-taken count.
436     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
437
438     /// forgetLoopBackedgeTakenCount - This method should be called by the
439     /// client when it has changed a loop in a way that may effect
440     /// ScalarEvolution's ability to compute a trip count, or if the loop
441     /// is deleted.
442     void forgetLoopBackedgeTakenCount(const Loop *L);
443
444     /// deleteValueFromRecords - This method should be called by the
445     /// client before it removes a Value from the program, to make sure
446     /// that no dangling references are left around.
447     void deleteValueFromRecords(Value *V);
448
449     virtual bool runOnFunction(Function &F);
450     virtual void releaseMemory();
451     virtual void getAnalysisUsage(AnalysisUsage &AU) const;
452     void print(raw_ostream &OS, const Module* = 0) const;
453     virtual void print(std::ostream &OS, const Module* = 0) const;
454     void print(std::ostream *OS, const Module* M = 0) const {
455       if (OS) print(*OS, M);
456     }
457   };
458 }
459
460 #endif