1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 // This analysis is primarily useful for induction variable substitution and
17 // strength reduction.
19 //===----------------------------------------------------------------------===//
21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H
22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H
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"
40 class AssumptionCache;
45 class ScalarEvolution;
47 class TargetLibraryInfo;
58 template <> struct FoldingSetTrait<SCEV>;
59 template <> struct FoldingSetTrait<SCEVPredicate>;
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.
64 class SCEV : public FoldingSetNode {
65 friend struct FoldingSetTrait<SCEV>;
67 /// A reference to an Interned FoldingSetNodeID for this node. The
68 /// ScalarEvolution's BumpPtrAllocator holds the data.
69 FoldingSetNodeIDRef FastID;
71 // The SCEV baseclass this node corresponds to
72 const unsigned short SCEVType;
75 /// This field is initialized to zero and may be used in subclasses to store
76 /// miscellaneous information.
77 unsigned short SubclassData;
80 SCEV(const SCEV &) = delete;
81 void operator=(const SCEV &) = delete;
84 /// NoWrapFlags are bitfield indices into SubclassData.
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
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.
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.
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
110 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy)
111 : FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
113 unsigned getSCEVType() const { return SCEVType; }
115 /// Return the LLVM type of this SCEV expression.
117 Type *getType() const;
119 /// Return true if the expression is a constant zero.
123 /// Return true if the expression is a constant one.
127 /// Return true if the expression is a constant all-ones value.
129 bool isAllOnesValue() const;
131 /// Return true if the specified scev is negated, but not a constant.
132 bool isNonConstantNegative() const;
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;
138 /// This method is used for debugging.
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;
151 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
152 return X.FastID.ComputeHash();
156 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
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();
168 /// Methods for support type inquiry through isa, cast, and dyn_cast:
169 static bool classof(const SCEV *S);
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>;
177 /// A reference to an Interned FoldingSetNodeID for this node. The
178 /// ScalarEvolution's BumpPtrAllocator holds the data.
179 FoldingSetNodeIDRef FastID;
182 enum SCEVPredicateKind { P_Union, P_Equal, P_Wrap };
185 SCEVPredicateKind Kind;
186 ~SCEVPredicate() = default;
187 SCEVPredicate(const SCEVPredicate &) = default;
188 SCEVPredicate &operator=(const SCEVPredicate &) = default;
191 SCEVPredicate(const FoldingSetNodeIDRef ID, SCEVPredicateKind Kind);
193 SCEVPredicateKind getKind() const { return Kind; }
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; }
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;
203 /// Returns true if this predicate implies \p N.
204 virtual bool implies(const SCEVPredicate *N) const = 0;
206 /// Prints a textual representation of this predicate with an indentation of
208 virtual void print(raw_ostream &OS, unsigned Depth = 0) const = 0;
210 /// Returns the SCEV to which this predicate applies, or nullptr if this is
211 /// a SCEVUnionPredicate.
212 virtual const SCEV *getExpr() const = 0;
215 inline raw_ostream &operator<<(raw_ostream &OS, const SCEVPredicate &P) {
220 // Specialize FoldingSetTrait for SCEVPredicate to avoid needing to compute
221 // temporary FoldingSetNodeID values.
223 struct FoldingSetTrait<SCEVPredicate> : DefaultFoldingSetTrait<SCEVPredicate> {
225 static void Profile(const SCEVPredicate &X, FoldingSetNodeID &ID) {
229 static bool Equals(const SCEVPredicate &X, const FoldingSetNodeID &ID,
230 unsigned IDHash, FoldingSetNodeID &TempID) {
231 return ID == X.FastID;
233 static unsigned ComputeHash(const SCEVPredicate &X,
234 FoldingSetNodeID &TempID) {
235 return X.FastID.ComputeHash();
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
245 const SCEVUnknown *LHS;
246 const SCEVConstant *RHS;
249 SCEVEqualPredicate(const FoldingSetNodeIDRef ID, const SCEVUnknown *LHS,
250 const SCEVConstant *RHS);
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;
258 /// Returns the left hand side of the equality.
259 const SCEVUnknown *getLHS() const { return LHS; }
261 /// Returns the right hand side of the equality.
262 const SCEVConstant *getRHS() const { return RHS; }
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;
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).
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 {
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)
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:
293 /// 0 <= Unsigned(a) + Signed(b) < 2^n
295 /// The IncrementNSSW flag has identical semantics with SCEV::FlagNSW.
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
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);
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!");
327 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags & Mask);
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!");
337 return (SCEVWrapPredicate::IncrementWrapFlags)(Flags | OnFlags);
340 /// Returns the set of SCEVWrapPredicate no wrap flags implied by a
342 LLVM_NODISCARD static SCEVWrapPredicate::IncrementWrapFlags
343 getImpliedFlags(const SCEVAddRecExpr *AR, ScalarEvolution &SE);
346 const SCEVAddRecExpr *AR;
347 IncrementWrapFlags Flags;
350 explicit SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
351 const SCEVAddRecExpr *AR,
352 IncrementWrapFlags Flags);
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;
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;
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.
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 {
376 typedef DenseMap<const SCEV *, SmallVector<const SCEVPredicate *, 4>>
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;
385 SCEVUnionPredicate();
387 const SmallVectorImpl<const SCEVPredicate *> &getPredicates() const {
391 /// Adds a predicate to this union.
392 void add(const SCEVPredicate *N);
394 /// Returns a reference to a vector containing all predicates which apply to
396 ArrayRef<const SCEVPredicate *> getPredicatesForExpr(const SCEV *Expr);
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;
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(); }
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;
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
417 class ScalarEvolution {
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.
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.
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,
437 return (SCEV::NoWrapFlags)(Flags & Mask);
439 LLVM_NODISCARD static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
440 SCEV::NoWrapFlags OnFlags) {
441 return (SCEV::NoWrapFlags)(Flags | OnFlags);
443 LLVM_NODISCARD static SCEV::NoWrapFlags
444 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
445 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
449 /// A CallbackVH to arrange for ScalarEvolution to be notified whenever a
450 /// Value is deleted.
451 class SCEVCallbackVH final : public CallbackVH {
453 void deleted() override;
454 void allUsesReplacedWith(Value *New) override;
457 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
460 friend class SCEVCallbackVH;
461 friend class SCEVExpander;
462 friend class SCEVUnknown;
464 /// The function we are analyzing.
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.
474 /// The target library information for the target we are targeting.
476 TargetLibraryInfo &TLI;
478 /// The tracker for @llvm.assume intrinsics in this function.
481 /// The dominator tree.
485 /// The loop information for the function we are currently analyzing.
489 /// This SCEV is used to represent unknown trip counts and things.
490 std::unique_ptr<SCEVCouldNotCompute> CouldNotCompute;
492 /// The typedef for HasRecMap.
494 typedef DenseMap<const SCEV *, bool> HasRecMapType;
496 /// This is a cache to record whether a SCEV contains any scAddRecExpr.
497 HasRecMapType HasRecMap;
499 /// The typedef for ExprValueMap.
501 typedef std::pair<Value *, ConstantInt *> ValueOffsetPair;
502 typedef DenseMap<const SCEV *, SetVector<ValueOffsetPair>> ExprValueMapType;
504 /// ExprValueMap -- This map records the original values from which
505 /// the SCEV expr is generated from.
507 /// We want to represent the mapping as SCEV -> ValueOffsetPair instead
508 /// of SCEV -> Value:
509 /// Suppose we know S1 expands to V1, and
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.
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.
522 /// Note: S->{V, Offset} in the ExprValueMap means S can be expanded
524 ExprValueMapType ExprValueMap;
526 /// The typedef for ValueExprMap.
528 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *>>
531 /// This is a cache of the values we have analyzed so far.
533 ValueExprMapType ValueExprMap;
535 /// Mark predicate values currently being processed by isImpliedCond.
536 SmallPtrSet<Value *, 6> PendingLoopPredicates;
538 /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
539 /// conditions dominating the backedge of a loop.
540 bool WalkingBEDominatingConds;
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;
546 /// Memoized values for the GetMinTrailingZeros
547 DenseMap<const SCEV *, uint32_t> MinTrailingZerosCache;
549 /// Private helper method for the GetMinTrailingZeros method
550 uint32_t GetMinTrailingZerosImpl(const SCEV *S);
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.
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
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
564 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
566 void addPredicate(const SCEVPredicate *P) {
567 assert(!isa<SCEVUnionPredicate>(P) && "Only add leaf predicates here!");
568 Predicates.insert(P);
571 /*implicit*/ ExitLimit(const SCEV *E)
572 : ExactNotTaken(E), MaxNotTaken(E), MaxOrZero(false) {}
575 const SCEV *E, const SCEV *M, bool MaxOrZero,
576 ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
577 : ExactNotTaken(E), MaxNotTaken(M), MaxOrZero(MaxOrZero) {
578 assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
579 !isa<SCEVCouldNotCompute>(MaxNotTaken)) &&
580 "Exact is not allowed to be less precise than Max");
581 for (auto *PredSet : PredSetList)
582 for (auto *P : *PredSet)
586 ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero,
587 const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
588 : ExitLimit(E, M, MaxOrZero, {&PredSet}) {}
590 ExitLimit(const SCEV *E, const SCEV *M, bool MaxOrZero)
591 : ExitLimit(E, M, MaxOrZero, None) {}
593 /// Test whether this ExitLimit contains any computed information, or
594 /// whether it's all SCEVCouldNotCompute values.
595 bool hasAnyInfo() const {
596 return !isa<SCEVCouldNotCompute>(ExactNotTaken) ||
597 !isa<SCEVCouldNotCompute>(MaxNotTaken);
600 /// Test whether this ExitLimit contains all information.
601 bool hasFullInfo() const {
602 return !isa<SCEVCouldNotCompute>(ExactNotTaken);
606 /// Information about the number of times a particular loop exit may be
607 /// reached before exiting the loop.
608 struct ExitNotTakenInfo {
609 PoisoningVH<BasicBlock> ExitingBlock;
610 const SCEV *ExactNotTaken;
611 std::unique_ptr<SCEVUnionPredicate> Predicate;
612 bool hasAlwaysTruePredicate() const {
613 return !Predicate || Predicate->isAlwaysTrue();
616 explicit ExitNotTakenInfo(PoisoningVH<BasicBlock> ExitingBlock,
617 const SCEV *ExactNotTaken,
618 std::unique_ptr<SCEVUnionPredicate> Predicate)
619 : ExitingBlock(ExitingBlock), ExactNotTaken(ExactNotTaken),
620 Predicate(std::move(Predicate)) {}
623 /// Information about the backedge-taken count of a loop. This currently
624 /// includes an exact count and a maximum count.
626 class BackedgeTakenInfo {
627 /// A list of computable exits and their not-taken counts. Loops almost
628 /// never have more than one computable exit.
629 SmallVector<ExitNotTakenInfo, 1> ExitNotTaken;
631 /// The pointer part of \c MaxAndComplete is an expression indicating the
632 /// least maximum backedge-taken count of the loop that is known, or a
633 /// SCEVCouldNotCompute. This expression is only valid if the predicates
634 /// associated with all loop exits are true.
636 /// The integer part of \c MaxAndComplete is a boolean indicating if \c
637 /// ExitNotTaken has an element for every exiting block in the loop.
638 PointerIntPair<const SCEV *, 1> MaxAndComplete;
640 /// True iff the backedge is taken either exactly Max or zero times.
643 /// \name Helper projection functions on \c MaxAndComplete.
645 bool isComplete() const { return MaxAndComplete.getInt(); }
646 const SCEV *getMax() const { return MaxAndComplete.getPointer(); }
650 BackedgeTakenInfo() : MaxAndComplete(nullptr, 0) {}
652 BackedgeTakenInfo(BackedgeTakenInfo &&) = default;
653 BackedgeTakenInfo &operator=(BackedgeTakenInfo &&) = default;
655 typedef std::pair<BasicBlock *, ExitLimit> EdgeExitInfo;
657 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
658 BackedgeTakenInfo(SmallVectorImpl<EdgeExitInfo> &&ExitCounts, bool Complete,
659 const SCEV *MaxCount, bool MaxOrZero);
661 /// Test whether this BackedgeTakenInfo contains any computed information,
662 /// or whether it's all SCEVCouldNotCompute values.
663 bool hasAnyInfo() const {
664 return !ExitNotTaken.empty() || !isa<SCEVCouldNotCompute>(getMax());
667 /// Test whether this BackedgeTakenInfo contains complete information.
668 bool hasFullInfo() const { return isComplete(); }
670 /// Return an expression indicating the exact backedge-taken count of the
671 /// loop if it is known or SCEVCouldNotCompute otherwise. This is the
672 /// number of times the loop header can be guaranteed to execute, minus
675 /// If the SCEV predicate associated with the answer can be different
676 /// from AlwaysTrue, we must add a (non null) Predicates argument.
677 /// The SCEV predicate associated with the answer will be added to
678 /// Predicates. A run-time check needs to be emitted for the SCEV
679 /// predicate in order for the answer to be valid.
681 /// Note that we should always know if we need to pass a predicate
682 /// argument or not from the way the ExitCounts vector was computed.
683 /// If we allowed SCEV predicates to be generated when populating this
684 /// vector, this information can contain them and therefore a
685 /// SCEVPredicate argument should be added to getExact.
686 const SCEV *getExact(ScalarEvolution *SE,
687 SCEVUnionPredicate *Predicates = nullptr) const;
689 /// Return the number of times this loop exit may fall through to the back
690 /// edge, or SCEVCouldNotCompute. The loop is guaranteed not to exit via
691 /// this block before this number of iterations, but may exit via another
693 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
695 /// Get the max backedge taken count for the loop.
696 const SCEV *getMax(ScalarEvolution *SE) const;
698 /// Return true if the number of times this backedge is taken is either the
699 /// value returned by getMax or zero.
700 bool isMaxOrZero(ScalarEvolution *SE) const;
702 /// Return true if any backedge taken count expressions refer to the given
704 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
706 /// Invalidate this result and free associated memory.
710 /// Cache the backedge-taken count of the loops for this function as they
712 DenseMap<const Loop *, BackedgeTakenInfo> BackedgeTakenCounts;
714 /// Cache the predicated backedge-taken count of the loops for this
715 /// function as they are computed.
716 DenseMap<const Loop *, BackedgeTakenInfo> PredicatedBackedgeTakenCounts;
718 /// This map contains entries for all of the PHI instructions that we
719 /// attempt to compute constant evolutions for. This allows us to avoid
720 /// potentially expensive recomputation of these properties. An instruction
721 /// maps to null if we are unable to compute its exit value.
722 DenseMap<PHINode *, Constant *> ConstantEvolutionLoopExitValue;
724 /// This map contains entries for all the expressions that we attempt to
725 /// compute getSCEVAtScope information for, which can be expensive in
727 DenseMap<const SCEV *, SmallVector<std::pair<const Loop *, const SCEV *>, 2>>
730 /// Memoized computeLoopDisposition results.
731 DenseMap<const SCEV *,
732 SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
735 struct LoopProperties {
736 /// Set to true if the loop contains no instruction that can have side
737 /// effects (i.e. via throwing an exception, volatile or atomic access).
738 bool HasNoAbnormalExits;
740 /// Set to true if the loop contains no instruction that can abnormally exit
741 /// the loop (i.e. via throwing an exception, by terminating the thread
742 /// cleanly or by infinite looping in a called function). Strictly
743 /// speaking, the last one is not leaving the loop, but is identical to
744 /// leaving the loop for reasoning about undefined behavior.
745 bool HasNoSideEffects;
748 /// Cache for \c getLoopProperties.
749 DenseMap<const Loop *, LoopProperties> LoopPropertiesCache;
751 /// Return a \c LoopProperties instance for \p L, creating one if necessary.
752 LoopProperties getLoopProperties(const Loop *L);
754 bool loopHasNoSideEffects(const Loop *L) {
755 return getLoopProperties(L).HasNoSideEffects;
758 bool loopHasNoAbnormalExits(const Loop *L) {
759 return getLoopProperties(L).HasNoAbnormalExits;
762 /// Compute a LoopDisposition value.
763 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
765 /// Memoized computeBlockDisposition results.
768 SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
771 /// Compute a BlockDisposition value.
772 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
774 /// Memoized results from getRange
775 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
777 /// Memoized results from getRange
778 DenseMap<const SCEV *, ConstantRange> SignedRanges;
780 /// Used to parameterize getRange
781 enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
783 /// Set the memoized range for the given SCEV.
784 const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
785 const ConstantRange &CR) {
786 DenseMap<const SCEV *, ConstantRange> &Cache =
787 Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
789 auto Pair = Cache.insert({S, CR});
791 Pair.first->second = CR;
792 return Pair.first->second;
795 /// Determine the range for a particular SCEV.
796 ConstantRange getRange(const SCEV *S, RangeSignHint Hint);
798 /// Determines the range for the affine SCEVAddRecExpr {\p Start,+,\p Stop}.
799 /// Helper for \c getRange.
800 ConstantRange getRangeForAffineAR(const SCEV *Start, const SCEV *Stop,
801 const SCEV *MaxBECount, unsigned BitWidth);
803 /// Try to compute a range for the affine SCEVAddRecExpr {\p Start,+,\p
804 /// Stop} by "factoring out" a ternary expression from the add recurrence.
805 /// Helper called by \c getRange.
806 ConstantRange getRangeViaFactoring(const SCEV *Start, const SCEV *Stop,
807 const SCEV *MaxBECount, unsigned BitWidth);
809 /// We know that there is no SCEV for the specified value. Analyze the
811 const SCEV *createSCEV(Value *V);
813 /// Provide the special handling we need to analyze PHI SCEVs.
814 const SCEV *createNodeForPHI(PHINode *PN);
816 /// Helper function called from createNodeForPHI.
817 const SCEV *createAddRecFromPHI(PHINode *PN);
819 /// Helper function called from createNodeForPHI.
820 const SCEV *createNodeFromSelectLikePHI(PHINode *PN);
822 /// Provide special handling for a select-like instruction (currently this
823 /// is either a select instruction or a phi node). \p I is the instruction
824 /// being processed, and it is assumed equivalent to "Cond ? TrueVal :
826 const SCEV *createNodeForSelectOrPHI(Instruction *I, Value *Cond,
827 Value *TrueVal, Value *FalseVal);
829 /// Provide the special handling we need to analyze GEP SCEVs.
830 const SCEV *createNodeForGEP(GEPOperator *GEP);
832 /// Implementation code for getSCEVAtScope; called at most once for each
835 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
837 /// This looks up computed SCEV values for all instructions that depend on
838 /// the given instruction and removes them from the ValueExprMap map if they
839 /// reference SymName. This is used during PHI resolution.
840 void forgetSymbolicName(Instruction *I, const SCEV *SymName);
842 /// Return the BackedgeTakenInfo for the given loop, lazily computing new
843 /// values if the loop hasn't been analyzed yet. The returned result is
844 /// guaranteed not to be predicated.
845 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
847 /// Similar to getBackedgeTakenInfo, but will add predicates as required
848 /// with the purpose of returning complete information.
849 const BackedgeTakenInfo &getPredicatedBackedgeTakenInfo(const Loop *L);
851 /// Compute the number of times the specified loop will iterate.
852 /// If AllowPredicates is set, we will create new SCEV predicates as
853 /// necessary in order to return an exact answer.
854 BackedgeTakenInfo computeBackedgeTakenCount(const Loop *L,
855 bool AllowPredicates = false);
857 /// Compute the number of times the backedge of the specified loop will
858 /// execute if it exits via the specified block. If AllowPredicates is set,
859 /// this call will try to use a minimal set of SCEV predicates in order to
860 /// return an exact answer.
861 ExitLimit computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
862 bool AllowPredicates = false);
864 /// Compute the number of times the backedge of the specified loop will
865 /// execute if its exit condition were a conditional branch of ExitCond,
868 /// \p ControlsExit is true if ExitCond directly controls the exit
869 /// branch. In this case, we can assume that the loop exits only if the
870 /// condition is true and can infer that failing to meet the condition prior
871 /// to integer wraparound results in undefined behavior.
873 /// If \p AllowPredicates is set, this call will try to use a minimal set of
874 /// SCEV predicates in order to return an exact answer.
875 ExitLimit computeExitLimitFromCond(const Loop *L, Value *ExitCond,
876 BasicBlock *TBB, BasicBlock *FBB,
878 bool AllowPredicates = false);
880 /// Compute the number of times the backedge of the specified loop will
881 /// execute if its exit condition were a conditional branch of the ICmpInst
882 /// ExitCond, TBB, and FBB. If AllowPredicates is set, this call will try
883 /// to use a minimal set of SCEV predicates in order to return an exact
885 ExitLimit computeExitLimitFromICmp(const Loop *L, ICmpInst *ExitCond,
886 BasicBlock *TBB, BasicBlock *FBB,
888 bool AllowPredicates = false);
890 /// Compute the number of times the backedge of the specified loop will
891 /// execute if its exit condition were a switch with a single exiting case
893 ExitLimit computeExitLimitFromSingleExitSwitch(const Loop *L,
895 BasicBlock *ExitingBB,
898 /// Given an exit condition of 'icmp op load X, cst', try to see if we can
899 /// compute the backedge-taken count.
900 ExitLimit computeLoadConstantCompareExitLimit(LoadInst *LI, Constant *RHS,
902 ICmpInst::Predicate p);
904 /// Compute the exit limit of a loop that is controlled by a
905 /// "(IV >> 1) != 0" type comparison. We cannot compute the exact trip
906 /// count in these cases (since SCEV has no way of expressing them), but we
907 /// can still sometimes compute an upper bound.
909 /// Return an ExitLimit for a loop whose backedge is guarded by `LHS Pred
911 ExitLimit computeShiftCompareExitLimit(Value *LHS, Value *RHS, const Loop *L,
912 ICmpInst::Predicate Pred);
914 /// If the loop is known to execute a constant number of times (the
915 /// condition evolves only from constants), try to evaluate a few iterations
916 /// of the loop until we get the exit condition gets a value of ExitWhen
917 /// (true or false). If we cannot evaluate the exit count of the loop,
918 /// return CouldNotCompute.
919 const SCEV *computeExitCountExhaustively(const Loop *L, Value *Cond,
922 /// Return the number of times an exit condition comparing the specified
923 /// value to zero will execute. If not computable, return CouldNotCompute.
924 /// If AllowPredicates is set, this call will try to use a minimal set of
925 /// SCEV predicates in order to return an exact answer.
926 ExitLimit howFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr,
927 bool AllowPredicates = false);
929 /// Return the number of times an exit condition checking the specified
930 /// value for nonzero will execute. If not computable, return
932 ExitLimit howFarToNonZero(const SCEV *V, const Loop *L);
934 /// Return the number of times an exit condition containing the specified
935 /// less-than comparison will execute. If not computable, return
938 /// \p isSigned specifies whether the less-than is signed.
940 /// \p ControlsExit is true when the LHS < RHS condition directly controls
941 /// the branch (loops exits only if condition is true). In this case, we can
942 /// use NoWrapFlags to skip overflow checks.
944 /// If \p AllowPredicates is set, this call will try to use a minimal set of
945 /// SCEV predicates in order to return an exact answer.
946 ExitLimit howManyLessThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
947 bool isSigned, bool ControlsExit,
948 bool AllowPredicates = false);
950 ExitLimit howManyGreaterThans(const SCEV *LHS, const SCEV *RHS, const Loop *L,
951 bool isSigned, bool IsSubExpr,
952 bool AllowPredicates = false);
954 /// Return a predecessor of BB (which may not be an immediate predecessor)
955 /// which has exactly one successor from which BB is reachable, or null if
956 /// no such block is found.
957 std::pair<BasicBlock *, BasicBlock *>
958 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
960 /// Test whether the condition described by Pred, LHS, and RHS is true
961 /// whenever the given FoundCondValue value evaluates to true.
962 bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
963 Value *FoundCondValue, bool Inverse);
965 /// Test whether the condition described by Pred, LHS, and RHS is true
966 /// whenever the condition described by FoundPred, FoundLHS, FoundRHS is
968 bool isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
969 ICmpInst::Predicate FoundPred, const SCEV *FoundLHS,
970 const SCEV *FoundRHS);
972 /// Test whether the condition described by Pred, LHS, and RHS is true
973 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
975 bool isImpliedCondOperands(ICmpInst::Predicate Pred, const SCEV *LHS,
976 const SCEV *RHS, const SCEV *FoundLHS,
977 const SCEV *FoundRHS);
979 /// Test whether the condition described by Pred, LHS, and RHS is true
980 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
981 /// true. Here LHS is an operation that includes FoundLHS as one of its
983 bool isImpliedViaOperations(ICmpInst::Predicate Pred,
984 const SCEV *LHS, const SCEV *RHS,
985 const SCEV *FoundLHS, const SCEV *FoundRHS,
988 /// Test whether the condition described by Pred, LHS, and RHS is true.
989 /// Use only simple non-recursive types of checks, such as range analysis etc.
990 bool isKnownViaSimpleReasoning(ICmpInst::Predicate Pred,
991 const SCEV *LHS, const SCEV *RHS);
993 /// Test whether the condition described by Pred, LHS, and RHS is true
994 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
996 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, const SCEV *LHS,
997 const SCEV *RHS, const SCEV *FoundLHS,
998 const SCEV *FoundRHS);
1000 /// Test whether the condition described by Pred, LHS, and RHS is true
1001 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1002 /// true. Utility function used by isImpliedCondOperands. Tries to get
1003 /// cases like "X `sgt` 0 => X - 1 `sgt` -1".
1004 bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred, const SCEV *LHS,
1005 const SCEV *RHS, const SCEV *FoundLHS,
1006 const SCEV *FoundRHS);
1008 /// Return true if the condition denoted by \p LHS \p Pred \p RHS is implied
1009 /// by a call to \c @llvm.experimental.guard in \p BB.
1010 bool isImpliedViaGuard(BasicBlock *BB, ICmpInst::Predicate Pred,
1011 const SCEV *LHS, const SCEV *RHS);
1013 /// Test whether the condition described by Pred, LHS, and RHS is true
1014 /// whenever the condition described by Pred, FoundLHS, and FoundRHS is
1017 /// This routine tries to rule out certain kinds of integer overflow, and
1018 /// then tries to reason about arithmetic properties of the predicates.
1019 bool isImpliedCondOperandsViaNoOverflow(ICmpInst::Predicate Pred,
1020 const SCEV *LHS, const SCEV *RHS,
1021 const SCEV *FoundLHS,
1022 const SCEV *FoundRHS);
1024 /// If we know that the specified Phi is in the header of its containing
1025 /// loop, we know the loop executes a constant number of times, and the PHI
1026 /// node is just a recurrence involving constants, fold it.
1027 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt &BEs,
1030 /// Test if the given expression is known to satisfy the condition described
1031 /// by Pred and the known constant ranges of LHS and RHS.
1033 bool isKnownPredicateViaConstantRanges(ICmpInst::Predicate Pred,
1034 const SCEV *LHS, const SCEV *RHS);
1036 /// Try to prove the condition described by "LHS Pred RHS" by ruling out
1037 /// integer overflow.
1039 /// For instance, this will return true for "A s< (A + C)<nsw>" if C is
1041 bool isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred, const SCEV *LHS,
1044 /// Try to split Pred LHS RHS into logical conjunctions (and's) and try to
1045 /// prove them individually.
1046 bool isKnownPredicateViaSplitting(ICmpInst::Predicate Pred, const SCEV *LHS,
1049 /// Try to match the Expr as "(L + R)<Flags>".
1050 bool splitBinaryAdd(const SCEV *Expr, const SCEV *&L, const SCEV *&R,
1051 SCEV::NoWrapFlags &Flags);
1053 /// Compute \p LHS - \p RHS and returns the result as an APInt if it is a
1054 /// constant, and None if it isn't.
1056 /// This is intended to be a cheaper version of getMinusSCEV. We can be
1057 /// frugal here since we just bail out of actually constructing and
1058 /// canonicalizing an expression in the cases where the result isn't going
1059 /// to be a constant.
1060 Optional<APInt> computeConstantDifference(const SCEV *LHS, const SCEV *RHS);
1062 /// Drop memoized information computed for S.
1063 void forgetMemoizedResults(const SCEV *S);
1065 /// Return an existing SCEV for V if there is one, otherwise return nullptr.
1066 const SCEV *getExistingSCEV(Value *V);
1068 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
1070 bool checkValidity(const SCEV *S) const;
1072 /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
1073 /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
1074 /// equivalent to proving no signed (resp. unsigned) wrap in
1075 /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
1076 /// (resp. `SCEVZeroExtendExpr`).
1078 template <typename ExtendOpTy>
1079 bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
1082 /// Try to prove NSW or NUW on \p AR relying on ConstantRange manipulation.
1083 SCEV::NoWrapFlags proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR);
1085 bool isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
1086 ICmpInst::Predicate Pred, bool &Increasing);
1088 /// Return SCEV no-wrap flags that can be proven based on reasoning about
1089 /// how poison produced from no-wrap flags on this value (e.g. a nuw add)
1090 /// would trigger undefined behavior on overflow.
1091 SCEV::NoWrapFlags getNoWrapFlagsFromUB(const Value *V);
1093 /// Return true if the SCEV corresponding to \p I is never poison. Proving
1094 /// this is more complex than proving that just \p I is never poison, since
1095 /// SCEV commons expressions across control flow, and you can have cases
1099 /// ptr[idx0] = 100;
1100 /// if (<condition>) {
1101 /// idx1 = a +nsw b;
1102 /// ptr[idx1] = 200;
1105 /// where the SCEV expression (+ a b) is guaranteed to not be poison (and
1106 /// hence not sign-overflow) only if "<condition>" is true. Since both
1107 /// `idx0` and `idx1` will be mapped to the same SCEV expression, (+ a b),
1108 /// it is not okay to annotate (+ a b) with <nsw> in the above example.
1109 bool isSCEVExprNeverPoison(const Instruction *I);
1111 /// This is like \c isSCEVExprNeverPoison but it specifically works for
1112 /// instructions that will get mapped to SCEV add recurrences. Return true
1113 /// if \p I will never generate poison under the assumption that \p I is an
1114 /// add recurrence on the loop \p L.
1115 bool isAddRecNeverPoison(const Instruction *I, const Loop *L);
1118 ScalarEvolution(Function &F, TargetLibraryInfo &TLI, AssumptionCache &AC,
1119 DominatorTree &DT, LoopInfo &LI);
1121 ScalarEvolution(ScalarEvolution &&Arg);
1123 LLVMContext &getContext() const { return F.getContext(); }
1125 /// Test if values of the given type are analyzable within the SCEV
1126 /// framework. This primarily includes integer types, and it can optionally
1127 /// include pointer types if the ScalarEvolution class has access to
1128 /// target-specific information.
1129 bool isSCEVable(Type *Ty) const;
1131 /// Return the size in bits of the specified type, for which isSCEVable must
1133 uint64_t getTypeSizeInBits(Type *Ty) const;
1135 /// Return a type with the same bitwidth as the given type and which
1136 /// represents how SCEV will treat the given type, for which isSCEVable must
1137 /// return true. For pointer types, this is the pointer-sized integer type.
1138 Type *getEffectiveSCEVType(Type *Ty) const;
1140 // Returns a wider type among {Ty1, Ty2}.
1141 Type *getWiderType(Type *Ty1, Type *Ty2) const;
1143 /// Return true if the SCEV is a scAddRecExpr or it contains
1144 /// scAddRecExpr. The result will be cached in HasRecMap.
1146 bool containsAddRecurrence(const SCEV *S);
1148 /// Return the Value set from which the SCEV expr is generated.
1149 SetVector<ValueOffsetPair> *getSCEVValues(const SCEV *S);
1151 /// Erase Value from ValueExprMap and ExprValueMap.
1152 void eraseValueFromMap(Value *V);
1154 /// Return a SCEV expression for the full generality of the specified
1156 const SCEV *getSCEV(Value *V);
1158 const SCEV *getConstant(ConstantInt *V);
1159 const SCEV *getConstant(const APInt &Val);
1160 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
1161 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
1163 typedef SmallDenseMap<std::pair<const SCEV *, Type *>, const SCEV *, 8>
1165 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
1166 const SCEV *getZeroExtendExprCached(const SCEV *Op, Type *Ty,
1167 ExtendCacheTy &Cache);
1168 const SCEV *getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
1169 ExtendCacheTy &Cache);
1171 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
1172 const SCEV *getSignExtendExprCached(const SCEV *Op, Type *Ty,
1173 ExtendCacheTy &Cache);
1174 const SCEV *getSignExtendExprImpl(const SCEV *Op, Type *Ty,
1175 ExtendCacheTy &Cache);
1176 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
1177 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1178 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap,
1179 unsigned Depth = 0);
1180 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
1181 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
1182 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
1183 return getAddExpr(Ops, Flags);
1185 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
1186 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
1187 SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
1188 return getAddExpr(Ops, Flags);
1190 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
1191 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
1192 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
1193 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
1194 SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
1195 return getMulExpr(Ops, Flags);
1197 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
1198 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
1199 SmallVector<const SCEV *, 3> Ops = {Op0, Op1, Op2};
1200 return getMulExpr(Ops, Flags);
1202 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
1203 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
1204 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L,
1205 SCEV::NoWrapFlags Flags);
1206 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
1207 const Loop *L, SCEV::NoWrapFlags Flags);
1208 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
1209 const Loop *L, SCEV::NoWrapFlags Flags) {
1210 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
1211 return getAddRecExpr(NewOp, L, Flags);
1213 /// Returns an expression for a GEP
1215 /// \p GEP The GEP. The indices contained in the GEP itself are ignored,
1216 /// instead we use IndexExprs.
1217 /// \p IndexExprs The expressions for the indices.
1218 const SCEV *getGEPExpr(GEPOperator *GEP,
1219 const SmallVectorImpl<const SCEV *> &IndexExprs);
1220 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
1221 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
1222 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
1223 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
1224 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
1225 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
1226 const SCEV *getUnknown(Value *V);
1227 const SCEV *getCouldNotCompute();
1229 /// Return a SCEV for the constant 0 of a specific type.
1230 const SCEV *getZero(Type *Ty) { return getConstant(Ty, 0); }
1232 /// Return a SCEV for the constant 1 of a specific type.
1233 const SCEV *getOne(Type *Ty) { return getConstant(Ty, 1); }
1235 /// Return an expression for sizeof AllocTy that is type IntTy
1237 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
1239 /// Return an expression for offsetof on the given field with type IntTy
1241 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
1243 /// Return the SCEV object corresponding to -V.
1245 const SCEV *getNegativeSCEV(const SCEV *V,
1246 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
1248 /// Return the SCEV object corresponding to ~V.
1250 const SCEV *getNotSCEV(const SCEV *V);
1252 /// Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
1253 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
1254 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
1256 /// Return a SCEV corresponding to a conversion of the input value to the
1257 /// specified type. If the type must be extended, it is zero extended.
1258 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
1260 /// Return a SCEV corresponding to a conversion of the input value to the
1261 /// specified type. If the type must be extended, it is sign extended.
1262 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
1264 /// Return a SCEV corresponding to a conversion of the input value to the
1265 /// specified type. If the type must be extended, it is zero extended. The
1266 /// conversion must not be narrowing.
1267 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
1269 /// Return a SCEV corresponding to a conversion of the input value to the
1270 /// specified type. If the type must be extended, it is sign extended. The
1271 /// conversion must not be narrowing.
1272 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
1274 /// Return a SCEV corresponding to a conversion of the input value to the
1275 /// specified type. If the type must be extended, it is extended with
1276 /// unspecified bits. The conversion must not be narrowing.
1277 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
1279 /// Return a SCEV corresponding to a conversion of the input value to the
1280 /// specified type. The conversion must not be widening.
1281 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
1283 /// Promote the operands to the wider of the types using zero-extension, and
1284 /// then perform a umax operation with them.
1285 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
1287 /// Promote the operands to the wider of the types using zero-extension, and
1288 /// then perform a umin operation with them.
1289 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS);
1291 /// Transitively follow the chain of pointer-type operands until reaching a
1292 /// SCEV that does not have a single pointer operand. This returns a
1293 /// SCEVUnknown pointer for well-formed pointer-type expressions, but corner
1295 const SCEV *getPointerBase(const SCEV *V);
1297 /// Return a SCEV expression for the specified value at the specified scope
1298 /// in the program. The L value specifies a loop nest to evaluate the
1299 /// expression at, where null is the top-level or a specified loop is
1300 /// immediately inside of the loop.
1302 /// This method can be used to compute the exit value for a variable defined
1303 /// in a loop by querying what the value will hold in the parent loop.
1305 /// In the case that a relevant loop exit value cannot be computed, the
1306 /// original value V is returned.
1307 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
1309 /// This is a convenience function which does getSCEVAtScope(getSCEV(V), L).
1310 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
1312 /// Test whether entry to the loop is protected by a conditional between LHS
1313 /// and RHS. This is used to help avoid max expressions in loop trip
1314 /// counts, and to eliminate casts.
1315 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1316 const SCEV *LHS, const SCEV *RHS);
1318 /// Test whether the backedge of the loop is protected by a conditional
1319 /// between LHS and RHS. This is used to to eliminate casts.
1320 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
1321 const SCEV *LHS, const SCEV *RHS);
1323 /// Returns the maximum trip count of the loop if it is a single-exit
1324 /// loop and we can compute a small maximum for that loop.
1326 /// Implemented in terms of the \c getSmallConstantTripCount overload with
1327 /// the single exiting block passed to it. See that routine for details.
1328 unsigned getSmallConstantTripCount(const Loop *L);
1330 /// Returns the maximum trip count of this loop as a normal unsigned
1331 /// value. Returns 0 if the trip count is unknown or not constant. This
1332 /// "trip count" assumes that control exits via ExitingBlock. More
1333 /// precisely, it is the number of times that control may reach ExitingBlock
1334 /// before taking the branch. For loops with multiple exits, it may not be
1335 /// the number times that the loop header executes if the loop exits
1336 /// prematurely via another branch.
1337 unsigned getSmallConstantTripCount(const Loop *L, BasicBlock *ExitingBlock);
1339 /// Returns the upper bound of the loop trip count as a normal unsigned
1341 /// Returns 0 if the trip count is unknown or not constant.
1342 unsigned getSmallConstantMaxTripCount(const Loop *L);
1344 /// Returns the largest constant divisor of the trip count of the
1345 /// loop if it is a single-exit loop and we can compute a small maximum for
1348 /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
1349 /// the single exiting block passed to it. See that routine for details.
1350 unsigned getSmallConstantTripMultiple(const Loop *L);
1352 /// Returns the largest constant divisor of the trip count of this loop as a
1353 /// normal unsigned value, if possible. This means that the actual trip
1354 /// count is always a multiple of the returned value (don't forget the trip
1355 /// count could very well be zero as well!). As explained in the comments
1356 /// for getSmallConstantTripCount, this assumes that control exits the loop
1357 /// via ExitingBlock.
1358 unsigned getSmallConstantTripMultiple(const Loop *L,
1359 BasicBlock *ExitingBlock);
1361 /// Get the expression for the number of loop iterations for which this loop
1362 /// is guaranteed not to exit via ExitingBlock. Otherwise return
1363 /// SCEVCouldNotCompute.
1364 const SCEV *getExitCount(const Loop *L, BasicBlock *ExitingBlock);
1366 /// If the specified loop has a predictable backedge-taken count, return it,
1367 /// otherwise return a SCEVCouldNotCompute object. The backedge-taken count
1368 /// is the number of times the loop header will be branched to from within
1369 /// the loop. This is one less than the trip count of the loop, since it
1370 /// doesn't count the first iteration, when the header is branched to from
1371 /// outside the loop.
1373 /// Note that it is not valid to call this method on a loop without a
1374 /// loop-invariant backedge-taken count (see
1375 /// hasLoopInvariantBackedgeTakenCount).
1377 const SCEV *getBackedgeTakenCount(const Loop *L);
1379 /// Similar to getBackedgeTakenCount, except it will add a set of
1380 /// SCEV predicates to Predicates that are required to be true in order for
1381 /// the answer to be correct. Predicates can be checked with run-time
1382 /// checks and can be used to perform loop versioning.
1383 const SCEV *getPredicatedBackedgeTakenCount(const Loop *L,
1384 SCEVUnionPredicate &Predicates);
1386 /// Similar to getBackedgeTakenCount, except return the least SCEV value
1387 /// that is known never to be less than the actual backedge taken count.
1388 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
1390 /// Return true if the backedge taken count is either the value returned by
1391 /// getMaxBackedgeTakenCount or zero.
1392 bool isBackedgeTakenCountMaxOrZero(const Loop *L);
1394 /// Return true if the specified loop has an analyzable loop-invariant
1395 /// backedge-taken count.
1396 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
1398 /// This method should be called by the client when it has changed a loop in
1399 /// a way that may effect ScalarEvolution's ability to compute a trip count,
1400 /// or if the loop is deleted. This call is potentially expensive for large
1402 void forgetLoop(const Loop *L);
1404 /// This method should be called by the client when it has changed a value
1405 /// in a way that may effect its value, or which may disconnect it from a
1406 /// def-use chain linking it to a loop.
1407 void forgetValue(Value *V);
1409 /// Called when the client has changed the disposition of values in
1412 /// We don't have a way to invalidate per-loop dispositions. Clear and
1413 /// recompute is simpler.
1414 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
1416 /// Determine the minimum number of zero bits that S is guaranteed to end in
1417 /// (at every loop iteration). It is, at the same time, the minimum number
1418 /// of times S is divisible by 2. For example, given {4,+,8} it returns 2.
1419 /// If S is guaranteed to be 0, it returns the bitwidth of S.
1420 uint32_t GetMinTrailingZeros(const SCEV *S);
1422 /// Determine the unsigned range for a particular SCEV.
1424 ConstantRange getUnsignedRange(const SCEV *S) {
1425 return getRange(S, HINT_RANGE_UNSIGNED);
1428 /// Determine the signed range for a particular SCEV.
1430 ConstantRange getSignedRange(const SCEV *S) {
1431 return getRange(S, HINT_RANGE_SIGNED);
1434 /// Test if the given expression is known to be negative.
1436 bool isKnownNegative(const SCEV *S);
1438 /// Test if the given expression is known to be positive.
1440 bool isKnownPositive(const SCEV *S);
1442 /// Test if the given expression is known to be non-negative.
1444 bool isKnownNonNegative(const SCEV *S);
1446 /// Test if the given expression is known to be non-positive.
1448 bool isKnownNonPositive(const SCEV *S);
1450 /// Test if the given expression is known to be non-zero.
1452 bool isKnownNonZero(const SCEV *S);
1454 /// Test if the given expression is known to satisfy the condition described
1455 /// by Pred, LHS, and RHS.
1457 bool isKnownPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
1460 /// Return true if, for all loop invariant X, the predicate "LHS `Pred` X"
1461 /// is monotonically increasing or decreasing. In the former case set
1462 /// `Increasing` to true and in the latter case set `Increasing` to false.
1464 /// A predicate is said to be monotonically increasing if may go from being
1465 /// false to being true as the loop iterates, but never the other way
1466 /// around. A predicate is said to be monotonically decreasing if may go
1467 /// from being true to being false as the loop iterates, but never the other
1469 bool isMonotonicPredicate(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred,
1472 /// Return true if the result of the predicate LHS `Pred` RHS is loop
1473 /// invariant with respect to L. Set InvariantPred, InvariantLHS and
1474 /// InvariantLHS so that InvariantLHS `InvariantPred` InvariantRHS is the
1475 /// loop invariant form of LHS `Pred` RHS.
1476 bool isLoopInvariantPredicate(ICmpInst::Predicate Pred, const SCEV *LHS,
1477 const SCEV *RHS, const Loop *L,
1478 ICmpInst::Predicate &InvariantPred,
1479 const SCEV *&InvariantLHS,
1480 const SCEV *&InvariantRHS);
1482 /// Simplify LHS and RHS in a comparison with predicate Pred. Return true
1483 /// iff any changes were made. If the operands are provably equal or
1484 /// unequal, LHS and RHS are set to the same value and Pred is set to either
1485 /// ICMP_EQ or ICMP_NE.
1487 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, const SCEV *&LHS,
1488 const SCEV *&RHS, unsigned Depth = 0);
1490 /// Return the "disposition" of the given SCEV with respect to the given
1492 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
1494 /// Return true if the value of the given SCEV is unchanging in the
1496 bool isLoopInvariant(const SCEV *S, const Loop *L);
1498 /// Return true if the given SCEV changes value in a known way in the
1499 /// specified loop. This property being true implies that the value is
1500 /// variant in the loop AND that we can emit an expression to compute the
1501 /// value of the expression at any particular loop iteration.
1502 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
1504 /// Return the "disposition" of the given SCEV with respect to the given
1506 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
1508 /// Return true if elements that makes up the given SCEV dominate the
1509 /// specified basic block.
1510 bool dominates(const SCEV *S, const BasicBlock *BB);
1512 /// Return true if elements that makes up the given SCEV properly dominate
1513 /// the specified basic block.
1514 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
1516 /// Test whether the given SCEV has Op as a direct or indirect operand.
1517 bool hasOperand(const SCEV *S, const SCEV *Op) const;
1519 /// Return the size of an element read or written by Inst.
1520 const SCEV *getElementSize(Instruction *Inst);
1522 /// Compute the array dimensions Sizes from the set of Terms extracted from
1523 /// the memory access function of this SCEVAddRecExpr (second step of
1524 /// delinearization).
1525 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
1526 SmallVectorImpl<const SCEV *> &Sizes,
1527 const SCEV *ElementSize) const;
1529 void print(raw_ostream &OS) const;
1530 void verify() const;
1531 bool invalidate(Function &F, const PreservedAnalyses &PA,
1532 FunctionAnalysisManager::Invalidator &Inv);
1534 /// Collect parametric terms occurring in step expressions (first step of
1535 /// delinearization).
1536 void collectParametricTerms(const SCEV *Expr,
1537 SmallVectorImpl<const SCEV *> &Terms);
1539 /// Return in Subscripts the access functions for each dimension in Sizes
1540 /// (third step of delinearization).
1541 void computeAccessFunctions(const SCEV *Expr,
1542 SmallVectorImpl<const SCEV *> &Subscripts,
1543 SmallVectorImpl<const SCEV *> &Sizes);
1545 /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
1546 /// subscripts and sizes of an array access.
1548 /// The delinearization is a 3 step process: the first two steps compute the
1549 /// sizes of each subscript and the third step computes the access functions
1550 /// for the delinearized array:
1552 /// 1. Find the terms in the step functions
1553 /// 2. Compute the array size
1554 /// 3. Compute the access function: divide the SCEV by the array size
1555 /// starting with the innermost dimensions found in step 2. The Quotient
1556 /// is the SCEV to be divided in the next step of the recursion. The
1557 /// Remainder is the subscript of the innermost dimension. Loop over all
1558 /// array dimensions computed in step 2.
1560 /// To compute a uniform array size for several memory accesses to the same
1561 /// object, one can collect in step 1 all the step terms for all the memory
1562 /// accesses, and compute in step 2 a unique array shape. This guarantees
1563 /// that the array shape will be the same across all memory accesses.
1565 /// FIXME: We could derive the result of steps 1 and 2 from a description of
1566 /// the array shape given in metadata.
1575 /// A[j+k][2i][5i] =
1577 /// The initial SCEV:
1579 /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1581 /// 1. Find the different terms in the step functions:
1582 /// -> [2*m, 5, n*m, n*m]
1584 /// 2. Compute the array size: sort and unique them
1585 /// -> [n*m, 2*m, 5]
1586 /// find the GCD of all the terms = 1
1587 /// divide by the GCD and erase constant terms
1590 /// divide by GCD -> [n, 2]
1591 /// remove constant terms
1593 /// size of the array is A[unknown][n][m]
1595 /// 3. Compute the access function
1596 /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1597 /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1598 /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1599 /// The remainder is the subscript of the innermost array dimension: [5i].
1601 /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1602 /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1603 /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1604 /// The Remainder is the subscript of the next array dimension: [2i].
1606 /// The subscript of the outermost dimension is the Quotient: [j+k].
1608 /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1609 void delinearize(const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
1610 SmallVectorImpl<const SCEV *> &Sizes,
1611 const SCEV *ElementSize);
1613 /// Return the DataLayout associated with the module this SCEV instance is
1615 const DataLayout &getDataLayout() const {
1616 return F.getParent()->getDataLayout();
1619 const SCEVPredicate *getEqualPredicate(const SCEVUnknown *LHS,
1620 const SCEVConstant *RHS);
1622 const SCEVPredicate *
1623 getWrapPredicate(const SCEVAddRecExpr *AR,
1624 SCEVWrapPredicate::IncrementWrapFlags AddedFlags);
1626 /// Re-writes the SCEV according to the Predicates in \p A.
1627 const SCEV *rewriteUsingPredicate(const SCEV *S, const Loop *L,
1628 SCEVUnionPredicate &A);
1629 /// Tries to convert the \p S expression to an AddRec expression,
1630 /// adding additional predicates to \p Preds as required.
1631 const SCEVAddRecExpr *convertSCEVToAddRecWithPredicates(
1632 const SCEV *S, const Loop *L,
1633 SmallPtrSetImpl<const SCEVPredicate *> &Preds);
1636 /// Compute the backedge taken count knowing the interval difference, the
1637 /// stride and presence of the equality in the comparison.
1638 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1641 /// Verify if an linear IV with positive stride can overflow when in a
1642 /// less-than comparison, knowing the invariant term of the comparison,
1643 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1644 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1647 /// Verify if an linear IV with negative stride can overflow when in a
1648 /// greater-than comparison, knowing the invariant term of the comparison,
1649 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1650 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, bool IsSigned,
1653 /// Get add expr already created or create a new one
1654 const SCEV *getOrCreateAddExpr(SmallVectorImpl<const SCEV *> &Ops,
1655 SCEV::NoWrapFlags Flags);
1658 FoldingSet<SCEV> UniqueSCEVs;
1659 FoldingSet<SCEVPredicate> UniquePreds;
1660 BumpPtrAllocator SCEVAllocator;
1662 /// The head of a linked list of all SCEVUnknown values that have been
1663 /// allocated. This is used by releaseMemory to locate them all and call
1664 /// their destructors.
1665 SCEVUnknown *FirstUnknown;
1668 /// Analysis pass that exposes the \c ScalarEvolution for a function.
1669 class ScalarEvolutionAnalysis
1670 : public AnalysisInfoMixin<ScalarEvolutionAnalysis> {
1671 friend AnalysisInfoMixin<ScalarEvolutionAnalysis>;
1672 static AnalysisKey Key;
1675 typedef ScalarEvolution Result;
1677 ScalarEvolution run(Function &F, FunctionAnalysisManager &AM);
1680 /// Printer pass for the \c ScalarEvolutionAnalysis results.
1681 class ScalarEvolutionPrinterPass
1682 : public PassInfoMixin<ScalarEvolutionPrinterPass> {
1686 explicit ScalarEvolutionPrinterPass(raw_ostream &OS) : OS(OS) {}
1687 PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM);
1690 class ScalarEvolutionWrapperPass : public FunctionPass {
1691 std::unique_ptr<ScalarEvolution> SE;
1696 ScalarEvolutionWrapperPass();
1698 ScalarEvolution &getSE() { return *SE; }
1699 const ScalarEvolution &getSE() const { return *SE; }
1701 bool runOnFunction(Function &F) override;
1702 void releaseMemory() override;
1703 void getAnalysisUsage(AnalysisUsage &AU) const override;
1704 void print(raw_ostream &OS, const Module * = nullptr) const override;
1705 void verifyAnalysis() const override;
1708 /// An interface layer with SCEV used to manage how we see SCEV expressions
1709 /// for values in the context of existing predicates. We can add new
1710 /// predicates, but we cannot remove them.
1712 /// This layer has multiple purposes:
1713 /// - provides a simple interface for SCEV versioning.
1714 /// - guarantees that the order of transformations applied on a SCEV
1715 /// expression for a single Value is consistent across two different
1716 /// getSCEV calls. This means that, for example, once we've obtained
1717 /// an AddRec expression for a certain value through expression
1718 /// rewriting, we will continue to get an AddRec expression for that
1720 /// - lowers the number of expression rewrites.
1721 class PredicatedScalarEvolution {
1723 PredicatedScalarEvolution(ScalarEvolution &SE, Loop &L);
1724 const SCEVUnionPredicate &getUnionPredicate() const;
1726 /// Returns the SCEV expression of V, in the context of the current SCEV
1727 /// predicate. The order of transformations applied on the expression of V
1728 /// returned by ScalarEvolution is guaranteed to be preserved, even when
1729 /// adding new predicates.
1730 const SCEV *getSCEV(Value *V);
1732 /// Get the (predicated) backedge count for the analyzed loop.
1733 const SCEV *getBackedgeTakenCount();
1735 /// Adds a new predicate.
1736 void addPredicate(const SCEVPredicate &Pred);
1738 /// Attempts to produce an AddRecExpr for V by adding additional SCEV
1739 /// predicates. If we can't transform the expression into an AddRecExpr we
1740 /// return nullptr and not add additional SCEV predicates to the current
1742 const SCEVAddRecExpr *getAsAddRec(Value *V);
1744 /// Proves that V doesn't overflow by adding SCEV predicate.
1745 void setNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1747 /// Returns true if we've proved that V doesn't wrap by means of a SCEV
1749 bool hasNoOverflow(Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags);
1751 /// Returns the ScalarEvolution analysis used.
1752 ScalarEvolution *getSE() const { return &SE; }
1754 /// We need to explicitly define the copy constructor because of FlagsMap.
1755 PredicatedScalarEvolution(const PredicatedScalarEvolution &);
1757 /// Print the SCEV mappings done by the Predicated Scalar Evolution.
1758 /// The printed text is indented by \p Depth.
1759 void print(raw_ostream &OS, unsigned Depth) const;
1762 /// Increments the version number of the predicate. This needs to be called
1763 /// every time the SCEV predicate changes.
1764 void updateGeneration();
1766 /// Holds a SCEV and the version number of the SCEV predicate used to
1767 /// perform the rewrite of the expression.
1768 typedef std::pair<unsigned, const SCEV *> RewriteEntry;
1770 /// Maps a SCEV to the rewrite result of that SCEV at a certain version
1771 /// number. If this number doesn't match the current Generation, we will
1772 /// need to do a rewrite. To preserve the transformation order of previous
1773 /// rewrites, we will rewrite the previous result instead of the original
1775 DenseMap<const SCEV *, RewriteEntry> RewriteMap;
1777 /// Records what NoWrap flags we've added to a Value *.
1778 ValueMap<Value *, SCEVWrapPredicate::IncrementWrapFlags> FlagsMap;
1780 /// The ScalarEvolution analysis.
1781 ScalarEvolution &SE;
1783 /// The analyzed Loop.
1786 /// The SCEVPredicate that forms our context. We will rewrite all
1787 /// expressions assuming that this predicate true.
1788 SCEVUnionPredicate Preds;
1790 /// Marks the version of the SCEV predicate used. When rewriting a SCEV
1791 /// expression we mark it with the version of the predicate. We use this to
1792 /// figure out if the predicate has changed from the last rewrite of the
1793 /// SCEV. If so, we need to perform a new rewrite.
1794 unsigned Generation;
1796 /// The backedge taken count.
1797 const SCEV *BackedgeCount;