1 //===- llvm/Analysis/ScalarEvolution.h - Scalar Evolution -------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 15 // 16 // This analysis is primarily useful for induction variable substitution and 17 // strength reduction. 18 // 19 //===----------------------------------------------------------------------===// 20 21 #ifndef LLVM_ANALYSIS_SCALAREVOLUTION_H 22 #define LLVM_ANALYSIS_SCALAREVOLUTION_H 23 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" 34 #include <map> 35 36 namespace llvm { 37 class APInt; 38 class Constant; 39 class ConstantInt; 40 class DominatorTree; 41 class Type; 42 class ScalarEvolution; 43 class TargetData; 44 class TargetLibraryInfo; 45 class LLVMContext; 46 class Loop; 47 class LoopInfo; 48 class Operator; 49 class SCEVUnknown; 50 class SCEV; 51 template<> struct FoldingSetTrait<SCEV>; 52 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 55 /// directly. 56 /// 57 class SCEV : public FoldingSetNode { 58 friend struct FoldingSetTrait<SCEV>; 59 60 /// FastID - A reference to an Interned FoldingSetNodeID for this node. 61 /// The ScalarEvolution's BumpPtrAllocator holds the data. 62 FoldingSetNodeIDRef FastID; 63 64 // The SCEV baseclass this node corresponds to 65 const unsigned short SCEVType; 66 67 protected: 68 /// SubclassData - This field is initialized to zero and may be used in 69 /// subclasses to store miscellaneous information. 70 unsigned short SubclassData; 71 72 private: 73 SCEV(const SCEV &); // DO NOT IMPLEMENT 74 void operator=(const SCEV &); // DO NOT IMPLEMENT 75 76 public: 77 /// NoWrapFlags are bitfield indices into SubclassData. 78 /// 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 82 /// underflow. 83 /// 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). 90 /// 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 }; 99 100 explicit SCEV(const FoldingSetNodeIDRef ID, unsigned SCEVTy) : 101 FastID(ID), SCEVType(SCEVTy), SubclassData(0) {} 102 103 unsigned getSCEVType() const { return SCEVType; } 104 105 /// getType - Return the LLVM type of this SCEV expression. 106 /// 107 Type *getType() const; 108 109 /// isZero - Return true if the expression is a constant zero. 110 /// 111 bool isZero() const; 112 113 /// isOne - Return true if the expression is a constant one. 114 /// 115 bool isOne() const; 116 117 /// isAllOnesValue - Return true if the expression is a constant 118 /// all-ones value. 119 /// 120 bool isAllOnesValue() const; 121 122 /// isNonConstantNegative - Return true if the specified scev is negated, 123 /// but not a constant. 124 bool isNonConstantNegative() const; 125 126 /// print - Print out the internal representation of this scalar to the 127 /// specified stream. This should really only be used for debugging 128 /// purposes. 129 void print(raw_ostream &OS) const; 130 131 /// dump - This method is used for debugging. 132 /// 133 void dump() const; 134 }; 135 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) { 140 ID = X.FastID; 141 } 142 static bool Equals(const SCEV &X, const FoldingSetNodeID &ID, 143 unsigned IDHash, FoldingSetNodeID &TempID) { 144 return ID == X.FastID; 145 } 146 static unsigned ComputeHash(const SCEV &X, FoldingSetNodeID &TempID) { 147 return X.FastID.ComputeHash(); 148 } 149 }; 150 151 inline raw_ostream &operator<<(raw_ostream &OS, const SCEV &S) { 152 S.print(OS); 153 return OS; 154 } 155 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 160 /// marker. 161 struct SCEVCouldNotCompute : public SCEV { 162 SCEVCouldNotCompute(); 163 164 /// Methods for support type inquiry through isa, cast, and dyn_cast: 165 static inline bool classof(const SCEVCouldNotCompute *S) { return true; } 166 static bool classof(const SCEV *S); 167 }; 168 169 /// ScalarEvolution - This class is the main scalar evolution driver. Because 170 /// client code (intentionally) can't do much with the SCEV objects directly, 171 /// they must ask this class for services. 172 /// 173 class ScalarEvolution : public FunctionPass { 174 public: 175 /// LoopDisposition - An enum describing the relationship between a 176 /// SCEV and a loop. 177 enum LoopDisposition { 178 LoopVariant, ///< The SCEV is loop-variant (unknown). 179 LoopInvariant, ///< The SCEV is loop-invariant. 180 LoopComputable ///< The SCEV varies predictably with the loop. 181 }; 182 183 /// BlockDisposition - An enum describing the relationship between a 184 /// SCEV and a basic block. 185 enum BlockDisposition { 186 DoesNotDominateBlock, ///< The SCEV does not dominate the block. 187 DominatesBlock, ///< The SCEV dominates the block. 188 ProperlyDominatesBlock ///< The SCEV properly dominates the block. 189 }; 190 191 /// Convenient NoWrapFlags manipulation that hides enum casts and is 192 /// visible in the ScalarEvolution name space. 193 static SCEV::NoWrapFlags maskFlags(SCEV::NoWrapFlags Flags, int Mask) { 194 return (SCEV::NoWrapFlags)(Flags & Mask); 195 } 196 static SCEV::NoWrapFlags setFlags(SCEV::NoWrapFlags Flags, 197 SCEV::NoWrapFlags OnFlags) { 198 return (SCEV::NoWrapFlags)(Flags | OnFlags); 199 } 200 static SCEV::NoWrapFlags clearFlags(SCEV::NoWrapFlags Flags, 201 SCEV::NoWrapFlags OffFlags) { 202 return (SCEV::NoWrapFlags)(Flags & ~OffFlags); 203 } 204 205 private: 206 /// SCEVCallbackVH - A CallbackVH to arrange for ScalarEvolution to be 207 /// notified whenever a Value is deleted. 208 class SCEVCallbackVH : public CallbackVH { 209 ScalarEvolution *SE; 210 virtual void deleted(); 211 virtual void allUsesReplacedWith(Value *New); 212 public: 213 SCEVCallbackVH(Value *V, ScalarEvolution *SE = 0); 214 }; 215 216 friend class SCEVCallbackVH; 217 friend class SCEVExpander; 218 friend class SCEVUnknown; 219 220 /// F - The function we are analyzing. 221 /// 222 Function *F; 223 224 /// LI - The loop information for the function we are currently analyzing. 225 /// 226 LoopInfo *LI; 227 228 /// TD - The target data information for the target we are targeting. 229 /// 230 TargetData *TD; 231 232 /// TLI - The target library information for the target we are targeting. 233 /// 234 TargetLibraryInfo *TLI; 235 236 /// DT - The dominator tree. 237 /// 238 DominatorTree *DT; 239 240 /// CouldNotCompute - This SCEV is used to represent unknown trip 241 /// counts and things. 242 SCEVCouldNotCompute CouldNotCompute; 243 244 /// ValueExprMapType - The typedef for ValueExprMap. 245 /// 246 typedef DenseMap<SCEVCallbackVH, const SCEV *, DenseMapInfo<Value *> > 247 ValueExprMapType; 248 249 /// ValueExprMap - This is a cache of the values we have analyzed so far. 250 /// 251 ValueExprMapType ValueExprMap; 252 253 /// ExitLimit - Information about the number of loop iterations for 254 /// which a loop exit's branch condition evaluates to the not-taken path. 255 /// This is a temporary pair of exact and max expressions that are 256 /// eventually summarized in ExitNotTakenInfo and BackedgeTakenInfo. 257 struct ExitLimit { 258 const SCEV *Exact; 259 const SCEV *Max; 260 261 /*implicit*/ ExitLimit(const SCEV *E) : Exact(E), Max(E) {} 262 263 ExitLimit(const SCEV *E, const SCEV *M) : Exact(E), Max(M) {} 264 265 /// hasAnyInfo - Test whether this ExitLimit contains any computed 266 /// information, or whether it's all SCEVCouldNotCompute values. 267 bool hasAnyInfo() const { 268 return !isa<SCEVCouldNotCompute>(Exact) || 269 !isa<SCEVCouldNotCompute>(Max); 270 } 271 }; 272 273 /// ExitNotTakenInfo - Information about the number of times a particular 274 /// loop exit may be reached before exiting the loop. 275 struct ExitNotTakenInfo { 276 AssertingVH<BasicBlock> ExitingBlock; 277 const SCEV *ExactNotTaken; 278 PointerIntPair<ExitNotTakenInfo*, 1> NextExit; 279 280 ExitNotTakenInfo() : ExitingBlock(0), ExactNotTaken(0) {} 281 282 /// isCompleteList - Return true if all loop exits are computable. 283 bool isCompleteList() const { 284 return NextExit.getInt() == 0; 285 } 286 287 void setIncomplete() { NextExit.setInt(1); } 288 289 /// getNextExit - Return a pointer to the next exit's not-taken info. 290 ExitNotTakenInfo *getNextExit() const { 291 return NextExit.getPointer(); 292 } 293 294 void setNextExit(ExitNotTakenInfo *ENT) { NextExit.setPointer(ENT); } 295 }; 296 297 /// BackedgeTakenInfo - Information about the backedge-taken count 298 /// of a loop. This currently includes an exact count and a maximum count. 299 /// 300 class BackedgeTakenInfo { 301 /// ExitNotTaken - A list of computable exits and their not-taken counts. 302 /// Loops almost never have more than one computable exit. 303 ExitNotTakenInfo ExitNotTaken; 304 305 /// Max - An expression indicating the least maximum backedge-taken 306 /// count of the loop that is known, or a SCEVCouldNotCompute. 307 const SCEV *Max; 308 309 public: 310 BackedgeTakenInfo() : Max(0) {} 311 312 /// Initialize BackedgeTakenInfo from a list of exact exit counts. 313 BackedgeTakenInfo( 314 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts, 315 bool Complete, const SCEV *MaxCount); 316 317 /// hasAnyInfo - Test whether this BackedgeTakenInfo contains any 318 /// computed information, or whether it's all SCEVCouldNotCompute 319 /// values. 320 bool hasAnyInfo() const { 321 return ExitNotTaken.ExitingBlock || !isa<SCEVCouldNotCompute>(Max); 322 } 323 324 /// getExact - Return an expression indicating the exact backedge-taken 325 /// count of the loop if it is known, or SCEVCouldNotCompute 326 /// otherwise. This is the number of times the loop header can be 327 /// guaranteed to execute, minus one. 328 const SCEV *getExact(ScalarEvolution *SE) const; 329 330 /// getExact - Return the number of times this loop exit may fall through 331 /// to the back edge, or SCEVCouldNotCompute. The loop is guaranteed not 332 /// to exit via this block before this number of iterations, but may exit 333 /// via another block. 334 const SCEV *getExact(BasicBlock *ExitingBlock, ScalarEvolution *SE) const; 335 336 /// getMax - Get the max backedge taken count for the loop. 337 const SCEV *getMax(ScalarEvolution *SE) const; 338 339 /// clear - Invalidate this result and free associated memory. 340 void clear(); 341 }; 342 343 /// BackedgeTakenCounts - Cache the backedge-taken count of the loops for 344 /// this function as they are computed. 345 DenseMap<const Loop*, BackedgeTakenInfo> BackedgeTakenCounts; 346 347 /// ConstantEvolutionLoopExitValue - This map contains entries for all of 348 /// the PHI instructions that we attempt to compute constant evolutions for. 349 /// This allows us to avoid potentially expensive recomputation of these 350 /// properties. An instruction maps to null if we are unable to compute its 351 /// exit value. 352 DenseMap<PHINode*, Constant*> ConstantEvolutionLoopExitValue; 353 354 /// ValuesAtScopes - This map contains entries for all the expressions 355 /// that we attempt to compute getSCEVAtScope information for, which can 356 /// be expensive in extreme cases. 357 DenseMap<const SCEV *, 358 std::map<const Loop *, const SCEV *> > ValuesAtScopes; 359 360 /// LoopDispositions - Memoized computeLoopDisposition results. 361 DenseMap<const SCEV *, 362 std::map<const Loop *, LoopDisposition> > LoopDispositions; 363 364 /// computeLoopDisposition - Compute a LoopDisposition value. 365 LoopDisposition computeLoopDisposition(const SCEV *S, const Loop *L); 366 367 /// BlockDispositions - Memoized computeBlockDisposition results. 368 DenseMap<const SCEV *, 369 std::map<const BasicBlock *, BlockDisposition> > BlockDispositions; 370 371 /// computeBlockDisposition - Compute a BlockDisposition value. 372 BlockDisposition computeBlockDisposition(const SCEV *S, const BasicBlock *BB); 373 374 /// UnsignedRanges - Memoized results from getUnsignedRange 375 DenseMap<const SCEV *, ConstantRange> UnsignedRanges; 376 377 /// SignedRanges - Memoized results from getSignedRange 378 DenseMap<const SCEV *, ConstantRange> SignedRanges; 379 380 /// setUnsignedRange - Set the memoized unsigned range for the given SCEV. 381 const ConstantRange &setUnsignedRange(const SCEV *S, 382 const ConstantRange &CR) { 383 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 384 UnsignedRanges.insert(std::make_pair(S, CR)); 385 if (!Pair.second) 386 Pair.first->second = CR; 387 return Pair.first->second; 388 } 389 390 /// setUnsignedRange - Set the memoized signed range for the given SCEV. 391 const ConstantRange &setSignedRange(const SCEV *S, 392 const ConstantRange &CR) { 393 std::pair<DenseMap<const SCEV *, ConstantRange>::iterator, bool> Pair = 394 SignedRanges.insert(std::make_pair(S, CR)); 395 if (!Pair.second) 396 Pair.first->second = CR; 397 return Pair.first->second; 398 } 399 400 /// createSCEV - We know that there is no SCEV for the specified value. 401 /// Analyze the expression. 402 const SCEV *createSCEV(Value *V); 403 404 /// createNodeForPHI - Provide the special handling we need to analyze PHI 405 /// SCEVs. 406 const SCEV *createNodeForPHI(PHINode *PN); 407 408 /// createNodeForGEP - Provide the special handling we need to analyze GEP 409 /// SCEVs. 410 const SCEV *createNodeForGEP(GEPOperator *GEP); 411 412 /// computeSCEVAtScope - Implementation code for getSCEVAtScope; called 413 /// at most once for each SCEV+Loop pair. 414 /// 415 const SCEV *computeSCEVAtScope(const SCEV *S, const Loop *L); 416 417 /// ForgetSymbolicValue - This looks up computed SCEV values for all 418 /// instructions that depend on the given instruction and removes them from 419 /// the ValueExprMap map if they reference SymName. This is used during PHI 420 /// resolution. 421 void ForgetSymbolicName(Instruction *I, const SCEV *SymName); 422 423 /// getBECount - Subtract the end and start values and divide by the step, 424 /// rounding up, to get the number of times the backedge is executed. Return 425 /// CouldNotCompute if an intermediate computation overflows. 426 const SCEV *getBECount(const SCEV *Start, 427 const SCEV *End, 428 const SCEV *Step, 429 bool NoWrap); 430 431 /// getBackedgeTakenInfo - Return the BackedgeTakenInfo for the given 432 /// loop, lazily computing new values if the loop hasn't been analyzed 433 /// yet. 434 const BackedgeTakenInfo &getBackedgeTakenInfo(const Loop *L); 435 436 /// ComputeBackedgeTakenCount - Compute the number of times the specified 437 /// loop will iterate. 438 BackedgeTakenInfo ComputeBackedgeTakenCount(const Loop *L); 439 440 /// ComputeExitLimit - Compute the number of times the backedge of the 441 /// specified loop will execute if it exits via the specified block. 442 ExitLimit ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock); 443 444 /// ComputeExitLimitFromCond - Compute the number of times the backedge of 445 /// the specified loop will execute if its exit condition were a conditional 446 /// branch of ExitCond, TBB, and FBB. 447 ExitLimit ComputeExitLimitFromCond(const Loop *L, 448 Value *ExitCond, 449 BasicBlock *TBB, 450 BasicBlock *FBB); 451 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, 456 ICmpInst *ExitCond, 457 BasicBlock *TBB, 458 BasicBlock *FBB); 459 460 /// ComputeLoadConstantCompareExitLimit - Given an exit condition 461 /// of 'icmp op load X, cst', try to see if we can compute the 462 /// backedge-taken count. 463 ExitLimit ComputeLoadConstantCompareExitLimit(LoadInst *LI, 464 Constant *RHS, 465 const Loop *L, 466 ICmpInst::Predicate p); 467 468 /// ComputeExitCountExhaustively - If the loop is known to execute a 469 /// constant number of times (the condition evolves only from constants), 470 /// try to evaluate a few iterations of the loop until we get the exit 471 /// condition gets a value of ExitWhen (true or false). If we cannot 472 /// evaluate the exit count of the loop, return CouldNotCompute. 473 const SCEV *ComputeExitCountExhaustively(const Loop *L, 474 Value *Cond, 475 bool ExitWhen); 476 477 /// HowFarToZero - Return the number of times an exit condition comparing 478 /// the specified value to zero will execute. If not computable, return 479 /// CouldNotCompute. 480 ExitLimit HowFarToZero(const SCEV *V, const Loop *L); 481 482 /// HowFarToNonZero - Return the number of times an exit condition checking 483 /// the specified value for nonzero will execute. If not computable, return 484 /// CouldNotCompute. 485 ExitLimit HowFarToNonZero(const SCEV *V, const Loop *L); 486 487 /// HowManyLessThans - Return the number of times an exit condition 488 /// containing the specified less-than comparison will execute. If not 489 /// computable, return CouldNotCompute. isSigned specifies whether the 490 /// less-than is signed. 491 ExitLimit HowManyLessThans(const SCEV *LHS, const SCEV *RHS, 492 const Loop *L, bool isSigned); 493 494 /// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB 495 /// (which may not be an immediate predecessor) which has exactly one 496 /// successor from which BB is reachable, or null if no such block is 497 /// found. 498 std::pair<BasicBlock *, BasicBlock *> 499 getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB); 500 501 /// isImpliedCond - Test whether the condition described by Pred, LHS, and 502 /// RHS is true whenever the given FoundCondValue value evaluates to true. 503 bool isImpliedCond(ICmpInst::Predicate Pred, 504 const SCEV *LHS, const SCEV *RHS, 505 Value *FoundCondValue, 506 bool Inverse); 507 508 /// isImpliedCondOperands - Test whether the condition described by Pred, 509 /// LHS, and RHS is true whenever the condition described by Pred, FoundLHS, 510 /// and FoundRHS is true. 511 bool isImpliedCondOperands(ICmpInst::Predicate Pred, 512 const SCEV *LHS, const SCEV *RHS, 513 const SCEV *FoundLHS, const SCEV *FoundRHS); 514 515 /// isImpliedCondOperandsHelper - Test whether the condition described by 516 /// Pred, LHS, and RHS is true whenever the condition described by Pred, 517 /// FoundLHS, and FoundRHS is true. 518 bool isImpliedCondOperandsHelper(ICmpInst::Predicate Pred, 519 const SCEV *LHS, const SCEV *RHS, 520 const SCEV *FoundLHS, 521 const SCEV *FoundRHS); 522 523 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is 524 /// in the header of its containing loop, we know the loop executes a 525 /// constant number of times, and the PHI node is just a recurrence 526 /// involving constants, fold it. 527 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, 528 const Loop *L); 529 530 /// isKnownPredicateWithRanges - Test if the given expression is known to 531 /// satisfy the condition described by Pred and the known constant ranges 532 /// of LHS and RHS. 533 /// 534 bool isKnownPredicateWithRanges(ICmpInst::Predicate Pred, 535 const SCEV *LHS, const SCEV *RHS); 536 537 /// forgetMemoizedResults - Drop memoized information computed for S. 538 void forgetMemoizedResults(const SCEV *S); 539 540 public: 541 static char ID; // Pass identification, replacement for typeid 542 ScalarEvolution(); 543 544 LLVMContext &getContext() const { return F->getContext(); } 545 546 /// isSCEVable - Test if values of the given type are analyzable within 547 /// the SCEV framework. This primarily includes integer types, and it 548 /// can optionally include pointer types if the ScalarEvolution class 549 /// has access to target-specific information. 550 bool isSCEVable(Type *Ty) const; 551 552 /// getTypeSizeInBits - Return the size in bits of the specified type, 553 /// for which isSCEVable must return true. 554 uint64_t getTypeSizeInBits(Type *Ty) const; 555 556 /// getEffectiveSCEVType - Return a type with the same bitwidth as 557 /// the given type and which represents how SCEV will treat the given 558 /// type, for which isSCEVable must return true. For pointer types, 559 /// this is the pointer-sized integer type. 560 Type *getEffectiveSCEVType(Type *Ty) const; 561 562 /// getSCEV - Return a SCEV expression for the full generality of the 563 /// specified expression. 564 const SCEV *getSCEV(Value *V); 565 566 const SCEV *getConstant(ConstantInt *V); 567 const SCEV *getConstant(const APInt& Val); 568 const SCEV *getConstant(Type *Ty, uint64_t V, bool isSigned = false); 569 const SCEV *getTruncateExpr(const SCEV *Op, Type *Ty); 570 const SCEV *getZeroExtendExpr(const SCEV *Op, Type *Ty); 571 const SCEV *getSignExtendExpr(const SCEV *Op, Type *Ty); 572 const SCEV *getAnyExtendExpr(const SCEV *Op, Type *Ty); 573 const SCEV *getAddExpr(SmallVectorImpl<const SCEV *> &Ops, 574 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 575 const SCEV *getAddExpr(const SCEV *LHS, const SCEV *RHS, 576 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 577 SmallVector<const SCEV *, 2> Ops; 578 Ops.push_back(LHS); 579 Ops.push_back(RHS); 580 return getAddExpr(Ops, Flags); 581 } 582 const SCEV *getAddExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 583 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 584 SmallVector<const SCEV *, 3> Ops; 585 Ops.push_back(Op0); 586 Ops.push_back(Op1); 587 Ops.push_back(Op2); 588 return getAddExpr(Ops, Flags); 589 } 590 const SCEV *getMulExpr(SmallVectorImpl<const SCEV *> &Ops, 591 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 592 const SCEV *getMulExpr(const SCEV *LHS, const SCEV *RHS, 593 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) 594 { 595 SmallVector<const SCEV *, 2> Ops; 596 Ops.push_back(LHS); 597 Ops.push_back(RHS); 598 return getMulExpr(Ops, Flags); 599 } 600 const SCEV *getMulExpr(const SCEV *Op0, const SCEV *Op1, const SCEV *Op2, 601 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap) { 602 SmallVector<const SCEV *, 3> Ops; 603 Ops.push_back(Op0); 604 Ops.push_back(Op1); 605 Ops.push_back(Op2); 606 return getMulExpr(Ops, Flags); 607 } 608 const SCEV *getUDivExpr(const SCEV *LHS, const SCEV *RHS); 609 const SCEV *getAddRecExpr(const SCEV *Start, const SCEV *Step, 610 const Loop *L, SCEV::NoWrapFlags Flags); 611 const SCEV *getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands, 612 const Loop *L, SCEV::NoWrapFlags Flags); 613 const SCEV *getAddRecExpr(const SmallVectorImpl<const SCEV *> &Operands, 614 const Loop *L, SCEV::NoWrapFlags Flags) { 615 SmallVector<const SCEV *, 4> NewOp(Operands.begin(), Operands.end()); 616 return getAddRecExpr(NewOp, L, Flags); 617 } 618 const SCEV *getSMaxExpr(const SCEV *LHS, const SCEV *RHS); 619 const SCEV *getSMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 620 const SCEV *getUMaxExpr(const SCEV *LHS, const SCEV *RHS); 621 const SCEV *getUMaxExpr(SmallVectorImpl<const SCEV *> &Operands); 622 const SCEV *getSMinExpr(const SCEV *LHS, const SCEV *RHS); 623 const SCEV *getUMinExpr(const SCEV *LHS, const SCEV *RHS); 624 const SCEV *getUnknown(Value *V); 625 const SCEV *getCouldNotCompute(); 626 627 /// getSizeOfExpr - Return an expression for sizeof on the given type. 628 /// 629 const SCEV *getSizeOfExpr(Type *AllocTy); 630 631 /// getAlignOfExpr - Return an expression for alignof on the given type. 632 /// 633 const SCEV *getAlignOfExpr(Type *AllocTy); 634 635 /// getOffsetOfExpr - Return an expression for offsetof on the given field. 636 /// 637 const SCEV *getOffsetOfExpr(StructType *STy, unsigned FieldNo); 638 639 /// getOffsetOfExpr - Return an expression for offsetof on the given field. 640 /// 641 const SCEV *getOffsetOfExpr(Type *CTy, Constant *FieldNo); 642 643 /// getNegativeSCEV - Return the SCEV object corresponding to -V. 644 /// 645 const SCEV *getNegativeSCEV(const SCEV *V); 646 647 /// getNotSCEV - Return the SCEV object corresponding to ~V. 648 /// 649 const SCEV *getNotSCEV(const SCEV *V); 650 651 /// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1. 652 const SCEV *getMinusSCEV(const SCEV *LHS, const SCEV *RHS, 653 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap); 654 655 /// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion 656 /// of the input value to the specified type. If the type must be 657 /// extended, it is zero extended. 658 const SCEV *getTruncateOrZeroExtend(const SCEV *V, Type *Ty); 659 660 /// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion 661 /// of the input value to the specified type. If the type must be 662 /// extended, it is sign extended. 663 const SCEV *getTruncateOrSignExtend(const SCEV *V, Type *Ty); 664 665 /// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of 666 /// the input value to the specified type. If the type must be extended, 667 /// it is zero extended. The conversion must not be narrowing. 668 const SCEV *getNoopOrZeroExtend(const SCEV *V, Type *Ty); 669 670 /// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of 671 /// the input value to the specified type. If the type must be extended, 672 /// it is sign extended. The conversion must not be narrowing. 673 const SCEV *getNoopOrSignExtend(const SCEV *V, Type *Ty); 674 675 /// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of 676 /// the input value to the specified type. If the type must be extended, 677 /// it is extended with unspecified bits. The conversion must not be 678 /// narrowing. 679 const SCEV *getNoopOrAnyExtend(const SCEV *V, Type *Ty); 680 681 /// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the 682 /// input value to the specified type. The conversion must not be 683 /// widening. 684 const SCEV *getTruncateOrNoop(const SCEV *V, Type *Ty); 685 686 /// getUMaxFromMismatchedTypes - Promote the operands to the wider of 687 /// the types using zero-extension, and then perform a umax operation 688 /// with them. 689 const SCEV *getUMaxFromMismatchedTypes(const SCEV *LHS, 690 const SCEV *RHS); 691 692 /// getUMinFromMismatchedTypes - Promote the operands to the wider of 693 /// the types using zero-extension, and then perform a umin operation 694 /// with them. 695 const SCEV *getUMinFromMismatchedTypes(const SCEV *LHS, 696 const SCEV *RHS); 697 698 /// getPointerBase - Transitively follow the chain of pointer-type operands 699 /// until reaching a SCEV that does not have a single pointer operand. This 700 /// returns a SCEVUnknown pointer for well-formed pointer-type expressions, 701 /// but corner cases do exist. 702 const SCEV *getPointerBase(const SCEV *V); 703 704 /// getSCEVAtScope - Return a SCEV expression for the specified value 705 /// at the specified scope in the program. The L value specifies a loop 706 /// nest to evaluate the expression at, where null is the top-level or a 707 /// specified loop is immediately inside of the loop. 708 /// 709 /// This method can be used to compute the exit value for a variable defined 710 /// in a loop by querying what the value will hold in the parent loop. 711 /// 712 /// In the case that a relevant loop exit value cannot be computed, the 713 /// original value V is returned. 714 const SCEV *getSCEVAtScope(const SCEV *S, const Loop *L); 715 716 /// getSCEVAtScope - This is a convenience function which does 717 /// getSCEVAtScope(getSCEV(V), L). 718 const SCEV *getSCEVAtScope(Value *V, const Loop *L); 719 720 /// isLoopEntryGuardedByCond - Test whether entry to the loop is protected 721 /// by a conditional between LHS and RHS. This is used to help avoid max 722 /// expressions in loop trip counts, and to eliminate casts. 723 bool isLoopEntryGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 724 const SCEV *LHS, const SCEV *RHS); 725 726 /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is 727 /// protected by a conditional between LHS and RHS. This is used to 728 /// to eliminate casts. 729 bool isLoopBackedgeGuardedByCond(const Loop *L, ICmpInst::Predicate Pred, 730 const SCEV *LHS, const SCEV *RHS); 731 732 /// getSmallConstantTripCount - Returns the maximum trip count of this loop 733 /// as a normal unsigned value. Returns 0 if the trip count is unknown or 734 /// not constant. This "trip count" assumes that control exits via 735 /// ExitingBlock. More precisely, it is the number of times that control may 736 /// reach ExitingBlock before taking the branch. For loops with multiple 737 /// exits, it may not be the number times that the loop header executes if 738 /// the loop exits prematurely via another branch. 739 unsigned getSmallConstantTripCount(Loop *L, BasicBlock *ExitingBlock); 740 741 /// getSmallConstantTripMultiple - Returns the largest constant divisor of 742 /// the trip count of this loop as a normal unsigned value, if 743 /// possible. This means that the actual trip count is always a multiple of 744 /// the returned value (don't forget the trip count could very well be zero 745 /// as well!). As explained in the comments for getSmallConstantTripCount, 746 /// this assumes that control exits the loop via ExitingBlock. 747 unsigned getSmallConstantTripMultiple(Loop *L, BasicBlock *ExitingBlock); 748 749 // getExitCount - Get the expression for the number of loop iterations for 750 // which this loop is guaranteed not to exit via ExitingBlock. Otherwise 751 // return SCEVCouldNotCompute. 752 const SCEV *getExitCount(Loop *L, BasicBlock *ExitingBlock); 753 754 /// getBackedgeTakenCount - If the specified loop has a predictable 755 /// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute 756 /// object. The backedge-taken count is the number of times the loop header 757 /// will be branched to from within the loop. This is one less than the 758 /// trip count of the loop, since it doesn't count the first iteration, 759 /// when the header is branched to from outside the loop. 760 /// 761 /// Note that it is not valid to call this method on a loop without a 762 /// loop-invariant backedge-taken count (see 763 /// hasLoopInvariantBackedgeTakenCount). 764 /// 765 const SCEV *getBackedgeTakenCount(const Loop *L); 766 767 /// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except 768 /// return the least SCEV value that is known never to be less than the 769 /// actual backedge taken count. 770 const SCEV *getMaxBackedgeTakenCount(const Loop *L); 771 772 /// hasLoopInvariantBackedgeTakenCount - Return true if the specified loop 773 /// has an analyzable loop-invariant backedge-taken count. 774 bool hasLoopInvariantBackedgeTakenCount(const Loop *L); 775 776 /// forgetLoop - This method should be called by the client when it has 777 /// changed a loop in a way that may effect ScalarEvolution's ability to 778 /// compute a trip count, or if the loop is deleted. 779 void forgetLoop(const Loop *L); 780 781 /// forgetValue - This method should be called by the client when it has 782 /// changed a value in a way that may effect its value, or which may 783 /// disconnect it from a def-use chain linking it to a loop. 784 void forgetValue(Value *V); 785 786 /// GetMinTrailingZeros - Determine the minimum number of zero bits that S 787 /// is guaranteed to end in (at every loop iteration). It is, at the same 788 /// time, the minimum number of times S is divisible by 2. For example, 789 /// given {4,+,8} it returns 2. If S is guaranteed to be 0, it returns the 790 /// bitwidth of S. 791 uint32_t GetMinTrailingZeros(const SCEV *S); 792 793 /// getUnsignedRange - Determine the unsigned range for a particular SCEV. 794 /// 795 ConstantRange getUnsignedRange(const SCEV *S); 796 797 /// getSignedRange - Determine the signed range for a particular SCEV. 798 /// 799 ConstantRange getSignedRange(const SCEV *S); 800 801 /// isKnownNegative - Test if the given expression is known to be negative. 802 /// 803 bool isKnownNegative(const SCEV *S); 804 805 /// isKnownPositive - Test if the given expression is known to be positive. 806 /// 807 bool isKnownPositive(const SCEV *S); 808 809 /// isKnownNonNegative - Test if the given expression is known to be 810 /// non-negative. 811 /// 812 bool isKnownNonNegative(const SCEV *S); 813 814 /// isKnownNonPositive - Test if the given expression is known to be 815 /// non-positive. 816 /// 817 bool isKnownNonPositive(const SCEV *S); 818 819 /// isKnownNonZero - Test if the given expression is known to be 820 /// non-zero. 821 /// 822 bool isKnownNonZero(const SCEV *S); 823 824 /// isKnownPredicate - Test if the given expression is known to satisfy 825 /// the condition described by Pred, LHS, and RHS. 826 /// 827 bool isKnownPredicate(ICmpInst::Predicate Pred, 828 const SCEV *LHS, const SCEV *RHS); 829 830 /// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with 831 /// predicate Pred. Return true iff any changes were made. If the 832 /// operands are provably equal or inequal, LHS and RHS are set to 833 /// the same value and Pred is set to either ICMP_EQ or ICMP_NE. 834 /// 835 bool SimplifyICmpOperands(ICmpInst::Predicate &Pred, 836 const SCEV *&LHS, 837 const SCEV *&RHS); 838 839 /// getLoopDisposition - Return the "disposition" of the given SCEV with 840 /// respect to the given loop. 841 LoopDisposition getLoopDisposition(const SCEV *S, const Loop *L); 842 843 /// isLoopInvariant - Return true if the value of the given SCEV is 844 /// unchanging in the specified loop. 845 bool isLoopInvariant(const SCEV *S, const Loop *L); 846 847 /// hasComputableLoopEvolution - Return true if the given SCEV changes value 848 /// in a known way in the specified loop. This property being true implies 849 /// that the value is variant in the loop AND that we can emit an expression 850 /// to compute the value of the expression at any particular loop iteration. 851 bool hasComputableLoopEvolution(const SCEV *S, const Loop *L); 852 853 /// getLoopDisposition - Return the "disposition" of the given SCEV with 854 /// respect to the given block. 855 BlockDisposition getBlockDisposition(const SCEV *S, const BasicBlock *BB); 856 857 /// dominates - Return true if elements that makes up the given SCEV 858 /// dominate the specified basic block. 859 bool dominates(const SCEV *S, const BasicBlock *BB); 860 861 /// properlyDominates - Return true if elements that makes up the given SCEV 862 /// properly dominate the specified basic block. 863 bool properlyDominates(const SCEV *S, const BasicBlock *BB); 864 865 /// hasOperand - Test whether the given SCEV has Op as a direct or 866 /// indirect operand. 867 bool hasOperand(const SCEV *S, const SCEV *Op) const; 868 869 virtual bool runOnFunction(Function &F); 870 virtual void releaseMemory(); 871 virtual void getAnalysisUsage(AnalysisUsage &AU) const; 872 virtual void print(raw_ostream &OS, const Module* = 0) const; 873 874 private: 875 FoldingSet<SCEV> UniqueSCEVs; 876 BumpPtrAllocator SCEVAllocator; 877 878 /// FirstUnknown - The head of a linked list of all SCEVUnknown 879 /// values that have been allocated. This is used by releaseMemory 880 /// to locate them all and call their destructors. 881 SCEVUnknown *FirstUnknown; 882 }; 883 } 884 885 #endif 886