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 /// Set to true by isLoopBackedgeGuardedByCond when we're walking the set of
260 /// conditions dominating the backedge of a loop.
261 bool WalkingBEDominatingConds;
263 /// ExitLimit - Information about the number of loop iterations for which a
264 /// loop exit's branch condition evaluates to the not-taken path. This is a
265 /// temporary pair of exact and max expressions that are eventually
266 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo.
271 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
273 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
275 /// hasAnyInfo - Test whether this ExitLimit contains any computed
276 /// information, or whether it's all SCEVCouldNotCompute values.
277 bool hasAnyInfo() const {
278 return !isa<SCEVCouldNotCompute>(Exact) ||
279 !isa<SCEVCouldNotCompute>(Max);
283 /// ExitNotTakenInfo - Information about the number of times a particular
284 /// loop exit may be reached before exiting the loop.
285 struct ExitNotTakenInfo {
286 AssertingVH<BasicBlock> ExitingBlock;
287 const SCEV *ExactNotTaken;
288 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
290 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {}
292 /// isCompleteList - Return true if all loop exits are computable.
293 bool isCompleteList() const {
294 return NextExit.getInt() == 0;
297 void setIncomplete() { NextExit.setInt(1); }
299 /// getNextExit - Return a pointer to the next exit's not-taken info.
300 ExitNotTakenInfo *getNextExit() const {
301 return NextExit.getPointer();
304 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
307 /// BackedgeTakenInfo - Information about the backedge-taken count
308 /// of a loop. This currently includes an exact count and a maximum count.
310 class BackedgeTakenInfo {
311 /// ExitNotTaken - A list of computable exits and their not-taken counts.
312 /// Loops almost never have more than one computable exit.
313 ExitNotTakenInfo ExitNotTaken;
315 /// Max - An expression indicating the least maximum backedge-taken
316 /// count of the loop that is known, or a SCEVCouldNotCompute.
320 BackedgeTakenInfo() : Max(nullptr) {}
322 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
324 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
325 bool Complete, const SCEV *MaxCount);
327 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
328 /// computed information, or whether it's all SCEVCouldNotCompute
330 bool hasAnyInfo() const {
331 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
334 /// getExact - Return an expression indicating the exact backedge-taken
335 /// count of the loop if it is known, or SCEVCouldNotCompute
336 /// otherwise. This is the number of times the loop header can be
337 /// guaranteed to execute, minus one.
338 const SCEV *getExact(ScalarEvolution *SE) const;
340 /// getExact - Return the number of times this loop exit may fall through
341 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
342 /// to exit via this block before this number of iterations, but may exit
343 /// via another block.
344 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
346 /// getMax - Get the max backedge taken count for the loop.
347 const SCEV *getMax(ScalarEvolution *SE) const;
349 /// Return true if any backedge taken count expressions refer to the given
351 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
353 /// clear - Invalidate this result and free associated memory.
357 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
358 /// this function as they are computed.
359 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
361 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
362 /// the PHI instructions that we attempt to compute constant evolutions for.
363 /// This allows us to avoid potentially expensive recomputation of these
364 /// properties. An instruction maps to null if we are unable to compute its
366 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
368 /// ValuesAtScopes - This map contains entries for all the expressions
369 /// that we attempt to compute getSCEVAtScope information for, which can
370 /// be expensive in extreme cases.
371 DenseMap<const SCEV *,
372 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
374 /// LoopDispositions - Memoized computeLoopDisposition results.
375 DenseMap<const SCEV *,
376 SmallVector<PointerIntPair<const Loop *, 2, LoopDisposition>, 2>>
379 /// computeLoopDisposition - Compute a LoopDisposition value.
380 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
382 /// BlockDispositions - Memoized computeBlockDisposition results.
385 SmallVector<PointerIntPair<const BasicBlock *, 2, BlockDisposition>, 2>>
388 /// computeBlockDisposition - Compute a BlockDisposition value.
389 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
391 /// UnsignedRanges - Memoized results from getRange
392 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
394 /// SignedRanges - Memoized results from getRange
395 DenseMap<const SCEV *, ConstantRange> SignedRanges;
397 /// RangeSignHint - Used to parameterize getRange
398 enum RangeSignHint { HINT_RANGE_UNSIGNED, HINT_RANGE_SIGNED };
400 /// setRange - Set the memoized range for the given SCEV.
401 const ConstantRange &setRange(const SCEV *S, RangeSignHint Hint,
402 const ConstantRange &CR) {
403 DenseMap<const SCEV *, ConstantRange> &Cache =
404 Hint == HINT_RANGE_UNSIGNED ? UnsignedRanges : SignedRanges;
406 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
407 Cache.insert(std::make_pair(S, CR));
409 Pair.first->second = CR;
410 return Pair.first->second;
413 /// getRange - Determine the range for a particular SCEV.
414 ConstantRange getRange(const SCEV *S, RangeSignHint Hint);
416 /// createSCEV - We know that there is no SCEV for the specified value.
417 /// Analyze the expression.
418 const SCEV *createSCEV(Value *V);
420 /// createNodeForPHI - Provide the special handling we need to analyze PHI
422 const SCEV *createNodeForPHI(PHINode *PN);
424 /// createNodeForGEP - Provide the special handling we need to analyze GEP
426 const SCEV *createNodeForGEP(GEPOperator *GEP);
428 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
429 /// at most once for each SCEV+Loop pair.
431 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
433 /// ForgetSymbolicValue - This looks up computed SCEV values for all
434 /// instructions that depend on the given instruction and removes them from
435 /// the ValueExprMap map if they reference SymName. This is used during PHI
437 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
439 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
440 /// loop, lazily computing new values if the loop hasn't been analyzed
442 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
444 /// ComputeBackedgeTakenCount - Compute the number of times the specified
445 /// loop will iterate.
446 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
448 /// ComputeExitLimit - Compute the number of times the backedge of the
449 /// specified loop will execute if it exits via the specified block.
450 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
452 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
453 /// the specified loop will execute if its exit condition were a conditional
454 /// branch of ExitCond, TBB, and FBB.
455 ExitLimit ComputeExitLimitFromCond(const Loop *L,
461 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
462 /// the specified loop will execute if its exit condition were a conditional
463 /// branch of the ICmpInst ExitCond, TBB, and FBB.
464 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
470 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the
471 /// backedge of the specified loop will execute if its exit condition were a
472 /// switch with a single exiting case to ExitingBB.
474 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch,
475 BasicBlock *ExitingBB, bool IsSubExpr);
477 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
478 /// of 'icmp op load X, cst', try to see if we can compute the
479 /// backedge-taken count.
480 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
483 ICmpInst::Predicate p);
485 /// ComputeExitCountExhaustively - If the loop is known to execute a
486 /// constant number of times (the condition evolves only from constants),
487 /// try to evaluate a few iterations of the loop until we get the exit
488 /// condition gets a value of ExitWhen (true or false). If we cannot
489 /// evaluate the exit count of the loop, return CouldNotCompute.
490 const SCEV *ComputeExitCountExhaustively(const Loop *L,
494 /// HowFarToZero - Return the number of times an exit condition comparing
495 /// the specified value to zero will execute. If not computable, return
497 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
499 /// HowFarToNonZero - Return the number of times an exit condition checking
500 /// the specified value for nonzero will execute. If not computable, return
502 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
504 /// HowManyLessThans - Return the number of times an exit condition
505 /// containing the specified less-than comparison will execute. If not
506 /// computable, return CouldNotCompute. isSigned specifies whether the
507 /// less-than is signed.
508 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
509 const Loop *L, bool isSigned, bool IsSubExpr);
510 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
511 const Loop *L, bool isSigned, bool IsSubExpr);
513 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
514 /// (which may not be an immediate predecessor) which has exactly one
515 /// successor from which BB is reachable, or null if no such block is
517 std::pair<BasicBlock *, BasicBlock *>
518 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
520 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
521 /// RHS is true whenever the given FoundCondValue value evaluates to true.
522 bool isImpliedCond(ICmpInst::Predicate Pred,
523 const SCEV *LHS, const SCEV *RHS,
524 Value *FoundCondValue,
527 /// isImpliedCondOperands - Test whether the condition described by Pred,
528 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
529 /// and FoundRHS is true.
530 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
531 const SCEV *LHS, const SCEV *RHS,
532 const SCEV *FoundLHS, const SCEV *FoundRHS);
534 /// isImpliedCondOperandsHelper - Test whether the condition described by
535 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
536 /// FoundLHS, and FoundRHS is true.
537 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
538 const SCEV *LHS, const SCEV *RHS,
539 const SCEV *FoundLHS,
540 const SCEV *FoundRHS);
542 /// isImpliedCondOperandsViaRanges - Test whether the condition described by
543 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
544 /// FoundLHS, and FoundRHS is true. Utility function used by
545 /// isImpliedCondOperands.
546 bool isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
547 const SCEV *LHS, const SCEV *RHS,
548 const SCEV *FoundLHS,
549 const SCEV *FoundRHS);
551 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
552 /// in the header of its containing loop, we know the loop executes a
553 /// constant number of times, and the PHI node is just a recurrence
554 /// involving constants, fold it.
555 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
558 /// isKnownPredicateWithRanges - Test if the given expression is known to
559 /// satisfy the condition described by Pred and the known constant ranges
562 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
563 const SCEV *LHS, const SCEV *RHS);
565 /// forgetMemoizedResults - Drop memoized information computed for S.
566 void forgetMemoizedResults(const SCEV *S);
568 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
570 bool checkValidity(const SCEV *S) const;
572 /// Return true if `ExtendOpTy`({`Start`,+,`Step`}) can be proved to be
573 /// equal to {`ExtendOpTy`(`Start`),+,`ExtendOpTy`(`Step`)}. This is
574 /// equivalent to proving no signed (resp. unsigned) wrap in
575 /// {`Start`,+,`Step`} if `ExtendOpTy` is `SCEVSignExtendExpr`
576 /// (resp. `SCEVZeroExtendExpr`).
578 template<typename ExtendOpTy>
579 bool proveNoWrapByVaryingStart(const SCEV *Start, const SCEV *Step,
583 static char ID; // Pass identification, replacement for typeid
586 LLVMContext &getContext() const { return F->getContext(); }
588 /// isSCEVable - Test if values of the given type are analyzable within
589 /// the SCEV framework. This primarily includes integer types, and it
590 /// can optionally include pointer types if the ScalarEvolution class
591 /// has access to target-specific information.
592 bool isSCEVable(Type *Ty) const;
594 /// getTypeSizeInBits - Return the size in bits of the specified type,
595 /// for which isSCEVable must return true.
596 uint64_t getTypeSizeInBits(Type *Ty) const;
598 /// getEffectiveSCEVType - Return a type with the same bitwidth as
599 /// the given type and which represents how SCEV will treat the given
600 /// type, for which isSCEVable must return true. For pointer types,
601 /// this is the pointer-sized integer type.
602 Type *getEffectiveSCEVType(Type *Ty) const;
604 /// getSCEV - Return a SCEV expression for the full generality of the
605 /// specified expression.
606 const SCEV *getSCEV(Value *V);
608 const SCEV *getConstant(ConstantInt *V);
609 const SCEV *getConstant(const APInt& Val);
610 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
611 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
612 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
613 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
614 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
615 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
616 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
617 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
618 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
619 SmallVector<const SCEV *, 2> Ops;
622 return getAddExpr(Ops, Flags);
624 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
625 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
626 SmallVector<const SCEV *, 3> Ops;
630 return getAddExpr(Ops, Flags);
632 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
633 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
634 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
635 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
637 SmallVector<const SCEV *, 2> Ops;
640 return getMulExpr(Ops, Flags);
642 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
643 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
644 SmallVector<const SCEV *, 3> Ops;
648 return getMulExpr(Ops, Flags);
650 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
651 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS);
652 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
653 const Loop *L, SCEV::NoWrapFlags Flags);
654 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
655 const Loop *L, SCEV::NoWrapFlags Flags);
656 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
657 const Loop *L, SCEV::NoWrapFlags Flags) {
658 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
659 return getAddRecExpr(NewOp, L, Flags);
661 /// \brief Returns an expression for a GEP
663 /// \p PointeeType The type used as the basis for the pointer arithmetics
664 /// \p BaseExpr The expression for the pointer operand.
665 /// \p IndexExprs The expressions for the indices.
666 /// \p InBounds Whether the GEP is in bounds.
667 const SCEV *getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
668 const SmallVectorImpl<const SCEV *> &IndexExprs,
669 bool InBounds = false);
670 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
671 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
672 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
673 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
674 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
675 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
676 const SCEV *getUnknown(Value *V);
677 const SCEV *getCouldNotCompute();
679 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
682 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
684 /// getOffsetOfExpr - Return an expression for offsetof on the given field
687 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
689 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
691 const SCEV *getNegativeSCEV(const SCEV *V);
693 /// getNotSCEV - Return the SCEV object corresponding to ~V.
695 const SCEV *getNotSCEV(const SCEV *V);
697 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
698 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
699 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
701 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
702 /// of the input value to the specified type. If the type must be
703 /// extended, it is zero extended.
704 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
706 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
707 /// of the input value to the specified type. If the type must be
708 /// extended, it is sign extended.
709 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
711 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
712 /// the input value to the specified type. If the type must be extended,
713 /// it is zero extended. The conversion must not be narrowing.
714 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
716 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
717 /// the input value to the specified type. If the type must be extended,
718 /// it is sign extended. The conversion must not be narrowing.
719 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
721 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
722 /// the input value to the specified type. If the type must be extended,
723 /// it is extended with unspecified bits. The conversion must not be
725 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
727 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
728 /// input value to the specified type. The conversion must not be
730 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
732 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
733 /// the types using zero-extension, and then perform a umax operation
735 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
738 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
739 /// the types using zero-extension, and then perform a umin operation
741 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
744 /// getPointerBase - Transitively follow the chain of pointer-type operands
745 /// until reaching a SCEV that does not have a single pointer operand. This
746 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
747 /// but corner cases do exist.
748 const SCEV *getPointerBase(const SCEV *V);
750 /// getSCEVAtScope - Return a SCEV expression for the specified value
751 /// at the specified scope in the program. The L value specifies a loop
752 /// nest to evaluate the expression at, where null is the top-level or a
753 /// specified loop is immediately inside of the loop.
755 /// This method can be used to compute the exit value for a variable defined
756 /// in a loop by querying what the value will hold in the parent loop.
758 /// In the case that a relevant loop exit value cannot be computed, the
759 /// original value V is returned.
760 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
762 /// getSCEVAtScope - This is a convenience function which does
763 /// getSCEVAtScope(getSCEV(V), L).
764 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
766 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
767 /// by a conditional between LHS and RHS. This is used to help avoid max
768 /// expressions in loop trip counts, and to eliminate casts.
769 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
770 const SCEV *LHS, const SCEV *RHS);
772 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
773 /// protected by a conditional between LHS and RHS. This is used to
774 /// to eliminate casts.
775 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
776 const SCEV *LHS, const SCEV *RHS);
778 /// \brief Returns the maximum trip count of the loop if it is a single-exit
779 /// loop and we can compute a small maximum for that loop.
781 /// Implemented in terms of the \c getSmallConstantTripCount overload with
782 /// the single exiting block passed to it. See that routine for details.
783 unsigned getSmallConstantTripCount(Loop *L);
785 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
786 /// as a normal unsigned value. Returns 0 if the trip count is unknown or
787 /// not constant. This "trip count" assumes that control exits via
788 /// ExitingBlock. More precisely, it is the number of times that control may
789 /// reach ExitingBlock before taking the branch. For loops with multiple
790 /// exits, it may not be the number times that the loop header executes if
791 /// the loop exits prematurely via another branch.
792 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
794 /// \brief Returns the largest constant divisor of the trip count of the
795 /// loop if it is a single-exit loop and we can compute a small maximum for
798 /// Implemented in terms of the \c getSmallConstantTripMultiple overload with
799 /// the single exiting block passed to it. See that routine for details.
800 unsigned getSmallConstantTripMultiple(Loop *L);
802 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
803 /// the trip count of this loop as a normal unsigned value, if
804 /// possible. This means that the actual trip count is always a multiple of
805 /// the returned value (don't forget the trip count could very well be zero
806 /// as well!). As explained in the comments for getSmallConstantTripCount,
807 /// this assumes that control exits the loop via ExitingBlock.
808 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
810 // getExitCount - Get the expression for the number of loop iterations for
811 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
812 // return SCEVCouldNotCompute.
813 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
815 /// getBackedgeTakenCount - If the specified loop has a predictable
816 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
817 /// object. The backedge-taken count is the number of times the loop header
818 /// will be branched to from within the loop. This is one less than the
819 /// trip count of the loop, since it doesn't count the first iteration,
820 /// when the header is branched to from outside the loop.
822 /// Note that it is not valid to call this method on a loop without a
823 /// loop-invariant backedge-taken count (see
824 /// hasLoopInvariantBackedgeTakenCount).
826 const SCEV *getBackedgeTakenCount(const Loop *L);
828 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
829 /// return the least SCEV value that is known never to be less than the
830 /// actual backedge taken count.
831 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
833 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
834 /// has an analyzable loop-invariant backedge-taken count.
835 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
837 /// forgetLoop - This method should be called by the client when it has
838 /// changed a loop in a way that may effect ScalarEvolution's ability to
839 /// compute a trip count, or if the loop is deleted. This call is
840 /// potentially expensive for large loop bodies.
841 void forgetLoop(const Loop *L);
843 /// forgetValue - This method should be called by the client when it has
844 /// changed a value in a way that may effect its value, or which may
845 /// disconnect it from a def-use chain linking it to a loop.
846 void forgetValue(Value *V);
848 /// \brief Called when the client has changed the disposition of values in
851 /// We don't have a way to invalidate per-loop dispositions. Clear and
852 /// recompute is simpler.
853 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); }
855 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
856 /// is guaranteed to end in (at every loop iteration). It is, at the same
857 /// time, the minimum number of times S is divisible by 2. For example,
858 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
860 uint32_t GetMinTrailingZeros(const SCEV *S);
862 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
864 ConstantRange getUnsignedRange(const SCEV *S) {
865 return getRange(S, HINT_RANGE_UNSIGNED);
868 /// getSignedRange - Determine the signed range for a particular SCEV.
870 ConstantRange getSignedRange(const SCEV *S) {
871 return getRange(S, HINT_RANGE_SIGNED);
874 /// isKnownNegative - Test if the given expression is known to be negative.
876 bool isKnownNegative(const SCEV *S);
878 /// isKnownPositive - Test if the given expression is known to be positive.
880 bool isKnownPositive(const SCEV *S);
882 /// isKnownNonNegative - Test if the given expression is known to be
885 bool isKnownNonNegative(const SCEV *S);
887 /// isKnownNonPositive - Test if the given expression is known to be
890 bool isKnownNonPositive(const SCEV *S);
892 /// isKnownNonZero - Test if the given expression is known to be
895 bool isKnownNonZero(const SCEV *S);
897 /// isKnownPredicate - Test if the given expression is known to satisfy
898 /// the condition described by Pred, LHS, and RHS.
900 bool isKnownPredicate(ICmpInst::Predicate Pred,
901 const SCEV *LHS, const SCEV *RHS);
903 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
904 /// predicate Pred. Return true iff any changes were made. If the
905 /// operands are provably equal or unequal, LHS and RHS are set to
906 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
908 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
913 /// getLoopDisposition - Return the "disposition" of the given SCEV with
914 /// respect to the given loop.
915 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
917 /// isLoopInvariant - Return true if the value of the given SCEV is
918 /// unchanging in the specified loop.
919 bool isLoopInvariant(const SCEV *S, const Loop *L);
921 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
922 /// in a known way in the specified loop. This property being true implies
923 /// that the value is variant in the loop AND that we can emit an expression
924 /// to compute the value of the expression at any particular loop iteration.
925 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
927 /// getLoopDisposition - Return the "disposition" of the given SCEV with
928 /// respect to the given block.
929 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
931 /// dominates - Return true if elements that makes up the given SCEV
932 /// dominate the specified basic block.
933 bool dominates(const SCEV *S, const BasicBlock *BB);
935 /// properlyDominates - Return true if elements that makes up the given SCEV
936 /// properly dominate the specified basic block.
937 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
939 /// hasOperand - Test whether the given SCEV has Op as a direct or
940 /// indirect operand.
941 bool hasOperand(const SCEV *S, const SCEV *Op) const;
943 /// Return the size of an element read or written by Inst.
944 const SCEV *getElementSize(Instruction *Inst);
946 /// Compute the array dimensions Sizes from the set of Terms extracted from
947 /// the memory access function of this SCEVAddRecExpr.
948 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
949 SmallVectorImpl<const SCEV *> &Sizes,
950 const SCEV *ElementSize) const;
952 bool runOnFunction(Function &F) override;
953 void releaseMemory() override;
954 void getAnalysisUsage(AnalysisUsage &AU) const override;
955 void print(raw_ostream &OS, const Module* = nullptr) const override;
956 void verifyAnalysis() const override;
958 /// Collect parametric terms occurring in step expressions.
959 void collectParametricTerms(const SCEV *Expr,
960 SmallVectorImpl<const SCEV *> &Terms);
964 /// Return in Subscripts the access functions for each dimension in Sizes.
965 void computeAccessFunctions(const SCEV *Expr,
966 SmallVectorImpl<const SCEV *> &Subscripts,
967 SmallVectorImpl<const SCEV *> &Sizes);
969 /// Split this SCEVAddRecExpr into two vectors of SCEVs representing the
970 /// subscripts and sizes of an array access.
972 /// The delinearization is a 3 step process: the first two steps compute the
973 /// sizes of each subscript and the third step computes the access functions
974 /// for the delinearized array:
976 /// 1. Find the terms in the step functions
977 /// 2. Compute the array size
978 /// 3. Compute the access function: divide the SCEV by the array size
979 /// starting with the innermost dimensions found in step 2. The Quotient
980 /// is the SCEV to be divided in the next step of the recursion. The
981 /// Remainder is the subscript of the innermost dimension. Loop over all
982 /// array dimensions computed in step 2.
984 /// To compute a uniform array size for several memory accesses to the same
985 /// object, one can collect in step 1 all the step terms for all the memory
986 /// accesses, and compute in step 2 a unique array shape. This guarantees
987 /// that the array shape will be the same across all memory accesses.
989 /// FIXME: We could derive the result of steps 1 and 2 from a description of
990 /// the array shape given in metadata.
1001 /// The initial SCEV:
1003 /// A[{{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k]
1005 /// 1. Find the different terms in the step functions:
1006 /// -> [2*m, 5, n*m, n*m]
1008 /// 2. Compute the array size: sort and unique them
1009 /// -> [n*m, 2*m, 5]
1010 /// find the GCD of all the terms = 1
1011 /// divide by the GCD and erase constant terms
1014 /// divide by GCD -> [n, 2]
1015 /// remove constant terms
1017 /// size of the array is A[unknown][n][m]
1019 /// 3. Compute the access function
1020 /// a. Divide {{{0,+,2*m+5}_i, +, n*m}_j, +, n*m}_k by the innermost size m
1021 /// Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k
1022 /// Remainder: {{{0,+,5}_i, +, 0}_j, +, 0}_k
1023 /// The remainder is the subscript of the innermost array dimension: [5i].
1025 /// b. Divide Quotient: {{{0,+,2}_i, +, n}_j, +, n}_k by next outer size n
1026 /// Quotient: {{{0,+,0}_i, +, 1}_j, +, 1}_k
1027 /// Remainder: {{{0,+,2}_i, +, 0}_j, +, 0}_k
1028 /// The Remainder is the subscript of the next array dimension: [2i].
1030 /// The subscript of the outermost dimension is the Quotient: [j+k].
1032 /// Overall, we have: A[][n][m], and the access function: A[j+k][2i][5i].
1033 void delinearize(const SCEV *Expr,
1034 SmallVectorImpl<const SCEV *> &Subscripts,
1035 SmallVectorImpl<const SCEV *> &Sizes,
1036 const SCEV *ElementSize);
1039 /// Compute the backedge taken count knowing the interval difference, the
1040 /// stride and presence of the equality in the comparison.
1041 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
1044 /// Verify if an linear IV with positive stride can overflow when in a
1045 /// less-than comparison, knowing the invariant term of the comparison,
1046 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1047 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
1048 bool IsSigned, bool NoWrap);
1050 /// Verify if an linear IV with negative stride can overflow when in a
1051 /// greater-than comparison, knowing the invariant term of the comparison,
1052 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
1053 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
1054 bool IsSigned, bool NoWrap);
1057 FoldingSet<SCEV> UniqueSCEVs;
1058 BumpPtrAllocator SCEVAllocator;
1060 /// FirstUnknown - The head of a linked list of all SCEVUnknown
1061 /// values that have been allocated. This is used by releaseMemory
1062 /// to locate them all and call their destructors.
1063 SCEVUnknown *FirstUnknown;