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/Pass.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Function.h"
27 #include "llvm/Operator.h"
28 #include "llvm/Support/DataTypes.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/ADT/FoldingSet.h"
33 #include "llvm/ADT/DenseMap.h"
42 class ScalarEvolution;
50 template<> struct FoldingSetTrait<SCEV>;
52 /// SCEV - This class represents an analyzed expression in the program. These
53 /// are opaque objects that the client is not allowed to do much with
56 class SCEV : public FoldingSetNode {
57 friend struct FoldingSetTrait<SCEV>;
59 /// FastID - A reference to an Interned FoldingSetNodeID for this node.
60 /// The ScalarEvolution's BumpPtrAllocator holds the data.
61 FoldingSetNodeIDRef FastID;
63 // The SCEV baseclass this node corresponds to
64 const unsigned short SCEVType;
67 /// SubclassData - This field is initialized to zero and may be used in
68 /// subclasses to store miscellaneous information.
69 unsigned short SubclassData;
72 SCEV(const SCEV &); // DO NOT IMPLEMENT
73 void operator=(const SCEV &); // DO NOT IMPLEMENT
76 /// NoWrapFlags are bitfield indices into SubclassData.
78 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or
79 /// no-signed-wrap <NSW> properties, which are derived from the IR
80 /// operator. NSW is a misnomer that we use to mean no signed overflow or
83 /// AddRec expression may have a no-self-wraparound <NW> property if the
84 /// result can never reach the start value. This property is independent of
85 /// the actual start value and step direction. Self-wraparound is defined
86 /// purely in terms of the recurrence's loop, step size, and
87 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies:
88 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth).
90 /// Note that NUW and NSW are also valid properties of a recurrence, and
91 /// either implies NW. For convenience, NW will be set for a recurrence
92 /// whenever either NUW or NSW are set.
93 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee.
94 FlagNW = (1 << 0), // No self-wrap.
95 FlagNUW = (1 << 1), // No unsigned wrap.
96 FlagNSW = (1 << 2), // No signed wrap.
97 NoWrapMask = (1 << 3) -1 };
99 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) :
100 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {}
102 unsigned getSCEVType() const { return SCEVType; }
104 /// getType - Return the LLVM type of this SCEV expression.
106 Type *getType() const;
108 /// isZero - Return true if the expression is a constant zero.
112 /// isOne - Return true if the expression is a constant one.
116 /// isAllOnesValue - Return true if the expression is a constant
119 bool isAllOnesValue() const;
121 /// print - Print out the internal representation of this scalar to the
122 /// specified stream. This should really only be used for debugging
124 void print(raw_ostream &OS) const;
126 /// dump - This method is used for debugging.
131 // Specialize FoldingSetTrait for SCEV to avoid needing to compute
132 // temporary FoldingSetNodeID values.
133 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> {
134 static void Profile(const SCEV &X, FoldingSetNodeID& ID) {
137 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID,
138 FoldingSetNodeID &TempID) {
139 return ID == X.FastID;
141 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) {
142 return X.FastID.ComputeHash();
146 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) {
151 /// SCEVCouldNotCompute - An object of this class is returned by queries that
152 /// could not be answered. For example, if you ask for the number of
153 /// iterations of a linked-list traversal loop, you will get one of these.
154 /// None of the standard SCEV operations are valid on this class, it is just a
156 struct SCEVCouldNotCompute : public SCEV {
157 SCEVCouldNotCompute();
159 /// Methods for support type inquiry through isa, cast, and dyn_cast:
160 static inline bool classof(const SCEVCouldNotCompute *S) { return true; }
161 static bool classof(const SCEV *S);
164 /// ScalarEvolution - This class is the main scalar evolution driver. Because
165 /// client code (intentionally) can't do much with the SCEV objects directly,
166 /// they must ask this class for services.
168 class ScalarEvolution : public FunctionPass {
170 /// LoopDisposition - An enum describing the relationship between a
172 enum LoopDisposition {
173 LoopVariant, ///< The SCEV is loop-variant (unknown).
174 LoopInvariant, ///< The SCEV is loop-invariant.
175 LoopComputable ///< The SCEV varies predictably with the loop.
178 /// BlockDisposition - An enum describing the relationship between a
179 /// SCEV and a basic block.
180 enum BlockDisposition {
181 DoesNotDominateBlock, ///< The SCEV does not dominate the block.
182 DominatesBlock, ///< The SCEV dominates the block.
183 ProperlyDominatesBlock ///< The SCEV properly dominates the block.
186 /// Convenient NoWrapFlags manipulation that hides enum casts and is
187 /// visible in the ScalarEvolution name space.
188 static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) {
189 return (SCEV::NoWrapFlags)(Flags & Mask);
191 static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags,
192 SCEV::NoWrapFlags OnFlags) {
193 return (SCEV::NoWrapFlags)(Flags | OnFlags);
195 static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags,
196 SCEV::NoWrapFlags OffFlags) {
197 return (SCEV::NoWrapFlags)(Flags & ~OffFlags);
201 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be
202 /// notified whenever a Value is deleted.
203 class SCEVCallbackVH : public CallbackVH {
205 virtual void deleted();
206 virtual void allUsesReplacedWith(Value *New);
208 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0);
211 friend class SCEVCallbackVH;
212 friend class SCEVExpander;
213 friend class SCEVUnknown;
215 /// F - The function we are analyzing.
219 /// LI - The loop information for the function we are currently analyzing.
223 /// TD - The target data information for the target we are targeting.
227 /// DT - The dominator tree.
231 /// CouldNotCompute - This SCEV is used to represent unknown trip
232 /// counts and things.
233 SCEVCouldNotCompute CouldNotCompute;
235 /// ValueExprMapType - The typedef for ValueExprMap.
237 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> >
240 /// ValueExprMap - This is a cache of the values we have analyzed so far.
242 ValueExprMapType ValueExprMap;
244 /// ExitLimit - Information about the number of loop iterations for
245 /// which a loop exit's branch condition evaluates to the not-taken path.
246 /// This is a temporary pair of exact and max expressions that are
247 /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo.
252 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {}
254 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {}
256 /// hasAnyInfo - Test whether this ExitLimit contains any computed
257 /// information, or whether it's all SCEVCouldNotCompute values.
258 bool hasAnyInfo() const {
259 return !isa<SCEVCouldNotCompute>(Exact) ||
260 !isa<SCEVCouldNotCompute>(Max);
264 /// ExitNotTakenInfo - Information about the number of times a particular
265 /// loop exit may be reached before exiting the loop.
266 struct ExitNotTakenInfo {
267 AssertingVH<BasicBlock> ExitingBlock;
268 const SCEV *ExactNotTaken;
269 PointerIntPair<ExitNotTakenInfo*, 1> NextExit;
271 ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {}
273 /// isCompleteList - Return true if all loop exits are computable.
274 bool isCompleteList() const {
275 return NextExit.getInt() == 0;
278 void setIncomplete() { NextExit.setInt(1); }
280 /// getNextExit - Return a pointer to the next exit's not-taken info.
281 ExitNotTakenInfo *getNextExit() const {
282 return NextExit.getPointer();
285 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); }
288 /// BackedgeTakenInfo - Information about the backedge-taken count
289 /// of a loop. This currently includes an exact count and a maximum count.
291 class BackedgeTakenInfo {
292 /// ExitNotTaken - A list of computable exits and their not-taken counts.
293 /// Loops almost never have more than one computable exit.
294 ExitNotTakenInfo ExitNotTaken;
296 /// Max - An expression indicating the least maximum backedge-taken
297 /// count of the loop that is known, or a SCEVCouldNotCompute.
301 BackedgeTakenInfo() : Max(0) {}
303 /// Initialize BackedgeTakenInfo from a list of exact exit counts.
305 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
306 bool Complete, const SCEV *MaxCount);
308 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any
309 /// computed information, or whether it's all SCEVCouldNotCompute
311 bool hasAnyInfo() const {
312 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max);
315 /// getExact - Return an expression indicating the exact backedge-taken
316 /// count of the loop if it is known, or SCEVCouldNotCompute
317 /// otherwise. This is the number of times the loop header can be
318 /// guaranteed to execute, minus one.
319 const SCEV *getExact(ScalarEvolution *SE) const;
321 /// getExact - Return the number of times this loop exit may fall through
322 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not
323 /// to exit via this block before this number of iterations, but may exit
324 /// via another block.
325 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const;
327 /// getMax - Get the max backedge taken count for the loop.
328 const SCEV *getMax(ScalarEvolution *SE) const;
330 /// clear - Invalidate this result and free associated memory.
334 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for
335 /// this function as they are computed.
336 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts;
338 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
339 /// the PHI instructions that we attempt to compute constant evolutions for.
340 /// This allows us to avoid potentially expensive recomputation of these
341 /// properties. An instruction maps to null if we are unable to compute its
343 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
345 /// ValuesAtScopes - This map contains entries for all the expressions
346 /// that we attempt to compute getSCEVAtScope information for, which can
347 /// be expensive in extreme cases.
348 DenseMap<const SCEV *,
349 std::map<const Loop *, const SCEV *> > ValuesAtScopes;
351 /// LoopDispositions - Memoized computeLoopDisposition results.
352 DenseMap<const SCEV *,
353 std::map<const Loop *, LoopDisposition> > LoopDispositions;
355 /// computeLoopDisposition - Compute a LoopDisposition value.
356 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L);
358 /// BlockDispositions - Memoized computeBlockDisposition results.
359 DenseMap<const SCEV *,
360 std::map<const BasicBlock *, BlockDisposition> > BlockDispositions;
362 /// computeBlockDisposition - Compute a BlockDisposition value.
363 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB);
365 /// UnsignedRanges - Memoized results from getUnsignedRange
366 DenseMap<const SCEV *, ConstantRange> UnsignedRanges;
368 /// SignedRanges - Memoized results from getSignedRange
369 DenseMap<const SCEV *, ConstantRange> SignedRanges;
371 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV.
372 const ConstantRange &setUnsignedRange(const SCEV *S,
373 const ConstantRange &CR) {
374 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
375 UnsignedRanges.insert(std::make_pair(S, CR));
377 Pair.first->second = CR;
378 return Pair.first->second;
381 /// setUnsignedRange - Set the memoized signed range for the given SCEV.
382 const ConstantRange &setSignedRange(const SCEV *S,
383 const ConstantRange &CR) {
384 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair =
385 SignedRanges.insert(std::make_pair(S, CR));
387 Pair.first->second = CR;
388 return Pair.first->second;
391 /// createSCEV - We know that there is no SCEV for the specified value.
392 /// Analyze the expression.
393 const SCEV *createSCEV(Value *V);
395 /// createNodeForPHI - Provide the special handling we need to analyze PHI
397 const SCEV *createNodeForPHI(PHINode *PN);
399 /// createNodeForGEP - Provide the special handling we need to analyze GEP
401 const SCEV *createNodeForGEP(GEPOperator *GEP);
403 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called
404 /// at most once for each SCEV+Loop pair.
406 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L);
408 /// ForgetSymbolicValue - This looks up computed SCEV values for all
409 /// instructions that depend on the given instruction and removes them from
410 /// the ValueExprMap map if they reference SymName. This is used during PHI
412 void ForgetSymbolicName(Instruction *I, const SCEV *SymName);
414 /// getBECount - Subtract the end and start values and divide by the step,
415 /// rounding up, to get the number of times the backedge is executed. Return
416 /// CouldNotCompute if an intermediate computation overflows.
417 const SCEV *getBECount(const SCEV *Start,
422 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given
423 /// loop, lazily computing new values if the loop hasn't been analyzed
425 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L);
427 /// ComputeBackedgeTakenCount - Compute the number of times the specified
428 /// loop will iterate.
429 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L);
431 /// ComputeExitLimit - Compute the number of times the backedge of the
432 /// specified loop will execute if it exits via the specified block.
433 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock);
435 /// ComputeExitLimitFromCond - Compute the number of times the backedge of
436 /// the specified loop will execute if its exit condition were a conditional
437 /// branch of ExitCond, TBB, and FBB.
438 ExitLimit ComputeExitLimitFromCond(const Loop *L,
443 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of
444 /// the specified loop will execute if its exit condition were a conditional
445 /// branch of the ICmpInst ExitCond, TBB, and FBB.
446 ExitLimit ComputeExitLimitFromICmp(const Loop *L,
451 /// ComputeLoadConstantCompareExitLimit - Given an exit condition
452 /// of 'icmp op load X, cst', try to see if we can compute the
453 /// backedge-taken count.
454 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI,
457 ICmpInst::Predicate p);
459 /// ComputeExitCountExhaustively - If the loop is known to execute a
460 /// constant number of times (the condition evolves only from constants),
461 /// try to evaluate a few iterations of the loop until we get the exit
462 /// condition gets a value of ExitWhen (true or false). If we cannot
463 /// evaluate the exit count of the loop, return CouldNotCompute.
464 const SCEV *ComputeExitCountExhaustively(const Loop *L,
468 /// HowFarToZero - Return the number of times an exit condition comparing
469 /// the specified value to zero will execute. If not computable, return
471 ExitLimit HowFarToZero(const SCEV *V, const Loop *L);
473 /// HowFarToNonZero - Return the number of times an exit condition checking
474 /// the specified value for nonzero will execute. If not computable, return
476 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L);
478 /// HowManyLessThans - Return the number of times an exit condition
479 /// containing the specified less-than comparison will execute. If not
480 /// computable, return CouldNotCompute. isSigned specifies whether the
481 /// less-than is signed.
482 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
483 const Loop *L, bool isSigned);
485 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
486 /// (which may not be an immediate predecessor) which has exactly one
487 /// successor from which BB is reachable, or null if no such block is
489 std::pair<BasicBlock *, BasicBlock *>
490 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB);
492 /// isImpliedCond - Test whether the condition described by Pred, LHS, and
493 /// RHS is true whenever the given FoundCondValue value evaluates to true.
494 bool isImpliedCond(ICmpInst::Predicate Pred,
495 const SCEV *LHS, const SCEV *RHS,
496 Value *FoundCondValue,
499 /// isImpliedCondOperands - Test whether the condition described by Pred,
500 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
501 /// and FoundRHS is true.
502 bool isImpliedCondOperands(ICmpInst::Predicate Pred,
503 const SCEV *LHS, const SCEV *RHS,
504 const SCEV *FoundLHS, const SCEV *FoundRHS);
506 /// isImpliedCondOperandsHelper - Test whether the condition described by
507 /// Pred, LHS, and RHS is true whenever the condition described by Pred,
508 /// FoundLHS, and FoundRHS is true.
509 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
510 const SCEV *LHS, const SCEV *RHS,
511 const SCEV *FoundLHS,
512 const SCEV *FoundRHS);
514 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
515 /// in the header of its containing loop, we know the loop executes a
516 /// constant number of times, and the PHI node is just a recurrence
517 /// involving constants, fold it.
518 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs,
521 /// isKnownPredicateWithRanges - Test if the given expression is known to
522 /// satisfy the condition described by Pred and the known constant ranges
525 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
526 const SCEV *LHS, const SCEV *RHS);
528 /// forgetMemoizedResults - Drop memoized information computed for S.
529 void forgetMemoizedResults(const SCEV *S);
532 static char ID; // Pass identification, replacement for typeid
535 LLVMContext &getContext() const { return F->getContext(); }
537 /// isSCEVable - Test if values of the given type are analyzable within
538 /// the SCEV framework. This primarily includes integer types, and it
539 /// can optionally include pointer types if the ScalarEvolution class
540 /// has access to target-specific information.
541 bool isSCEVable(Type *Ty) const;
543 /// getTypeSizeInBits - Return the size in bits of the specified type,
544 /// for which isSCEVable must return true.
545 uint64_t getTypeSizeInBits(Type *Ty) const;
547 /// getEffectiveSCEVType - Return a type with the same bitwidth as
548 /// the given type and which represents how SCEV will treat the given
549 /// type, for which isSCEVable must return true. For pointer types,
550 /// this is the pointer-sized integer type.
551 Type *getEffectiveSCEVType(Type *Ty) const;
553 /// getSCEV - Return a SCEV expression for the full generality of the
554 /// specified expression.
555 const SCEV *getSCEV(Value *V);
557 const SCEV *getConstant(ConstantInt *V);
558 const SCEV *getConstant(const APInt& Val);
559 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false);
560 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty);
561 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty);
562 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty);
563 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty);
564 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
565 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
566 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS,
567 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
568 SmallVector<const SCEV *, 2> Ops;
571 return getAddExpr(Ops, Flags);
573 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
574 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
575 SmallVector<const SCEV *, 3> Ops;
579 return getAddExpr(Ops, Flags);
581 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
582 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
583 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS,
584 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap)
586 SmallVector<const SCEV *, 2> Ops;
589 return getMulExpr(Ops, Flags);
591 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2,
592 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) {
593 SmallVector<const SCEV *, 3> Ops;
597 return getMulExpr(Ops, Flags);
599 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS);
600 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step,
601 const Loop *L, SCEV::NoWrapFlags Flags);
602 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
603 const Loop *L, SCEV::NoWrapFlags Flags);
604 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands,
605 const Loop *L, SCEV::NoWrapFlags Flags) {
606 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end());
607 return getAddRecExpr(NewOp, L, Flags);
609 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS);
610 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
611 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS);
612 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands);
613 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS);
614 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS);
615 const SCEV *getUnknown(Value *V);
616 const SCEV *getCouldNotCompute();
618 /// getSizeOfExpr - Return an expression for sizeof on the given type.
620 const SCEV *getSizeOfExpr(Type *AllocTy);
622 /// getAlignOfExpr - Return an expression for alignof on the given type.
624 const SCEV *getAlignOfExpr(Type *AllocTy);
626 /// getOffsetOfExpr - Return an expression for offsetof on the given field.
628 const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo);
630 /// getOffsetOfExpr - Return an expression for offsetof on the given field.
632 const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo);
634 /// getNegativeSCEV - Return the SCEV object corresponding to -V.
636 const SCEV *getNegativeSCEV(const SCEV *V);
638 /// getNotSCEV - Return the SCEV object corresponding to ~V.
640 const SCEV *getNotSCEV(const SCEV *V);
642 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
643 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
644 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap);
646 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
647 /// of the input value to the specified type. If the type must be
648 /// extended, it is zero extended.
649 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty);
651 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion
652 /// of the input value to the specified type. If the type must be
653 /// extended, it is sign extended.
654 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty);
656 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of
657 /// the input value to the specified type. If the type must be extended,
658 /// it is zero extended. The conversion must not be narrowing.
659 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty);
661 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of
662 /// the input value to the specified type. If the type must be extended,
663 /// it is sign extended. The conversion must not be narrowing.
664 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty);
666 /// getNoopOrAnyExtend - 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 extended with unspecified bits. The conversion must not be
670 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty);
672 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
673 /// input value to the specified type. The conversion must not be
675 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty);
677 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of
678 /// the types using zero-extension, and then perform a umax operation
680 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS,
683 /// getUMinFromMismatchedTypes - Promote the operands to the wider of
684 /// the types using zero-extension, and then perform a umin operation
686 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS,
689 /// getPointerBase - Transitively follow the chain of pointer-type operands
690 /// until reaching a SCEV that does not have a single pointer operand. This
691 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
692 /// but corner cases do exist.
693 const SCEV *getPointerBase(const SCEV *V);
695 /// getSCEVAtScope - Return a SCEV expression for the specified value
696 /// at the specified scope in the program. The L value specifies a loop
697 /// nest to evaluate the expression at, where null is the top-level or a
698 /// specified loop is immediately inside of the loop.
700 /// This method can be used to compute the exit value for a variable defined
701 /// in a loop by querying what the value will hold in the parent loop.
703 /// In the case that a relevant loop exit value cannot be computed, the
704 /// original value V is returned.
705 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L);
707 /// getSCEVAtScope - This is a convenience function which does
708 /// getSCEVAtScope(getSCEV(V), L).
709 const SCEV *getSCEVAtScope(Value *V, const Loop *L);
711 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
712 /// by a conditional between LHS and RHS. This is used to help avoid max
713 /// expressions in loop trip counts, and to eliminate casts.
714 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
715 const SCEV *LHS, const SCEV *RHS);
717 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
718 /// protected by a conditional between LHS and RHS. This is used to
719 /// to eliminate casts.
720 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred,
721 const SCEV *LHS, const SCEV *RHS);
723 /// getSmallConstantTripCount - Returns the maximum trip count of this loop
724 /// as a normal unsigned value, if possible. Returns 0 if the trip count is
725 /// unknown or not constant.
726 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitBlock);
728 /// getSmallConstantTripMultiple - Returns the largest constant divisor of
729 /// the trip count of this loop as a normal unsigned value, if
730 /// possible. This means that the actual trip count is always a multiple of
731 /// the returned value (don't forget the trip count could very well be zero
733 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitBlock);
735 // getExitCount - Get the expression for the number of loop iterations for
736 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise
737 // return SCEVCouldNotCompute.
738 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock);
740 /// getBackedgeTakenCount - If the specified loop has a predictable
741 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
742 /// object. The backedge-taken count is the number of times the loop header
743 /// will be branched to from within the loop. This is one less than the
744 /// trip count of the loop, since it doesn't count the first iteration,
745 /// when the header is branched to from outside the loop.
747 /// Note that it is not valid to call this method on a loop without a
748 /// loop-invariant backedge-taken count (see
749 /// hasLoopInvariantBackedgeTakenCount).
751 const SCEV *getBackedgeTakenCount(const Loop *L);
753 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
754 /// return the least SCEV value that is known never to be less than the
755 /// actual backedge taken count.
756 const SCEV *getMaxBackedgeTakenCount(const Loop *L);
758 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop
759 /// has an analyzable loop-invariant backedge-taken count.
760 bool hasLoopInvariantBackedgeTakenCount(const Loop *L);
762 /// forgetLoop - This method should be called by the client when it has
763 /// changed a loop in a way that may effect ScalarEvolution's ability to
764 /// compute a trip count, or if the loop is deleted.
765 void forgetLoop(const Loop *L);
767 /// forgetValue - This method should be called by the client when it has
768 /// changed a value in a way that may effect its value, or which may
769 /// disconnect it from a def-use chain linking it to a loop.
770 void forgetValue(Value *V);
772 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S
773 /// is guaranteed to end in (at every loop iteration). It is, at the same
774 /// time, the minimum number of times S is divisible by 2. For example,
775 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the
777 uint32_t GetMinTrailingZeros(const SCEV *S);
779 /// getUnsignedRange - Determine the unsigned range for a particular SCEV.
781 ConstantRange getUnsignedRange(const SCEV *S);
783 /// getSignedRange - Determine the signed range for a particular SCEV.
785 ConstantRange getSignedRange(const SCEV *S);
787 /// isKnownNegative - Test if the given expression is known to be negative.
789 bool isKnownNegative(const SCEV *S);
791 /// isKnownPositive - Test if the given expression is known to be positive.
793 bool isKnownPositive(const SCEV *S);
795 /// isKnownNonNegative - Test if the given expression is known to be
798 bool isKnownNonNegative(const SCEV *S);
800 /// isKnownNonPositive - Test if the given expression is known to be
803 bool isKnownNonPositive(const SCEV *S);
805 /// isKnownNonZero - Test if the given expression is known to be
808 bool isKnownNonZero(const SCEV *S);
810 /// isKnownPredicate - Test if the given expression is known to satisfy
811 /// the condition described by Pred, LHS, and RHS.
813 bool isKnownPredicate(ICmpInst::Predicate Pred,
814 const SCEV *LHS, const SCEV *RHS);
816 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
817 /// predicate Pred. Return true iff any changes were made. If the
818 /// operands are provably equal or inequal, LHS and RHS are set to
819 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE.
821 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred,
825 /// getLoopDisposition - Return the "disposition" of the given SCEV with
826 /// respect to the given loop.
827 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L);
829 /// isLoopInvariant - Return true if the value of the given SCEV is
830 /// unchanging in the specified loop.
831 bool isLoopInvariant(const SCEV *S, const Loop *L);
833 /// hasComputableLoopEvolution - Return true if the given SCEV changes value
834 /// in a known way in the specified loop. This property being true implies
835 /// that the value is variant in the loop AND that we can emit an expression
836 /// to compute the value of the expression at any particular loop iteration.
837 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L);
839 /// getLoopDisposition - Return the "disposition" of the given SCEV with
840 /// respect to the given block.
841 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB);
843 /// dominates - Return true if elements that makes up the given SCEV
844 /// dominate the specified basic block.
845 bool dominates(const SCEV *S, const BasicBlock *BB);
847 /// properlyDominates - Return true if elements that makes up the given SCEV
848 /// properly dominate the specified basic block.
849 bool properlyDominates(const SCEV *S, const BasicBlock *BB);
851 /// hasOperand - Test whether the given SCEV has Op as a direct or
852 /// indirect operand.
853 bool hasOperand(const SCEV *S, const SCEV *Op) const;
855 virtual bool runOnFunction(Function &F);
856 virtual void releaseMemory();
857 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
858 virtual void print(raw_ostream &OS, const Module* = 0) const;
861 FoldingSet<SCEV> UniqueSCEVs;
862 BumpPtrAllocator SCEVAllocator;
864 /// FirstUnknown - The head of a linked list of all SCEVUnknown
865 /// values that have been allocated. This is used by releaseMemory
866 /// to locate them all and call their destructors.
867 SCEVUnknown *FirstUnknown;