0413b6849bdb1ed9b184fc6f123e0884cdd0c030
[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/PassManager.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Allocator.h"
34 #include "llvm/Support/DataTypes.h"
35 #include <map>
36
37 namespace llvm {
38   class APInt;
39   class AssumptionCache;
40   class Constant;
41   class ConstantInt;
42   class DominatorTree;
43   class Type;
44   class ScalarEvolution;
45   class DataLayout;
46   class TargetLibraryInfo;
47   class LLVMContext;
48   class Loop;
49   class LoopInfo;
50   class Operator;
51   class SCEVUnknown;
52   class SCEVAddRecExpr;
53   class SCEV;
54   template<> struct FoldingSetTrait<SCEV>;
55
56   /// This class represents an analyzed expression in the program.  These are
57   /// opaque objects that the client is not allowed to do much with directly.
58   ///
59   class SCEV : public FoldingSetNode {
60     friend struct FoldingSetTrait<SCEV>;
61
62     /// A reference to an Interned FoldingSetNodeID for this node.  The
63     /// ScalarEvolution's BumpPtrAllocator holds the data.
64     FoldingSetNodeIDRef FastID;
65
66     // The SCEV baseclass this node corresponds to
67     const unsigned short SCEVType;
68
69   protected:
70     /// This field is initialized to zero and may be used in subclasses to store
71     /// miscellaneous information.
72     unsigned short SubclassData;
73
74   private:
75     SCEV(const SCEV &) = delete;
76     void operator=(const SCEV &) = delete;
77
78   public:
79     /// NoWrapFlags are bitfield indices into SubclassData.
80     ///
81     /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
82     /// no-signed-wrap <NSW> properties, which are derived from the IR
83     /// operator. NSW is a misnomer that we use to mean no signed overflow or
84     /// underflow.
85     ///
86     /// AddRec expressions may have a no-self-wraparound <NW> property if, in
87     /// the integer domain, abs(step) * max-iteration(loop) <=
88     /// unsigned-max(bitwidth).  This means that the recurrence will never reach
89     /// its start value if the step is non-zero.  Computing the same value on
90     /// each iteration is not considered wrapping, and recurrences with step = 0
91     /// are trivially <NW>.  <NW> is independent of the sign of step and the
92     /// value the add recurrence starts with.
93     ///
94     /// Note that NUW and NSW are also valid properties of a recurrence, and
95     /// either implies NW. For convenience, NW will be set for a recurrence
96     /// whenever either NUW or NSW are set.
97     enum NoWrapFlags { FlagAnyWrap = 0,          // No guarantee.
98                        FlagNW      = (1 << 0),   // No self-wrap.
99                        FlagNUW     = (1 << 1),   // No unsigned wrap.
100                        FlagNSW     = (1 << 2),   // No signed wrap.
101                        NoWrapMask  = (1 << 3) -1 };
102
103     explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
104       FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
105
106     unsigned getSCEVType() const { return SCEVType; }
107
108     /// Return the LLVM type of this SCEV expression.
109     ///
110     Type *getType() const;
111
112     /// Return true if the expression is a constant zero.
113     ///
114     bool isZero() const;
115
116     /// Return true if the expression is a constant one.
117     ///
118     bool isOne() const;
119
120     /// Return true if the expression is a constant all-ones value.
121     ///
122     bool isAllOnesValue() const;
123
124     /// Return true if the specified scev is negated, but not a constant.
125     bool isNonConstantNegative() const;
126
127     /// Print out the internal representation of this scalar to the specified
128     /// stream.  This should really only be used for debugging purposes.
129     void print(raw_ostream &OS) const;
130
131 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
132     /// This method is used for debugging.
133     ///
134     void dump() const;
135 #endif
136   };
137
138   // Specialize FoldingSetTrait for SCEV to avoid needing to compute
139   // temporary FoldingSetNodeID values.
140   template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
141     static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
142       ID = X.FastID;
143     }
144     static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
145                        unsigned IDHash, FoldingSetNodeID &TempID) {
146       return ID == X.FastID;
147     }
148     static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
149       return X.FastID.ComputeHash();
150     }
151   };
152
153   inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
154     S.print(OS);
155     return OS;
156   }
157
158   /// An object of this class is returned by queries that could not be answered.
159   /// For example, if you ask for the number of iterations of a linked-list
160   /// traversal loop, you will get one of these.  None of the standard SCEV
161   /// operations are valid on this class, it is just a marker.
162   struct SCEVCouldNotCompute : public SCEV {
163     SCEVCouldNotCompute();
164
165     /// Methods for support type inquiry through isa, cast, and dyn_cast:
166     static bool classof(const SCEV *S);
167   };
168
169   /// The main scalar evolution driver. Because client code (intentionally)
170   /// can't do much with the SCEV objects directly, they must ask this class
171   /// for services.
172   class ScalarEvolution {
173   public:
174     /// An enum describing the relationship between a SCEV and a loop.
175     enum LoopDisposition {
176       LoopVariant,    ///< The SCEV is loop-variant (unknown).
177       LoopInvariant,  ///< The SCEV is loop-invariant.
178       LoopComputable  ///< The SCEV varies predictably with the loop.
179     };
180
181     /// An enum describing the relationship between a SCEV and a basic block.
182     enum BlockDisposition {
183       DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
184       DominatesBlock,        ///< The SCEV dominates the block.
185       ProperlyDominatesBlock ///< The SCEV properly dominates the block.
186     };
187
188     /// Convenient NoWrapFlags manipulation that hides enum casts and is
189     /// visible in the ScalarEvolution name space.
190     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
191     maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
192       return (SCEV::NoWrapFlags)(Flags & Mask);
193     }
194     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
195     setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
196       return (SCEV::NoWrapFlags)(Flags | OnFlags);
197     }
198     static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
199     clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
200       return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
201     }
202
203   private:
204     /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
205     /// Value is deleted.
206     class SCEVCallbackVH final : public CallbackVH {
207       ScalarEvolution *SE;
208       void deleted() override;
209       void allUsesReplacedWith(Value *New) override;
210     public:
211       SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
212     };
213
214     friend class SCEVCallbackVH;
215     friend class SCEVExpander;
216     friend class SCEVUnknown;
217
218     /// The function we are analyzing.
219     ///
220     Function &F;
221
222     /// The target library information for the target we are targeting.
223     ///
224     TargetLibraryInfo &TLI;
225
226     /// The tracker for @llvm.assume intrinsics in this function.
227     AssumptionCache &AC;
228
229     /// The dominator tree.
230     ///
231     DominatorTree &DT;
232
233     /// The loop information for the function we are currently analyzing.
234     ///
235     LoopInfo &LI;
236
237     /// This SCEV is used to represent unknown trip counts and things.
238     std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
239
240     /// The typedef for ValueExprMap.
241     ///
242     typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
243       ValueExprMapType;
244
245     /// This is a cache of the values we have analyzed so far.
246     ///
247     ValueExprMapType ValueExprMap;
248
249     /// Mark predicate values currently being processed by isImpliedCond.
250     DenseSet<Value*> PendingLoopPredicates;
251
252     /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
253     /// conditions dominating the backedge of a loop.
254     bool WalkingBEDominatingConds;
255
256     /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
257     /// predicate by splitting it into a set of independent predicates.
258     bool ProvingSplitPredicate;
259
260     /// Information about the number of loop iterations for which a loop exit's
261     /// branch condition evaluates to the not-taken path.  This is a temporary
262     /// pair of exact and max expressions that are eventually summarized in
263     /// ExitNotTakenInfo and BackedgeTakenInfo.
264     struct ExitLimit {
265       const SCEV *Exact;
266       const SCEV *Max;
267
268       /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
269
270       ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
271
272       /// Test whether this ExitLimit contains any computed information, or
273       /// whether it's all SCEVCouldNotCompute values.
274       bool hasAnyInfo() const {
275         return !isa<SCEVCouldNotCompute>(Exact) ||
276           !isa<SCEVCouldNotCompute>(Max);
277       }
278     };
279
280     /// Information about the number of times a particular loop exit may be
281     /// reached before exiting the loop.
282     struct ExitNotTakenInfo {
283       AssertingVH<BasicBlock> ExitingBlock;
284       const SCEV *ExactNotTaken;
285       PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
286
287       ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
288
289       /// Return true if all loop exits are computable.
290       bool isCompleteList() const {
291         return NextExit.getInt() == 0;
292       }
293
294       void setIncomplete() { NextExit.setInt(1); }
295
296       /// Return a pointer to the next exit's not-taken info.
297       ExitNotTakenInfo *getNextExit() const {
298         return NextExit.getPointer();
299       }
300
301       void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
302     };
303
304     /// Information about the backedge-taken count of a loop. This currently
305     /// includes an exact count and a maximum count.
306     ///
307     class BackedgeTakenInfo {
308       /// A list of computable exits and their not-taken counts.  Loops almost
309       /// never have more than one computable exit.
310       ExitNotTakenInfo ExitNotTaken;
311
312       /// An expression indicating the least maximum backedge-taken count of the
313       /// loop that is known, or a SCEVCouldNotCompute.
314       const SCEV *Max;
315
316     public:
317       BackedgeTakenInfo() : Max(nullptr) {}
318
319       /// Initialize BackedgeTakenInfo from a list of exact exit counts.
320       BackedgeTakenInfo(
321         SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
322         bool Complete, const SCEV *MaxCount);
323
324       /// Test whether this BackedgeTakenInfo contains any computed information,
325       /// or whether it's all SCEVCouldNotCompute values.
326       bool hasAnyInfo() const {
327         return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
328       }
329
330       /// Return an expression indicating the exact backedge-taken count of the
331       /// loop if it is known, or SCEVCouldNotCompute otherwise. This is the
332       /// number of times the loop header can be guaranteed to execute, minus
333       /// one.
334       const SCEV *getExact(ScalarEvolution *SE) const;
335
336       /// Return the number of times this loop exit may fall through to the back
337       /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
338       /// this block before this number of iterations, but may exit via another
339       /// block.
340       const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
341
342       /// 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       /// Invalidate this result and free associated memory.
350       void clear();
351     };
352
353     /// Cache the backedge-taken count of the loops for this function as they
354     /// are computed.
355     DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
356
357     /// This map contains entries for all of the PHI instructions that we
358     /// attempt to compute constant evolutions for.  This allows us to avoid
359     /// potentially expensive recomputation of these properties.  An instruction
360     /// maps to null if we are unable to compute its exit value.
361     DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
362
363     /// This map contains entries for all the expressions that we attempt to
364     /// compute getSCEVAtScope information for, which can be expensive in
365     /// extreme cases.
366     DenseMap<const SCEV *,
367              SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
368
369     /// Memoized computeLoopDisposition results.
370     DenseMap<const SCEV *,
371              SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
372         LoopDispositions;
373
374     /// Compute a LoopDisposition value.
375     LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
376
377     /// Memoized computeBlockDisposition results.
378     DenseMap<
379         const SCEV *,
380         SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
381         BlockDispositions;
382
383     /// Compute a BlockDisposition value.
384     BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
385
386     /// Memoized results from getRange
387     DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
388
389     /// Memoized results from getRange
390     DenseMap<const SCEV *, ConstantRange> SignedRanges;
391
392     /// Used to parameterize getRange
393     enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
394
395     /// Set the memoized range for the given SCEV.
396     const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
397                                   const ConstantRange &CR) {
398       DenseMap<const SCEV *, ConstantRange> &Cache =
399           Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
400
401       std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
402           Cache.insert(std::make_pair(S, CR));
403       if (!Pair.second)
404         Pair.first->second = CR;
405       return Pair.first->second;
406     }
407
408     /// Determine the range for a particular SCEV.
409     ConstantRange getRange(const SCEV *S, RangeSignHint Hint);
410
411     /// We know that there is no SCEV for the specified value.  Analyze the
412     /// expression.
413     const SCEV *createSCEV(Value *V);
414
415     /// Provide the special handling we need to analyze PHI SCEVs.
416     const SCEV *createNodeForPHI(PHINode *PN);
417
418     /// Helper function called from createNodeForPHI.
419     const SCEV *createAddRecFromPHI(PHINode *PN);
420
421     /// Helper function called from createNodeForPHI.
422     const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
423
424     /// Provide special handling for a select-like instruction (currently this
425     /// is either a select instruction or a phi node).  \p I is the instruction
426     /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
427     /// FalseVal".
428     const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond,
429                                          Value *TrueVal, Value *FalseVal);
430
431     /// Provide the special handling we need to analyze GEP SCEVs.
432     const SCEV *createNodeForGEP(GEPOperator *GEP);
433
434     /// Implementation code for getSCEVAtScope; called at most once for each
435     /// SCEV+Loop pair.
436     ///
437     const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
438
439     /// This looks up computed SCEV values for all instructions that depend on
440     /// the given instruction and removes them from the ValueExprMap map if they
441     /// reference SymName. This is used during PHI resolution.
442     void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
443
444     /// Return the BackedgeTakenInfo for the given loop, lazily computing new
445     /// values if the loop hasn't been analyzed yet.
446     const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
447
448     /// Compute the number of times the specified loop will iterate.
449     BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L);
450
451     /// Compute the number of times the backedge of the specified loop will
452     /// execute if it exits via the specified block.
453     ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
454
455     /// Compute the number of times the backedge of the specified loop will
456     /// execute if its exit condition were a conditional branch of ExitCond,
457     /// TBB, and FBB.
458     ExitLimit computeExitLimitFromCond(const Loop *L,
459                                        Value *ExitCond,
460                                        BasicBlock *TBB,
461                                        BasicBlock *FBB,
462                                        bool IsSubExpr);
463
464     /// Compute the number of times the backedge of the specified loop will
465     /// execute if its exit condition were a conditional branch of the ICmpInst
466     /// ExitCond, TBB, and FBB.
467     ExitLimit computeExitLimitFromICmp(const Loop *L,
468                                        ICmpInst *ExitCond,
469                                        BasicBlock *TBB,
470                                        BasicBlock *FBB,
471                                        bool IsSubExpr);
472
473     /// Compute the number of times the backedge of the specified loop will
474     /// execute if its exit condition were a switch with a single exiting case
475     /// to ExitingBB.
476     ExitLimit
477     computeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
478                                BasicBlock *ExitingBB, bool IsSubExpr);
479
480     /// Given an exit condition of 'icmp op load X, cst', try to see if we can
481     /// compute the backedge-taken count.
482     ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI,
483                                                   Constant *RHS,
484                                                   const Loop *L,
485                                                   ICmpInst::Predicate p);
486
487     /// If the loop is known to execute a constant number of times (the
488     /// condition evolves only from constants), try to evaluate a few iterations
489     /// of the loop until we get the exit condition gets a value of ExitWhen
490     /// (true or false).  If we cannot evaluate the exit count of the loop,
491     /// return CouldNotCompute.
492     const SCEV *computeExitCountExhaustively(const Loop *L,
493                                              Value *Cond,
494                                              bool ExitWhen);
495
496     /// Return the number of times an exit condition comparing the specified
497     /// value to zero will execute.  If not computable, return CouldNotCompute.
498     ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
499
500     /// Return the number of times an exit condition checking the specified
501     /// value for nonzero will execute.  If not computable, return
502     /// CouldNotCompute.
503     ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
504
505     /// Return the number of times an exit condition containing the specified
506     /// less-than comparison will execute.  If not computable, return
507     /// CouldNotCompute. isSigned specifies whether the 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     /// Return a predecessor of BB (which may not be an immediate predecessor)
514     /// which has exactly one successor from which BB is reachable, or null if
515     /// no such block is found.
516     std::pair<BasicBlock *, BasicBlock *>
517     getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
518
519     /// Test whether the condition described by Pred, LHS, and RHS is true
520     /// whenever the given FoundCondValue value evaluates to true.
521     bool isImpliedCond(ICmpInst::Predicate Pred,
522                        const SCEV *LHS, const SCEV *RHS,
523                        Value *FoundCondValue,
524                        bool Inverse);
525
526     /// Test whether the condition described by Pred, LHS, and RHS is true
527     /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
528     /// true.
529     bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
530                        const SCEV *RHS, ICmpInst::Predicate FoundPred,
531                        const SCEV *FoundLHS, const SCEV *FoundRHS);
532
533     /// Test whether the condition described by Pred, LHS, and RHS is true
534     /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
535     /// true.
536     bool isImpliedCondOperands(ICmpInst::Predicate Pred,
537                                const SCEV *LHS, const SCEV *RHS,
538                                const SCEV *FoundLHS, const SCEV *FoundRHS);
539
540     /// Test whether the condition described by Pred, LHS, and RHS is true
541     /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
542     /// true.
543     bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
544                                      const SCEV *LHS, const SCEV *RHS,
545                                      const SCEV *FoundLHS,
546                                      const SCEV *FoundRHS);
547
548     /// Test whether the condition described by Pred, LHS, and RHS is true
549     /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
550     /// true.  Utility function used by isImpliedCondOperands.
551     bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
552                                         const SCEV *LHS, const SCEV *RHS,
553                                         const SCEV *FoundLHS,
554                                         const SCEV *FoundRHS);
555
556     /// Test whether the condition described by Pred, LHS, and RHS is true
557     /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
558     /// true.
559     ///
560     /// This routine tries to rule out certain kinds of integer overflow, and
561     /// then tries to reason about arithmetic properties of the predicates.
562     bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
563                                             const SCEV *LHS, const SCEV *RHS,
564                                             const SCEV *FoundLHS,
565                                             const SCEV *FoundRHS);
566
567     /// If we know that the specified Phi is in the header of its containing
568     /// loop, we know the loop executes a constant number of times, and the PHI
569     /// node is just a recurrence involving constants, fold it.
570     Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
571                                                 const Loop *L);
572
573     /// Test if the given expression is known to satisfy the condition described
574     /// by Pred and the known constant ranges of LHS and RHS.
575     ///
576     bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
577                                     const SCEV *LHS, const SCEV *RHS);
578
579     /// Try to prove the condition described by "LHS Pred RHS" by ruling out
580     /// integer overflow.
581     ///
582     /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
583     /// positive.
584     bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
585                                        const SCEV *LHS, const SCEV *RHS);
586
587     /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
588     /// prove them individually.
589     bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
590                                       const SCEV *RHS);
591
592     /// Try to match the Expr as "(L + R)<Flags>".
593     bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R,
594                         SCEV::NoWrapFlags &Flags);
595
596     /// Return true if More == (Less + C), where C is a constant.  This is
597     /// intended to be used as a cheaper substitute for full SCEV subtraction.
598     bool computeConstantDifference(const SCEV *Less, const SCEV *More,
599                                    APInt &C);
600
601     /// Drop memoized information computed for S.
602     void forgetMemoizedResults(const SCEV *S);
603
604     /// Return an existing SCEV for V if there is one, otherwise return nullptr.
605     const SCEV *getExistingSCEV(Value *V);
606
607     /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
608     /// pointer.
609     bool checkValidity(const SCEV *S) const;
610
611     /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
612     /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}.  This is
613     /// equivalent to proving no signed (resp. unsigned) wrap in
614     /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
615     /// (resp. `SCEVZeroExtendExpr`).
616     ///
617     template<typename ExtendOpTy>
618     bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
619                                    const Loop *L);
620
621     bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
622                                   ICmpInst::Predicate Pred, bool &Increasing);
623
624     /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
625     /// is monotonically increasing or decreasing.  In the former case set
626     /// `Increasing` to true and in the latter case set `Increasing` to false.
627     ///
628     /// A predicate is said to be monotonically increasing if may go from being
629     /// false to being true as the loop iterates, but never the other way
630     /// around.  A predicate is said to be monotonically decreasing if may go
631     /// from being true to being false as the loop iterates, but never the other
632     /// way around.
633     bool isMonotonicPredicate(const SCEVAddRecExpr *LHS,
634                               ICmpInst::Predicate Pred, bool &Increasing);
635
636     // Return SCEV no-wrap flags that can be proven based on reasoning
637     // about how poison produced from no-wrap flags on this value
638     // (e.g. a nuw add) would trigger undefined behavior on overflow.
639     SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
640
641   public:
642     ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC,
643                     DominatorTree &DT, LoopInfo &LI);
644     ~ScalarEvolution();
645     ScalarEvolution(ScalarEvolution &&Arg);
646
647     LLVMContext &getContext() const { return F.getContext(); }
648
649     /// Test if values of the given type are analyzable within the SCEV
650     /// framework. This primarily includes integer types, and it can optionally
651     /// include pointer types if the ScalarEvolution class has access to
652     /// target-specific information.
653     bool isSCEVable(Type *Ty) const;
654
655     /// Return the size in bits of the specified type, for which isSCEVable must
656     /// return true.
657     uint64_t getTypeSizeInBits(Type *Ty) const;
658
659     /// Return a type with the same bitwidth as the given type and which
660     /// represents how SCEV will treat the given type, for which isSCEVable must
661     /// return true. For pointer types, this is the pointer-sized integer type.
662     Type *getEffectiveSCEVType(Type *Ty) const;
663
664     /// Return a SCEV expression for the full generality of the specified
665     /// expression.
666     const SCEV *getSCEV(Value *V);
667
668     const SCEV *getConstant(ConstantInt *V);
669     const SCEV *getConstant(const APInt& Val);
670     const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
671     const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
672     const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
673     const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
674     const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
675     const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
676                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
677     const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
678                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
679       SmallVector<const SCEV *, 2> Ops;
680       Ops.push_back(LHS);
681       Ops.push_back(RHS);
682       return getAddExpr(Ops, Flags);
683     }
684     const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
685                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
686       SmallVector<const SCEV *, 3> Ops;
687       Ops.push_back(Op0);
688       Ops.push_back(Op1);
689       Ops.push_back(Op2);
690       return getAddExpr(Ops, Flags);
691     }
692     const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
693                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
694     const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
695                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
696     {
697       SmallVector<const SCEV *, 2> Ops;
698       Ops.push_back(LHS);
699       Ops.push_back(RHS);
700       return getMulExpr(Ops, Flags);
701     }
702     const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
703                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
704       SmallVector<const SCEV *, 3> Ops;
705       Ops.push_back(Op0);
706       Ops.push_back(Op1);
707       Ops.push_back(Op2);
708       return getMulExpr(Ops, Flags);
709     }
710     const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
711     const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
712     const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
713                               const Loop *L, SCEV::NoWrapFlags Flags);
714     const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
715                               const Loop *L, SCEV::NoWrapFlags Flags);
716     const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
717                               const Loop *L, SCEV::NoWrapFlags Flags) {
718       SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
719       return getAddRecExpr(NewOp, L, Flags);
720     }
721     /// \brief Returns an expression for a GEP
722     ///
723     /// \p PointeeType The type used as the basis for the pointer arithmetics
724     /// \p BaseExpr The expression for the pointer operand.
725     /// \p IndexExprs The expressions for the indices.
726     /// \p InBounds Whether the GEP is in bounds.
727     const SCEV *getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
728                            const SmallVectorImpl<const SCEV *> &IndexExprs,
729                            bool InBounds = false);
730     const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
731     const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
732     const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
733     const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
734     const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
735     const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
736     const SCEV *getUnknown(Value *V);
737     const SCEV *getCouldNotCompute();
738
739     /// \brief Return a SCEV for the constant 0 of a specific type.
740     const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
741
742     /// \brief Return a SCEV for the constant 1 of a specific type.
743     const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
744
745     /// Return an expression for sizeof AllocTy that is type IntTy
746     ///
747     const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
748
749     /// Return an expression for offsetof on the given field with type IntTy
750     ///
751     const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
752
753     /// Return the SCEV object corresponding to -V.
754     ///
755     const SCEV *getNegativeSCEV(const SCEV *V,
756                                 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
757
758     /// Return the SCEV object corresponding to ~V.
759     ///
760     const SCEV *getNotSCEV(const SCEV *V);
761
762     /// Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
763     const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
764                              SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
765
766     /// Return a SCEV corresponding to a conversion of the input value to the
767     /// specified type.  If the type must be extended, it is zero extended.
768     const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
769
770     /// Return a SCEV corresponding to a conversion of the input value to the
771     /// specified type.  If the type must be extended, it is sign extended.
772     const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
773
774     /// Return a SCEV corresponding to a conversion of the input value to the
775     /// specified type.  If the type must be extended, it is zero extended.  The
776     /// conversion must not be narrowing.
777     const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
778
779     /// Return a SCEV corresponding to a conversion of the input value to the
780     /// specified type.  If the type must be extended, it is sign extended.  The
781     /// conversion must not be narrowing.
782     const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
783
784     /// Return a SCEV corresponding to a conversion of the input value to the
785     /// specified type. If the type must be extended, it is extended with
786     /// unspecified bits. The conversion must not be narrowing.
787     const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
788
789     /// Return a SCEV corresponding to a conversion of the input value to the
790     /// specified type.  The conversion must not be widening.
791     const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
792
793     /// Promote the operands to the wider of the types using zero-extension, and
794     /// then perform a umax operation with them.
795     const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
796                                            const SCEV *RHS);
797
798     /// Promote the operands to the wider of the types using zero-extension, and
799     /// then perform a umin operation with them.
800     const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
801                                            const SCEV *RHS);
802
803     /// Transitively follow the chain of pointer-type operands until reaching a
804     /// SCEV that does not have a single pointer operand. This returns a
805     /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
806     /// cases do exist.
807     const SCEV *getPointerBase(const SCEV *V);
808
809     /// Return a SCEV expression for the specified value at the specified scope
810     /// in the program.  The L value specifies a loop nest to evaluate the
811     /// expression at, where null is the top-level or a specified loop is
812     /// immediately inside of the loop.
813     ///
814     /// This method can be used to compute the exit value for a variable defined
815     /// in a loop by querying what the value will hold in the parent loop.
816     ///
817     /// In the case that a relevant loop exit value cannot be computed, the
818     /// original value V is returned.
819     const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
820
821     /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
822     const SCEV *getSCEVAtScope(Value *V, const Loop *L);
823
824     /// Test whether entry to the loop is protected by a conditional between LHS
825     /// and RHS.  This is used to help avoid max expressions in loop trip
826     /// counts, and to eliminate casts.
827     bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
828                                   const SCEV *LHS, const SCEV *RHS);
829
830     /// Test whether the backedge of the loop is protected by a conditional
831     /// between LHS and RHS.  This is used to to eliminate casts.
832     bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
833                                      const SCEV *LHS, const SCEV *RHS);
834
835     /// \brief Returns the maximum trip count of the loop if it is a single-exit
836     /// loop and we can compute a small maximum for that loop.
837     ///
838     /// Implemented in terms of the \c getSmallConstantTripCount overload with
839     /// the single exiting block passed to it. See that routine for details.
840     unsigned getSmallConstantTripCount(Loop *L);
841
842     /// Returns the maximum trip count of this loop as a normal unsigned
843     /// value. Returns 0 if the trip count is unknown or not constant. This
844     /// "trip count" assumes that control exits via ExitingBlock. More
845     /// precisely, it is the number of times that control may reach ExitingBlock
846     /// before taking the branch. For loops with multiple exits, it may not be
847     /// the number times that the loop header executes if the loop exits
848     /// prematurely via another branch.
849     unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
850
851     /// \brief Returns the largest constant divisor of the trip count of the
852     /// loop if it is a single-exit loop and we can compute a small maximum for
853     /// that loop.
854     ///
855     /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
856     /// the single exiting block passed to it. See that routine for details.
857     unsigned getSmallConstantTripMultiple(Loop *L);
858
859     /// Returns the largest constant divisor of the trip count of this loop as a
860     /// normal unsigned value, if possible. This means that the actual trip
861     /// count is always a multiple of the returned value (don't forget the trip
862     /// count could very well be zero as well!). As explained in the comments
863     /// for getSmallConstantTripCount, this assumes that control exits the loop
864     /// via ExitingBlock.
865     unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
866
867     /// Get the expression for the number of loop iterations for which this loop
868     /// is guaranteed not to exit via ExitingBlock. Otherwise return
869     /// SCEVCouldNotCompute.
870     const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
871
872     /// If the specified loop has a predictable backedge-taken count, return it,
873     /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count
874     /// is the number of times the loop header will be branched to from within
875     /// the loop. This is one less than the trip count of the loop, since it
876     /// doesn't count the first iteration, when the header is branched to from
877     /// outside the loop.
878     ///
879     /// Note that it is not valid to call this method on a loop without a
880     /// loop-invariant backedge-taken count (see
881     /// hasLoopInvariantBackedgeTakenCount).
882     ///
883     const SCEV *getBackedgeTakenCount(const Loop *L);
884
885     /// Similar to getBackedgeTakenCount, except return the least SCEV value
886     /// that is known never to be less than the actual backedge taken count.
887     const SCEV *getMaxBackedgeTakenCount(const Loop *L);
888
889     /// Return true if the specified loop has an analyzable loop-invariant
890     /// backedge-taken count.
891     bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
892
893     /// This method should be called by the client when it has changed a loop in
894     /// a way that may effect ScalarEvolution's ability to compute a trip count,
895     /// or if the loop is deleted.  This call is potentially expensive for large
896     /// loop bodies.
897     void forgetLoop(const Loop *L);
898
899     /// This method should be called by the client when it has changed a value
900     /// in a way that may effect its value, or which may disconnect it from a
901     /// def-use chain linking it to a loop.
902     void forgetValue(Value *V);
903
904     /// \brief Called when the client has changed the disposition of values in
905     /// this loop.
906     ///
907     /// We don't have a way to invalidate per-loop dispositions. Clear and
908     /// recompute is simpler.
909     void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
910
911     /// Determine the minimum number of zero bits that S is guaranteed to end in
912     /// (at every loop iteration).  It is, at the same time, the minimum number
913     /// of times S is divisible by 2.  For example, given {4,+,8} it returns 2.
914     /// If S is guaranteed to be 0, it returns the bitwidth of S.
915     uint32_t GetMinTrailingZeros(const SCEV *S);
916
917     /// Determine the unsigned range for a particular SCEV.
918     ///
919     ConstantRange getUnsignedRange(const SCEV *S) {
920       return getRange(S, HINT_RANGE_UNSIGNED);
921     }
922
923     /// Determine the signed range for a particular SCEV.
924     ///
925     ConstantRange getSignedRange(const SCEV *S) {
926       return getRange(S, HINT_RANGE_SIGNED);
927     }
928
929     /// Test if the given expression is known to be negative.
930     ///
931     bool isKnownNegative(const SCEV *S);
932
933     /// Test if the given expression is known to be positive.
934     ///
935     bool isKnownPositive(const SCEV *S);
936
937     /// Test if the given expression is known to be non-negative.
938     ///
939     bool isKnownNonNegative(const SCEV *S);
940
941     /// Test if the given expression is known to be non-positive.
942     ///
943     bool isKnownNonPositive(const SCEV *S);
944
945     /// Test if the given expression is known to be non-zero.
946     ///
947     bool isKnownNonZero(const SCEV *S);
948
949     /// Test if the given expression is known to satisfy the condition described
950     /// by Pred, LHS, and RHS.
951     ///
952     bool isKnownPredicate(ICmpInst::Predicate Pred,
953                           const SCEV *LHS, const SCEV *RHS);
954
955     /// Return true if the result of the predicate LHS `Pred` RHS is loop
956     /// invariant with respect to L.  Set InvariantPred, InvariantLHS and
957     /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
958     /// loop invariant form of LHS `Pred` RHS.
959     bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
960                                   const SCEV *RHS, const Loop *L,
961                                   ICmpInst::Predicate &InvariantPred,
962                                   const SCEV *&InvariantLHS,
963                                   const SCEV *&InvariantRHS);
964
965     /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
966     /// iff any changes were made. If the operands are provably equal or
967     /// unequal, LHS and RHS are set to the same value and Pred is set to either
968     /// ICMP_EQ or ICMP_NE.
969     ///
970     bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
971                               const SCEV *&LHS,
972                               const SCEV *&RHS,
973                               unsigned Depth = 0);
974
975     /// Return the "disposition" of the given SCEV with respect to the given
976     /// loop.
977     LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
978
979     /// Return true if the value of the given SCEV is unchanging in the
980     /// specified loop.
981     bool isLoopInvariant(const SCEV *S, const Loop *L);
982
983     /// Return true if the given SCEV changes value in a known way in the
984     /// specified loop.  This property being true implies that the value is
985     /// variant in the loop AND that we can emit an expression to compute the
986     /// value of the expression at any particular loop iteration.
987     bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
988
989     /// Return the "disposition" of the given SCEV with respect to the given
990     /// block.
991     BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
992
993     /// Return true if elements that makes up the given SCEV dominate the
994     /// specified basic block.
995     bool dominates(const SCEV *S, const BasicBlock *BB);
996
997     /// Return true if elements that makes up the given SCEV properly dominate
998     /// the specified basic block.
999     bool properlyDominates(const SCEV *S, const BasicBlock *BB);
1000
1001     /// Test whether the given SCEV has Op as a direct or indirect operand.
1002     bool hasOperand(const SCEV *S, const SCEV *Op) const;
1003
1004     /// Return the size of an element read or written by Inst.
1005     const SCEV *getElementSize(Instruction *Inst);
1006
1007     /// Compute the array dimensions Sizes from the set of Terms extracted from
1008     /// the memory access function of this SCEVAddRecExpr.
1009     void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
1010                              SmallVectorImpl<const SCEV *> &Sizes,
1011                              const SCEV *ElementSize) const;
1012
1013     void print(raw_ostream &OS) const;
1014     void verify() const;
1015
1016     /// Collect parametric terms occurring in step expressions.
1017     void collectParametricTerms(const SCEV *Expr,
1018                                 SmallVectorImpl<const SCEV *> &Terms);
1019
1020
1021
1022     /// Return in Subscripts the access functions for each dimension in Sizes.
1023     void computeAccessFunctions(const SCEV *Expr,
1024                                 SmallVectorImpl<const SCEV *> &Subscripts,
1025                                 SmallVectorImpl<const SCEV *> &Sizes);
1026
1027     /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
1028     /// subscripts and sizes of an array access.
1029     ///
1030     /// The delinearization is a 3 step process: the first two steps compute the
1031     /// sizes of each subscript and the third step computes the access functions
1032     /// for the delinearized array:
1033     ///
1034     /// 1. Find the terms in the step functions
1035     /// 2. Compute the array size
1036     /// 3. Compute the access function: divide the SCEV by the array size
1037     ///    starting with the innermost dimensions found in step 2. The Quotient
1038     ///    is the SCEV to be divided in the next step of the recursion. The
1039     ///    Remainder is the subscript of the innermost dimension. Loop over all
1040     ///    array dimensions computed in step 2.
1041     ///
1042     /// To compute a uniform array size for several memory accesses to the same
1043     /// object, one can collect in step 1 all the step terms for all the memory
1044     /// accesses, and compute in step 2 a unique array shape. This guarantees
1045     /// that the array shape will be the same across all memory accesses.
1046     ///
1047     /// FIXME: We could derive the result of steps 1 and 2 from a description of
1048     /// the array shape given in metadata.
1049     ///
1050     /// Example:
1051     ///
1052     /// A[][n][m]
1053     ///
1054     /// for i
1055     ///   for j
1056     ///     for k
1057     ///       A[j+k][2i][5i] =
1058     ///
1059     /// The initial SCEV:
1060     ///
1061     /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1062     ///
1063     /// 1. Find the different terms in the step functions:
1064     /// -> [2*m, 5, n*m, n*m]
1065     ///
1066     /// 2. Compute the array size: sort and unique them
1067     /// -> [n*m, 2*m, 5]
1068     /// find the GCD of all the terms = 1
1069     /// divide by the GCD and erase constant terms
1070     /// -> [n*m, 2*m]
1071     /// GCD = m
1072     /// divide by GCD -> [n, 2]
1073     /// remove constant terms
1074     /// -> [n]
1075     /// size of the array is A[unknown][n][m]
1076     ///
1077     /// 3. Compute the access function
1078     /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1079     /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1080     /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1081     /// The remainder is the subscript of the innermost array dimension: [5i].
1082     ///
1083     /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1084     /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1085     /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1086     /// The Remainder is the subscript of the next array dimension: [2i].
1087     ///
1088     /// The subscript of the outermost dimension is the Quotient: [j+k].
1089     ///
1090     /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1091     void delinearize(const SCEV *Expr,
1092                      SmallVectorImpl<const SCEV *> &Subscripts,
1093                      SmallVectorImpl<const SCEV *> &Sizes,
1094                      const SCEV *ElementSize);
1095
1096   private:
1097     /// Compute the backedge taken count knowing the interval difference, the
1098     /// stride and presence of the equality in the comparison.
1099     const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1100                                bool Equality);
1101
1102     /// Verify if an linear IV with positive stride can overflow when in a
1103     /// less-than comparison, knowing the invariant term of the comparison,
1104     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1105     bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
1106                             bool IsSigned, bool NoWrap);
1107
1108     /// Verify if an linear IV with negative stride can overflow when in a
1109     /// greater-than comparison, knowing the invariant term of the comparison,
1110     /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1111     bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
1112                             bool IsSigned, bool NoWrap);
1113
1114   private:
1115     FoldingSet<SCEV> UniqueSCEVs;
1116     BumpPtrAllocator SCEVAllocator;
1117
1118     /// The head of a linked list of all SCEVUnknown values that have been
1119     /// allocated. This is used by releaseMemory to locate them all and call
1120     /// their destructors.
1121     SCEVUnknown *FirstUnknown;
1122   };
1123
1124   /// \brief Analysis pass that exposes the \c ScalarEvolution for a function.
1125   class ScalarEvolutionAnalysis {
1126     static char PassID;
1127
1128   public:
1129     typedef ScalarEvolution Result;
1130
1131     /// \brief Opaque, unique identifier for this analysis pass.
1132     static void *ID() { return (void *)&PassID; }
1133
1134     /// \brief Provide a name for the analysis for debugging and logging.
1135     static StringRef name() { return "ScalarEvolutionAnalysis"; }
1136
1137     ScalarEvolution run(Function &F, AnalysisManager<Function> *AM);
1138   };
1139
1140   /// \brief Printer pass for the \c ScalarEvolutionAnalysis results.
1141   class ScalarEvolutionPrinterPass {
1142     raw_ostream &OS;
1143
1144   public:
1145     explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
1146     PreservedAnalyses run(Function &F, AnalysisManager<Function> *AM);
1147
1148     static StringRef name() { return "ScalarEvolutionPrinterPass"; }
1149   };
1150
1151   class ScalarEvolutionWrapperPass : public FunctionPass {
1152     std::unique_ptr<ScalarEvolution> SE;
1153
1154   public:
1155     static char ID;
1156
1157     ScalarEvolutionWrapperPass();
1158
1159     ScalarEvolution &getSE() { return *SE; }
1160     const ScalarEvolution &getSE() const { return *SE; }
1161
1162     bool runOnFunction(Function &F) override;
1163     void releaseMemory() override;
1164     void getAnalysisUsage(AnalysisUsage &AU) const override;
1165     void print(raw_ostream &OS, const Module * = nullptr) const override;
1166     void verifyAnalysis() const override;
1167   };
1168 }
1169
1170 #endif