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/IR/ConstantRange.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Instructions.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Pass.h"
32 #include "llvm/Support/Allocator.h"
33 #include "llvm/Support/DataTypes.h"
38 class AssumptionTracker;
43 class ScalarEvolution;
45 class TargetLibraryInfo;
52 template<> struct FoldingSetTrait<SCEV>;
54 /// SCEV - This class represents an analyzed expression in the program. These
55 /// are opaque objects that the client is not allowed to do much with
58 class SCEV : public FoldingSetNode {
59 friend struct FoldingSetTrait<SCEV>;
61 /// FastID - A reference to an Interned FoldingSetNodeID for this node.
62 /// The ScalarEvolution's BumpPtrAllocator holds the data.
63 FoldingSetNodeIDRef FastID;
65 // The SCEV baseclass this node corresponds to
66 const unsigned short SCEVType;
69 /// SubclassData - This field is initialized to zero and may be used in
70 /// subclasses to store miscellaneous information.
71 unsigned short SubclassData;
74 SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
75 void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
78 /// NoWrapFlags are bitfield indices into SubclassData.
80 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
81 /// no-signed-wrap <NSW> properties, which are derived from the IR
82 /// operator. NSW is a misnomer that we use to mean no signed overflow or
85 /// AddRec expression may have a no-self-wraparound <NW> property if the
86 /// result can never reach the start value. This property is independent of
87 /// the actual start value and step direction. Self-wraparound is defined
88 /// purely in terms of the recurrence's loop, step size, and
89 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
90 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
92 /// Note that NUW and NSW are also valid properties of a recurrence, and
93 /// either implies NW. For convenience, NW will be set for a recurrence
94 /// whenever either NUW or NSW are set.
95 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
96 FlagNW = (1 << 0), // No self-wrap.
97 FlagNUW = (1 << 1), // No unsigned wrap.
98 FlagNSW = (1 << 2), // No signed wrap.
99 NoWrapMask = (1 << 3) -1 };
101 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
102 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
104 unsigned getSCEVType() const { return SCEVType; }
106 /// getType - Return the LLVM type of this SCEV expression.
108 Type *getType() const;
110 /// isZero - Return true if the expression is a constant zero.
114 /// isOne - Return true if the expression is a constant one.
118 /// isAllOnesValue - Return true if the expression is a constant
121 bool isAllOnesValue() const;
123 /// isNonConstantNegative - Return true if the specified scev is negated,
124 /// but not a constant.
125 bool isNonConstantNegative() const;
127 /// print - Print out the internal representation of this scalar to the
128 /// specified stream. This should really only be used for debugging
130 void print(raw_ostream &OS) const;
132 /// dump - This method is used for debugging.
137 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
138 // temporary FoldingSetNodeID values.
139 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
140 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
143 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
144 unsigned IDHash, FoldingSetNodeID &TempID) {
145 return ID == X.FastID;
147 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
148 return X.FastID.ComputeHash();
152 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
157 /// SCEVCouldNotCompute - An object of this class is returned by queries that
158 /// could not be answered. For example, if you ask for the number of
159 /// iterations of a linked-list traversal loop, you will get one of these.
160 /// None of the standard SCEV operations are valid on this class, it is just a
162 struct SCEVCouldNotCompute : public SCEV {
163 SCEVCouldNotCompute();
165 /// Methods for support type inquiry through isa, cast, and dyn_cast:
166 static bool classof(const SCEV *S);
169 /// ScalarEvolution - This class is the main scalar evolution driver. Because
170 /// client code (intentionally) can't do much with the SCEV objects directly,
171 /// they must ask this class for services.
173 class ScalarEvolution : public FunctionPass {
175 /// LoopDisposition - An enum describing the relationship between a
177 enum LoopDisposition {
178 LoopVariant, ///< The SCEV is loop-variant (unknown).
179 LoopInvariant, ///< The SCEV is loop-invariant.
180 LoopComputable ///< The SCEV varies predictably with the loop.
183 /// BlockDisposition - An enum describing the relationship between a
184 /// SCEV and a basic block.
185 enum BlockDisposition {
186 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
187 DominatesBlock, ///< The SCEV dominates the block.
188 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
191 /// Convenient NoWrapFlags manipulation that hides enum casts and is
192 /// visible in the ScalarEvolution name space.
193 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
194 maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
195 return (SCEV::NoWrapFlags)(Flags & Mask);
197 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
198 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
199 return (SCEV::NoWrapFlags)(Flags | OnFlags);
201 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
202 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
203 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
207 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
208 /// notified whenever a Value is deleted.
209 class SCEVCallbackVH : public CallbackVH {
211 void deleted() override;
212 void allUsesReplacedWith(Value *New) override;
214 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr);
217 friend class SCEVCallbackVH;
218 friend class SCEVExpander;
219 friend class SCEVUnknown;
221 /// F - The function we are analyzing.
225 /// The tracker for @llvm.assume intrinsics in this function.
226 AssumptionTracker *AT;
228 /// LI - The loop information for the function we are currently analyzing.
232 /// The DataLayout information for the target we are targeting.
234 const DataLayout *DL;
236 /// TLI - The target library information for the target we are targeting.
238 TargetLibraryInfo *TLI;
240 /// DT - The dominator tree.
244 /// CouldNotCompute - This SCEV is used to represent unknown trip
245 /// counts and things.
246 SCEVCouldNotCompute CouldNotCompute;
248 /// ValueExprMapType - The typedef for ValueExprMap.
250 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
253 /// ValueExprMap - This is a cache of the values we have analyzed so far.
255 ValueExprMapType ValueExprMap;
257 /// Mark predicate values currently being processed by isImpliedCond.
258 DenseSet<Value*> PendingLoopPredicates;
260 /// ExitLimit - Information about the number of loop iterations for which a
261 /// loop exit's branch condition evaluates to the not-taken path. This is a
262 /// temporary pair of exact and max expressions that are eventually
263 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo.
268 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
270 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
272 /// hasAnyInfo - Test whether this ExitLimit contains any computed
273 /// information, or whether it's all SCEVCouldNotCompute values.
274 bool hasAnyInfo() const {
275 return !isa<SCEVCouldNotCompute>(Exact) ||
276 !isa<SCEVCouldNotCompute>(Max);
280 /// ExitNotTakenInfo - Information about the number of times a particular
281 /// loop exit may be reached before exiting the loop.
282 struct ExitNotTakenInfo {
283 AssertingVH<BasicBlock> ExitingBlock;
284 const SCEV *ExactNotTaken;
285 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
287 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
289 /// isCompleteList - Return true if all loop exits are computable.
290 bool isCompleteList() const {
291 return NextExit.getInt() == 0;
294 void setIncomplete() { NextExit.setInt(1); }
296 /// getNextExit - Return a pointer to the next exit's not-taken info.
297 ExitNotTakenInfo *getNextExit() const {
298 return NextExit.getPointer();
301 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
304 /// BackedgeTakenInfo - Information about the backedge-taken count
305 /// of a loop. This currently includes an exact count and a maximum count.
307 class BackedgeTakenInfo {
308 /// ExitNotTaken - A list of computable exits and their not-taken counts.
309 /// Loops almost never have more than one computable exit.
310 ExitNotTakenInfo ExitNotTaken;
312 /// Max - An expression indicating the least maximum backedge-taken
313 /// count of the loop that is known, or a SCEVCouldNotCompute.
317 BackedgeTakenInfo() : Max(nullptr) {}
319 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
321 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
322 bool Complete, const SCEV *MaxCount);
324 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
325 /// computed information, or whether it's all SCEVCouldNotCompute
327 bool hasAnyInfo() const {
328 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
331 /// getExact - Return an expression indicating the exact backedge-taken
332 /// count of the loop if it is known, or SCEVCouldNotCompute
333 /// otherwise. This is the number of times the loop header can be
334 /// guaranteed to execute, minus one.
335 const SCEV *getExact(ScalarEvolution *SE) const;
337 /// getExact - Return the number of times this loop exit may fall through
338 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
339 /// to exit via this block before this number of iterations, but may exit
340 /// via another block.
341 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
343 /// getMax - Get the max backedge taken count for the loop.
344 const SCEV *getMax(ScalarEvolution *SE) const;
346 /// Return true if any backedge taken count expressions refer to the given
348 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
350 /// clear - Invalidate this result and free associated memory.
354 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
355 /// this function as they are computed.
356 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
358 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
359 /// the PHI instructions that we attempt to compute constant evolutions for.
360 /// This allows us to avoid potentially expensive recomputation of these
361 /// properties. An instruction maps to null if we are unable to compute its
363 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
365 /// ValuesAtScopes - This map contains entries for all the expressions
366 /// that we attempt to compute getSCEVAtScope information for, which can
367 /// be expensive in extreme cases.
368 DenseMap<const SCEV *,
369 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
371 /// LoopDispositions - Memoized computeLoopDisposition results.
372 DenseMap<const SCEV *,
373 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions;
375 /// computeLoopDisposition - Compute a LoopDisposition value.
376 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
378 /// BlockDispositions - Memoized computeBlockDisposition results.
379 DenseMap<const SCEV *,
380 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions;
382 /// computeBlockDisposition - Compute a BlockDisposition value.
383 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
385 /// UnsignedRanges - Memoized results from getUnsignedRange
386 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
388 /// SignedRanges - Memoized results from getSignedRange
389 DenseMap<const SCEV *, ConstantRange> SignedRanges;
391 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
392 const ConstantRange &setUnsignedRange(const SCEV *S,
393 const ConstantRange &CR) {
394 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
395 UnsignedRanges.insert(std::make_pair(S, CR));
397 Pair.first->second = CR;
398 return Pair.first->second;
401 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
402 const ConstantRange &setSignedRange(const SCEV *S,
403 const ConstantRange &CR) {
404 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
405 SignedRanges.insert(std::make_pair(S, CR));
407 Pair.first->second = CR;
408 return Pair.first->second;
411 /// createSCEV - We know that there is no SCEV for the specified value.
412 /// Analyze the expression.
413 const SCEV *createSCEV(Value *V);
415 /// createNodeForPHI - Provide the special handling we need to analyze PHI
417 const SCEV *createNodeForPHI(PHINode *PN);
419 /// createNodeForGEP - Provide the special handling we need to analyze GEP
421 const SCEV *createNodeForGEP(GEPOperator *GEP);
423 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
424 /// at most once for each SCEV+Loop pair.
426 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
428 /// ForgetSymbolicValue - This looks up computed SCEV values for all
429 /// instructions that depend on the given instruction and removes them from
430 /// the ValueExprMap map if they reference SymName. This is used during PHI
432 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
434 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
435 /// loop, lazily computing new values if the loop hasn't been analyzed
437 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
439 /// ComputeBackedgeTakenCount - Compute the number of times the specified
440 /// loop will iterate.
441 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
443 /// ComputeExitLimit - Compute the number of times the backedge of the
444 /// specified loop will execute if it exits via the specified block.
445 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
447 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
448 /// the specified loop will execute if its exit condition were a conditional
449 /// branch of ExitCond, TBB, and FBB.
450 ExitLimit ComputeExitLimitFromCond(const Loop *L,
456 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
457 /// the specified loop will execute if its exit condition were a conditional
458 /// branch of the ICmpInst ExitCond, TBB, and FBB.
459 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
465 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
466 /// backedge of the specified loop will execute if its exit condition were a
467 /// switch with a single exiting case to ExitingBB.
469 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
470 BasicBlock *ExitingBB, bool IsSubExpr);
472 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
473 /// of 'icmp op load X, cst', try to see if we can compute the
474 /// backedge-taken count.
475 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
478 ICmpInst::Predicate p);
480 /// ComputeExitCountExhaustively - If the loop is known to execute a
481 /// constant number of times (the condition evolves only from constants),
482 /// try to evaluate a few iterations of the loop until we get the exit
483 /// condition gets a value of ExitWhen (true or false). If we cannot
484 /// evaluate the exit count of the loop, return CouldNotCompute.
485 const SCEV *ComputeExitCountExhaustively(const Loop *L,
489 /// HowFarToZero - Return the number of times an exit condition comparing
490 /// the specified value to zero will execute. If not computable, return
492 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
494 /// HowFarToNonZero - Return the number of times an exit condition checking
495 /// the specified value for nonzero will execute. If not computable, return
497 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
499 /// HowManyLessThans - Return the number of times an exit condition
500 /// containing the specified less-than comparison will execute. If not
501 /// computable, return CouldNotCompute. isSigned specifies whether the
502 /// less-than is signed.
503 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
504 const Loop *L, bool isSigned, bool IsSubExpr);
505 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
506 const Loop *L, bool isSigned, bool IsSubExpr);
508 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
509 /// (which may not be an immediate predecessor) which has exactly one
510 /// successor from which BB is reachable, or null if no such block is
512 std::pair<BasicBlock *, BasicBlock *>
513 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
515 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
516 /// RHS is true whenever the given FoundCondValue value evaluates to true.
517 bool isImpliedCond(ICmpInst::Predicate Pred,
518 const SCEV *LHS, const SCEV *RHS,
519 Value *FoundCondValue,
522 /// isImpliedCondOperands - Test whether the condition described by Pred,
523 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
524 /// and FoundRHS is true.
525 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
526 const SCEV *LHS, const SCEV *RHS,
527 const SCEV *FoundLHS, const SCEV *FoundRHS);
529 /// isImpliedCondOperandsHelper - Test whether the condition described by
530 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
531 /// FoundLHS, and FoundRHS is true.
532 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
533 const SCEV *LHS, const SCEV *RHS,
534 const SCEV *FoundLHS,
535 const SCEV *FoundRHS);
537 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
538 /// in the header of its containing loop, we know the loop executes a
539 /// constant number of times, and the PHI node is just a recurrence
540 /// involving constants, fold it.
541 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
544 /// isKnownPredicateWithRanges - Test if the given expression is known to
545 /// satisfy the condition described by Pred and the known constant ranges
548 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
549 const SCEV *LHS, const SCEV *RHS);
551 /// forgetMemoizedResults - Drop memoized information computed for S.
552 void forgetMemoizedResults(const SCEV *S);
554 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
556 bool checkValidity(const SCEV *S) const;
559 static char ID; // Pass identification, replacement for typeid
562 LLVMContext &getContext() const { return F->getContext(); }
564 /// isSCEVable - Test if values of the given type are analyzable within
565 /// the SCEV framework. This primarily includes integer types, and it
566 /// can optionally include pointer types if the ScalarEvolution class
567 /// has access to target-specific information.
568 bool isSCEVable(Type *Ty) const;
570 /// getTypeSizeInBits - Return the size in bits of the specified type,
571 /// for which isSCEVable must return true.
572 uint64_t getTypeSizeInBits(Type *Ty) const;
574 /// getEffectiveSCEVType - Return a type with the same bitwidth as
575 /// the given type and which represents how SCEV will treat the given
576 /// type, for which isSCEVable must return true. For pointer types,
577 /// this is the pointer-sized integer type.
578 Type *getEffectiveSCEVType(Type *Ty) const;
580 /// getSCEV - Return a SCEV expression for the full generality of the
581 /// specified expression.
582 const SCEV *getSCEV(Value *V);
584 const SCEV *getConstant(ConstantInt *V);
585 const SCEV *getConstant(const APInt& Val);
586 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
587 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
588 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
589 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
590 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
591 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
592 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
593 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
594 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
595 SmallVector<const SCEV *, 2> Ops;
598 return getAddExpr(Ops, Flags);
600 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
601 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
602 SmallVector<const SCEV *, 3> Ops;
606 return getAddExpr(Ops, Flags);
608 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
609 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
610 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
611 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
613 SmallVector<const SCEV *, 2> Ops;
616 return getMulExpr(Ops, Flags);
618 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
619 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
620 SmallVector<const SCEV *, 3> Ops;
624 return getMulExpr(Ops, Flags);
626 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
627 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
628 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
629 const Loop *L, SCEV::NoWrapFlags Flags);
630 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
631 const Loop *L, SCEV::NoWrapFlags Flags);
632 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
633 const Loop *L, SCEV::NoWrapFlags Flags) {
634 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
635 return getAddRecExpr(NewOp, L, Flags);
637 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
638 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
639 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
640 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
641 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
642 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
643 const SCEV *getUnknown(Value *V);
644 const SCEV *getCouldNotCompute();
646 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
649 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
651 /// getOffsetOfExpr - Return an expression for offsetof on the given field
654 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
656 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
658 const SCEV *getNegativeSCEV(const SCEV *V);
660 /// getNotSCEV - Return the SCEV object corresponding to ~V.
662 const SCEV *getNotSCEV(const SCEV *V);
664 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
665 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
666 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
668 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
669 /// of the input value to the specified type. If the type must be
670 /// extended, it is zero extended.
671 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
673 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
674 /// of the input value to the specified type. If the type must be
675 /// extended, it is sign extended.
676 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
678 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
679 /// the input value to the specified type. If the type must be extended,
680 /// it is zero extended. The conversion must not be narrowing.
681 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
683 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
684 /// the input value to the specified type. If the type must be extended,
685 /// it is sign extended. The conversion must not be narrowing.
686 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
688 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
689 /// the input value to the specified type. If the type must be extended,
690 /// it is extended with unspecified bits. The conversion must not be
692 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
694 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
695 /// input value to the specified type. The conversion must not be
697 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
699 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
700 /// the types using zero-extension, and then perform a umax operation
702 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
705 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
706 /// the types using zero-extension, and then perform a umin operation
708 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
711 /// getPointerBase - Transitively follow the chain of pointer-type operands
712 /// until reaching a SCEV that does not have a single pointer operand. This
713 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
714 /// but corner cases do exist.
715 const SCEV *getPointerBase(const SCEV *V);
717 /// getSCEVAtScope - Return a SCEV expression for the specified value
718 /// at the specified scope in the program. The L value specifies a loop
719 /// nest to evaluate the expression at, where null is the top-level or a
720 /// specified loop is immediately inside of the loop.
722 /// This method can be used to compute the exit value for a variable defined
723 /// in a loop by querying what the value will hold in the parent loop.
725 /// In the case that a relevant loop exit value cannot be computed, the
726 /// original value V is returned.
727 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
729 /// getSCEVAtScope - This is a convenience function which does
730 /// getSCEVAtScope(getSCEV(V), L).
731 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
733 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
734 /// by a conditional between LHS and RHS. This is used to help avoid max
735 /// expressions in loop trip counts, and to eliminate casts.
736 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
737 const SCEV *LHS, const SCEV *RHS);
739 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
740 /// protected by a conditional between LHS and RHS. This is used to
741 /// to eliminate casts.
742 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
743 const SCEV *LHS, const SCEV *RHS);
745 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
746 /// as a normal unsigned value. Returns 0 if the trip count is unknown or
747 /// not constant. This "trip count" assumes that control exits via
748 /// ExitingBlock. More precisely, it is the number of times that control may
749 /// reach ExitingBlock before taking the branch. For loops with multiple
750 /// exits, it may not be the number times that the loop header executes if
751 /// the loop exits prematurely via another branch.
752 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
754 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
755 /// the trip count of this loop as a normal unsigned value, if
756 /// possible. This means that the actual trip count is always a multiple of
757 /// the returned value (don't forget the trip count could very well be zero
758 /// as well!). As explained in the comments for getSmallConstantTripCount,
759 /// this assumes that control exits the loop via ExitingBlock.
760 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
762 // getExitCount - Get the expression for the number of loop iterations for
763 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
764 // return SCEVCouldNotCompute.
765 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
767 /// getBackedgeTakenCount - If the specified loop has a predictable
768 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
769 /// object. The backedge-taken count is the number of times the loop header
770 /// will be branched to from within the loop. This is one less than the
771 /// trip count of the loop, since it doesn't count the first iteration,
772 /// when the header is branched to from outside the loop.
774 /// Note that it is not valid to call this method on a loop without a
775 /// loop-invariant backedge-taken count (see
776 /// hasLoopInvariantBackedgeTakenCount).
778 const SCEV *getBackedgeTakenCount(const Loop *L);
780 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
781 /// return the least SCEV value that is known never to be less than the
782 /// actual backedge taken count.
783 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
785 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
786 /// has an analyzable loop-invariant backedge-taken count.
787 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
789 /// forgetLoop - This method should be called by the client when it has
790 /// changed a loop in a way that may effect ScalarEvolution's ability to
791 /// compute a trip count, or if the loop is deleted. This call is
792 /// potentially expensive for large loop bodies.
793 void forgetLoop(const Loop *L);
795 /// forgetValue - This method should be called by the client when it has
796 /// changed a value in a way that may effect its value, or which may
797 /// disconnect it from a def-use chain linking it to a loop.
798 void forgetValue(Value *V);
800 /// \brief Called when the client has changed the disposition of values in
803 /// We don't have a way to invalidate per-loop dispositions. Clear and
804 /// recompute is simpler.
805 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
807 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
808 /// is guaranteed to end in (at every loop iteration). It is, at the same
809 /// time, the minimum number of times S is divisible by 2. For example,
810 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
812 uint32_t GetMinTrailingZeros(const SCEV *S);
814 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
816 ConstantRange getUnsignedRange(const SCEV *S);
818 /// getSignedRange - Determine the signed range for a particular SCEV.
820 ConstantRange getSignedRange(const SCEV *S);
822 /// isKnownNegative - Test if the given expression is known to be negative.
824 bool isKnownNegative(const SCEV *S);
826 /// isKnownPositive - Test if the given expression is known to be positive.
828 bool isKnownPositive(const SCEV *S);
830 /// isKnownNonNegative - Test if the given expression is known to be
833 bool isKnownNonNegative(const SCEV *S);
835 /// isKnownNonPositive - Test if the given expression is known to be
838 bool isKnownNonPositive(const SCEV *S);
840 /// isKnownNonZero - Test if the given expression is known to be
843 bool isKnownNonZero(const SCEV *S);
845 /// isKnownPredicate - Test if the given expression is known to satisfy
846 /// the condition described by Pred, LHS, and RHS.
848 bool isKnownPredicate(ICmpInst::Predicate Pred,
849 const SCEV *LHS, const SCEV *RHS);
851 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
852 /// predicate Pred. Return true iff any changes were made. If the
853 /// operands are provably equal or unequal, LHS and RHS are set to
854 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
856 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
861 /// getLoopDisposition - Return the "disposition" of the given SCEV with
862 /// respect to the given loop.
863 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
865 /// isLoopInvariant - Return true if the value of the given SCEV is
866 /// unchanging in the specified loop.
867 bool isLoopInvariant(const SCEV *S, const Loop *L);
869 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
870 /// in a known way in the specified loop. This property being true implies
871 /// that the value is variant in the loop AND that we can emit an expression
872 /// to compute the value of the expression at any particular loop iteration.
873 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
875 /// getLoopDisposition - Return the "disposition" of the given SCEV with
876 /// respect to the given block.
877 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
879 /// dominates - Return true if elements that makes up the given SCEV
880 /// dominate the specified basic block.
881 bool dominates(const SCEV *S, const BasicBlock *BB);
883 /// properlyDominates - Return true if elements that makes up the given SCEV
884 /// properly dominate the specified basic block.
885 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
887 /// hasOperand - Test whether the given SCEV has Op as a direct or
888 /// indirect operand.
889 bool hasOperand(const SCEV *S, const SCEV *Op) const;
891 /// Return the size of an element read or written by Inst.
892 const SCEV *getElementSize(Instruction *Inst);
894 /// Compute the array dimensions Sizes from the set of Terms extracted from
895 /// the memory access function of this SCEVAddRecExpr.
896 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
897 SmallVectorImpl<const SCEV *> &Sizes,
898 const SCEV *ElementSize) const;
900 bool runOnFunction(Function &F) override;
901 void releaseMemory() override;
902 void getAnalysisUsage(AnalysisUsage &AU) const override;
903 void print(raw_ostream &OS, const Module* = nullptr) const override;
904 void verifyAnalysis() const override;
907 /// Compute the backedge taken count knowing the interval difference, the
908 /// stride and presence of the equality in the comparison.
909 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
912 /// Verify if an linear IV with positive stride can overflow when in a
913 /// less-than comparison, knowing the invariant term of the comparison,
914 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
915 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
916 bool IsSigned, bool NoWrap);
918 /// Verify if an linear IV with negative stride can overflow when in a
919 /// greater-than comparison, knowing the invariant term of the comparison,
920 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
921 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
922 bool IsSigned, bool NoWrap);
925 FoldingSet<SCEV> UniqueSCEVs;
926 BumpPtrAllocator SCEVAllocator;
928 /// FirstUnknown - The head of a linked list of all SCEVUnknown
929 /// values that have been allocated. This is used by releaseMemory
930 /// to locate them all and call their destructors.
931 SCEVUnknown *FirstUnknown;