Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

893 lines
38 KiB

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