LLVM API Documentation
00001 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // The ScalarEvolution class is an LLVM pass which can be used to analyze and 00011 // categorize scalar expressions in loops. It specializes in recognizing 00012 // general induction variables, representing them with the abstract and opaque 00013 // SCEV class. Given this analysis, trip counts of loops and other important 00014 // properties can be obtained. 00015 // 00016 // This analysis is primarily useful for induction variable substitution and 00017 // strength reduction. 00018 // 00019 //===----------------------------------------------------------------------===// 00020 00021 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H 00022 #define LLVM_ANALYSIS_SCALAREVOLUTION_H 00023 00024 #include "llvm/ADT/DenseSet.h" 00025 #include "llvm/ADT/FoldingSet.h" 00026 #include "llvm/IR/ConstantRange.h" 00027 #include "llvm/IR/Function.h" 00028 #include "llvm/IR/Instructions.h" 00029 #include "llvm/IR/Operator.h" 00030 #include "llvm/IR/ValueHandle.h" 00031 #include "llvm/Pass.h" 00032 #include "llvm/Support/Allocator.h" 00033 #include "llvm/Support/DataTypes.h" 00034 #include <map> 00035 00036 namespace llvm { 00037 class APInt; 00038 class AssumptionTracker; 00039 class Constant; 00040 class ConstantInt; 00041 class DominatorTree; 00042 class Type; 00043 class ScalarEvolution; 00044 class DataLayout; 00045 class TargetLibraryInfo; 00046 class LLVMContext; 00047 class Loop; 00048 class LoopInfo; 00049 class Operator; 00050 class SCEVUnknown; 00051 class SCEV; 00052 template<> struct FoldingSetTrait<SCEV>; 00053 00054 /// SCEV - This class represents an analyzed expression in the program. These 00055 /// are opaque objects that the client is not allowed to do much with 00056 /// directly. 00057 /// 00058 class SCEV : public FoldingSetNode { 00059 friend struct FoldingSetTrait<SCEV>; 00060 00061 /// FastID - A reference to an Interned FoldingSetNodeID for this node. 00062 /// The ScalarEvolution's BumpPtrAllocator holds the data. 00063 FoldingSetNodeIDRef FastID; 00064 00065 // The SCEV baseclass this node corresponds to 00066 const unsigned short SCEVType; 00067 00068 protected: 00069 /// SubclassData - This field is initialized to zero and may be used in 00070 /// subclasses to store miscellaneous information. 00071 unsigned short SubclassData; 00072 00073 private: 00074 SCEV(const SCEV &) LLVM_DELETED_FUNCTION; 00075 void operator=(const SCEV &) LLVM_DELETED_FUNCTION; 00076 00077 public: 00078 /// NoWrapFlags are bitfield indices into SubclassData. 00079 /// 00080 /// Add and Mul expressions may have no-unsigned-wrap <NUW> or 00081 /// no-signed-wrap <NSW> properties, which are derived from the IR 00082 /// operator. NSW is a misnomer that we use to mean no signed overflow or 00083 /// underflow. 00084 /// 00085 /// AddRec expression may have a no-self-wraparound <NW> property if the 00086 /// result can never reach the start value. This property is independent of 00087 /// the actual start value and step direction. Self-wraparound is defined 00088 /// purely in terms of the recurrence's loop, step size, and 00089 /// bitwidth. Formally, a recurrence with no self-wraparound satisfies: 00090 /// abs(step) * max-iteration(loop) <= unsigned-max(bitwidth). 00091 /// 00092 /// Note that NUW and NSW are also valid properties of a recurrence, and 00093 /// either implies NW. For convenience, NW will be set for a recurrence 00094 /// whenever either NUW or NSW are set. 00095 enum NoWrapFlags { FlagAnyWrap = 0, // No guarantee. 00096 FlagNW = (1 << 0), // No self-wrap. 00097 FlagNUW = (1 << 1), // No unsigned wrap. 00098 FlagNSW = (1 << 2), // No signed wrap. 00099 NoWrapMask = (1 << 3) -1 }; 00100 00101 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) : 00102 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {} 00103 00104 unsigned getSCEVType() const { return SCEVType; } 00105 00106 /// getType - Return the LLVM type of this SCEV expression. 00107 /// 00108 Type *getType() const; 00109 00110 /// isZero - Return true if the expression is a constant zero. 00111 /// 00112 bool isZero() const; 00113 00114 /// isOne - Return true if the expression is a constant one. 00115 /// 00116 bool isOne() const; 00117 00118 /// isAllOnesValue - Return true if the expression is a constant 00119 /// all-ones value. 00120 /// 00121 bool isAllOnesValue() const; 00122 00123 /// isNonConstantNegative - Return true if the specified scev is negated, 00124 /// but not a constant. 00125 bool isNonConstantNegative() const; 00126 00127 /// print - Print out the internal representation of this scalar to the 00128 /// specified stream. This should really only be used for debugging 00129 /// purposes. 00130 void print(raw_ostream &OS) const; 00131 00132 /// dump - This method is used for debugging. 00133 /// 00134 void dump() const; 00135 }; 00136 00137 // Specialize FoldingSetTrait for SCEV to avoid needing to compute 00138 // temporary FoldingSetNodeID values. 00139 template<> struct FoldingSetTrait<SCEV> : DefaultFoldingSetTrait<SCEV> { 00140 static void Profile(const SCEV &X, FoldingSetNodeID& ID) { 00141 ID = X.FastID; 00142 } 00143 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, 00144 unsigned IDHash, FoldingSetNodeID &TempID) { 00145 return ID == X.FastID; 00146 } 00147 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) { 00148 return X.FastID.ComputeHash(); 00149 } 00150 }; 00151 00152 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) { 00153 S.print(OS); 00154 return OS; 00155 } 00156 00157 /// SCEVCouldNotCompute - An object of this class is returned by queries that 00158 /// could not be answered. For example, if you ask for the number of 00159 /// iterations of a linked-list traversal loop, you will get one of these. 00160 /// None of the standard SCEV operations are valid on this class, it is just a 00161 /// marker. 00162 struct SCEVCouldNotCompute : public SCEV { 00163 SCEVCouldNotCompute(); 00164 00165 /// Methods for support type inquiry through isa, cast, and dyn_cast: 00166 static bool classof(const SCEV *S); 00167 }; 00168 00169 /// ScalarEvolution - This class is the main scalar evolution driver. Because 00170 /// client code (intentionally) can't do much with the SCEV objects directly, 00171 /// they must ask this class for services. 00172 /// 00173 class ScalarEvolution : public FunctionPass { 00174 public: 00175 /// LoopDisposition - An enum describing the relationship between a 00176 /// SCEV and a loop. 00177 enum LoopDisposition { 00178 LoopVariant, ///< The SCEV is loop-variant (unknown). 00179 LoopInvariant, ///< The SCEV is loop-invariant. 00180 LoopComputable ///< The SCEV varies predictably with the loop. 00181 }; 00182 00183 /// BlockDisposition - An enum describing the relationship between a 00184 /// SCEV and a basic block. 00185 enum BlockDisposition { 00186 DoesNotDominateBlock, ///< The SCEV does not dominate the block. 00187 DominatesBlock, ///< The SCEV dominates the block. 00188 ProperlyDominatesBlock ///< The SCEV properly dominates the block. 00189 }; 00190 00191 /// Convenient NoWrapFlags manipulation that hides enum casts and is 00192 /// visible in the ScalarEvolution name space. 00193 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 00194 maskFlags(SCEV::NoWrapFlags Flags, int Mask) { 00195 return (SCEV::NoWrapFlags)(Flags & Mask); 00196 } 00197 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 00198 setFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OnFlags) { 00199 return (SCEV::NoWrapFlags)(Flags | OnFlags); 00200 } 00201 static SCEV::NoWrapFlags LLVM_ATTRIBUTE_UNUSED_RESULT 00202 clearFlags(SCEV::NoWrapFlags Flags, SCEV::NoWrapFlags OffFlags) { 00203 return (SCEV::NoWrapFlags)(Flags & ~OffFlags); 00204 } 00205 00206 private: 00207 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be 00208 /// notified whenever a Value is deleted. 00209 class SCEVCallbackVH : public CallbackVH { 00210 ScalarEvolution *SE; 00211 void deleted() override; 00212 void allUsesReplacedWith(Value *New) override; 00213 public: 00214 SCEVCallbackVH(Value *V, ScalarEvolution *SE = nullptr); 00215 }; 00216 00217 friend class SCEVCallbackVH; 00218 friend class SCEVExpander; 00219 friend class SCEVUnknown; 00220 00221 /// F - The function we are analyzing. 00222 /// 00223 Function *F; 00224 00225 /// The tracker for @llvm.assume intrinsics in this function. 00226 AssumptionTracker *AT; 00227 00228 /// LI - The loop information for the function we are currently analyzing. 00229 /// 00230 LoopInfo *LI; 00231 00232 /// The DataLayout information for the target we are targeting. 00233 /// 00234 const DataLayout *DL; 00235 00236 /// TLI - The target library information for the target we are targeting. 00237 /// 00238 TargetLibraryInfo *TLI; 00239 00240 /// DT - The dominator tree. 00241 /// 00242 DominatorTree *DT; 00243 00244 /// CouldNotCompute - This SCEV is used to represent unknown trip 00245 /// counts and things. 00246 SCEVCouldNotCompute CouldNotCompute; 00247 00248 /// ValueExprMapType - The typedef for ValueExprMap. 00249 /// 00250 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> > 00251 ValueExprMapType; 00252 00253 /// ValueExprMap - This is a cache of the values we have analyzed so far. 00254 /// 00255 ValueExprMapType ValueExprMap; 00256 00257 /// Mark predicate values currently being processed by isImpliedCond. 00258 DenseSet<Value*> PendingLoopPredicates; 00259 00260 /// ExitLimit - Information about the number of loop iterations for which a 00261 /// loop exit's branch condition evaluates to the not-taken path. This is a 00262 /// temporary pair of exact and max expressions that are eventually 00263 /// summarized in ExitNotTakenInfo and BackedgeTakenInfo. 00264 /// 00265 /// If MustExit is true, then the exit must be taken when the BECount 00266 /// reaches Exact (and before surpassing Max). If MustExit is false, then 00267 /// BECount may exceed Exact or Max if the loop exits via another branch. In 00268 /// either case, the loop may exit early via another branch. 00269 /// 00270 /// MustExit is true for most cases. However, an exit guarded by an 00271 /// (in)equality on a nonunit stride may be skipped. 00272 struct ExitLimit { 00273 const SCEV *Exact; 00274 const SCEV *Max; 00275 bool MustExit; 00276 00277 /*implicit*/ ExitLimit(const SCEV *E) 00278 : Exact(E), Max(E), MustExit(true) {} 00279 00280 ExitLimit(const SCEV *E, const SCEV *M, bool MustExit) 00281 : Exact(E), Max(M), MustExit(MustExit) {} 00282 00283 /// hasAnyInfo - Test whether this ExitLimit contains any computed 00284 /// information, or whether it's all SCEVCouldNotCompute values. 00285 bool hasAnyInfo() const { 00286 return !isa<SCEVCouldNotCompute>(Exact) || 00287 !isa<SCEVCouldNotCompute>(Max); 00288 } 00289 }; 00290 00291 /// ExitNotTakenInfo - Information about the number of times a particular 00292 /// loop exit may be reached before exiting the loop. 00293 struct ExitNotTakenInfo { 00294 AssertingVH<BasicBlock> ExitingBlock; 00295 const SCEV *ExactNotTaken; 00296 PointerIntPair<ExitNotTakenInfo*, 1> NextExit; 00297 00298 ExitNotTakenInfo() : ExitingBlock(nullptr), ExactNotTaken(nullptr) {} 00299 00300 /// isCompleteList - Return true if all loop exits are computable. 00301 bool isCompleteList() const { 00302 return NextExit.getInt() == 0; 00303 } 00304 00305 void setIncomplete() { NextExit.setInt(1); } 00306 00307 /// getNextExit - Return a pointer to the next exit's not-taken info. 00308 ExitNotTakenInfo *getNextExit() const { 00309 return NextExit.getPointer(); 00310 } 00311 00312 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); } 00313 }; 00314 00315 /// BackedgeTakenInfo - Information about the backedge-taken count 00316 /// of a loop. This currently includes an exact count and a maximum count. 00317 /// 00318 class BackedgeTakenInfo { 00319 /// ExitNotTaken - A list of computable exits and their not-taken counts. 00320 /// Loops almost never have more than one computable exit. 00321 ExitNotTakenInfo ExitNotTaken; 00322 00323 /// Max - An expression indicating the least maximum backedge-taken 00324 /// count of the loop that is known, or a SCEVCouldNotCompute. 00325 const SCEV *Max; 00326 00327 public: 00328 BackedgeTakenInfo() : Max(nullptr) {} 00329 00330 /// Initialize BackedgeTakenInfo from a list of exact exit counts. 00331 BackedgeTakenInfo( 00332 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 00333 bool Complete, const SCEV *MaxCount); 00334 00335 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any 00336 /// computed information, or whether it's all SCEVCouldNotCompute 00337 /// values. 00338 bool hasAnyInfo() const { 00339 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max); 00340 } 00341 00342 /// getExact - Return an expression indicating the exact backedge-taken 00343 /// count of the loop if it is known, or SCEVCouldNotCompute 00344 /// otherwise. This is the number of times the loop header can be 00345 /// guaranteed to execute, minus one. 00346 const SCEV *getExact(ScalarEvolution *SE) const; 00347 00348 /// getExact - Return the number of times this loop exit may fall through 00349 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not 00350 /// to exit via this block before this number of iterations, but may exit 00351 /// via another block. 00352 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const; 00353 00354 /// getMax - Get the max backedge taken count for the loop. 00355 const SCEV *getMax(ScalarEvolution *SE) const; 00356 00357 /// Return true if any backedge taken count expressions refer to the given 00358 /// subexpression. 00359 bool hasOperand(const SCEV *S, ScalarEvolution *SE) const; 00360 00361 /// clear - Invalidate this result and free associated memory. 00362 void clear(); 00363 }; 00364 00365 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for 00366 /// this function as they are computed. 00367 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts; 00368 00369 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 00370 /// the PHI instructions that we attempt to compute constant evolutions for. 00371 /// This allows us to avoid potentially expensive recomputation of these 00372 /// properties. An instruction maps to null if we are unable to compute its 00373 /// exit value. 00374 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 00375 00376 /// ValuesAtScopes - This map contains entries for all the expressions 00377 /// that we attempt to compute getSCEVAtScope information for, which can 00378 /// be expensive in extreme cases. 00379 DenseMap<const SCEV *, 00380 SmallVector<std::pair<const Loop *, const SCEV *>, 2> > ValuesAtScopes; 00381 00382 /// LoopDispositions - Memoized computeLoopDisposition results. 00383 DenseMap<const SCEV *, 00384 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> > LoopDispositions; 00385 00386 /// computeLoopDisposition - Compute a LoopDisposition value. 00387 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L); 00388 00389 /// BlockDispositions - Memoized computeBlockDisposition results. 00390 DenseMap<const SCEV *, 00391 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> > BlockDispositions; 00392 00393 /// computeBlockDisposition - Compute a BlockDisposition value. 00394 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB); 00395 00396 /// UnsignedRanges - Memoized results from getUnsignedRange 00397 DenseMap<const SCEV *, ConstantRange> UnsignedRanges; 00398 00399 /// SignedRanges - Memoized results from getSignedRange 00400 DenseMap<const SCEV *, ConstantRange> SignedRanges; 00401 00402 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV. 00403 const ConstantRange &setUnsignedRange(const SCEV *S, 00404 const ConstantRange &CR) { 00405 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 00406 UnsignedRanges.insert(std::make_pair(S, CR)); 00407 if (!Pair.second) 00408 Pair.first->second = CR; 00409 return Pair.first->second; 00410 } 00411 00412 /// setUnsignedRange - Set the memoized signed range for the given SCEV. 00413 const ConstantRange &setSignedRange(const SCEV *S, 00414 const ConstantRange &CR) { 00415 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 00416 SignedRanges.insert(std::make_pair(S, CR)); 00417 if (!Pair.second) 00418 Pair.first->second = CR; 00419 return Pair.first->second; 00420 } 00421 00422 /// createSCEV - We know that there is no SCEV for the specified value. 00423 /// Analyze the expression. 00424 const SCEV *createSCEV(Value *V); 00425 00426 /// createNodeForPHI - Provide the special handling we need to analyze PHI 00427 /// SCEVs. 00428 const SCEV *createNodeForPHI(PHINode *PN); 00429 00430 /// createNodeForGEP - Provide the special handling we need to analyze GEP 00431 /// SCEVs. 00432 const SCEV *createNodeForGEP(GEPOperator *GEP); 00433 00434 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called 00435 /// at most once for each SCEV+Loop pair. 00436 /// 00437 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L); 00438 00439 /// ForgetSymbolicValue - This looks up computed SCEV values for all 00440 /// instructions that depend on the given instruction and removes them from 00441 /// the ValueExprMap map if they reference SymName. This is used during PHI 00442 /// resolution. 00443 void ForgetSymbolicName(Instruction *I, const SCEV *SymName); 00444 00445 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given 00446 /// loop, lazily computing new values if the loop hasn't been analyzed 00447 /// yet. 00448 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L); 00449 00450 /// ComputeBackedgeTakenCount - Compute the number of times the specified 00451 /// loop will iterate. 00452 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L); 00453 00454 /// ComputeExitLimit - Compute the number of times the backedge of the 00455 /// specified loop will execute if it exits via the specified block. 00456 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock); 00457 00458 /// ComputeExitLimitFromCond - Compute the number of times the backedge of 00459 /// the specified loop will execute if its exit condition were a conditional 00460 /// branch of ExitCond, TBB, and FBB. 00461 ExitLimit ComputeExitLimitFromCond(const Loop *L, 00462 Value *ExitCond, 00463 BasicBlock *TBB, 00464 BasicBlock *FBB, 00465 bool IsSubExpr); 00466 00467 /// ComputeExitLimitFromICmp - Compute the number of times the backedge of 00468 /// the specified loop will execute if its exit condition were a conditional 00469 /// branch of the ICmpInst ExitCond, TBB, and FBB. 00470 ExitLimit ComputeExitLimitFromICmp(const Loop *L, 00471 ICmpInst *ExitCond, 00472 BasicBlock *TBB, 00473 BasicBlock *FBB, 00474 bool IsSubExpr); 00475 00476 /// ComputeExitLimitFromSingleExitSwitch - Compute the number of times the 00477 /// backedge of the specified loop will execute if its exit condition were a 00478 /// switch with a single exiting case to ExitingBB. 00479 ExitLimit 00480 ComputeExitLimitFromSingleExitSwitch(const Loop *L, SwitchInst *Switch, 00481 BasicBlock *ExitingBB, bool IsSubExpr); 00482 00483 /// ComputeLoadConstantCompareExitLimit - Given an exit condition 00484 /// of 'icmp op load X, cst', try to see if we can compute the 00485 /// backedge-taken count. 00486 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI, 00487 Constant *RHS, 00488 const Loop *L, 00489 ICmpInst::Predicate p); 00490 00491 /// ComputeExitCountExhaustively - If the loop is known to execute a 00492 /// constant number of times (the condition evolves only from constants), 00493 /// try to evaluate a few iterations of the loop until we get the exit 00494 /// condition gets a value of ExitWhen (true or false). If we cannot 00495 /// evaluate the exit count of the loop, return CouldNotCompute. 00496 const SCEV *ComputeExitCountExhaustively(const Loop *L, 00497 Value *Cond, 00498 bool ExitWhen); 00499 00500 /// HowFarToZero - Return the number of times an exit condition comparing 00501 /// the specified value to zero will execute. If not computable, return 00502 /// CouldNotCompute. 00503 ExitLimit HowFarToZero(const SCEV *V, const Loop *L, bool IsSubExpr); 00504 00505 /// HowFarToNonZero - Return the number of times an exit condition checking 00506 /// the specified value for nonzero will execute. If not computable, return 00507 /// CouldNotCompute. 00508 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L); 00509 00510 /// HowManyLessThans - Return the number of times an exit condition 00511 /// containing the specified less-than comparison will execute. If not 00512 /// computable, return CouldNotCompute. isSigned specifies whether the 00513 /// less-than is signed. 00514 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 00515 const Loop *L, bool isSigned, bool IsSubExpr); 00516 ExitLimit HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS, 00517 const Loop *L, bool isSigned, bool IsSubExpr); 00518 00519 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 00520 /// (which may not be an immediate predecessor) which has exactly one 00521 /// successor from which BB is reachable, or null if no such block is 00522 /// found. 00523 std::pair<BasicBlock *, BasicBlock *> 00524 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB); 00525 00526 /// isImpliedCond - Test whether the condition described by Pred, LHS, and 00527 /// RHS is true whenever the given FoundCondValue value evaluates to true. 00528 bool isImpliedCond(ICmpInst::Predicate Pred, 00529 const SCEV *LHS, const SCEV *RHS, 00530 Value *FoundCondValue, 00531 bool Inverse); 00532 00533 /// isImpliedCondOperands - Test whether the condition described by Pred, 00534 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 00535 /// and FoundRHS is true. 00536 bool isImpliedCondOperands(ICmpInst::Predicate Pred, 00537 const SCEV *LHS, const SCEV *RHS, 00538 const SCEV *FoundLHS, const SCEV *FoundRHS); 00539 00540 /// isImpliedCondOperandsHelper - Test whether the condition described by 00541 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 00542 /// FoundLHS, and FoundRHS is true. 00543 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 00544 const SCEV *LHS, const SCEV *RHS, 00545 const SCEV *FoundLHS, 00546 const SCEV *FoundRHS); 00547 00548 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 00549 /// in the header of its containing loop, we know the loop executes a 00550 /// constant number of times, and the PHI node is just a recurrence 00551 /// involving constants, fold it. 00552 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, 00553 const Loop *L); 00554 00555 /// isKnownPredicateWithRanges - Test if the given expression is known to 00556 /// satisfy the condition described by Pred and the known constant ranges 00557 /// of LHS and RHS. 00558 /// 00559 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred, 00560 const SCEV *LHS, const SCEV *RHS); 00561 00562 /// forgetMemoizedResults - Drop memoized information computed for S. 00563 void forgetMemoizedResults(const SCEV *S); 00564 00565 /// Return false iff given SCEV contains a SCEVUnknown with NULL value- 00566 /// pointer. 00567 bool checkValidity(const SCEV *S) const; 00568 00569 public: 00570 static char ID; // Pass identification, replacement for typeid 00571 ScalarEvolution(); 00572 00573 LLVMContext &getContext() const { return F->getContext(); } 00574 00575 /// isSCEVable - Test if values of the given type are analyzable within 00576 /// the SCEV framework. This primarily includes integer types, and it 00577 /// can optionally include pointer types if the ScalarEvolution class 00578 /// has access to target-specific information. 00579 bool isSCEVable(Type *Ty) const; 00580 00581 /// getTypeSizeInBits - Return the size in bits of the specified type, 00582 /// for which isSCEVable must return true. 00583 uint64_t getTypeSizeInBits(Type *Ty) const; 00584 00585 /// getEffectiveSCEVType - Return a type with the same bitwidth as 00586 /// the given type and which represents how SCEV will treat the given 00587 /// type, for which isSCEVable must return true. For pointer types, 00588 /// this is the pointer-sized integer type. 00589 Type *getEffectiveSCEVType(Type *Ty) const; 00590 00591 /// getSCEV - Return a SCEV expression for the full generality of the 00592 /// specified expression. 00593 const SCEV *getSCEV(Value *V); 00594 00595 const SCEV *getConstant(ConstantInt *V); 00596 const SCEV *getConstant(const APInt& Val); 00597 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false); 00598 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty); 00599 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty); 00600 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty); 00601 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty); 00602 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 00603 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 00604 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS, 00605 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 00606 SmallVector<const SCEV *, 2> Ops; 00607 Ops.push_back(LHS); 00608 Ops.push_back(RHS); 00609 return getAddExpr(Ops, Flags); 00610 } 00611 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 00612 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 00613 SmallVector<const SCEV *, 3> Ops; 00614 Ops.push_back(Op0); 00615 Ops.push_back(Op1); 00616 Ops.push_back(Op2); 00617 return getAddExpr(Ops, Flags); 00618 } 00619 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 00620 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 00621 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS, 00622 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) 00623 { 00624 SmallVector<const SCEV *, 2> Ops; 00625 Ops.push_back(LHS); 00626 Ops.push_back(RHS); 00627 return getMulExpr(Ops, Flags); 00628 } 00629 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 00630 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 00631 SmallVector<const SCEV *, 3> Ops; 00632 Ops.push_back(Op0); 00633 Ops.push_back(Op1); 00634 Ops.push_back(Op2); 00635 return getMulExpr(Ops, Flags); 00636 } 00637 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS); 00638 const SCEV *getUDivExactExpr(const SCEV *LHS, const SCEV *RHS); 00639 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, 00640 const Loop *L, SCEV::NoWrapFlags Flags); 00641 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 00642 const Loop *L, SCEV::NoWrapFlags Flags); 00643 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands, 00644 const Loop *L, SCEV::NoWrapFlags Flags) { 00645 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end()); 00646 return getAddRecExpr(NewOp, L, Flags); 00647 } 00648 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS); 00649 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 00650 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS); 00651 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 00652 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS); 00653 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS); 00654 const SCEV *getUnknown(Value *V); 00655 const SCEV *getCouldNotCompute(); 00656 00657 /// getSizeOfExpr - Return an expression for sizeof AllocTy that is type 00658 /// IntTy 00659 /// 00660 const SCEV *getSizeOfExpr(Type *IntTy, Type *AllocTy); 00661 00662 /// getOffsetOfExpr - Return an expression for offsetof on the given field 00663 /// with type IntTy 00664 /// 00665 const SCEV *getOffsetOfExpr(Type *IntTy, StructType *STy, unsigned FieldNo); 00666 00667 /// getNegativeSCEV - Return the SCEV object corresponding to -V. 00668 /// 00669 const SCEV *getNegativeSCEV(const SCEV *V); 00670 00671 /// getNotSCEV - Return the SCEV object corresponding to ~V. 00672 /// 00673 const SCEV *getNotSCEV(const SCEV *V); 00674 00675 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 00676 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 00677 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 00678 00679 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion 00680 /// of the input value to the specified type. If the type must be 00681 /// extended, it is zero extended. 00682 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty); 00683 00684 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion 00685 /// of the input value to the specified type. If the type must be 00686 /// extended, it is sign extended. 00687 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty); 00688 00689 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of 00690 /// the input value to the specified type. If the type must be extended, 00691 /// it is zero extended. The conversion must not be narrowing. 00692 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty); 00693 00694 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of 00695 /// the input value to the specified type. If the type must be extended, 00696 /// it is sign extended. The conversion must not be narrowing. 00697 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty); 00698 00699 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 00700 /// the input value to the specified type. If the type must be extended, 00701 /// it is extended with unspecified bits. The conversion must not be 00702 /// narrowing. 00703 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty); 00704 00705 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 00706 /// input value to the specified type. The conversion must not be 00707 /// widening. 00708 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty); 00709 00710 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 00711 /// the types using zero-extension, and then perform a umax operation 00712 /// with them. 00713 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, 00714 const SCEV *RHS); 00715 00716 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 00717 /// the types using zero-extension, and then perform a umin operation 00718 /// with them. 00719 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, 00720 const SCEV *RHS); 00721 00722 /// getPointerBase - Transitively follow the chain of pointer-type operands 00723 /// until reaching a SCEV that does not have a single pointer operand. This 00724 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 00725 /// but corner cases do exist. 00726 const SCEV *getPointerBase(const SCEV *V); 00727 00728 /// getSCEVAtScope - Return a SCEV expression for the specified value 00729 /// at the specified scope in the program. The L value specifies a loop 00730 /// nest to evaluate the expression at, where null is the top-level or a 00731 /// specified loop is immediately inside of the loop. 00732 /// 00733 /// This method can be used to compute the exit value for a variable defined 00734 /// in a loop by querying what the value will hold in the parent loop. 00735 /// 00736 /// In the case that a relevant loop exit value cannot be computed, the 00737 /// original value V is returned. 00738 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L); 00739 00740 /// getSCEVAtScope - This is a convenience function which does 00741 /// getSCEVAtScope(getSCEV(V), L). 00742 const SCEV *getSCEVAtScope(Value *V, const Loop *L); 00743 00744 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 00745 /// by a conditional between LHS and RHS. This is used to help avoid max 00746 /// expressions in loop trip counts, and to eliminate casts. 00747 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 00748 const SCEV *LHS, const SCEV *RHS); 00749 00750 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 00751 /// protected by a conditional between LHS and RHS. This is used to 00752 /// to eliminate casts. 00753 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 00754 const SCEV *LHS, const SCEV *RHS); 00755 00756 /// getSmallConstantTripCount - Returns the maximum trip count of this loop 00757 /// as a normal unsigned value. Returns 0 if the trip count is unknown or 00758 /// not constant. This "trip count" assumes that control exits via 00759 /// ExitingBlock. More precisely, it is the number of times that control may 00760 /// reach ExitingBlock before taking the branch. For loops with multiple 00761 /// exits, it may not be the number times that the loop header executes if 00762 /// the loop exits prematurely via another branch. 00763 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock); 00764 00765 /// getSmallConstantTripMultiple - Returns the largest constant divisor of 00766 /// the trip count of this loop as a normal unsigned value, if 00767 /// possible. This means that the actual trip count is always a multiple of 00768 /// the returned value (don't forget the trip count could very well be zero 00769 /// as well!). As explained in the comments for getSmallConstantTripCount, 00770 /// this assumes that control exits the loop via ExitingBlock. 00771 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock); 00772 00773 // getExitCount - Get the expression for the number of loop iterations for 00774 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise 00775 // return SCEVCouldNotCompute. 00776 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock); 00777 00778 /// getBackedgeTakenCount - If the specified loop has a predictable 00779 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 00780 /// object. The backedge-taken count is the number of times the loop header 00781 /// will be branched to from within the loop. This is one less than the 00782 /// trip count of the loop, since it doesn't count the first iteration, 00783 /// when the header is branched to from outside the loop. 00784 /// 00785 /// Note that it is not valid to call this method on a loop without a 00786 /// loop-invariant backedge-taken count (see 00787 /// hasLoopInvariantBackedgeTakenCount). 00788 /// 00789 const SCEV *getBackedgeTakenCount(const Loop *L); 00790 00791 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 00792 /// return the least SCEV value that is known never to be less than the 00793 /// actual backedge taken count. 00794 const SCEV *getMaxBackedgeTakenCount(const Loop *L); 00795 00796 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop 00797 /// has an analyzable loop-invariant backedge-taken count. 00798 bool hasLoopInvariantBackedgeTakenCount(const Loop *L); 00799 00800 /// forgetLoop - This method should be called by the client when it has 00801 /// changed a loop in a way that may effect ScalarEvolution's ability to 00802 /// compute a trip count, or if the loop is deleted. This call is 00803 /// potentially expensive for large loop bodies. 00804 void forgetLoop(const Loop *L); 00805 00806 /// forgetValue - This method should be called by the client when it has 00807 /// changed a value in a way that may effect its value, or which may 00808 /// disconnect it from a def-use chain linking it to a loop. 00809 void forgetValue(Value *V); 00810 00811 /// \brief Called when the client has changed the disposition of values in 00812 /// this loop. 00813 /// 00814 /// We don't have a way to invalidate per-loop dispositions. Clear and 00815 /// recompute is simpler. 00816 void forgetLoopDispositions(const Loop *L) { LoopDispositions.clear(); } 00817 00818 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S 00819 /// is guaranteed to end in (at every loop iteration). It is, at the same 00820 /// time, the minimum number of times S is divisible by 2. For example, 00821 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the 00822 /// bitwidth of S. 00823 uint32_t GetMinTrailingZeros(const SCEV *S); 00824 00825 /// getUnsignedRange - Determine the unsigned range for a particular SCEV. 00826 /// 00827 ConstantRange getUnsignedRange(const SCEV *S); 00828 00829 /// getSignedRange - Determine the signed range for a particular SCEV. 00830 /// 00831 ConstantRange getSignedRange(const SCEV *S); 00832 00833 /// isKnownNegative - Test if the given expression is known to be negative. 00834 /// 00835 bool isKnownNegative(const SCEV *S); 00836 00837 /// isKnownPositive - Test if the given expression is known to be positive. 00838 /// 00839 bool isKnownPositive(const SCEV *S); 00840 00841 /// isKnownNonNegative - Test if the given expression is known to be 00842 /// non-negative. 00843 /// 00844 bool isKnownNonNegative(const SCEV *S); 00845 00846 /// isKnownNonPositive - Test if the given expression is known to be 00847 /// non-positive. 00848 /// 00849 bool isKnownNonPositive(const SCEV *S); 00850 00851 /// isKnownNonZero - Test if the given expression is known to be 00852 /// non-zero. 00853 /// 00854 bool isKnownNonZero(const SCEV *S); 00855 00856 /// isKnownPredicate - Test if the given expression is known to satisfy 00857 /// the condition described by Pred, LHS, and RHS. 00858 /// 00859 bool isKnownPredicate(ICmpInst::Predicate Pred, 00860 const SCEV *LHS, const SCEV *RHS); 00861 00862 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 00863 /// predicate Pred. Return true iff any changes were made. If the 00864 /// operands are provably equal or unequal, LHS and RHS are set to 00865 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE. 00866 /// 00867 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, 00868 const SCEV *&LHS, 00869 const SCEV *&RHS, 00870 unsigned Depth = 0); 00871 00872 /// getLoopDisposition - Return the "disposition" of the given SCEV with 00873 /// respect to the given loop. 00874 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L); 00875 00876 /// isLoopInvariant - Return true if the value of the given SCEV is 00877 /// unchanging in the specified loop. 00878 bool isLoopInvariant(const SCEV *S, const Loop *L); 00879 00880 /// hasComputableLoopEvolution - Return true if the given SCEV changes value 00881 /// in a known way in the specified loop. This property being true implies 00882 /// that the value is variant in the loop AND that we can emit an expression 00883 /// to compute the value of the expression at any particular loop iteration. 00884 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L); 00885 00886 /// getLoopDisposition - Return the "disposition" of the given SCEV with 00887 /// respect to the given block. 00888 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB); 00889 00890 /// dominates - Return true if elements that makes up the given SCEV 00891 /// dominate the specified basic block. 00892 bool dominates(const SCEV *S, const BasicBlock *BB); 00893 00894 /// properlyDominates - Return true if elements that makes up the given SCEV 00895 /// properly dominate the specified basic block. 00896 bool properlyDominates(const SCEV *S, const BasicBlock *BB); 00897 00898 /// hasOperand - Test whether the given SCEV has Op as a direct or 00899 /// indirect operand. 00900 bool hasOperand(const SCEV *S, const SCEV *Op) const; 00901 00902 /// Return the size of an element read or written by Inst. 00903 const SCEV *getElementSize(Instruction *Inst); 00904 00905 /// Compute the array dimensions Sizes from the set of Terms extracted from 00906 /// the memory access function of this SCEVAddRecExpr. 00907 void findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms, 00908 SmallVectorImpl<const SCEV *> &Sizes, 00909 const SCEV *ElementSize) const; 00910 00911 bool runOnFunction(Function &F) override; 00912 void releaseMemory() override; 00913 void getAnalysisUsage(AnalysisUsage &AU) const override; 00914 void print(raw_ostream &OS, const Module* = nullptr) const override; 00915 void verifyAnalysis() const override; 00916 00917 private: 00918 /// Compute the backedge taken count knowing the interval difference, the 00919 /// stride and presence of the equality in the comparison. 00920 const SCEV *computeBECount(const SCEV *Delta, const SCEV *Stride, 00921 bool Equality); 00922 00923 /// Verify if an linear IV with positive stride can overflow when in a 00924 /// less-than comparison, knowing the invariant term of the comparison, 00925 /// the stride and the knowledge of NSW/NUW flags on the recurrence. 00926 bool doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride, 00927 bool IsSigned, bool NoWrap); 00928 00929 /// Verify if an linear IV with negative stride can overflow when in a 00930 /// greater-than comparison, knowing the invariant term of the comparison, 00931 /// the stride and the knowledge of NSW/NUW flags on the recurrence. 00932 bool doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride, 00933 bool IsSigned, bool NoWrap); 00934 00935 private: 00936 FoldingSet<SCEV> UniqueSCEVs; 00937 BumpPtrAllocator SCEVAllocator; 00938 00939 /// FirstUnknown - The head of a linked list of all SCEVUnknown 00940 /// values that have been allocated. This is used by releaseMemory 00941 /// to locate them all and call their destructors. 00942 SCEVUnknown *FirstUnknown; 00943 }; 00944 } 00945 00946 #endif