]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/Analysis/ScalarEvolution.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r306325, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/SetVector.h"
27 #include "llvm/Analysis/LoopInfo.h"
28 #include "llvm/IR/ConstantRange.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Operator.h"
31 #include "llvm/IR/PassManager.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/IR/ValueMap.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/Allocator.h"
36 #include "llvm/Support/DataTypes.h"
37
38 namespace llvm {
39 class APInt;
40 class AssumptionCache;
41 class Constant;
42 class ConstantInt;
43 class DominatorTree;
44 class Type;
45 class ScalarEvolution;
46 class DataLayout;
47 class TargetLibraryInfo;
48 class LLVMContext;
49 class Operator;
50 class SCEV;
51 class SCEVAddRecExpr;
52 class SCEVConstant;
53 class SCEVExpander;
54 class SCEVPredicate;
55 class SCEVUnknown;
56 class Function;
57
58 template <> struct FoldingSetTrait<SCEV>;
59 template <> struct FoldingSetTrait<SCEVPredicate>;
60
61 /// This class represents an analyzed expression in the program.  These are
62 /// opaque objects that the client is not allowed to do much with directly.
63 ///
64 class SCEV : public FoldingSetNode {
65   friend struct FoldingSetTrait<SCEV>;
66
67   /// A reference to an Interned FoldingSetNodeID for this node.  The
68   /// ScalarEvolution's BumpPtrAllocator holds the data.
69   FoldingSetNodeIDRef FastID;
70
71   // The SCEV baseclass this node corresponds to
72   const unsigned short SCEVType;
73
74 protected:
75   /// This field is initialized to zero and may be used in subclasses to store
76   /// miscellaneous information.
77   unsigned short SubclassData;
78
79 private:
80   SCEV(const SCEV &) = delete;
81   void operator=(const SCEV &) = delete;
82
83 public:
84   /// NoWrapFlags are bitfield indices into SubclassData.
85   ///
86   /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
87   /// no-signed-wrap <NSW> properties, which are derived from the IR
88   /// operator. NSW is a misnomer that we use to mean no signed overflow or
89   /// underflow.
90   ///
91   /// AddRec expressions may have a no-self-wraparound <NW> property if, in
92   /// the integer domain, abs(step) * max-iteration(loop) <=
93   /// unsigned-max(bitwidth).  This means that the recurrence will never reach
94   /// its start value if the step is non-zero.  Computing the same value on
95   /// each iteration is not considered wrapping, and recurrences with step = 0
96   /// are trivially <NW>.  <NW> is independent of the sign of step and the
97   /// value the add recurrence starts with.
98   ///
99   /// Note that NUW and NSW are also valid properties of a recurrence, and
100   /// either implies NW. For convenience, NW will be set for a recurrence
101   /// whenever either NUW or NSW are set.
102   enum NoWrapFlags {
103     FlagAnyWrap = 0,    // No guarantee.
104     FlagNW = (1 << 0),  // No self-wrap.
105     FlagNUW = (1 << 1), // No unsigned wrap.
106     FlagNSW = (1 << 2), // No signed wrap.
107     NoWrapMask = (1 << 3) - 1
108   };
109
110   explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy)
111       : FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
112
113   unsigned getSCEVType() const { return SCEVType; }
114
115   /// Return the LLVM type of this SCEV expression.
116   ///
117   Type *getType() const;
118
119   /// Return true if the expression is a constant zero.
120   ///
121   bool isZero() const;
122
123   /// Return true if the expression is a constant one.
124   ///
125   bool isOne() const;
126
127   /// Return true if the expression is a constant all-ones value.
128   ///
129   bool isAllOnesValue() const;
130
131   /// Return true if the specified scev is negated, but not a constant.
132   bool isNonConstantNegative() const;
133
134   /// Print out the internal representation of this scalar to the specified
135   /// stream.  This should really only be used for debugging purposes.
136   void print(raw_ostream &OS) const;
137
138   /// This method is used for debugging.
139   ///
140   void dump() const;
141 };
142
143 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
144 // temporary FoldingSetNodeID values.
145 template <> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
146   static void Profile(const SCEV &X, FoldingSetNodeID &ID) { ID = X.FastID; }
147   static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, unsigned IDHash,
148                      FoldingSetNodeID &TempID) {
149     return ID == X.FastID;
150   }
151   static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
152     return X.FastID.ComputeHash();
153   }
154 };
155
156 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
157   S.print(OS);
158   return OS;
159 }
160
161 /// An object of this class is returned by queries that could not be answered.
162 /// For example, if you ask for the number of iterations of a linked-list
163 /// traversal loop, you will get one of these.  None of the standard SCEV
164 /// operations are valid on this class, it is just a 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 /// This class represents an assumption made using SCEV expressions which can
173 /// be checked at run-time.
174 class SCEVPredicate : public FoldingSetNode {
175   friend struct FoldingSetTrait<SCEVPredicate>;
176
177   /// A reference to an Interned FoldingSetNodeID for this node.  The
178   /// ScalarEvolution's BumpPtrAllocator holds the data.
179   FoldingSetNodeIDRef FastID;
180
181 public:
182   enum SCEVPredicateKind { P_Union, P_Equal, P_Wrap };
183
184 protected:
185   SCEVPredicateKind Kind;
186   ~SCEVPredicate() = default;
187   SCEVPredicate(const SCEVPredicate &) = default;
188   SCEVPredicate &operator=(const SCEVPredicate &) = default;
189
190 public:
191   SCEVPredicate(const FoldingSetNodeIDRef ID, SCEVPredicateKind Kind);
192
193   SCEVPredicateKind getKind() const { return Kind; }
194
195   /// Returns the estimated complexity of this predicate.  This is roughly
196   /// measured in the number of run-time checks required.
197   virtual unsigned getComplexity() const { return 1; }
198
199   /// Returns true if the predicate is always true. This means that no
200   /// assumptions were made and nothing needs to be checked at run-time.
201   virtual bool isAlwaysTrue() const = 0;
202
203   /// Returns true if this predicate implies \p N.
204   virtual bool implies(const SCEVPredicate *N) const = 0;
205
206   /// Prints a textual representation of this predicate with an indentation of
207   /// \p Depth.
208   virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
209
210   /// Returns the SCEV to which this predicate applies, or nullptr if this is
211   /// a SCEVUnionPredicate.
212   virtual const SCEV *getExpr() const = 0;
213 };
214
215 inline raw_ostream &operator<<(raw_ostream &OS, const SCEVPredicate &P) {
216   P.print(OS);
217   return OS;
218 }
219
220 // Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
221 // temporary FoldingSetNodeID values.
222 template <>
223 struct FoldingSetTrait<SCEVPredicate> : DefaultFoldingSetTrait<SCEVPredicate> {
224
225   static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
226     ID = X.FastID;
227   }
228
229   static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID,
230                      unsigned IDHash, FoldingSetNodeID &TempID) {
231     return ID == X.FastID;
232   }
233   static unsigned ComputeHash(const SCEVPredicate &X,
234                               FoldingSetNodeID &TempID) {
235     return X.FastID.ComputeHash();
236   }
237 };
238
239 /// This class represents an assumption that two SCEV expressions are equal,
240 /// and this can be checked at run-time. We assume that the left hand side is
241 /// a SCEVUnknown and the right hand side a constant.
242 class SCEVEqualPredicate final : public SCEVPredicate {
243   /// We assume that LHS == RHS, where LHS is a SCEVUnknown and RHS a
244   /// constant.
245   const SCEVUnknown *LHS;
246   const SCEVConstant *RHS;
247
248 public:
249   SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEVUnknown *LHS,
250                      const SCEVConstant *RHS);
251
252   /// Implementation of the SCEVPredicate interface
253   bool implies(const SCEVPredicate *N) const override;
254   void print(raw_ostream &OS, unsigned Depth = 0) const override;
255   bool isAlwaysTrue() const override;
256   const SCEV *getExpr() const override;
257
258   /// Returns the left hand side of the equality.
259   const SCEVUnknown *getLHS() const { return LHS; }
260
261   /// Returns the right hand side of the equality.
262   const SCEVConstant *getRHS() const { return RHS; }
263
264   /// Methods for support type inquiry through isa, cast, and dyn_cast:
265   static inline bool classof(const SCEVPredicate *P) {
266     return P->getKind() == P_Equal;
267   }
268 };
269
270 /// This class represents an assumption made on an AddRec expression. Given an
271 /// affine AddRec expression {a,+,b}, we assume that it has the nssw or nusw
272 /// flags (defined below) in the first X iterations of the loop, where X is a
273 /// SCEV expression returned by getPredicatedBackedgeTakenCount).
274 ///
275 /// Note that this does not imply that X is equal to the backedge taken
276 /// count. This means that if we have a nusw predicate for i32 {0,+,1} with a
277 /// predicated backedge taken count of X, we only guarantee that {0,+,1} has
278 /// nusw in the first X iterations. {0,+,1} may still wrap in the loop if we
279 /// have more than X iterations.
280 class SCEVWrapPredicate final : public SCEVPredicate {
281 public:
282   /// Similar to SCEV::NoWrapFlags, but with slightly different semantics
283   /// for FlagNUSW. The increment is considered to be signed, and a + b
284   /// (where b is the increment) is considered to wrap if:
285   ///    zext(a + b) != zext(a) + sext(b)
286   ///
287   /// If Signed is a function that takes an n-bit tuple and maps to the
288   /// integer domain as the tuples value interpreted as twos complement,
289   /// and Unsigned a function that takes an n-bit tuple and maps to the
290   /// integer domain as as the base two value of input tuple, then a + b
291   /// has IncrementNUSW iff:
292   ///
293   /// 0 <= Unsigned(a) + Signed(b) < 2^n
294   ///
295   /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
296   ///
297   /// Note that the IncrementNUSW flag is not commutative: if base + inc
298   /// has IncrementNUSW, then inc + base doesn't neccessarily have this
299   /// property. The reason for this is that this is used for sign/zero
300   /// extending affine AddRec SCEV expressions when a SCEVWrapPredicate is
301   /// assumed. A {base,+,inc} expression is already non-commutative with
302   /// regards to base and inc, since it is interpreted as:
303   ///     (((base + inc) + inc) + inc) ...
304   enum IncrementWrapFlags {
305     IncrementAnyWrap = 0,     // No guarantee.
306     IncrementNUSW = (1 << 0), // No unsigned with signed increment wrap.
307     IncrementNSSW = (1 << 1), // No signed with signed increment wrap
308                               // (equivalent with SCEV::NSW)
309     IncrementNoWrapMask = (1 << 2) - 1
310   };
311
312   /// Convenient IncrementWrapFlags manipulation methods.
313   LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
314   clearFlags(SCEVWrapPredicate::IncrementWrapFlags Flags,
315              SCEVWrapPredicate::IncrementWrapFlags OffFlags) {
316     assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
317     assert((OffFlags & IncrementNoWrapMask) == OffFlags &&
318            "Invalid flags value!");
319     return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & ~OffFlags);
320   }
321
322   LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
323   maskFlags(SCEVWrapPredicate::IncrementWrapFlags Flags, int Mask) {
324     assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
325     assert((Mask & IncrementNoWrapMask) == Mask && "Invalid mask value!");
326
327     return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask);
328   }
329
330   LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
331   setFlags(SCEVWrapPredicate::IncrementWrapFlags Flags,
332            SCEVWrapPredicate::IncrementWrapFlags OnFlags) {
333     assert((Flags & IncrementNoWrapMask) == Flags && "Invalid flags value!");
334     assert((OnFlags & IncrementNoWrapMask) == OnFlags &&
335            "Invalid flags value!");
336
337     return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
338   }
339
340   /// Returns the set of SCEVWrapPredicate no wrap flags implied by a
341   /// SCEVAddRecExpr.
342   LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
343   getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE);
344
345 private:
346   const SCEVAddRecExpr *AR;
347   IncrementWrapFlags Flags;
348
349 public:
350   explicit SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
351                              const SCEVAddRecExpr *AR,
352                              IncrementWrapFlags Flags);
353
354   /// Returns the set assumed no overflow flags.
355   IncrementWrapFlags getFlags() const { return Flags; }
356   /// Implementation of the SCEVPredicate interface
357   const SCEV *getExpr() const override;
358   bool implies(const SCEVPredicate *N) const override;
359   void print(raw_ostream &OS, unsigned Depth = 0) const override;
360   bool isAlwaysTrue() const override;
361
362   /// Methods for support type inquiry through isa, cast, and dyn_cast:
363   static inline bool classof(const SCEVPredicate *P) {
364     return P->getKind() == P_Wrap;
365   }
366 };
367
368 /// This class represents a composition of other SCEV predicates, and is the
369 /// class that most clients will interact with.  This is equivalent to a
370 /// logical "AND" of all the predicates in the union.
371 ///
372 /// NB! Unlike other SCEVPredicate sub-classes this class does not live in the
373 /// ScalarEvolution::Preds folding set.  This is why the \c add function is sound.
374 class SCEVUnionPredicate final : public SCEVPredicate {
375 private:
376   typedef DenseMap<const SCEV *, SmallVector<const SCEVPredicate *, 4>>
377       PredicateMap;
378
379   /// Vector with references to all predicates in this union.
380   SmallVector<const SCEVPredicate *, 16> Preds;
381   /// Maps SCEVs to predicates for quick look-ups.
382   PredicateMap SCEVToPreds;
383
384 public:
385   SCEVUnionPredicate();
386
387   const SmallVectorImpl<const SCEVPredicate *> &getPredicates() const {
388     return Preds;
389   }
390
391   /// Adds a predicate to this union.
392   void add(const SCEVPredicate *N);
393
394   /// Returns a reference to a vector containing all predicates which apply to
395   /// \p Expr.
396   ArrayRef<const SCEVPredicate *> getPredicatesForExpr(const SCEV *Expr);
397
398   /// Implementation of the SCEVPredicate interface
399   bool isAlwaysTrue() const override;
400   bool implies(const SCEVPredicate *N) const override;
401   void print(raw_ostream &OS, unsigned Depth) const override;
402   const SCEV *getExpr() const override;
403
404   /// We estimate the complexity of a union predicate as the size number of
405   /// predicates in the union.
406   unsigned getComplexity() const override { return Preds.size(); }
407
408   /// Methods for support type inquiry through isa, cast, and dyn_cast:
409   static inline bool classof(const SCEVPredicate *P) {
410     return P->getKind() == P_Union;
411   }
412 };
413
414 /// The main scalar evolution driver. Because client code (intentionally)
415 /// can't do much with the SCEV objects directly, they must ask this class
416 /// for services.
417 class ScalarEvolution {
418 public:
419   /// An enum describing the relationship between a SCEV and a loop.
420   enum LoopDisposition {
421     LoopVariant,   ///< The SCEV is loop-variant (unknown).
422     LoopInvariant, ///< The SCEV is loop-invariant.
423     LoopComputable ///< The SCEV varies predictably with the loop.
424   };
425
426   /// An enum describing the relationship between a SCEV and a basic block.
427   enum BlockDisposition {
428     DoesNotDominateBlock,  ///< The SCEV does not dominate the block.
429     DominatesBlock,        ///< The SCEV dominates the block.
430     ProperlyDominatesBlock ///< The SCEV properly dominates the block.
431   };
432
433   /// Convenient NoWrapFlags manipulation that hides enum casts and is
434   /// visible in the ScalarEvolution name space.
435   LLVM_NODISCARD static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags,
436                                                     int Mask) {
437     return (SCEV::NoWrapFlags)(Flags & Mask);
438   }
439   LLVM_NODISCARD static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
440                                                    SCEV::NoWrapFlags OnFlags) {
441     return (SCEV::NoWrapFlags)(Flags | OnFlags);
442   }
443   LLVM_NODISCARD static SCEV::NoWrapFlags
444   clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
445     return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
446   }
447
448 private:
449   /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
450   /// Value is deleted.
451   class SCEVCallbackVH final : public CallbackVH {
452     ScalarEvolution *SE;
453     void deleted() override;
454     void allUsesReplacedWith(Value *New) override;
455
456   public:
457     SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
458   };
459
460   friend class SCEVCallbackVH;
461   friend class SCEVExpander;
462   friend class SCEVUnknown;
463
464   /// The function we are analyzing.
465   ///
466   Function &F;
467
468   /// Does the module have any calls to the llvm.experimental.guard intrinsic
469   /// at all?  If this is false, we avoid doing work that will only help if
470   /// thare are guards present in the IR.
471   ///
472   bool HasGuards;
473
474   /// The target library information for the target we are targeting.
475   ///
476   TargetLibraryInfo &TLI;
477
478   /// The tracker for @llvm.assume intrinsics in this function.
479   AssumptionCache &AC;
480
481   /// The dominator tree.
482   ///
483   DominatorTree &DT;
484
485   /// The loop information for the function we are currently analyzing.
486   ///
487   LoopInfo &LI;
488
489   /// This SCEV is used to represent unknown trip counts and things.
490   std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
491
492   /// The typedef for HasRecMap.
493   ///
494   typedef DenseMap<const SCEV *, bool> HasRecMapType;
495
496   /// This is a cache to record whether a SCEV contains any scAddRecExpr.
497   HasRecMapType HasRecMap;
498
499   /// The typedef for ExprValueMap.
500   ///
501   typedef std::pair<Value *, ConstantInt *> ValueOffsetPair;
502   typedef DenseMap<const SCEV *, SetVector<ValueOffsetPair>> ExprValueMapType;
503
504   /// ExprValueMap -- This map records the original values from which
505   /// the SCEV expr is generated from.
506   ///
507   /// We want to represent the mapping as SCEV -> ValueOffsetPair instead
508   /// of SCEV -> Value:
509   /// Suppose we know S1 expands to V1, and
510   ///  S1 = S2 + C_a
511   ///  S3 = S2 + C_b
512   /// where C_a and C_b are different SCEVConstants. Then we'd like to
513   /// expand S3 as V1 - C_a + C_b instead of expanding S2 literally.
514   /// It is helpful when S2 is a complex SCEV expr.
515   ///
516   /// In order to do that, we represent ExprValueMap as a mapping from
517   /// SCEV to ValueOffsetPair. We will save both S1->{V1, 0} and
518   /// S2->{V1, C_a} into the map when we create SCEV for V1. When S3
519   /// is expanded, it will first expand S2 to V1 - C_a because of
520   /// S2->{V1, C_a} in the map, then expand S3 to V1 - C_a + C_b.
521   ///
522   /// Note: S->{V, Offset} in the ExprValueMap means S can be expanded
523   /// to V - Offset.
524   ExprValueMapType ExprValueMap;
525
526   /// The typedef for ValueExprMap.
527   ///
528   typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *>>
529       ValueExprMapType;
530
531   /// This is a cache of the values we have analyzed so far.
532   ///
533   ValueExprMapType ValueExprMap;
534
535   /// Mark predicate values currently being processed by isImpliedCond.
536   SmallPtrSet<Value *, 6> PendingLoopPredicates;
537
538   /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
539   /// conditions dominating the backedge of a loop.
540   bool WalkingBEDominatingConds;
541
542   /// Set to true by isKnownPredicateViaSplitting when we're trying to prove a
543   /// predicate by splitting it into a set of independent predicates.
544   bool ProvingSplitPredicate;
545
546   /// Memoized values for the GetMinTrailingZeros
547   DenseMap<const SCEV *, uint32_t> MinTrailingZerosCache;
548
549   /// Private helper method for the GetMinTrailingZeros method
550   uint32_t GetMinTrailingZerosImpl(const SCEV *S);
551
552   /// Information about the number of loop iterations for which a loop exit's
553   /// branch condition evaluates to the not-taken path.  This is a temporary
554   /// pair of exact and max expressions that are eventually summarized in
555   /// ExitNotTakenInfo and BackedgeTakenInfo.
556   struct ExitLimit {
557     const SCEV *ExactNotTaken; // The exit is not taken exactly this many times
558     const SCEV *MaxNotTaken; // The exit is not taken at most this many times
559     bool MaxOrZero; // Not taken either exactly MaxNotTaken or zero times
560
561     /// A set of predicate guards for this ExitLimit. The result is only valid
562     /// if all of the predicates in \c Predicates evaluate to 'true' at
563     /// run-time.
564     SmallPtrSet<const SCEVPredicate *, 4> Predicates;
565
566     void addPredicate(const SCEVPredicate *P) {
567       assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
568       Predicates.insert(P);
569     }
570
571     /*implicit*/ ExitLimit(const SCEV *E);
572
573     ExitLimit(
574         const SCEV *E, const SCEV *M, bool MaxOrZero,
575         ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList);
576
577     ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero,
578               const SmallPtrSetImpl<const SCEVPredicate *> &PredSet);
579
580     ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero);
581
582     /// Test whether this ExitLimit contains any computed information, or
583     /// whether it's all SCEVCouldNotCompute values.
584     bool hasAnyInfo() const {
585       return !isa<SCEVCouldNotCompute>(ExactNotTaken) ||
586              !isa<SCEVCouldNotCompute>(MaxNotTaken);
587     }
588
589     /// Test whether this ExitLimit contains all information.
590     bool hasFullInfo() const {
591       return !isa<SCEVCouldNotCompute>(ExactNotTaken);
592     }
593   };
594
595   /// Information about the number of times a particular loop exit may be
596   /// reached before exiting the loop.
597   struct ExitNotTakenInfo {
598     PoisoningVH<BasicBlock> ExitingBlock;
599     const SCEV *ExactNotTaken;
600     std::unique_ptr<SCEVUnionPredicate> Predicate;
601     bool hasAlwaysTruePredicate() const {
602       return !Predicate || Predicate->isAlwaysTrue();
603     }
604
605     explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
606                               const SCEV *ExactNotTaken,
607                               std::unique_ptr<SCEVUnionPredicate> Predicate)
608         : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
609           Predicate(std::move(Predicate)) {}
610   };
611
612   /// Information about the backedge-taken count of a loop. This currently
613   /// includes an exact count and a maximum count.
614   ///
615   class BackedgeTakenInfo {
616     /// A list of computable exits and their not-taken counts.  Loops almost
617     /// never have more than one computable exit.
618     SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
619
620     /// The pointer part of \c MaxAndComplete is an expression indicating the
621     /// least maximum backedge-taken count of the loop that is known, or a
622     /// SCEVCouldNotCompute. This expression is only valid if the predicates
623     /// associated with all loop exits are true.
624     ///
625     /// The integer part of \c MaxAndComplete is a boolean indicating if \c
626     /// ExitNotTaken has an element for every exiting block in the loop.
627     PointerIntPair<const SCEV *, 1> MaxAndComplete;
628
629     /// True iff the backedge is taken either exactly Max or zero times.
630     bool MaxOrZero;
631
632     /// \name Helper projection functions on \c MaxAndComplete.
633     /// @{
634     bool isComplete() const { return MaxAndComplete.getInt(); }
635     const SCEV *getMax() const { return MaxAndComplete.getPointer(); }
636     /// @}
637
638   public:
639     BackedgeTakenInfo() : MaxAndComplete(nullptr, 0), MaxOrZero(false) {}
640
641     BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
642     BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
643
644     typedef std::pair<BasicBlock *, ExitLimit> EdgeExitInfo;
645
646     /// Initialize BackedgeTakenInfo from a list of exact exit counts.
647     BackedgeTakenInfo(SmallVectorImpl<EdgeExitInfo> &&ExitCounts, bool Complete,
648                       const SCEV *MaxCount, bool MaxOrZero);
649
650     /// Test whether this BackedgeTakenInfo contains any computed information,
651     /// or whether it's all SCEVCouldNotCompute values.
652     bool hasAnyInfo() const {
653       return !ExitNotTaken.empty() || !isa<SCEVCouldNotCompute>(getMax());
654     }
655
656     /// Test whether this BackedgeTakenInfo contains complete information.
657     bool hasFullInfo() const { return isComplete(); }
658
659     /// Return an expression indicating the exact *backedge-taken*
660     /// count of the loop if it is known or SCEVCouldNotCompute
661     /// otherwise.  If execution makes it to the backedge on every
662     /// iteration (i.e. there are no abnormal exists like exception
663     /// throws and thread exits) then this is the number of times the
664     /// loop header will execute minus one.
665     ///
666     /// If the SCEV predicate associated with the answer can be different
667     /// from AlwaysTrue, we must add a (non null) Predicates argument.
668     /// The SCEV predicate associated with the answer will be added to
669     /// Predicates. A run-time check needs to be emitted for the SCEV
670     /// predicate in order for the answer to be valid.
671     ///
672     /// Note that we should always know if we need to pass a predicate
673     /// argument or not from the way the ExitCounts vector was computed.
674     /// If we allowed SCEV predicates to be generated when populating this
675     /// vector, this information can contain them and therefore a
676     /// SCEVPredicate argument should be added to getExact.
677     const SCEV *getExact(ScalarEvolution *SE,
678                          SCEVUnionPredicate *Predicates = nullptr) const;
679
680     /// Return the number of times this loop exit may fall through to the back
681     /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
682     /// this block before this number of iterations, but may exit via another
683     /// block.
684     const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
685
686     /// Get the max backedge taken count for the loop.
687     const SCEV *getMax(ScalarEvolution *SE) const;
688
689     /// Return true if the number of times this backedge is taken is either the
690     /// value returned by getMax or zero.
691     bool isMaxOrZero(ScalarEvolution *SE) const;
692
693     /// Return true if any backedge taken count expressions refer to the given
694     /// subexpression.
695     bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
696
697     /// Invalidate this result and free associated memory.
698     void clear();
699   };
700
701   /// Cache the backedge-taken count of the loops for this function as they
702   /// are computed.
703   DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
704
705   /// Cache the predicated backedge-taken count of the loops for this
706   /// function as they are computed.
707   DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
708
709   /// This map contains entries for all of the PHI instructions that we
710   /// attempt to compute constant evolutions for.  This allows us to avoid
711   /// potentially expensive recomputation of these properties.  An instruction
712   /// maps to null if we are unable to compute its exit value.
713   DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
714
715   /// This map contains entries for all the expressions that we attempt to
716   /// compute getSCEVAtScope information for, which can be expensive in
717   /// extreme cases.
718   DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
719       ValuesAtScopes;
720
721   /// Memoized computeLoopDisposition results.
722   DenseMap<const SCEV *,
723            SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
724       LoopDispositions;
725
726   struct LoopProperties {
727     /// Set to true if the loop contains no instruction that can have side
728     /// effects (i.e. via throwing an exception, volatile or atomic access).
729     bool HasNoAbnormalExits;
730
731     /// Set to true if the loop contains no instruction that can abnormally exit
732     /// the loop (i.e. via throwing an exception, by terminating the thread
733     /// cleanly or by infinite looping in a called function).  Strictly
734     /// speaking, the last one is not leaving the loop, but is identical to
735     /// leaving the loop for reasoning about undefined behavior.
736     bool HasNoSideEffects;
737   };
738
739   /// Cache for \c getLoopProperties.
740   DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
741
742   /// Return a \c LoopProperties instance for \p L, creating one if necessary.
743   LoopProperties getLoopProperties(const Loop *L);
744
745   bool loopHasNoSideEffects(const Loop *L) {
746     return getLoopProperties(L).HasNoSideEffects;
747   }
748
749   bool loopHasNoAbnormalExits(const Loop *L) {
750     return getLoopProperties(L).HasNoAbnormalExits;
751   }
752
753   /// Compute a LoopDisposition value.
754   LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
755
756   /// Memoized computeBlockDisposition results.
757   DenseMap<
758       const SCEV *,
759       SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
760       BlockDispositions;
761
762   /// Compute a BlockDisposition value.
763   BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
764
765   /// Memoized results from getRange
766   DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
767
768   /// Memoized results from getRange
769   DenseMap<const SCEV *, ConstantRange> SignedRanges;
770
771   /// Used to parameterize getRange
772   enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
773
774   /// Set the memoized range for the given SCEV.
775   const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
776                                 ConstantRange CR) {
777     DenseMap<const SCEV *, ConstantRange> &Cache =
778         Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
779
780     auto Pair = Cache.try_emplace(S, std::move(CR));
781     if (!Pair.second)
782       Pair.first->second = std::move(CR);
783     return Pair.first->second;
784   }
785
786   /// Determine the range for a particular SCEV.
787   /// NOTE: This returns a reference to an entry in a cache. It must be
788   /// copied if its needed for longer.
789   const ConstantRange &getRangeRef(const SCEV *S, RangeSignHint Hint);
790
791   /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Stop}.
792   /// Helper for \c getRange.
793   ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Stop,
794                                     const SCEV *MaxBECount, unsigned BitWidth);
795
796   /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
797   /// Stop} by "factoring out" a ternary expression from the add recurrence.
798   /// Helper called by \c getRange.
799   ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Stop,
800                                      const SCEV *MaxBECount, unsigned BitWidth);
801
802   /// We know that there is no SCEV for the specified value.  Analyze the
803   /// expression.
804   const SCEV *createSCEV(Value *V);
805
806   /// Provide the special handling we need to analyze PHI SCEVs.
807   const SCEV *createNodeForPHI(PHINode *PN);
808
809   /// Helper function called from createNodeForPHI.
810   const SCEV *createAddRecFromPHI(PHINode *PN);
811
812   /// A helper function for createAddRecFromPHI to handle simple cases.
813   const SCEV *createSimpleAffineAddRec(PHINode *PN, Value *BEValueV,
814                                             Value *StartValueV);
815
816   /// Helper function called from createNodeForPHI.
817   const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
818
819   /// Provide special handling for a select-like instruction (currently this
820   /// is either a select instruction or a phi node).  \p I is the instruction
821   /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
822   /// FalseVal".
823   const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond,
824                                        Value *TrueVal, Value *FalseVal);
825
826   /// Provide the special handling we need to analyze GEP SCEVs.
827   const SCEV *createNodeForGEP(GEPOperator *GEP);
828
829   /// Implementation code for getSCEVAtScope; called at most once for each
830   /// SCEV+Loop pair.
831   ///
832   const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
833
834   /// This looks up computed SCEV values for all instructions that depend on
835   /// the given instruction and removes them from the ValueExprMap map if they
836   /// reference SymName. This is used during PHI resolution.
837   void forgetSymbolicName(Instruction *I, const SCEV *SymName);
838
839   /// Return the BackedgeTakenInfo for the given loop, lazily computing new
840   /// values if the loop hasn't been analyzed yet. The returned result is
841   /// guaranteed not to be predicated.
842   const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
843
844   /// Similar to getBackedgeTakenInfo, but will add predicates as required
845   /// with the purpose of returning complete information.
846   const BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
847
848   /// Compute the number of times the specified loop will iterate.
849   /// If AllowPredicates is set, we will create new SCEV predicates as
850   /// necessary in order to return an exact answer.
851   BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
852                                               bool AllowPredicates = false);
853
854   /// Compute the number of times the backedge of the specified loop will
855   /// execute if it exits via the specified block. If AllowPredicates is set,
856   /// this call will try to use a minimal set of SCEV predicates in order to
857   /// return an exact answer.
858   ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
859                              bool AllowPredicates = false);
860
861   /// Compute the number of times the backedge of the specified loop will
862   /// execute if its exit condition were a conditional branch of ExitCond,
863   /// TBB, and FBB.
864   ///
865   /// \p ControlsExit is true if ExitCond directly controls the exit
866   /// branch. In this case, we can assume that the loop exits only if the
867   /// condition is true and can infer that failing to meet the condition prior
868   /// to integer wraparound results in undefined behavior.
869   ///
870   /// If \p AllowPredicates is set, this call will try to use a minimal set of
871   /// SCEV predicates in order to return an exact answer.
872   ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
873                                      BasicBlock *TBB, BasicBlock *FBB,
874                                      bool ControlsExit,
875                                      bool AllowPredicates = false);
876
877   // Helper functions for computeExitLimitFromCond to avoid exponential time
878   // complexity.
879
880   class ExitLimitCache {
881     // It may look like we need key on the whole (L, TBB, FBB, ControlsExit,
882     // AllowPredicates) tuple, but recursive calls to
883     // computeExitLimitFromCondCached from computeExitLimitFromCondImpl only
884     // vary the in \c ExitCond and \c ControlsExit parameters.  We remember the
885     // initial values of the other values to assert our assumption.
886     SmallDenseMap<PointerIntPair<Value *, 1>, ExitLimit> TripCountMap;
887
888     const Loop *L;
889     BasicBlock *TBB;
890     BasicBlock *FBB;
891     bool AllowPredicates;
892
893   public:
894     ExitLimitCache(const Loop *L, BasicBlock *TBB, BasicBlock *FBB,
895                    bool AllowPredicates)
896         : L(L), TBB(TBB), FBB(FBB), AllowPredicates(AllowPredicates) {}
897
898     Optional<ExitLimit> find(const Loop *L, Value *ExitCond, BasicBlock *TBB,
899                              BasicBlock *FBB, bool ControlsExit,
900                              bool AllowPredicates);
901
902     void insert(const Loop *L, Value *ExitCond, BasicBlock *TBB,
903                 BasicBlock *FBB, bool ControlsExit, bool AllowPredicates,
904                 const ExitLimit &EL);
905   };
906
907   typedef ExitLimitCache ExitLimitCacheTy;
908   ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache,
909                                            const Loop *L, Value *ExitCond,
910                                            BasicBlock *TBB, BasicBlock *FBB,
911                                            bool ControlsExit,
912                                            bool AllowPredicates);
913   ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const Loop *L,
914                                          Value *ExitCond, BasicBlock *TBB,
915                                          BasicBlock *FBB, bool ControlsExit,
916                                          bool AllowPredicates);
917
918   /// Compute the number of times the backedge of the specified loop will
919   /// execute if its exit condition were a conditional branch of the ICmpInst
920   /// ExitCond, TBB, and FBB. If AllowPredicates is set, this call will try
921   /// to use a minimal set of SCEV predicates in order to return an exact
922   /// answer.
923   ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
924                                      BasicBlock *TBB, BasicBlock *FBB,
925                                      bool IsSubExpr,
926                                      bool AllowPredicates = false);
927
928   /// Compute the number of times the backedge of the specified loop will
929   /// execute if its exit condition were a switch with a single exiting case
930   /// to ExitingBB.
931   ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
932                                                  SwitchInst *Switch,
933                                                  BasicBlock *ExitingBB,
934                                                  bool IsSubExpr);
935
936   /// Given an exit condition of 'icmp op load X, cst', try to see if we can
937   /// compute the backedge-taken count.
938   ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI, Constant *RHS,
939                                                 const Loop *L,
940                                                 ICmpInst::Predicate p);
941
942   /// Compute the exit limit of a loop that is controlled by a
943   /// "(IV >> 1) != 0" type comparison.  We cannot compute the exact trip
944   /// count in these cases (since SCEV has no way of expressing them), but we
945   /// can still sometimes compute an upper bound.
946   ///
947   /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
948   /// RHS`.
949   ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
950                                          ICmpInst::Predicate Pred);
951
952   /// If the loop is known to execute a constant number of times (the
953   /// condition evolves only from constants), try to evaluate a few iterations
954   /// of the loop until we get the exit condition gets a value of ExitWhen
955   /// (true or false).  If we cannot evaluate the exit count of the loop,
956   /// return CouldNotCompute.
957   const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
958                                            bool ExitWhen);
959
960   /// Return the number of times an exit condition comparing the specified
961   /// value to zero will execute.  If not computable, return CouldNotCompute.
962   /// If AllowPredicates is set, this call will try to use a minimal set of
963   /// SCEV predicates in order to return an exact answer.
964   ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
965                          bool AllowPredicates = false);
966
967   /// Return the number of times an exit condition checking the specified
968   /// value for nonzero will execute.  If not computable, return
969   /// CouldNotCompute.
970   ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
971
972   /// Return the number of times an exit condition containing the specified
973   /// less-than comparison will execute.  If not computable, return
974   /// CouldNotCompute.
975   ///
976   /// \p isSigned specifies whether the less-than is signed.
977   ///
978   /// \p ControlsExit is true when the LHS < RHS condition directly controls
979   /// the branch (loops exits only if condition is true). In this case, we can
980   /// use NoWrapFlags to skip overflow checks.
981   ///
982   /// If \p AllowPredicates is set, this call will try to use a minimal set of
983   /// SCEV predicates in order to return an exact answer.
984   ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
985                              bool isSigned, bool ControlsExit,
986                              bool AllowPredicates = false);
987
988   ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
989                                 bool isSigned, bool IsSubExpr,
990                                 bool AllowPredicates = false);
991
992   /// Return a predecessor of BB (which may not be an immediate predecessor)
993   /// which has exactly one successor from which BB is reachable, or null if
994   /// no such block is found.
995   std::pair<BasicBlock *, BasicBlock *>
996   getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
997
998   /// Test whether the condition described by Pred, LHS, and RHS is true
999   /// whenever the given FoundCondValue value evaluates to true.
1000   bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
1001                      Value *FoundCondValue, bool Inverse);
1002
1003   /// Test whether the condition described by Pred, LHS, and RHS is true
1004   /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
1005   /// true.
1006   bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
1007                      ICmpInst::Predicate FoundPred, const SCEV *FoundLHS,
1008                      const SCEV *FoundRHS);
1009
1010   /// Test whether the condition described by Pred, LHS, and RHS is true
1011   /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1012   /// true.
1013   bool isImpliedCondOperands(ICmpInst::Predicate Pred, const SCEV *LHS,
1014                              const SCEV *RHS, const SCEV *FoundLHS,
1015                              const SCEV *FoundRHS);
1016
1017   /// Test whether the condition described by Pred, LHS, and RHS is true
1018   /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1019   /// true. Here LHS is an operation that includes FoundLHS as one of its
1020   /// arguments.
1021   bool isImpliedViaOperations(ICmpInst::Predicate Pred,
1022                               const SCEV *LHS, const SCEV *RHS,
1023                               const SCEV *FoundLHS, const SCEV *FoundRHS,
1024                               unsigned Depth = 0);
1025
1026   /// Test whether the condition described by Pred, LHS, and RHS is true.
1027   /// Use only simple non-recursive types of checks, such as range analysis etc.
1028   bool isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
1029                                  const SCEV *LHS, const SCEV *RHS);
1030
1031   /// Test whether the condition described by Pred, LHS, and RHS is true
1032   /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1033   /// true.
1034   bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, const SCEV *LHS,
1035                                    const SCEV *RHS, const SCEV *FoundLHS,
1036                                    const SCEV *FoundRHS);
1037
1038   /// Test whether the condition described by Pred, LHS, and RHS is true
1039   /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1040   /// true.  Utility function used by isImpliedCondOperands.  Tries to get
1041   /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
1042   bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, const SCEV *LHS,
1043                                       const SCEV *RHS, const SCEV *FoundLHS,
1044                                       const SCEV *FoundRHS);
1045
1046   /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
1047   /// by a call to \c @llvm.experimental.guard in \p BB.
1048   bool isImpliedViaGuard(BasicBlock *BB, ICmpInst::Predicate Pred,
1049                          const SCEV *LHS, const SCEV *RHS);
1050
1051   /// Test whether the condition described by Pred, LHS, and RHS is true
1052   /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1053   /// true.
1054   ///
1055   /// This routine tries to rule out certain kinds of integer overflow, and
1056   /// then tries to reason about arithmetic properties of the predicates.
1057   bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
1058                                           const SCEV *LHS, const SCEV *RHS,
1059                                           const SCEV *FoundLHS,
1060                                           const SCEV *FoundRHS);
1061
1062   /// If we know that the specified Phi is in the header of its containing
1063   /// loop, we know the loop executes a constant number of times, and the PHI
1064   /// node is just a recurrence involving constants, fold it.
1065   Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
1066                                               const Loop *L);
1067
1068   /// Test if the given expression is known to satisfy the condition described
1069   /// by Pred and the known constant ranges of LHS and RHS.
1070   ///
1071   bool isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,
1072                                          const SCEV *LHS, const SCEV *RHS);
1073
1074   /// Try to prove the condition described by "LHS Pred RHS" by ruling out
1075   /// integer overflow.
1076   ///
1077   /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
1078   /// positive.
1079   bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS,
1080                                      const SCEV *RHS);
1081
1082   /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
1083   /// prove them individually.
1084   bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
1085                                     const SCEV *RHS);
1086
1087   /// Try to match the Expr as "(L + R)<Flags>".
1088   bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R,
1089                       SCEV::NoWrapFlags &Flags);
1090
1091   /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
1092   /// constant, and None if it isn't.
1093   ///
1094   /// This is intended to be a cheaper version of getMinusSCEV.  We can be
1095   /// frugal here since we just bail out of actually constructing and
1096   /// canonicalizing an expression in the cases where the result isn't going
1097   /// to be a constant.
1098   Optional<APInt> computeConstantDifference(const SCEV *LHS, const SCEV *RHS);
1099
1100   /// Drop memoized information computed for S.
1101   void forgetMemoizedResults(const SCEV *S);
1102
1103   /// Return an existing SCEV for V if there is one, otherwise return nullptr.
1104   const SCEV *getExistingSCEV(Value *V);
1105
1106   /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
1107   /// pointer.
1108   bool checkValidity(const SCEV *S) const;
1109
1110   /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
1111   /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}.  This is
1112   /// equivalent to proving no signed (resp. unsigned) wrap in
1113   /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
1114   /// (resp. `SCEVZeroExtendExpr`).
1115   ///
1116   template <typename ExtendOpTy>
1117   bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
1118                                  const Loop *L);
1119
1120   /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation.
1121   SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
1122
1123   bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
1124                                 ICmpInst::Predicate Pred, bool &Increasing);
1125
1126   /// Return SCEV no-wrap flags that can be proven based on reasoning about
1127   /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
1128   /// would trigger undefined behavior on overflow.
1129   SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
1130
1131   /// Return true if the SCEV corresponding to \p I is never poison.  Proving
1132   /// this is more complex than proving that just \p I is never poison, since
1133   /// SCEV commons expressions across control flow, and you can have cases
1134   /// like:
1135   ///
1136   ///   idx0 = a + b;
1137   ///   ptr[idx0] = 100;
1138   ///   if (<condition>) {
1139   ///     idx1 = a +nsw b;
1140   ///     ptr[idx1] = 200;
1141   ///   }
1142   ///
1143   /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
1144   /// hence not sign-overflow) only if "<condition>" is true.  Since both
1145   /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
1146   /// it is not okay to annotate (+ a b) with <nsw> in the above example.
1147   bool isSCEVExprNeverPoison(const Instruction *I);
1148
1149   /// This is like \c isSCEVExprNeverPoison but it specifically works for
1150   /// instructions that will get mapped to SCEV add recurrences.  Return true
1151   /// if \p I will never generate poison under the assumption that \p I is an
1152   /// add recurrence on the loop \p L.
1153   bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
1154
1155 public:
1156   ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC,
1157                   DominatorTree &DT, LoopInfo &LI);
1158   ~ScalarEvolution();
1159   ScalarEvolution(ScalarEvolution &&Arg);
1160
1161   LLVMContext &getContext() const { return F.getContext(); }
1162
1163   /// Test if values of the given type are analyzable within the SCEV
1164   /// framework. This primarily includes integer types, and it can optionally
1165   /// include pointer types if the ScalarEvolution class has access to
1166   /// target-specific information.
1167   bool isSCEVable(Type *Ty) const;
1168
1169   /// Return the size in bits of the specified type, for which isSCEVable must
1170   /// return true.
1171   uint64_t getTypeSizeInBits(Type *Ty) const;
1172
1173   /// Return a type with the same bitwidth as the given type and which
1174   /// represents how SCEV will treat the given type, for which isSCEVable must
1175   /// return true. For pointer types, this is the pointer-sized integer type.
1176   Type *getEffectiveSCEVType(Type *Ty) const;
1177
1178   // Returns a wider type among {Ty1, Ty2}.
1179   Type *getWiderType(Type *Ty1, Type *Ty2) const;
1180
1181   /// Return true if the SCEV is a scAddRecExpr or it contains
1182   /// scAddRecExpr. The result will be cached in HasRecMap.
1183   ///
1184   bool containsAddRecurrence(const SCEV *S);
1185
1186   /// Return the Value set from which the SCEV expr is generated.
1187   SetVector<ValueOffsetPair> *getSCEVValues(const SCEV *S);
1188
1189   /// Erase Value from ValueExprMap and ExprValueMap.
1190   void eraseValueFromMap(Value *V);
1191
1192   /// Return a SCEV expression for the full generality of the specified
1193   /// expression.
1194   const SCEV *getSCEV(Value *V);
1195
1196   const SCEV *getConstant(ConstantInt *V);
1197   const SCEV *getConstant(const APInt &Val);
1198   const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
1199   const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
1200
1201   typedef SmallDenseMap<std::pair<const SCEV *, Type *>, const SCEV *, 8>
1202       ExtendCacheTy;
1203   const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
1204   const SCEV *getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1205                                       ExtendCacheTy &Cache);
1206   const SCEV *getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1207                                     ExtendCacheTy &Cache);
1208
1209   const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
1210   const SCEV *getSignExtendExprCached(const SCEV *Op, Type *Ty,
1211                                       ExtendCacheTy &Cache);
1212   const SCEV *getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1213                                     ExtendCacheTy &Cache);
1214   const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
1215   const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1216                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1217                          unsigned Depth = 0);
1218   const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
1219                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1220                          unsigned Depth = 0) {
1221     SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
1222     return getAddExpr(Ops, Flags, Depth);
1223   }
1224   const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
1225                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1226                          unsigned Depth = 0) {
1227     SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
1228     return getAddExpr(Ops, Flags, Depth);
1229   }
1230   const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1231                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1232                          unsigned Depth = 0);
1233   const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
1234                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1235                          unsigned Depth = 0) {
1236     SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
1237     return getMulExpr(Ops, Flags, Depth);
1238   }
1239   const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
1240                          SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1241                          unsigned Depth = 0) {
1242     SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
1243     return getMulExpr(Ops, Flags, Depth);
1244   }
1245   const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
1246   const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
1247   const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L,
1248                             SCEV::NoWrapFlags Flags);
1249   const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1250                             const Loop *L, SCEV::NoWrapFlags Flags);
1251   const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
1252                             const Loop *L, SCEV::NoWrapFlags Flags) {
1253     SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
1254     return getAddRecExpr(NewOp, L, Flags);
1255   }
1256   /// Returns an expression for a GEP
1257   ///
1258   /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
1259   /// instead we use IndexExprs.
1260   /// \p IndexExprs The expressions for the indices.
1261   const SCEV *getGEPExpr(GEPOperator *GEP,
1262                          const SmallVectorImpl<const SCEV *> &IndexExprs);
1263   const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
1264   const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
1265   const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
1266   const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
1267   const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
1268   const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
1269   const SCEV *getUnknown(Value *V);
1270   const SCEV *getCouldNotCompute();
1271
1272   /// Return a SCEV for the constant 0 of a specific type.
1273   const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
1274
1275   /// Return a SCEV for the constant 1 of a specific type.
1276   const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
1277
1278   /// Return an expression for sizeof AllocTy that is type IntTy
1279   ///
1280   const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
1281
1282   /// Return an expression for offsetof on the given field with type IntTy
1283   ///
1284   const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
1285
1286   /// Return the SCEV object corresponding to -V.
1287   ///
1288   const SCEV *getNegativeSCEV(const SCEV *V,
1289                               SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
1290
1291   /// Return the SCEV object corresponding to ~V.
1292   ///
1293   const SCEV *getNotSCEV(const SCEV *V);
1294
1295   /// Return LHS-RHS.  Minus is represented in SCEV as A+B*-1.
1296   const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
1297                            SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1298                            unsigned Depth = 0);
1299
1300   /// Return a SCEV corresponding to a conversion of the input value to the
1301   /// specified type.  If the type must be extended, it is zero extended.
1302   const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
1303
1304   /// Return a SCEV corresponding to a conversion of the input value to the
1305   /// specified type.  If the type must be extended, it is sign extended.
1306   const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
1307
1308   /// Return a SCEV corresponding to a conversion of the input value to the
1309   /// specified type.  If the type must be extended, it is zero extended.  The
1310   /// conversion must not be narrowing.
1311   const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
1312
1313   /// Return a SCEV corresponding to a conversion of the input value to the
1314   /// specified type.  If the type must be extended, it is sign extended.  The
1315   /// conversion must not be narrowing.
1316   const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
1317
1318   /// Return a SCEV corresponding to a conversion of the input value to the
1319   /// specified type. If the type must be extended, it is extended with
1320   /// unspecified bits. The conversion must not be narrowing.
1321   const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
1322
1323   /// Return a SCEV corresponding to a conversion of the input value to the
1324   /// specified type.  The conversion must not be widening.
1325   const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
1326
1327   /// Promote the operands to the wider of the types using zero-extension, and
1328   /// then perform a umax operation with them.
1329   const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
1330
1331   /// Promote the operands to the wider of the types using zero-extension, and
1332   /// then perform a umin operation with them.
1333   const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
1334
1335   /// Transitively follow the chain of pointer-type operands until reaching a
1336   /// SCEV that does not have a single pointer operand. This returns a
1337   /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
1338   /// cases do exist.
1339   const SCEV *getPointerBase(const SCEV *V);
1340
1341   /// Return a SCEV expression for the specified value at the specified scope
1342   /// in the program.  The L value specifies a loop nest to evaluate the
1343   /// expression at, where null is the top-level or a specified loop is
1344   /// immediately inside of the loop.
1345   ///
1346   /// This method can be used to compute the exit value for a variable defined
1347   /// in a loop by querying what the value will hold in the parent loop.
1348   ///
1349   /// In the case that a relevant loop exit value cannot be computed, the
1350   /// original value V is returned.
1351   const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
1352
1353   /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
1354   const SCEV *getSCEVAtScope(Value *V, const Loop *L);
1355
1356   /// Test whether entry to the loop is protected by a conditional between LHS
1357   /// and RHS.  This is used to help avoid max expressions in loop trip
1358   /// counts, and to eliminate casts.
1359   bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1360                                 const SCEV *LHS, const SCEV *RHS);
1361
1362   /// Test whether the backedge of the loop is protected by a conditional
1363   /// between LHS and RHS.  This is used to to eliminate casts.
1364   bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1365                                    const SCEV *LHS, const SCEV *RHS);
1366
1367   /// Returns the maximum trip count of the loop if it is a single-exit
1368   /// loop and we can compute a small maximum for that loop.
1369   ///
1370   /// Implemented in terms of the \c getSmallConstantTripCount overload with
1371   /// the single exiting block passed to it. See that routine for details.
1372   unsigned getSmallConstantTripCount(const Loop *L);
1373
1374   /// Returns the maximum trip count of this loop as a normal unsigned
1375   /// value. Returns 0 if the trip count is unknown or not constant. This
1376   /// "trip count" assumes that control exits via ExitingBlock. More
1377   /// precisely, it is the number of times that control may reach ExitingBlock
1378   /// before taking the branch. For loops with multiple exits, it may not be
1379   /// the number times that the loop header executes if the loop exits
1380   /// prematurely via another branch.
1381   unsigned getSmallConstantTripCount(const Loop *L, BasicBlock *ExitingBlock);
1382
1383   /// Returns the upper bound of the loop trip count as a normal unsigned
1384   /// value.
1385   /// Returns 0 if the trip count is unknown or not constant.
1386   unsigned getSmallConstantMaxTripCount(const Loop *L);
1387
1388   /// Returns the largest constant divisor of the trip count of the
1389   /// loop if it is a single-exit loop and we can compute a small maximum for
1390   /// that loop.
1391   ///
1392   /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
1393   /// the single exiting block passed to it. See that routine for details.
1394   unsigned getSmallConstantTripMultiple(const Loop *L);
1395
1396   /// Returns the largest constant divisor of the trip count of this loop as a
1397   /// normal unsigned value, if possible. This means that the actual trip
1398   /// count is always a multiple of the returned value (don't forget the trip
1399   /// count could very well be zero as well!). As explained in the comments
1400   /// for getSmallConstantTripCount, this assumes that control exits the loop
1401   /// via ExitingBlock.
1402   unsigned getSmallConstantTripMultiple(const Loop *L,
1403                                         BasicBlock *ExitingBlock);
1404
1405   /// Get the expression for the number of loop iterations for which this loop
1406   /// is guaranteed not to exit via ExitingBlock. Otherwise return
1407   /// SCEVCouldNotCompute.
1408   const SCEV *getExitCount(const Loop *L, BasicBlock *ExitingBlock);
1409
1410   /// If the specified loop has a predictable backedge-taken count, return it,
1411   /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count is
1412   /// the number of times the loop header will be branched to from within the
1413   /// loop, assuming there are no abnormal exists like exception throws. This is
1414   /// one less than the trip count of the loop, since it doesn't count the first
1415   /// iteration, when the header is branched to from outside the loop.
1416   ///
1417   /// Note that it is not valid to call this method on a loop without a
1418   /// loop-invariant backedge-taken count (see
1419   /// hasLoopInvariantBackedgeTakenCount).
1420   ///
1421   const SCEV *getBackedgeTakenCount(const Loop *L);
1422
1423   /// Similar to getBackedgeTakenCount, except it will add a set of
1424   /// SCEV predicates to Predicates that are required to be true in order for
1425   /// the answer to be correct. Predicates can be checked with run-time
1426   /// checks and can be used to perform loop versioning.
1427   const SCEV *getPredicatedBackedgeTakenCount(const Loop *L,
1428                                               SCEVUnionPredicate &Predicates);
1429
1430   /// When successful, this returns a SCEVConstant that is greater than or equal
1431   /// to (i.e. a "conservative over-approximation") of the value returend by
1432   /// getBackedgeTakenCount.  If such a value cannot be computed, it returns the
1433   /// SCEVCouldNotCompute object.
1434   const SCEV *getMaxBackedgeTakenCount(const Loop *L);
1435
1436   /// Return true if the backedge taken count is either the value returned by
1437   /// getMaxBackedgeTakenCount or zero.
1438   bool isBackedgeTakenCountMaxOrZero(const Loop *L);
1439
1440   /// Return true if the specified loop has an analyzable loop-invariant
1441   /// backedge-taken count.
1442   bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
1443
1444   /// This method should be called by the client when it has changed a loop in
1445   /// a way that may effect ScalarEvolution's ability to compute a trip count,
1446   /// or if the loop is deleted.  This call is potentially expensive for large
1447   /// loop bodies.
1448   void forgetLoop(const Loop *L);
1449
1450   /// This method should be called by the client when it has changed a value
1451   /// in a way that may effect its value, or which may disconnect it from a
1452   /// def-use chain linking it to a loop.
1453   void forgetValue(Value *V);
1454
1455   /// Called when the client has changed the disposition of values in
1456   /// this loop.
1457   ///
1458   /// We don't have a way to invalidate per-loop dispositions. Clear and
1459   /// recompute is simpler.
1460   void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
1461
1462   /// Determine the minimum number of zero bits that S is guaranteed to end in
1463   /// (at every loop iteration).  It is, at the same time, the minimum number
1464   /// of times S is divisible by 2.  For example, given {4,+,8} it returns 2.
1465   /// If S is guaranteed to be 0, it returns the bitwidth of S.
1466   uint32_t GetMinTrailingZeros(const SCEV *S);
1467
1468   /// Determine the unsigned range for a particular SCEV.
1469   /// NOTE: This returns a copy of the reference returned by getRangeRef.
1470   ConstantRange getUnsignedRange(const SCEV *S) {
1471     return getRangeRef(S, HINT_RANGE_UNSIGNED);
1472   }
1473
1474   /// Determine the min of the unsigned range for a particular SCEV.
1475   APInt getUnsignedRangeMin(const SCEV *S) {
1476     return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMin();
1477   }
1478
1479   /// Determine the max of the unsigned range for a particular SCEV.
1480   APInt getUnsignedRangeMax(const SCEV *S) {
1481     return getRangeRef(S, HINT_RANGE_UNSIGNED).getUnsignedMax();
1482   }
1483
1484   /// Determine the signed range for a particular SCEV.
1485   /// NOTE: This returns a copy of the reference returned by getRangeRef.
1486   ConstantRange getSignedRange(const SCEV *S) {
1487     return getRangeRef(S, HINT_RANGE_SIGNED);
1488   }
1489
1490   /// Determine the min of the signed range for a particular SCEV.
1491   APInt getSignedRangeMin(const SCEV *S) {
1492     return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMin();
1493   }
1494
1495   /// Determine the max of the signed range for a particular SCEV.
1496   APInt getSignedRangeMax(const SCEV *S) {
1497     return getRangeRef(S, HINT_RANGE_SIGNED).getSignedMax();
1498   }
1499
1500   /// Test if the given expression is known to be negative.
1501   ///
1502   bool isKnownNegative(const SCEV *S);
1503
1504   /// Test if the given expression is known to be positive.
1505   ///
1506   bool isKnownPositive(const SCEV *S);
1507
1508   /// Test if the given expression is known to be non-negative.
1509   ///
1510   bool isKnownNonNegative(const SCEV *S);
1511
1512   /// Test if the given expression is known to be non-positive.
1513   ///
1514   bool isKnownNonPositive(const SCEV *S);
1515
1516   /// Test if the given expression is known to be non-zero.
1517   ///
1518   bool isKnownNonZero(const SCEV *S);
1519
1520   /// Test if the given expression is known to satisfy the condition described
1521   /// by Pred, LHS, and RHS.
1522   ///
1523   bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
1524                         const SCEV *RHS);
1525
1526   /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
1527   /// is monotonically increasing or decreasing.  In the former case set
1528   /// `Increasing` to true and in the latter case set `Increasing` to false.
1529   ///
1530   /// A predicate is said to be monotonically increasing if may go from being
1531   /// false to being true as the loop iterates, but never the other way
1532   /// around.  A predicate is said to be monotonically decreasing if may go
1533   /// from being true to being false as the loop iterates, but never the other
1534   /// way around.
1535   bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred,
1536                             bool &Increasing);
1537
1538   /// Return true if the result of the predicate LHS `Pred` RHS is loop
1539   /// invariant with respect to L.  Set InvariantPred, InvariantLHS and
1540   /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
1541   /// loop invariant form of LHS `Pred` RHS.
1542   bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
1543                                 const SCEV *RHS, const Loop *L,
1544                                 ICmpInst::Predicate &InvariantPred,
1545                                 const SCEV *&InvariantLHS,
1546                                 const SCEV *&InvariantRHS);
1547
1548   /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
1549   /// iff any changes were made. If the operands are provably equal or
1550   /// unequal, LHS and RHS are set to the same value and Pred is set to either
1551   /// ICMP_EQ or ICMP_NE.
1552   ///
1553   bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS,
1554                             const SCEV *&RHS, unsigned Depth = 0);
1555
1556   /// Return the "disposition" of the given SCEV with respect to the given
1557   /// loop.
1558   LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
1559
1560   /// Return true if the value of the given SCEV is unchanging in the
1561   /// specified loop.
1562   bool isLoopInvariant(const SCEV *S, const Loop *L);
1563
1564   /// Determine if the SCEV can be evaluated at loop's entry. It is true if it
1565   /// doesn't depend on a SCEVUnknown of an instruction which is dominated by
1566   /// the header of loop L.
1567   bool isAvailableAtLoopEntry(const SCEV *S, const Loop *L);
1568
1569   /// Return true if the given SCEV changes value in a known way in the
1570   /// specified loop.  This property being true implies that the value is
1571   /// variant in the loop AND that we can emit an expression to compute the
1572   /// value of the expression at any particular loop iteration.
1573   bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
1574
1575   /// Return the "disposition" of the given SCEV with respect to the given
1576   /// block.
1577   BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
1578
1579   /// Return true if elements that makes up the given SCEV dominate the
1580   /// specified basic block.
1581   bool dominates(const SCEV *S, const BasicBlock *BB);
1582
1583   /// Return true if elements that makes up the given SCEV properly dominate
1584   /// the specified basic block.
1585   bool properlyDominates(const SCEV *S, const BasicBlock *BB);
1586
1587   /// Test whether the given SCEV has Op as a direct or indirect operand.
1588   bool hasOperand(const SCEV *S, const SCEV *Op) const;
1589
1590   /// Return the size of an element read or written by Inst.
1591   const SCEV *getElementSize(Instruction *Inst);
1592
1593   /// Compute the array dimensions Sizes from the set of Terms extracted from
1594   /// the memory access function of this SCEVAddRecExpr (second step of
1595   /// delinearization).
1596   void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
1597                            SmallVectorImpl<const SCEV *> &Sizes,
1598                            const SCEV *ElementSize);
1599
1600   void print(raw_ostream &OS) const;
1601   void verify() const;
1602   bool invalidate(Function &F, const PreservedAnalyses &PA,
1603                   FunctionAnalysisManager::Invalidator &Inv);
1604
1605   /// Collect parametric terms occurring in step expressions (first step of
1606   /// delinearization).
1607   void collectParametricTerms(const SCEV *Expr,
1608                               SmallVectorImpl<const SCEV *> &Terms);
1609
1610   /// Return in Subscripts the access functions for each dimension in Sizes
1611   /// (third step of delinearization).
1612   void computeAccessFunctions(const SCEV *Expr,
1613                               SmallVectorImpl<const SCEV *> &Subscripts,
1614                               SmallVectorImpl<const SCEV *> &Sizes);
1615
1616   /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
1617   /// subscripts and sizes of an array access.
1618   ///
1619   /// The delinearization is a 3 step process: the first two steps compute the
1620   /// sizes of each subscript and the third step computes the access functions
1621   /// for the delinearized array:
1622   ///
1623   /// 1. Find the terms in the step functions
1624   /// 2. Compute the array size
1625   /// 3. Compute the access function: divide the SCEV by the array size
1626   ///    starting with the innermost dimensions found in step 2. The Quotient
1627   ///    is the SCEV to be divided in the next step of the recursion. The
1628   ///    Remainder is the subscript of the innermost dimension. Loop over all
1629   ///    array dimensions computed in step 2.
1630   ///
1631   /// To compute a uniform array size for several memory accesses to the same
1632   /// object, one can collect in step 1 all the step terms for all the memory
1633   /// accesses, and compute in step 2 a unique array shape. This guarantees
1634   /// that the array shape will be the same across all memory accesses.
1635   ///
1636   /// FIXME: We could derive the result of steps 1 and 2 from a description of
1637   /// the array shape given in metadata.
1638   ///
1639   /// Example:
1640   ///
1641   /// A[][n][m]
1642   ///
1643   /// for i
1644   ///   for j
1645   ///     for k
1646   ///       A[j+k][2i][5i] =
1647   ///
1648   /// The initial SCEV:
1649   ///
1650   /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1651   ///
1652   /// 1. Find the different terms in the step functions:
1653   /// -> [2*m, 5, n*m, n*m]
1654   ///
1655   /// 2. Compute the array size: sort and unique them
1656   /// -> [n*m, 2*m, 5]
1657   /// find the GCD of all the terms = 1
1658   /// divide by the GCD and erase constant terms
1659   /// -> [n*m, 2*m]
1660   /// GCD = m
1661   /// divide by GCD -> [n, 2]
1662   /// remove constant terms
1663   /// -> [n]
1664   /// size of the array is A[unknown][n][m]
1665   ///
1666   /// 3. Compute the access function
1667   /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1668   /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1669   /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1670   /// The remainder is the subscript of the innermost array dimension: [5i].
1671   ///
1672   /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1673   /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1674   /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1675   /// The Remainder is the subscript of the next array dimension: [2i].
1676   ///
1677   /// The subscript of the outermost dimension is the Quotient: [j+k].
1678   ///
1679   /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1680   void delinearize(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
1681                    SmallVectorImpl<const SCEV *> &Sizes,
1682                    const SCEV *ElementSize);
1683
1684   /// Return the DataLayout associated with the module this SCEV instance is
1685   /// operating on.
1686   const DataLayout &getDataLayout() const {
1687     return F.getParent()->getDataLayout();
1688   }
1689
1690   const SCEVPredicate *getEqualPredicate(const SCEVUnknown *LHS,
1691                                          const SCEVConstant *RHS);
1692
1693   const SCEVPredicate *
1694   getWrapPredicate(const SCEVAddRecExpr *AR,
1695                    SCEVWrapPredicate::IncrementWrapFlags AddedFlags);
1696
1697   /// Re-writes the SCEV according to the Predicates in \p A.
1698   const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
1699                                     SCEVUnionPredicate &A);
1700   /// Tries to convert the \p S expression to an AddRec expression,
1701   /// adding additional predicates to \p Preds as required.
1702   const SCEVAddRecExpr *convertSCEVToAddRecWithPredicates(
1703       const SCEV *S, const Loop *L,
1704       SmallPtrSetImpl<const SCEVPredicate *> &Preds);
1705
1706 private:
1707   /// Compute the backedge taken count knowing the interval difference, the
1708   /// stride and presence of the equality in the comparison.
1709   const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1710                              bool Equality);
1711
1712   /// Verify if an linear IV with positive stride can overflow when in a
1713   /// less-than comparison, knowing the invariant term of the comparison,
1714   /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1715   bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1716                           bool NoWrap);
1717
1718   /// Verify if an linear IV with negative stride can overflow when in a
1719   /// greater-than comparison, knowing the invariant term of the comparison,
1720   /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1721   bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1722                           bool NoWrap);
1723
1724   /// Get add expr already created or create a new one.
1725   const SCEV *getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1726                                  SCEV::NoWrapFlags Flags);
1727
1728   /// Get mul expr already created or create a new one.
1729   const SCEV *getOrCreateMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1730                                  SCEV::NoWrapFlags Flags);
1731
1732 private:
1733   FoldingSet<SCEV> UniqueSCEVs;
1734   FoldingSet<SCEVPredicate> UniquePreds;
1735   BumpPtrAllocator SCEVAllocator;
1736
1737   /// The head of a linked list of all SCEVUnknown values that have been
1738   /// allocated. This is used by releaseMemory to locate them all and call
1739   /// their destructors.
1740   SCEVUnknown *FirstUnknown;
1741 };
1742
1743 /// Analysis pass that exposes the \c ScalarEvolution for a function.
1744 class ScalarEvolutionAnalysis
1745     : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
1746   friend AnalysisInfoMixin<ScalarEvolutionAnalysis>;
1747   static AnalysisKey Key;
1748
1749 public:
1750   typedef ScalarEvolution Result;
1751
1752   ScalarEvolution run(Function &F, FunctionAnalysisManager &AM);
1753 };
1754
1755 /// Printer pass for the \c ScalarEvolutionAnalysis results.
1756 class ScalarEvolutionPrinterPass
1757     : public PassInfoMixin<ScalarEvolutionPrinterPass> {
1758   raw_ostream &OS;
1759
1760 public:
1761   explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
1762   PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
1763 };
1764
1765 class ScalarEvolutionWrapperPass : public FunctionPass {
1766   std::unique_ptr<ScalarEvolution> SE;
1767
1768 public:
1769   static char ID;
1770
1771   ScalarEvolutionWrapperPass();
1772
1773   ScalarEvolution &getSE() { return *SE; }
1774   const ScalarEvolution &getSE() const { return *SE; }
1775
1776   bool runOnFunction(Function &F) override;
1777   void releaseMemory() override;
1778   void getAnalysisUsage(AnalysisUsage &AU) const override;
1779   void print(raw_ostream &OS, const Module * = nullptr) const override;
1780   void verifyAnalysis() const override;
1781 };
1782
1783 /// An interface layer with SCEV used to manage how we see SCEV expressions
1784 /// for values in the context of existing predicates. We can add new
1785 /// predicates, but we cannot remove them.
1786 ///
1787 /// This layer has multiple purposes:
1788 ///   - provides a simple interface for SCEV versioning.
1789 ///   - guarantees that the order of transformations applied on a SCEV
1790 ///     expression for a single Value is consistent across two different
1791 ///     getSCEV calls. This means that, for example, once we've obtained
1792 ///     an AddRec expression for a certain value through expression
1793 ///     rewriting, we will continue to get an AddRec expression for that
1794 ///     Value.
1795 ///   - lowers the number of expression rewrites.
1796 class PredicatedScalarEvolution {
1797 public:
1798   PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L);
1799   const SCEVUnionPredicate &getUnionPredicate() const;
1800
1801   /// Returns the SCEV expression of V, in the context of the current SCEV
1802   /// predicate.  The order of transformations applied on the expression of V
1803   /// returned by ScalarEvolution is guaranteed to be preserved, even when
1804   /// adding new predicates.
1805   const SCEV *getSCEV(Value *V);
1806
1807   /// Get the (predicated) backedge count for the analyzed loop.
1808   const SCEV *getBackedgeTakenCount();
1809
1810   /// Adds a new predicate.
1811   void addPredicate(const SCEVPredicate &Pred);
1812
1813   /// Attempts to produce an AddRecExpr for V by adding additional SCEV
1814   /// predicates. If we can't transform the expression into an AddRecExpr we
1815   /// return nullptr and not add additional SCEV predicates to the current
1816   /// context.
1817   const SCEVAddRecExpr *getAsAddRec(Value *V);
1818
1819   /// Proves that V doesn't overflow by adding SCEV predicate.
1820   void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1821
1822   /// Returns true if we've proved that V doesn't wrap by means of a SCEV
1823   /// predicate.
1824   bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1825
1826   /// Returns the ScalarEvolution analysis used.
1827   ScalarEvolution *getSE() const { return &SE; }
1828
1829   /// We need to explicitly define the copy constructor because of FlagsMap.
1830   PredicatedScalarEvolution(const PredicatedScalarEvolution &);
1831
1832   /// Print the SCEV mappings done by the Predicated Scalar Evolution.
1833   /// The printed text is indented by \p Depth.
1834   void print(raw_ostream &OS, unsigned Depth) const;
1835
1836 private:
1837   /// Increments the version number of the predicate.  This needs to be called
1838   /// every time the SCEV predicate changes.
1839   void updateGeneration();
1840
1841   /// Holds a SCEV and the version number of the SCEV predicate used to
1842   /// perform the rewrite of the expression.
1843   typedef std::pair<unsigned, const SCEV *> RewriteEntry;
1844
1845   /// Maps a SCEV to the rewrite result of that SCEV at a certain version
1846   /// number. If this number doesn't match the current Generation, we will
1847   /// need to do a rewrite. To preserve the transformation order of previous
1848   /// rewrites, we will rewrite the previous result instead of the original
1849   /// SCEV.
1850   DenseMap<const SCEV *, RewriteEntry> RewriteMap;
1851
1852   /// Records what NoWrap flags we've added to a Value *.
1853   ValueMap<Value *, SCEVWrapPredicate::IncrementWrapFlags> FlagsMap;
1854
1855   /// The ScalarEvolution analysis.
1856   ScalarEvolution &SE;
1857
1858   /// The analyzed Loop.
1859   const Loop &L;
1860
1861   /// The SCEVPredicate that forms our context. We will rewrite all
1862   /// expressions assuming that this predicate true.
1863   SCEVUnionPredicate Preds;
1864
1865   /// Marks the version of the SCEV predicate used. When rewriting a SCEV
1866   /// expression we mark it with the version of the predicate. We use this to
1867   /// figure out if the predicate has changed from the last rewrite of the
1868   /// SCEV. If so, we need to perform a new rewrite.
1869   unsigned Generation;
1870
1871   /// The backedge taken count.
1872   const SCEV *BackedgeCount;
1873 };
1874 }
1875
1876 #endif