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/Function.h"
27 #include "llvm/IR/Instructions.h"
28 #include "llvm/IR/Operator.h"
29 #include "llvm/Pass.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/Support/DataTypes.h"
33 #include "llvm/Support/ValueHandle.h"
42 class ScalarEvolution;
44 class TargetLibraryInfo;
51 template<> struct FoldingSetTrait<SCEV>;
53 /// SCEV - This class represents an analyzed expression in the program. These
54 /// are opaque objects that the client is not allowed to do much with
57 class SCEV : public FoldingSetNode {
58 friend struct FoldingSetTrait<SCEV>;
60 /// FastID - A reference to an Interned FoldingSetNodeID for this node.
61 /// The ScalarEvolution's BumpPtrAllocator holds the data.
62 FoldingSetNodeIDRef FastID;
64 // The SCEV baseclass this node corresponds to
65 const unsigned short SCEVType;
68 /// SubclassData - This field is initialized to zero and may be used in
69 /// subclasses to store miscellaneous information.
70 unsigned short SubclassData;
73 SCEV(const SCEV &) LLVM_DELETED_FUNCTION;
74 void operator=(const SCEV &) LLVM_DELETED_FUNCTION;
77 /// NoWrapFlags are bitfield indices into SubclassData.
79 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
80 /// no-signed-wrap <NSW> properties, which are derived from the IR
81 /// operator. NSW is a misnomer that we use to mean no signed overflow or
84 /// AddRec expression may have a no-self-wraparound <NW> property if the
85 /// result can never reach the start value. This property is independent of
86 /// the actual start value and step direction. Self-wraparound is defined
87 /// purely in terms of the recurrence's loop, step size, and
88 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
89 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
91 /// Note that NUW and NSW are also valid properties of a recurrence, and
92 /// either implies NW. For convenience, NW will be set for a recurrence
93 /// whenever either NUW or NSW are set.
94 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
95 FlagNW = (1 << 0), // No self-wrap.
96 FlagNUW = (1 << 1), // No unsigned wrap.
97 FlagNSW = (1 << 2), // No signed wrap.
98 NoWrapMask = (1 << 3) -1 };
100 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
101 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
103 unsigned getSCEVType() const { return SCEVType; }
105 /// getType - Return the LLVM type of this SCEV expression.
107 Type *getType() const;
109 /// isZero - Return true if the expression is a constant zero.
113 /// isOne - Return true if the expression is a constant one.
117 /// isAllOnesValue - Return true if the expression is a constant
120 bool isAllOnesValue() const;
122 /// isNonConstantNegative - Return true if the specified scev is negated,
123 /// but not a constant.
124 bool isNonConstantNegative() const;
126 /// print - Print out the internal representation of this scalar to the
127 /// specified stream. This should really only be used for debugging
129 void print(raw_ostream &OS) const;
131 /// dump - This method is used for debugging.
136 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
137 // temporary FoldingSetNodeID values.
138 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
139 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
142 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
143 unsigned IDHash, FoldingSetNodeID &TempID) {
144 return ID == X.FastID;
146 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
147 return X.FastID.ComputeHash();
151 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
156 /// SCEVCouldNotCompute - An object of this class is returned by queries that
157 /// could not be answered. For example, if you ask for the number of
158 /// iterations of a linked-list traversal loop, you will get one of these.
159 /// None of the standard SCEV operations are valid on this class, it is just a
161 struct SCEVCouldNotCompute : public SCEV {
162 SCEVCouldNotCompute();
164 /// Methods for support type inquiry through isa, cast, and dyn_cast:
165 static bool classof(const SCEV *S);
168 /// ScalarEvolution - This class is the main scalar evolution driver. Because
169 /// client code (intentionally) can't do much with the SCEV objects directly,
170 /// they must ask this class for services.
172 class ScalarEvolution : public FunctionPass {
174 /// LoopDisposition - An enum describing the relationship between a
176 enum LoopDisposition {
177 LoopVariant, ///< The SCEV is loop-variant (unknown).
178 LoopInvariant, ///< The SCEV is loop-invariant.
179 LoopComputable ///< The SCEV varies predictably with the loop.
182 /// BlockDisposition - An enum describing the relationship between a
183 /// SCEV and a basic block.
184 enum BlockDisposition {
185 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
186 DominatesBlock, ///< The SCEV dominates the block.
187 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
190 /// Convenient NoWrapFlags manipulation that hides enum casts and is
191 /// visible in the ScalarEvolution name space.
192 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
193 maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
194 return (SCEV::NoWrapFlags)(Flags & Mask);
196 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
197 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) {
198 return (SCEV::NoWrapFlags)(Flags | OnFlags);
200 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT
201 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) {
202 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
206 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
207 /// notified whenever a Value is deleted.
208 class SCEVCallbackVH : public CallbackVH {
210 virtual void deleted();
211 virtual void allUsesReplacedWith(Value *New);
213 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
216 friend class SCEVCallbackVH;
217 friend class SCEVExpander;
218 friend class SCEVUnknown;
220 /// F - The function we are analyzing.
224 /// LI - The loop information for the function we are currently analyzing.
228 /// TD - The target data information for the target we are targeting.
232 /// TLI - The target library information for the target we are targeting.
234 TargetLibraryInfo *TLI;
236 /// DT - The dominator tree.
240 /// CouldNotCompute - This SCEV is used to represent unknown trip
241 /// counts and things.
242 SCEVCouldNotCompute CouldNotCompute;
244 /// ValueExprMapType - The typedef for ValueExprMap.
246 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
249 /// ValueExprMap - This is a cache of the values we have analyzed so far.
251 ValueExprMapType ValueExprMap;
253 /// Mark predicate values currently being processed by isImpliedCond.
254 DenseSet<Value*> PendingLoopPredicates;
256 /// ExitLimit - Information about the number of loop iterations for
257 /// which a loop exit's branch condition evaluates to the not-taken path.
258 /// This is a temporary pair of exact and max expressions that are
259 /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
264 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
266 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
268 /// hasAnyInfo - Test whether this ExitLimit contains any computed
269 /// information, or whether it's all SCEVCouldNotCompute values.
270 bool hasAnyInfo() const {
271 return !isa<SCEVCouldNotCompute>(Exact) ||
272 !isa<SCEVCouldNotCompute>(Max);
276 /// ExitNotTakenInfo - Information about the number of times a particular
277 /// loop exit may be reached before exiting the loop.
278 struct ExitNotTakenInfo {
279 AssertingVH<BasicBlock> ExitingBlock;
280 const SCEV *ExactNotTaken;
281 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
283 ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
285 /// isCompleteList - Return true if all loop exits are computable.
286 bool isCompleteList() const {
287 return NextExit.getInt() == 0;
290 void setIncomplete() { NextExit.setInt(1); }
292 /// getNextExit - Return a pointer to the next exit's not-taken info.
293 ExitNotTakenInfo *getNextExit() const {
294 return NextExit.getPointer();
297 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
300 /// BackedgeTakenInfo - Information about the backedge-taken count
301 /// of a loop. This currently includes an exact count and a maximum count.
303 class BackedgeTakenInfo {
304 /// ExitNotTaken - A list of computable exits and their not-taken counts.
305 /// Loops almost never have more than one computable exit.
306 ExitNotTakenInfo ExitNotTaken;
308 /// Max - An expression indicating the least maximum backedge-taken
309 /// count of the loop that is known, or a SCEVCouldNotCompute.
313 BackedgeTakenInfo() : Max(0) {}
315 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
317 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
318 bool Complete, const SCEV *MaxCount);
320 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
321 /// computed information, or whether it's all SCEVCouldNotCompute
323 bool hasAnyInfo() const {
324 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
327 /// getExact - Return an expression indicating the exact backedge-taken
328 /// count of the loop if it is known, or SCEVCouldNotCompute
329 /// otherwise. This is the number of times the loop header can be
330 /// guaranteed to execute, minus one.
331 const SCEV *getExact(ScalarEvolution *SE) const;
333 /// getExact - Return the number of times this loop exit may fall through
334 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
335 /// to exit via this block before this number of iterations, but may exit
336 /// via another block.
337 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
339 /// getMax - Get the max backedge taken count for the loop.
340 const SCEV *getMax(ScalarEvolution *SE) const;
342 /// Return true if any backedge taken count expressions refer to the given
344 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const;
346 /// clear - Invalidate this result and free associated memory.
350 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
351 /// this function as they are computed.
352 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
354 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
355 /// the PHI instructions that we attempt to compute constant evolutions for.
356 /// This allows us to avoid potentially expensive recomputation of these
357 /// properties. An instruction maps to null if we are unable to compute its
359 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
361 /// ValuesAtScopes - This map contains entries for all the expressions
362 /// that we attempt to compute getSCEVAtScope information for, which can
363 /// be expensive in extreme cases.
364 DenseMap<const SCEV *,
365 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes;
367 /// LoopDispositions - Memoized computeLoopDisposition results.
368 DenseMap<const SCEV *,
369 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions;
371 /// computeLoopDisposition - Compute a LoopDisposition value.
372 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
374 /// BlockDispositions - Memoized computeBlockDisposition results.
375 DenseMap<const SCEV *,
376 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions;
378 /// computeBlockDisposition - Compute a BlockDisposition value.
379 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
381 /// UnsignedRanges - Memoized results from getUnsignedRange
382 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
384 /// SignedRanges - Memoized results from getSignedRange
385 DenseMap<const SCEV *, ConstantRange> SignedRanges;
387 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
388 const ConstantRange &setUnsignedRange(const SCEV *S,
389 const ConstantRange &CR) {
390 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
391 UnsignedRanges.insert(std::make_pair(S, CR));
393 Pair.first->second = CR;
394 return Pair.first->second;
397 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
398 const ConstantRange &setSignedRange(const SCEV *S,
399 const ConstantRange &CR) {
400 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
401 SignedRanges.insert(std::make_pair(S, CR));
403 Pair.first->second = CR;
404 return Pair.first->second;
407 /// createSCEV - We know that there is no SCEV for the specified value.
408 /// Analyze the expression.
409 const SCEV *createSCEV(Value *V);
411 /// createNodeForPHI - Provide the special handling we need to analyze PHI
413 const SCEV *createNodeForPHI(PHINode *PN);
415 /// createNodeForGEP - Provide the special handling we need to analyze GEP
417 const SCEV *createNodeForGEP(GEPOperator *GEP);
419 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
420 /// at most once for each SCEV+Loop pair.
422 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
424 /// ForgetSymbolicValue - This looks up computed SCEV values for all
425 /// instructions that depend on the given instruction and removes them from
426 /// the ValueExprMap map if they reference SymName. This is used during PHI
428 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
430 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
431 /// loop, lazily computing new values if the loop hasn't been analyzed
433 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
435 /// ComputeBackedgeTakenCount - Compute the number of times the specified
436 /// loop will iterate.
437 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
439 /// ComputeExitLimit - Compute the number of times the backedge of the
440 /// specified loop will execute if it exits via the specified block.
441 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
443 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
444 /// the specified loop will execute if its exit condition were a conditional
445 /// branch of ExitCond, TBB, and FBB.
446 ExitLimit ComputeExitLimitFromCond(const Loop *L,
452 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
453 /// the specified loop will execute if its exit condition were a conditional
454 /// branch of the ICmpInst ExitCond, TBB, and FBB.
455 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
461 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
462 /// of 'icmp op load X, cst', try to see if we can compute the
463 /// backedge-taken count.
464 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
467 ICmpInst::Predicate p);
469 /// ComputeExitCountExhaustively - If the loop is known to execute a
470 /// constant number of times (the condition evolves only from constants),
471 /// try to evaluate a few iterations of the loop until we get the exit
472 /// condition gets a value of ExitWhen (true or false). If we cannot
473 /// evaluate the exit count of the loop, return CouldNotCompute.
474 const SCEV *ComputeExitCountExhaustively(const Loop *L,
478 /// HowFarToZero - Return the number of times an exit condition comparing
479 /// the specified value to zero will execute. If not computable, return
481 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr);
483 /// HowFarToNonZero - Return the number of times an exit condition checking
484 /// the specified value for nonzero will execute. If not computable, return
486 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
488 /// HowManyLessThans - Return the number of times an exit condition
489 /// containing the specified less-than comparison will execute. If not
490 /// computable, return CouldNotCompute. isSigned specifies whether the
491 /// less-than is signed.
492 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
493 const Loop *L, bool isSigned, bool IsSubExpr);
494 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
495 const Loop *L, bool isSigned, bool IsSubExpr);
497 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
498 /// (which may not be an immediate predecessor) which has exactly one
499 /// successor from which BB is reachable, or null if no such block is
501 std::pair<BasicBlock *, BasicBlock *>
502 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
504 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
505 /// RHS is true whenever the given FoundCondValue value evaluates to true.
506 bool isImpliedCond(ICmpInst::Predicate Pred,
507 const SCEV *LHS, const SCEV *RHS,
508 Value *FoundCondValue,
511 /// isImpliedCondOperands - Test whether the condition described by Pred,
512 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
513 /// and FoundRHS is true.
514 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
515 const SCEV *LHS, const SCEV *RHS,
516 const SCEV *FoundLHS, const SCEV *FoundRHS);
518 /// isImpliedCondOperandsHelper - Test whether the condition described by
519 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
520 /// FoundLHS, and FoundRHS is true.
521 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
522 const SCEV *LHS, const SCEV *RHS,
523 const SCEV *FoundLHS,
524 const SCEV *FoundRHS);
526 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
527 /// in the header of its containing loop, we know the loop executes a
528 /// constant number of times, and the PHI node is just a recurrence
529 /// involving constants, fold it.
530 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
533 /// isKnownPredicateWithRanges - Test if the given expression is known to
534 /// satisfy the condition described by Pred and the known constant ranges
537 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
538 const SCEV *LHS, const SCEV *RHS);
540 /// forgetMemoizedResults - Drop memoized information computed for S.
541 void forgetMemoizedResults(const SCEV *S);
543 /// Return false iff given SCEV contains a SCEVUnknown with NULL value-
545 bool checkValidity(const SCEV *S) const;
548 static char ID; // Pass identification, replacement for typeid
551 LLVMContext &getContext() const { return F->getContext(); }
553 /// isSCEVable - Test if values of the given type are analyzable within
554 /// the SCEV framework. This primarily includes integer types, and it
555 /// can optionally include pointer types if the ScalarEvolution class
556 /// has access to target-specific information.
557 bool isSCEVable(Type *Ty) const;
559 /// getTypeSizeInBits - Return the size in bits of the specified type,
560 /// for which isSCEVable must return true.
561 uint64_t getTypeSizeInBits(Type *Ty) const;
563 /// getEffectiveSCEVType - Return a type with the same bitwidth as
564 /// the given type and which represents how SCEV will treat the given
565 /// type, for which isSCEVable must return true. For pointer types,
566 /// this is the pointer-sized integer type.
567 Type *getEffectiveSCEVType(Type *Ty) const;
569 /// getSCEV - Return a SCEV expression for the full generality of the
570 /// specified expression.
571 const SCEV *getSCEV(Value *V);
573 const SCEV *getConstant(ConstantInt *V);
574 const SCEV *getConstant(const APInt& Val);
575 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
576 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
577 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
578 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
579 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
580 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
581 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
582 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
583 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
584 SmallVector<const SCEV *, 2> Ops;
587 return getAddExpr(Ops, Flags);
589 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
590 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
591 SmallVector<const SCEV *, 3> Ops;
595 return getAddExpr(Ops, Flags);
597 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
598 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
599 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
600 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
602 SmallVector<const SCEV *, 2> Ops;
605 return getMulExpr(Ops, Flags);
607 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
608 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
609 SmallVector<const SCEV *, 3> Ops;
613 return getMulExpr(Ops, Flags);
615 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
616 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
617 const Loop *L, SCEV::NoWrapFlags Flags);
618 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
619 const Loop *L, SCEV::NoWrapFlags Flags);
620 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
621 const Loop *L, SCEV::NoWrapFlags Flags) {
622 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
623 return getAddRecExpr(NewOp, L, Flags);
625 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
626 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
627 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
628 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
629 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
630 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
631 const SCEV *getUnknown(Value *V);
632 const SCEV *getCouldNotCompute();
634 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type
637 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy);
639 /// getOffsetOfExpr - Return an expression for offsetof on the given field
642 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo);
644 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
646 const SCEV *getNegativeSCEV(const SCEV *V);
648 /// getNotSCEV - Return the SCEV object corresponding to ~V.
650 const SCEV *getNotSCEV(const SCEV *V);
652 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
653 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
654 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
656 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
657 /// of the input value to the specified type. If the type must be
658 /// extended, it is zero extended.
659 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
661 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
662 /// of the input value to the specified type. If the type must be
663 /// extended, it is sign extended.
664 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
666 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
667 /// the input value to the specified type. If the type must be extended,
668 /// it is zero extended. The conversion must not be narrowing.
669 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
671 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
672 /// the input value to the specified type. If the type must be extended,
673 /// it is sign extended. The conversion must not be narrowing.
674 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
676 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
677 /// the input value to the specified type. If the type must be extended,
678 /// it is extended with unspecified bits. The conversion must not be
680 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
682 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
683 /// input value to the specified type. The conversion must not be
685 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
687 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
688 /// the types using zero-extension, and then perform a umax operation
690 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
693 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
694 /// the types using zero-extension, and then perform a umin operation
696 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
699 /// getPointerBase - Transitively follow the chain of pointer-type operands
700 /// until reaching a SCEV that does not have a single pointer operand. This
701 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
702 /// but corner cases do exist.
703 const SCEV *getPointerBase(const SCEV *V);
705 /// getSCEVAtScope - Return a SCEV expression for the specified value
706 /// at the specified scope in the program. The L value specifies a loop
707 /// nest to evaluate the expression at, where null is the top-level or a
708 /// specified loop is immediately inside of the loop.
710 /// This method can be used to compute the exit value for a variable defined
711 /// in a loop by querying what the value will hold in the parent loop.
713 /// In the case that a relevant loop exit value cannot be computed, the
714 /// original value V is returned.
715 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
717 /// getSCEVAtScope - This is a convenience function which does
718 /// getSCEVAtScope(getSCEV(V), L).
719 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
721 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
722 /// by a conditional between LHS and RHS. This is used to help avoid max
723 /// expressions in loop trip counts, and to eliminate casts.
724 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
725 const SCEV *LHS, const SCEV *RHS);
727 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
728 /// protected by a conditional between LHS and RHS. This is used to
729 /// to eliminate casts.
730 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
731 const SCEV *LHS, const SCEV *RHS);
733 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
734 /// as a normal unsigned value. Returns 0 if the trip count is unknown or
735 /// not constant. This "trip count" assumes that control exits via
736 /// ExitingBlock. More precisely, it is the number of times that control may
737 /// reach ExitingBlock before taking the branch. For loops with multiple
738 /// exits, it may not be the number times that the loop header executes if
739 /// the loop exits prematurely via another branch.
740 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock);
742 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
743 /// the trip count of this loop as a normal unsigned value, if
744 /// possible. This means that the actual trip count is always a multiple of
745 /// the returned value (don't forget the trip count could very well be zero
746 /// as well!). As explained in the comments for getSmallConstantTripCount,
747 /// this assumes that control exits the loop via ExitingBlock.
748 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock);
750 // getExitCount - Get the expression for the number of loop iterations for
751 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
752 // return SCEVCouldNotCompute.
753 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
755 /// getBackedgeTakenCount - If the specified loop has a predictable
756 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
757 /// object. The backedge-taken count is the number of times the loop header
758 /// will be branched to from within the loop. This is one less than the
759 /// trip count of the loop, since it doesn't count the first iteration,
760 /// when the header is branched to from outside the loop.
762 /// Note that it is not valid to call this method on a loop without a
763 /// loop-invariant backedge-taken count (see
764 /// hasLoopInvariantBackedgeTakenCount).
766 const SCEV *getBackedgeTakenCount(const Loop *L);
768 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
769 /// return the least SCEV value that is known never to be less than the
770 /// actual backedge taken count.
771 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
773 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
774 /// has an analyzable loop-invariant backedge-taken count.
775 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
777 /// forgetLoop - This method should be called by the client when it has
778 /// changed a loop in a way that may effect ScalarEvolution's ability to
779 /// compute a trip count, or if the loop is deleted.
780 void forgetLoop(const Loop *L);
782 /// forgetValue - This method should be called by the client when it has
783 /// changed a value in a way that may effect its value, or which may
784 /// disconnect it from a def-use chain linking it to a loop.
785 void forgetValue(Value *V);
787 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
788 /// is guaranteed to end in (at every loop iteration). It is, at the same
789 /// time, the minimum number of times S is divisible by 2. For example,
790 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
792 uint32_t GetMinTrailingZeros(const SCEV *S);
794 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
796 ConstantRange getUnsignedRange(const SCEV *S);
798 /// getSignedRange - Determine the signed range for a particular SCEV.
800 ConstantRange getSignedRange(const SCEV *S);
802 /// isKnownNegative - Test if the given expression is known to be negative.
804 bool isKnownNegative(const SCEV *S);
806 /// isKnownPositive - Test if the given expression is known to be positive.
808 bool isKnownPositive(const SCEV *S);
810 /// isKnownNonNegative - Test if the given expression is known to be
813 bool isKnownNonNegative(const SCEV *S);
815 /// isKnownNonPositive - Test if the given expression is known to be
818 bool isKnownNonPositive(const SCEV *S);
820 /// isKnownNonZero - Test if the given expression is known to be
823 bool isKnownNonZero(const SCEV *S);
825 /// isKnownPredicate - Test if the given expression is known to satisfy
826 /// the condition described by Pred, LHS, and RHS.
828 bool isKnownPredicate(ICmpInst::Predicate Pred,
829 const SCEV *LHS, const SCEV *RHS);
831 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
832 /// predicate Pred. Return true iff any changes were made. If the
833 /// operands are provably equal or unequal, LHS and RHS are set to
834 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
836 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
841 /// getLoopDisposition - Return the "disposition" of the given SCEV with
842 /// respect to the given loop.
843 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
845 /// isLoopInvariant - Return true if the value of the given SCEV is
846 /// unchanging in the specified loop.
847 bool isLoopInvariant(const SCEV *S, const Loop *L);
849 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
850 /// in a known way in the specified loop. This property being true implies
851 /// that the value is variant in the loop AND that we can emit an expression
852 /// to compute the value of the expression at any particular loop iteration.
853 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
855 /// getLoopDisposition - Return the "disposition" of the given SCEV with
856 /// respect to the given block.
857 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
859 /// dominates - Return true if elements that makes up the given SCEV
860 /// dominate the specified basic block.
861 bool dominates(const SCEV *S, const BasicBlock *BB);
863 /// properlyDominates - Return true if elements that makes up the given SCEV
864 /// properly dominate the specified basic block.
865 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
867 /// hasOperand - Test whether the given SCEV has Op as a direct or
868 /// indirect operand.
869 bool hasOperand(const SCEV *S, const SCEV *Op) const;
871 virtual bool runOnFunction(Function &F);
872 virtual void releaseMemory();
873 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
874 virtual void print(raw_ostream &OS, const Module* = 0) const;
875 virtual void verifyAnalysis() const;
878 /// Compute the backedge taken count knowing the interval difference, the
879 /// stride and presence of the equality in the comparison.
880 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride,
883 /// Verify if an linear IV with positive stride can overflow when in a
884 /// less-than comparison, knowing the invariant term of the comparison,
885 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
886 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
887 bool IsSigned, bool NoWrap);
889 /// Verify if an linear IV with negative stride can overflow when in a
890 /// greater-than comparison, knowing the invariant term of the comparison,
891 /// the stride and the knowledge of NSW/NUW flags on the recurrence.
892 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
893 bool IsSigned, bool NoWrap);
896 FoldingSet<SCEV> UniqueSCEVs;
897 BumpPtrAllocator SCEVAllocator;
899 /// FirstUnknown - The head of a linked list of all SCEVUnknown
900 /// values that have been allocated. This is used by releaseMemory
901 /// to locate them all and call their destructors.
902 SCEVUnknown *FirstUnknown;