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