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