SCEV: Compress disposition pairs.
[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/ADT/DenseSet.h"
25 #include "llvm/ADT/FoldingSet.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/DataTypes.h"
34 #include <map>
35
36 namespace llvm {
37   class APInt;
38   class AssumptionCache;
39   class Constant;
40   class ConstantInt;
41   class DominatorTree;
42   class Type;
43   class ScalarEvolution;
44   class DataLayout;
45   class TargetLibraryInfo;
46   class LLVMContext;
47   class Loop;
48   class LoopInfo;
49   class Operator;
50   class SCEVUnknown;
51   class SCEV;
52   template<> struct FoldingSetTrait<SCEV>;
53
54   /// SCEV - This class represents an analyzed expression in the program.  These
55   /// are opaque objects that the client is not allowed to do much with
56   /// directly.
57   ///
58   class SCEV : public FoldingSetNode {
59     friend struct FoldingSetTrait<SCEV>;
60
61     /// FastID - A reference to an Interned FoldingSetNodeID for this node.
62     /// The ScalarEvolution's BumpPtrAllocator holds the data.
63     FoldingSetNodeIDRef FastID;
64
65     // The SCEV baseclass this node corresponds to
66     const unsigned short SCEVType;
67
68   protected:
69     /// SubclassData - This field is initialized to zero and may be used in
70     /// subclasses to store miscellaneous information.
71     unsigned short SubclassData;
72
73   private:
74     SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
75     void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
76
77   public:
78     /// NoWrapFlags are bitfield indices into SubclassData.
79     ///
80     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
81     /// no-signed-wrap <NSW> properties, which are derived from the IR
82     /// operator. NSW is a misnomer that we use to mean no signed overflow or
83     /// underflow.
84     ///
85     /// AddRec expression may have a no-self-wraparound <NW> property if the
86     /// result can never reach the start value. This property is independent of
87     /// the actual start value and step direction. Self-wraparound is defined
88     /// purely in terms of the recurrence's loop, step size, and
89     /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
90     /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
91     ///
92     /// Note that NUW and NSW are also valid properties of a recurrence, and
93     /// either implies NW. For convenience, NW will be set for a recurrence
94     /// whenever either NUW or NSW are set.
95     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
96                        FlagNW      = (1 << 0),   // No self-wrap.
97                        FlagNUW     = (1 << 1),   // No unsigned wrap.
98                        FlagNSW     = (1 << 2),   // No signed wrap.
99                        NoWrapMask  = (1 << 3) -1 };
100
101     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
102       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
103
104     unsigned getSCEVType() const { return SCEVType; }
105
106     /// getType - Return the LLVM type of this SCEV expression.
107     ///
108     Type *getType() const;
109
110     /// isZero - Return true if the expression is a constant zero.
111     ///
112     bool isZero() const;
113
114     /// isOne - Return true if the expression is a constant one.
115     ///
116     bool isOne() const;
117
118     /// isAllOnesValue - Return true if the expression is a constant
119     /// all-ones value.
120     ///
121     bool isAllOnesValue() const;
122
123     /// isNonConstantNegative - Return true if the specified scev is negated,
124     /// but not a constant.
125     bool isNonConstantNegative() const;
126
127     /// print - Print out the internal representation of this scalar to the
128     /// specified stream.  This should really only be used for debugging
129     /// purposes.
130     void print(raw_ostream &OS) const;
131
132 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
133     /// dump - This method is used for debugging.
134     ///
135     void dump() const;
136 #endif
137   };
138
139   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
140   // temporary FoldingSetNodeID values.
141   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
142     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
143       ID = X.FastID;
144     }
145     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
146                        unsigned IDHash, FoldingSetNodeID &TempID) {
147       return ID == X.FastID;
148     }
149     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
150       return X.FastID.ComputeHash();
151     }
152   };
153
154   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
155     S.print(OS);
156     return OS;
157   }
158
159   /// SCEVCouldNotCompute - An object of this class is returned by queries that
160   /// could not be answered.  For example, if you ask for the number of
161   /// iterations of a linked-list traversal loop, you will get one of these.
162   /// None of the standard SCEV operations are valid on this class, it is just a
163   /// marker.
164   struct SCEVCouldNotCompute : public SCEV {
165     SCEVCouldNotCompute();
166
167     /// Methods for support type inquiry through isa, cast, and dyn_cast:
168     static bool classof(const SCEV *S);
169   };
170
171   /// ScalarEvolution - This class is the main scalar evolution driver.  Because
172   /// client code (intentionally) can't do much with the SCEV objects directly,
173   /// they must ask this class for services.
174   ///
175   class ScalarEvolution : public FunctionPass {
176   public:
177     /// LoopDisposition - An enum describing the relationship between a
178     /// SCEV and a loop.
179     enum LoopDisposition {
180       LoopVariant,    ///< The SCEV is loop-variant (unknown).
181       LoopInvariant,  ///< The SCEV is loop-invariant.
182       LoopComputable  ///< The SCEV varies predictably with the loop.
183     };
184
185     /// BlockDisposition - An enum describing the relationship between a
186     /// SCEV and a basic block.
187     enum BlockDisposition {
188       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
189       DominatesBlock,        ///< The SCEV dominates the block.
190       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
191     };
192
193     /// Convenient NoWrapFlags manipulation that hides enum casts and is
194     /// visible in the ScalarEvolution name space.
195     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
196     maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
197       return (SCEV::NoWrapFlags)(Flags & Mask);
198     }
199     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
200     setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
201       return (SCEV::NoWrapFlags)(Flags | OnFlags);
202     }
203     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
204     clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
205       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
206     }
207
208   private:
209     /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
210     /// notified whenever a Value is deleted.
211     class SCEVCallbackVH : public CallbackVH {
212       ScalarEvolution *SE;
213       void deleted() override;
214       void allUsesReplacedWith(Value *New) override;
215     public:
216       SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
217     };
218
219     friend class SCEVCallbackVH;
220     friend class SCEVExpander;
221     friend class SCEVUnknown;
222
223     /// F - The function we are analyzing.
224     ///
225     Function *F;
226
227     /// The tracker for @llvm.assume intrinsics in this function.
228     AssumptionCache *AC;
229
230     /// LI - The loop information for the function we are currently analyzing.
231     ///
232     LoopInfo *LI;
233
234     /// The DataLayout information for the target we are targeting.
235     ///
236     const DataLayout *DL;
237
238     /// TLI - The target library information for the target we are targeting.
239     ///
240     TargetLibraryInfo *TLI;
241
242     /// DT - The dominator tree.
243     ///
244     DominatorTree *DT;
245
246     /// CouldNotCompute - This SCEV is used to represent unknown trip
247     /// counts and things.
248     SCEVCouldNotCompute CouldNotCompute;
249
250     /// ValueExprMapType - The typedef for ValueExprMap.
251     ///
252     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
253       ValueExprMapType;
254
255     /// ValueExprMap - This is a cache of the values we have analyzed so far.
256     ///
257     ValueExprMapType ValueExprMap;
258
259     /// Mark predicate values currently being processed by isImpliedCond.
260     DenseSet<Value*> PendingLoopPredicates;
261
262     /// ExitLimit - Information about the number of loop iterations for which a
263     /// loop exit's branch condition evaluates to the not-taken path.  This is a
264     /// temporary pair of exact and max expressions that are eventually
265     /// summarized in ExitNotTakenInfo and BackedgeTakenInfo.
266     struct ExitLimit {
267       const SCEV *Exact;
268       const SCEV *Max;
269
270       /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
271
272       ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
273
274       /// hasAnyInfo - Test whether this ExitLimit contains any computed
275       /// information, or whether it's all SCEVCouldNotCompute values.
276       bool hasAnyInfo() const {
277         return !isa<SCEVCouldNotCompute>(Exact) ||
278           !isa<SCEVCouldNotCompute>(Max);
279       }
280     };
281
282     /// ExitNotTakenInfo - Information about the number of times a particular
283     /// loop exit may be reached before exiting the loop.
284     struct ExitNotTakenInfo {
285       AssertingVH<BasicBlock> ExitingBlock;
286       const SCEV *ExactNotTaken;
287       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
288
289       ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
290
291       /// isCompleteList - Return true if all loop exits are computable.
292       bool isCompleteList() const {
293         return NextExit.getInt() == 0;
294       }
295
296       void setIncomplete() { NextExit.setInt(1); }
297
298       /// getNextExit - Return a pointer to the next exit's not-taken info.
299       ExitNotTakenInfo *getNextExit() const {
300         return NextExit.getPointer();
301       }
302
303       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
304     };
305
306     /// BackedgeTakenInfo - Information about the backedge-taken count
307     /// of a loop. This currently includes an exact count and a maximum count.
308     ///
309     class BackedgeTakenInfo {
310       /// ExitNotTaken - A list of computable exits and their not-taken counts.
311       /// Loops almost never have more than one computable exit.
312       ExitNotTakenInfo ExitNotTaken;
313
314       /// Max - An expression indicating the least maximum backedge-taken
315       /// count of the loop that is known, or a SCEVCouldNotCompute.
316       const SCEV *Max;
317
318     public:
319       BackedgeTakenInfo() : Max(nullptr) {}
320
321       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
322       BackedgeTakenInfo(
323         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
324         bool Complete, const SCEV *MaxCount);
325
326       /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
327       /// computed information, or whether it's all SCEVCouldNotCompute
328       /// values.
329       bool hasAnyInfo() const {
330         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
331       }
332
333       /// getExact - Return an expression indicating the exact backedge-taken
334       /// count of the loop if it is known, or SCEVCouldNotCompute
335       /// otherwise. This is the number of times the loop header can be
336       /// guaranteed to execute, minus one.
337       const SCEV *getExact(ScalarEvolution *SE) const;
338
339       /// getExact - Return the number of times this loop exit may fall through
340       /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
341       /// to exit via this block before this number of iterations, but may exit
342       /// via another block.
343       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
344
345       /// getMax - Get the max backedge taken count for the loop.
346       const SCEV *getMax(ScalarEvolution *SE) const;
347
348       /// Return true if any backedge taken count expressions refer to the given
349       /// subexpression.
350       bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
351
352       /// clear - Invalidate this result and free associated memory.
353       void clear();
354     };
355
356     /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
357     /// this function as they are computed.
358     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
359
360     /// ConstantEvolutionLoopExitValue - This map contains entries for all of
361     /// the PHI instructions that we attempt to compute constant evolutions for.
362     /// This allows us to avoid potentially expensive recomputation of these
363     /// properties.  An instruction maps to null if we are unable to compute its
364     /// exit value.
365     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
366
367     /// ValuesAtScopes - This map contains entries for all the expressions
368     /// that we attempt to compute getSCEVAtScope information for, which can
369     /// be expensive in extreme cases.
370     DenseMap<const SCEV *,
371              SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
372
373     /// LoopDispositions - Memoized computeLoopDisposition results.
374     DenseMap<const SCEV *,
375              SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
376         LoopDispositions;
377
378     /// computeLoopDisposition - Compute a LoopDisposition value.
379     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
380
381     /// BlockDispositions - Memoized computeBlockDisposition results.
382     DenseMap<
383         const SCEV *,
384         SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
385         BlockDispositions;
386
387     /// computeBlockDisposition - Compute a BlockDisposition value.
388     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
389
390     /// UnsignedRanges - Memoized results from getUnsignedRange
391     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
392
393     /// SignedRanges - Memoized results from getSignedRange
394     DenseMap<const SCEV *, ConstantRange> SignedRanges;
395
396     /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
397     const ConstantRange &setUnsignedRange(const SCEV *S,
398                                           const ConstantRange &CR) {
399       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
400         UnsignedRanges.insert(std::make_pair(S, CR));
401       if (!Pair.second)
402         Pair.first->second = CR;
403       return Pair.first->second;
404     }
405
406     /// setUnsignedRange - Set the memoized signed range for the given SCEV.
407     const ConstantRange &setSignedRange(const SCEV *S,
408                                         const ConstantRange &CR) {
409       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
410         SignedRanges.insert(std::make_pair(S, CR));
411       if (!Pair.second)
412         Pair.first->second = CR;
413       return Pair.first->second;
414     }
415
416     /// createSCEV - We know that there is no SCEV for the specified value.
417     /// Analyze the expression.
418     const SCEV *createSCEV(Value *V);
419
420     /// createNodeForPHI - Provide the special handling we need to analyze PHI
421     /// SCEVs.
422     const SCEV *createNodeForPHI(PHINode *PN);
423
424     /// createNodeForGEP - Provide the special handling we need to analyze GEP
425     /// SCEVs.
426     const SCEV *createNodeForGEP(GEPOperator *GEP);
427
428     /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
429     /// at most once for each SCEV+Loop pair.
430     ///
431     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
432
433     /// ForgetSymbolicValue - This looks up computed SCEV values for all
434     /// instructions that depend on the given instruction and removes them from
435     /// the ValueExprMap map if they reference SymName. This is used during PHI
436     /// resolution.
437     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
438
439     /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
440     /// loop, lazily computing new values if the loop hasn't been analyzed
441     /// yet.
442     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
443
444     /// ComputeBackedgeTakenCount - Compute the number of times the specified
445     /// loop will iterate.
446     BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
447
448     /// ComputeExitLimit - Compute the number of times the backedge of the
449     /// specified loop will execute if it exits via the specified block.
450     ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
451
452     /// ComputeExitLimitFromCond - Compute the number of times the backedge of
453     /// the specified loop will execute if its exit condition were a conditional
454     /// branch of ExitCond, TBB, and FBB.
455     ExitLimit ComputeExitLimitFromCond(const Loop *L,
456                                        Value *ExitCond,
457                                        BasicBlock *TBB,
458                                        BasicBlock *FBB,
459                                        bool IsSubExpr);
460
461     /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
462     /// the specified loop will execute if its exit condition were a conditional
463     /// branch of the ICmpInst ExitCond, TBB, and FBB.
464     ExitLimit ComputeExitLimitFromICmp(const Loop *L,
465                                        ICmpInst *ExitCond,
466                                        BasicBlock *TBB,
467                                        BasicBlock *FBB,
468                                        bool IsSubExpr);
469
470     /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
471     /// backedge of the specified loop will execute if its exit condition were a
472     /// switch with a single exiting case to ExitingBB.
473     ExitLimit
474     ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
475                                BasicBlock *ExitingBB, bool IsSubExpr);
476
477     /// ComputeLoadConstantCompareExitLimit - Given an exit condition
478     /// of 'icmp op load X, cst', try to see if we can compute the
479     /// backedge-taken count.
480     ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
481                                                   Constant *RHS,
482                                                   const Loop *L,
483                                                   ICmpInst::Predicate p);
484
485     /// ComputeExitCountExhaustively - If the loop is known to execute a
486     /// constant number of times (the condition evolves only from constants),
487     /// try to evaluate a few iterations of the loop until we get the exit
488     /// condition gets a value of ExitWhen (true or false).  If we cannot
489     /// evaluate the exit count of the loop, return CouldNotCompute.
490     const SCEV *ComputeExitCountExhaustively(const Loop *L,
491                                              Value *Cond,
492                                              bool ExitWhen);
493
494     /// HowFarToZero - Return the number of times an exit condition comparing
495     /// the specified value to zero will execute.  If not computable, return
496     /// CouldNotCompute.
497     ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
498
499     /// HowFarToNonZero - Return the number of times an exit condition checking
500     /// the specified value for nonzero will execute.  If not computable, return
501     /// CouldNotCompute.
502     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
503
504     /// HowManyLessThans - Return the number of times an exit condition
505     /// containing the specified less-than comparison will execute.  If not
506     /// computable, return CouldNotCompute. isSigned specifies whether the
507     /// less-than is signed.
508     ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
509                                const Loop *L, bool isSigned, bool IsSubExpr);
510     ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
511                                   const Loop *L, bool isSigned, bool IsSubExpr);
512
513     /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
514     /// (which may not be an immediate predecessor) which has exactly one
515     /// successor from which BB is reachable, or null if no such block is
516     /// found.
517     std::pair<BasicBlock *, BasicBlock *>
518     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
519
520     /// isImpliedCond - Test whether the condition described by Pred, LHS, and
521     /// RHS is true whenever the given FoundCondValue value evaluates to true.
522     bool isImpliedCond(ICmpInst::Predicate Pred,
523                        const SCEV *LHS, const SCEV *RHS,
524                        Value *FoundCondValue,
525                        bool Inverse);
526
527     /// isImpliedCondOperands - Test whether the condition described by Pred,
528     /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
529     /// and FoundRHS is true.
530     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
531                                const SCEV *LHS, const SCEV *RHS,
532                                const SCEV *FoundLHS, const SCEV *FoundRHS);
533
534     /// isImpliedCondOperandsHelper - Test whether the condition described by
535     /// Pred, LHS, and RHS is true whenever the condition described by Pred,
536     /// FoundLHS, and FoundRHS is true.
537     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
538                                      const SCEV *LHS, const SCEV *RHS,
539                                      const SCEV *FoundLHS,
540                                      const SCEV *FoundRHS);
541
542     /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
543     /// in the header of its containing loop, we know the loop executes a
544     /// constant number of times, and the PHI node is just a recurrence
545     /// involving constants, fold it.
546     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
547                                                 const Loop *L);
548
549     /// isKnownPredicateWithRanges - Test if the given expression is known to
550     /// satisfy the condition described by Pred and the known constant ranges
551     /// of LHS and RHS.
552     ///
553     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
554                                     const SCEV *LHS, const SCEV *RHS);
555
556     /// forgetMemoizedResults - Drop memoized information computed for S.
557     void forgetMemoizedResults(const SCEV *S);
558
559     /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
560     /// pointer.
561     bool checkValidity(const SCEV *S) const;
562
563   public:
564     static char ID; // Pass identification, replacement for typeid
565     ScalarEvolution();
566
567     LLVMContext &getContext() const { return F->getContext(); }
568
569     /// isSCEVable - Test if values of the given type are analyzable within
570     /// the SCEV framework. This primarily includes integer types, and it
571     /// can optionally include pointer types if the ScalarEvolution class
572     /// has access to target-specific information.
573     bool isSCEVable(Type *Ty) const;
574
575     /// getTypeSizeInBits - Return the size in bits of the specified type,
576     /// for which isSCEVable must return true.
577     uint64_t getTypeSizeInBits(Type *Ty) const;
578
579     /// getEffectiveSCEVType - Return a type with the same bitwidth as
580     /// the given type and which represents how SCEV will treat the given
581     /// type, for which isSCEVable must return true. For pointer types,
582     /// this is the pointer-sized integer type.
583     Type *getEffectiveSCEVType(Type *Ty) const;
584
585     /// getSCEV - Return a SCEV expression for the full generality of the
586     /// specified expression.
587     const SCEV *getSCEV(Value *V);
588
589     const SCEV *getConstant(ConstantInt *V);
590     const SCEV *getConstant(const APInt& Val);
591     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
592     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
593     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
594     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
595     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
596     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
597                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
598     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
599                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
600       SmallVector<const SCEV *, 2> Ops;
601       Ops.push_back(LHS);
602       Ops.push_back(RHS);
603       return getAddExpr(Ops, Flags);
604     }
605     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
606                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
607       SmallVector<const SCEV *, 3> Ops;
608       Ops.push_back(Op0);
609       Ops.push_back(Op1);
610       Ops.push_back(Op2);
611       return getAddExpr(Ops, Flags);
612     }
613     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
614                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
615     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
616                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
617     {
618       SmallVector<const SCEV *, 2> Ops;
619       Ops.push_back(LHS);
620       Ops.push_back(RHS);
621       return getMulExpr(Ops, Flags);
622     }
623     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
624                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
625       SmallVector<const SCEV *, 3> Ops;
626       Ops.push_back(Op0);
627       Ops.push_back(Op1);
628       Ops.push_back(Op2);
629       return getMulExpr(Ops, Flags);
630     }
631     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
632     const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
633     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
634                               const Loop *L, SCEV::NoWrapFlags Flags);
635     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
636                               const Loop *L, SCEV::NoWrapFlags Flags);
637     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
638                               const Loop *L, SCEV::NoWrapFlags Flags) {
639       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
640       return getAddRecExpr(NewOp, L, Flags);
641     }
642     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
643     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
644     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
645     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
646     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
647     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
648     const SCEV *getUnknown(Value *V);
649     const SCEV *getCouldNotCompute();
650
651     /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
652     /// IntTy
653     ///
654     const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
655
656     /// getOffsetOfExpr - Return an expression for offsetof on the given field
657     /// with type IntTy
658     ///
659     const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
660
661     /// getNegativeSCEV - Return the SCEV object corresponding to -V.
662     ///
663     const SCEV *getNegativeSCEV(const SCEV *V);
664
665     /// getNotSCEV - Return the SCEV object corresponding to ~V.
666     ///
667     const SCEV *getNotSCEV(const SCEV *V);
668
669     /// getMinusSCEV - Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
670     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
671                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
672
673     /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
674     /// of the input value to the specified type.  If the type must be
675     /// extended, it is zero extended.
676     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
677
678     /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
679     /// of the input value to the specified type.  If the type must be
680     /// extended, it is sign extended.
681     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
682
683     /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
684     /// the input value to the specified type.  If the type must be extended,
685     /// it is zero extended.  The conversion must not be narrowing.
686     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
687
688     /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
689     /// the input value to the specified type.  If the type must be extended,
690     /// it is sign extended.  The conversion must not be narrowing.
691     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
692
693     /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
694     /// the input value to the specified type. If the type must be extended,
695     /// it is extended with unspecified bits. The conversion must not be
696     /// narrowing.
697     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
698
699     /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
700     /// input value to the specified type.  The conversion must not be
701     /// widening.
702     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
703
704     /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
705     /// the types using zero-extension, and then perform a umax operation
706     /// with them.
707     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
708                                            const SCEV *RHS);
709
710     /// getUMinFromMismatchedTypes - Promote the operands to the wider of
711     /// the types using zero-extension, and then perform a umin operation
712     /// with them.
713     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
714                                            const SCEV *RHS);
715
716     /// getPointerBase - Transitively follow the chain of pointer-type operands
717     /// until reaching a SCEV that does not have a single pointer operand. This
718     /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
719     /// but corner cases do exist.
720     const SCEV *getPointerBase(const SCEV *V);
721
722     /// getSCEVAtScope - Return a SCEV expression for the specified value
723     /// at the specified scope in the program.  The L value specifies a loop
724     /// nest to evaluate the expression at, where null is the top-level or a
725     /// specified loop is immediately inside of the loop.
726     ///
727     /// This method can be used to compute the exit value for a variable defined
728     /// in a loop by querying what the value will hold in the parent loop.
729     ///
730     /// In the case that a relevant loop exit value cannot be computed, the
731     /// original value V is returned.
732     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
733
734     /// getSCEVAtScope - This is a convenience function which does
735     /// getSCEVAtScope(getSCEV(V), L).
736     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
737
738     /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
739     /// by a conditional between LHS and RHS.  This is used to help avoid max
740     /// expressions in loop trip counts, and to eliminate casts.
741     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
742                                   const SCEV *LHS, const SCEV *RHS);
743
744     /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
745     /// protected by a conditional between LHS and RHS.  This is used to
746     /// to eliminate casts.
747     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
748                                      const SCEV *LHS, const SCEV *RHS);
749
750     /// \brief Returns the maximum trip count of the loop if it is a single-exit
751     /// loop and we can compute a small maximum for that loop.
752     ///
753     /// Implemented in terms of the \c getSmallConstantTripCount overload with
754     /// the single exiting block passed to it. See that routine for details.
755     unsigned getSmallConstantTripCount(Loop *L);
756
757     /// getSmallConstantTripCount - Returns the maximum trip count of this loop
758     /// as a normal unsigned value. Returns 0 if the trip count is unknown or
759     /// not constant. This "trip count" assumes that control exits via
760     /// ExitingBlock. More precisely, it is the number of times that control may
761     /// reach ExitingBlock before taking the branch. For loops with multiple
762     /// exits, it may not be the number times that the loop header executes if
763     /// the loop exits prematurely via another branch.
764     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
765
766     /// \brief Returns the largest constant divisor of the trip count of the
767     /// loop if it is a single-exit loop and we can compute a small maximum for
768     /// that loop.
769     ///
770     /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
771     /// the single exiting block passed to it. See that routine for details.
772     unsigned getSmallConstantTripMultiple(Loop *L);
773
774     /// getSmallConstantTripMultiple - Returns the largest constant divisor of
775     /// the trip count of this loop as a normal unsigned value, if
776     /// possible. This means that the actual trip count is always a multiple of
777     /// the returned value (don't forget the trip count could very well be zero
778     /// as well!). As explained in the comments for getSmallConstantTripCount,
779     /// this assumes that control exits the loop via ExitingBlock.
780     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
781
782     // getExitCount - Get the expression for the number of loop iterations for
783     // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
784     // return SCEVCouldNotCompute.
785     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
786
787     /// getBackedgeTakenCount - If the specified loop has a predictable
788     /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
789     /// object. The backedge-taken count is the number of times the loop header
790     /// will be branched to from within the loop. This is one less than the
791     /// trip count of the loop, since it doesn't count the first iteration,
792     /// when the header is branched to from outside the loop.
793     ///
794     /// Note that it is not valid to call this method on a loop without a
795     /// loop-invariant backedge-taken count (see
796     /// hasLoopInvariantBackedgeTakenCount).
797     ///
798     const SCEV *getBackedgeTakenCount(const Loop *L);
799
800     /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
801     /// return the least SCEV value that is known never to be less than the
802     /// actual backedge taken count.
803     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
804
805     /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
806     /// has an analyzable loop-invariant backedge-taken count.
807     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
808
809     /// forgetLoop - This method should be called by the client when it has
810     /// changed a loop in a way that may effect ScalarEvolution's ability to
811     /// compute a trip count, or if the loop is deleted.  This call is
812     /// potentially expensive for large loop bodies.
813     void forgetLoop(const Loop *L);
814
815     /// forgetValue - This method should be called by the client when it has
816     /// changed a value in a way that may effect its value, or which may
817     /// disconnect it from a def-use chain linking it to a loop.
818     void forgetValue(Value *V);
819
820     /// \brief Called when the client has changed the disposition of values in
821     /// this loop.
822     ///
823     /// We don't have a way to invalidate per-loop dispositions. Clear and
824     /// recompute is simpler.
825     void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
826
827     /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
828     /// is guaranteed to end in (at every loop iteration).  It is, at the same
829     /// time, the minimum number of times S is divisible by 2.  For example,
830     /// given {4,+,8} it returns 2.  If S is guaranteed to be 0, it returns the
831     /// bitwidth of S.
832     uint32_t GetMinTrailingZeros(const SCEV *S);
833
834     /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
835     ///
836     ConstantRange getUnsignedRange(const SCEV *S);
837
838     /// getSignedRange - Determine the signed range for a particular SCEV.
839     ///
840     ConstantRange getSignedRange(const SCEV *S);
841
842     /// isKnownNegative - Test if the given expression is known to be negative.
843     ///
844     bool isKnownNegative(const SCEV *S);
845
846     /// isKnownPositive - Test if the given expression is known to be positive.
847     ///
848     bool isKnownPositive(const SCEV *S);
849
850     /// isKnownNonNegative - Test if the given expression is known to be
851     /// non-negative.
852     ///
853     bool isKnownNonNegative(const SCEV *S);
854
855     /// isKnownNonPositive - Test if the given expression is known to be
856     /// non-positive.
857     ///
858     bool isKnownNonPositive(const SCEV *S);
859
860     /// isKnownNonZero - Test if the given expression is known to be
861     /// non-zero.
862     ///
863     bool isKnownNonZero(const SCEV *S);
864
865     /// isKnownPredicate - Test if the given expression is known to satisfy
866     /// the condition described by Pred, LHS, and RHS.
867     ///
868     bool isKnownPredicate(ICmpInst::Predicate Pred,
869                           const SCEV *LHS, const SCEV *RHS);
870
871     /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
872     /// predicate Pred. Return true iff any changes were made. If the
873     /// operands are provably equal or unequal, LHS and RHS are set to
874     /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
875     ///
876     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
877                               const SCEV *&LHS,
878                               const SCEV *&RHS,
879                               unsigned Depth = 0);
880
881     /// getLoopDisposition - Return the "disposition" of the given SCEV with
882     /// respect to the given loop.
883     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
884
885     /// isLoopInvariant - Return true if the value of the given SCEV is
886     /// unchanging in the specified loop.
887     bool isLoopInvariant(const SCEV *S, const Loop *L);
888
889     /// hasComputableLoopEvolution - Return true if the given SCEV changes value
890     /// in a known way in the specified loop.  This property being true implies
891     /// that the value is variant in the loop AND that we can emit an expression
892     /// to compute the value of the expression at any particular loop iteration.
893     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
894
895     /// getLoopDisposition - Return the "disposition" of the given SCEV with
896     /// respect to the given block.
897     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
898
899     /// dominates - Return true if elements that makes up the given SCEV
900     /// dominate the specified basic block.
901     bool dominates(const SCEV *S, const BasicBlock *BB);
902
903     /// properlyDominates - Return true if elements that makes up the given SCEV
904     /// properly dominate the specified basic block.
905     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
906
907     /// hasOperand - Test whether the given SCEV has Op as a direct or
908     /// indirect operand.
909     bool hasOperand(const SCEV *S, const SCEV *Op) const;
910
911     /// Return the size of an element read or written by Inst.
912     const SCEV *getElementSize(Instruction *Inst);
913
914     /// Compute the array dimensions Sizes from the set of Terms extracted from
915     /// the memory access function of this SCEVAddRecExpr.
916     void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
917                              SmallVectorImpl<const SCEV *> &Sizes,
918                              const SCEV *ElementSize) const;
919
920     bool runOnFunction(Function &F) override;
921     void releaseMemory() override;
922     void getAnalysisUsage(AnalysisUsage &AU) const override;
923     void print(raw_ostream &OS, const Module* = nullptr) const override;
924     void verifyAnalysis() const override;
925
926   private:
927     /// Compute the backedge taken count knowing the interval difference, the
928     /// stride and presence of the equality in the comparison.
929     const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
930                                bool Equality);
931
932     /// Verify if an linear IV with positive stride can overflow when in a
933     /// less-than comparison, knowing the invariant term of the comparison,
934     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
935     bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
936                             bool IsSigned, bool NoWrap);
937
938     /// Verify if an linear IV with negative stride can overflow when in a
939     /// greater-than comparison, knowing the invariant term of the comparison,
940     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
941     bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
942                             bool IsSigned, bool NoWrap);
943
944   private:
945     FoldingSet<SCEV> UniqueSCEVs;
946     BumpPtrAllocator SCEVAllocator;
947
948     /// FirstUnknown - The head of a linked list of all SCEVUnknown
949     /// values that have been allocated. This is used by releaseMemory
950     /// to locate them all and call their destructors.
951     SCEVUnknown *FirstUnknown;
952   };
953 }
954
955 #endif