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