ValueTracking.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. //===- llvm/Analysis/ValueTracking.h - Walk computations --------*- 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. // This file contains routines that help analyze properties that chains of
  11. // computations have.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_ANALYSIS_VALUETRACKING_H
  15. #define LLVM_ANALYSIS_VALUETRACKING_H
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/IR/Instruction.h"
  18. #include "llvm/Support/DataTypes.h"
  19. namespace llvm {
  20. class Value;
  21. class Instruction;
  22. class APInt;
  23. class DataLayout;
  24. class StringRef;
  25. class MDNode;
  26. class AssumptionCache;
  27. class DominatorTree;
  28. class TargetLibraryInfo;
  29. class LoopInfo;
  30. /// Determine which bits of V are known to be either zero or one and return
  31. /// them in the KnownZero/KnownOne bit sets.
  32. ///
  33. /// This function is defined on values with integer type, values with pointer
  34. /// type, and vectors of integers. In the case
  35. /// where V is a vector, the known zero and known one values are the
  36. /// same width as the vector element, and the bit is set only if it is true
  37. /// for all of the elements in the vector.
  38. void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
  39. const DataLayout &DL, unsigned Depth = 0,
  40. AssumptionCache *AC = nullptr,
  41. const Instruction *CxtI = nullptr,
  42. const DominatorTree *DT = nullptr);
  43. /// Compute known bits from the range metadata.
  44. /// \p KnownZero the set of bits that are known to be zero
  45. void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
  46. APInt &KnownZero);
  47. /// Returns true if LHS and RHS have no common bits set.
  48. bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
  49. AssumptionCache *AC = nullptr,
  50. const Instruction *CxtI = nullptr,
  51. const DominatorTree *DT = nullptr);
  52. /// ComputeSignBit - Determine whether the sign bit is known to be zero or
  53. /// one. Convenience wrapper around computeKnownBits.
  54. void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
  55. const DataLayout &DL, unsigned Depth = 0,
  56. AssumptionCache *AC = nullptr,
  57. const Instruction *CxtI = nullptr,
  58. const DominatorTree *DT = nullptr);
  59. /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
  60. /// exactly one bit set when defined. For vectors return true if every
  61. /// element is known to be a power of two when defined. Supports values with
  62. /// integer or pointer type and vectors of integers. If 'OrZero' is set then
  63. /// returns true if the given value is either a power of two or zero.
  64. bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
  65. bool OrZero = false, unsigned Depth = 0,
  66. AssumptionCache *AC = nullptr,
  67. const Instruction *CxtI = nullptr,
  68. const DominatorTree *DT = nullptr);
  69. /// isKnownNonZero - Return true if the given value is known to be non-zero
  70. /// when defined. For vectors return true if every element is known to be
  71. /// non-zero when defined. Supports values with integer or pointer type and
  72. /// vectors of integers.
  73. bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
  74. AssumptionCache *AC = nullptr,
  75. const Instruction *CxtI = nullptr,
  76. const DominatorTree *DT = nullptr);
  77. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  78. /// this predicate to simplify operations downstream. Mask is known to be
  79. /// zero for bits that V cannot have.
  80. ///
  81. /// This function is defined on values with integer type, values with pointer
  82. /// type, and vectors of integers. In the case
  83. /// where V is a vector, the mask, known zero, and known one values are the
  84. /// same width as the vector element, and the bit is set only if it is true
  85. /// for all of the elements in the vector.
  86. bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
  87. unsigned Depth = 0, AssumptionCache *AC = nullptr,
  88. const Instruction *CxtI = nullptr,
  89. const DominatorTree *DT = nullptr);
  90. /// ComputeNumSignBits - Return the number of times the sign bit of the
  91. /// register is replicated into the other bits. We know that at least 1 bit
  92. /// is always equal to the sign bit (itself), but other cases can give us
  93. /// information. For example, immediately after an "ashr X, 2", we know that
  94. /// the top 3 bits are all equal to each other, so we return 3.
  95. ///
  96. /// 'Op' must have a scalar integer type.
  97. ///
  98. unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
  99. unsigned Depth = 0, AssumptionCache *AC = nullptr,
  100. const Instruction *CxtI = nullptr,
  101. const DominatorTree *DT = nullptr);
  102. /// ComputeMultiple - This function computes the integer multiple of Base that
  103. /// equals V. If successful, it returns true and returns the multiple in
  104. /// Multiple. If unsuccessful, it returns false. Also, if V can be
  105. /// simplified to an integer, then the simplified V is returned in Val. Look
  106. /// through sext only if LookThroughSExt=true.
  107. bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
  108. bool LookThroughSExt = false,
  109. unsigned Depth = 0);
  110. /// CannotBeNegativeZero - Return true if we can prove that the specified FP
  111. /// value is never equal to -0.0.
  112. ///
  113. bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
  114. /// CannotBeOrderedLessThanZero - Return true if we can prove that the
  115. /// specified FP value is either a NaN or never less than 0.0.
  116. ///
  117. bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
  118. /// isBytewiseValue - If the specified value can be set by repeating the same
  119. /// byte in memory, return the i8 value that it is represented with. This is
  120. /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
  121. /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
  122. /// byte store (e.g. i16 0x1234), return null.
  123. Value *isBytewiseValue(Value *V);
  124. /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
  125. /// the scalar value indexed is already around as a register, for example if
  126. /// it were inserted directly into the aggregrate.
  127. ///
  128. /// If InsertBefore is not null, this function will duplicate (modified)
  129. /// insertvalues when a part of a nested struct is extracted.
  130. Value *FindInsertedValue(Value *V,
  131. ArrayRef<unsigned> idx_range,
  132. Instruction *InsertBefore = nullptr);
  133. /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
  134. /// it can be expressed as a base pointer plus a constant offset. Return the
  135. /// base and offset to the caller.
  136. Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
  137. const DataLayout &DL);
  138. static inline const Value *
  139. GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
  140. const DataLayout &DL) {
  141. return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
  142. DL);
  143. }
  144. /// getConstantStringInfo - This function computes the length of a
  145. /// null-terminated C string pointed to by V. If successful, it returns true
  146. /// and returns the string in Str. If unsuccessful, it returns false. This
  147. /// does not include the trailing nul character by default. If TrimAtNul is
  148. /// set to false, then this returns any trailing nul characters as well as any
  149. /// other characters that come after it.
  150. bool getConstantStringInfo(const Value *V, StringRef &Str,
  151. uint64_t Offset = 0, bool TrimAtNul = true);
  152. /// GetStringLength - If we can compute the length of the string pointed to by
  153. /// the specified pointer, return 'len+1'. If we can't, return 0.
  154. uint64_t GetStringLength(Value *V);
  155. /// GetUnderlyingObject - This method strips off any GEP address adjustments
  156. /// and pointer casts from the specified value, returning the original object
  157. /// being addressed. Note that the returned value has pointer type if the
  158. /// specified value does. If the MaxLookup value is non-zero, it limits the
  159. /// number of instructions to be stripped off.
  160. Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
  161. unsigned MaxLookup = 6);
  162. static inline const Value *GetUnderlyingObject(const Value *V,
  163. const DataLayout &DL,
  164. unsigned MaxLookup = 6) {
  165. return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
  166. }
  167. /// \brief This method is similar to GetUnderlyingObject except that it can
  168. /// look through phi and select instructions and return multiple objects.
  169. ///
  170. /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
  171. /// accesses different objects in each iteration, we don't look through the
  172. /// phi node. E.g. consider this loop nest:
  173. ///
  174. /// int **A;
  175. /// for (i)
  176. /// for (j) {
  177. /// A[i][j] = A[i-1][j] * B[j]
  178. /// }
  179. ///
  180. /// This is transformed by Load-PRE to stash away A[i] for the next iteration
  181. /// of the outer loop:
  182. ///
  183. /// Curr = A[0]; // Prev_0
  184. /// for (i: 1..N) {
  185. /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
  186. /// Curr = A[i];
  187. /// for (j: 0..N) {
  188. /// Curr[j] = Prev[j] * B[j]
  189. /// }
  190. /// }
  191. ///
  192. /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
  193. /// should not assume that Curr and Prev share the same underlying object thus
  194. /// it shouldn't look through the phi above.
  195. void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
  196. const DataLayout &DL, LoopInfo *LI = nullptr,
  197. unsigned MaxLookup = 6);
  198. /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
  199. /// are lifetime markers.
  200. bool onlyUsedByLifetimeMarkers(const Value *V);
  201. /// isDereferenceablePointer - Return true if this is always a dereferenceable
  202. /// pointer. If the context instruction is specified perform context-sensitive
  203. /// analysis and return true if the pointer is dereferenceable at the
  204. /// specified instruction.
  205. bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
  206. const Instruction *CtxI = nullptr,
  207. const DominatorTree *DT = nullptr,
  208. const TargetLibraryInfo *TLI = nullptr);
  209. /// isSafeToSpeculativelyExecute - Return true if the instruction does not
  210. /// have any effects besides calculating the result and does not have
  211. /// undefined behavior.
  212. ///
  213. /// This method never returns true for an instruction that returns true for
  214. /// mayHaveSideEffects; however, this method also does some other checks in
  215. /// addition. It checks for undefined behavior, like dividing by zero or
  216. /// loading from an invalid pointer (but not for undefined results, like a
  217. /// shift with a shift amount larger than the width of the result). It checks
  218. /// for malloc and alloca because speculatively executing them might cause a
  219. /// memory leak. It also returns false for instructions related to control
  220. /// flow, specifically terminators and PHI nodes.
  221. ///
  222. /// If the CtxI is specified this method performs context-sensitive analysis
  223. /// and returns true if it is safe to execute the instruction immediately
  224. /// before the CtxI.
  225. ///
  226. /// If the CtxI is NOT specified this method only looks at the instruction
  227. /// itself and its operands, so if this method returns true, it is safe to
  228. /// move the instruction as long as the correct dominance relationships for
  229. /// the operands and users hold.
  230. ///
  231. /// This method can return true for instructions that read memory;
  232. /// for such instructions, moving them may change the resulting value.
  233. bool isSafeToSpeculativelyExecute(const Value *V,
  234. const Instruction *CtxI = nullptr,
  235. const DominatorTree *DT = nullptr,
  236. const TargetLibraryInfo *TLI = nullptr);
  237. /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
  238. /// its definition. This returns true for allocas, non-extern-weak globals
  239. /// and byval arguments.
  240. bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
  241. /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
  242. /// If the context instruction is specified perform context-sensitive analysis
  243. /// and return true if the pointer couldn't possibly be null at the specified
  244. /// instruction.
  245. bool isKnownNonNullAt(const Value *V,
  246. const Instruction *CtxI = nullptr,
  247. const DominatorTree *DT = nullptr,
  248. const TargetLibraryInfo *TLI = nullptr);
  249. /// Return true if it is valid to use the assumptions provided by an
  250. /// assume intrinsic, I, at the point in the control-flow identified by the
  251. /// context instruction, CxtI.
  252. bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
  253. const DominatorTree *DT = nullptr);
  254. enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
  255. OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
  256. const DataLayout &DL,
  257. AssumptionCache *AC,
  258. const Instruction *CxtI,
  259. const DominatorTree *DT);
  260. OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
  261. const DataLayout &DL,
  262. AssumptionCache *AC,
  263. const Instruction *CxtI,
  264. const DominatorTree *DT);
  265. /// \brief Specific patterns of select instructions we can match.
  266. enum SelectPatternFlavor {
  267. SPF_UNKNOWN = 0,
  268. SPF_SMIN, // Signed minimum
  269. SPF_UMIN, // Unsigned minimum
  270. SPF_SMAX, // Signed maximum
  271. SPF_UMAX, // Unsigned maximum
  272. SPF_ABS, // Absolute value
  273. SPF_NABS // Negated absolute value
  274. };
  275. /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
  276. /// and providing the out parameter results if we successfully match.
  277. ///
  278. /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
  279. /// not match that of the original select. If this is the case, the cast
  280. /// operation (one of Trunc,SExt,Zext) that must be done to transform the
  281. /// type of LHS and RHS into the type of V is returned in CastOp.
  282. ///
  283. /// For example:
  284. /// %1 = icmp slt i32 %a, i32 4
  285. /// %2 = sext i32 %a to i64
  286. /// %3 = select i1 %1, i64 %2, i64 4
  287. ///
  288. /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
  289. ///
  290. SelectPatternFlavor matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
  291. Instruction::CastOps *CastOp = nullptr);
  292. } // end namespace llvm
  293. #endif