1 //===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains routines that help analyze properties that chains of
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_VALUETRACKING_H
16 #define LLVM_ANALYSIS_VALUETRACKING_H
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/Support/DataTypes.h"
29 class AssumptionCache;
31 class TargetLibraryInfo;
35 /// Determine which bits of V are known to be either zero or one and return
36 /// them in the KnownZero/KnownOne bit sets.
38 /// This function is defined on values with integer type, values with pointer
39 /// type, and vectors of integers. In the case
40 /// where V is a vector, the known zero and known one values are the
41 /// same width as the vector element, and the bit is set only if it is true
42 /// for all of the elements in the vector.
43 void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
44 const DataLayout &DL, unsigned Depth = 0,
45 AssumptionCache *AC = nullptr,
46 const Instruction *CxtI = nullptr,
47 const DominatorTree *DT = nullptr);
48 /// Compute known bits from the range metadata.
49 /// \p KnownZero the set of bits that are known to be zero
50 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
52 /// Return true if LHS and RHS have no common bits set.
53 bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
54 AssumptionCache *AC = nullptr,
55 const Instruction *CxtI = nullptr,
56 const DominatorTree *DT = nullptr);
58 /// ComputeSignBit - Determine whether the sign bit is known to be zero or
59 /// one. Convenience wrapper around computeKnownBits.
60 void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
61 const DataLayout &DL, unsigned Depth = 0,
62 AssumptionCache *AC = nullptr,
63 const Instruction *CxtI = nullptr,
64 const DominatorTree *DT = nullptr);
66 /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
67 /// exactly one bit set when defined. For vectors return true if every
68 /// element is known to be a power of two when defined. Supports values with
69 /// integer or pointer type and vectors of integers. If 'OrZero' is set then
70 /// return true if the given value is either a power of two or zero.
71 bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
72 bool OrZero = false, unsigned Depth = 0,
73 AssumptionCache *AC = nullptr,
74 const Instruction *CxtI = nullptr,
75 const DominatorTree *DT = nullptr);
77 /// isKnownNonZero - Return true if the given value is known to be non-zero
78 /// when defined. For vectors return true if every element is known to be
79 /// non-zero when defined. Supports values with integer or pointer type and
80 /// vectors of integers.
81 bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
82 AssumptionCache *AC = nullptr,
83 const Instruction *CxtI = nullptr,
84 const DominatorTree *DT = nullptr);
86 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
87 /// this predicate to simplify operations downstream. Mask is known to be
88 /// zero for bits that V cannot have.
90 /// This function is defined on values with integer type, values with pointer
91 /// type, and vectors of integers. In the case
92 /// where V is a vector, the mask, known zero, and known one values are the
93 /// same width as the vector element, and the bit is set only if it is true
94 /// for all of the elements in the vector.
95 bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
96 unsigned Depth = 0, AssumptionCache *AC = nullptr,
97 const Instruction *CxtI = nullptr,
98 const DominatorTree *DT = nullptr);
100 /// ComputeNumSignBits - Return the number of times the sign bit of the
101 /// register is replicated into the other bits. We know that at least 1 bit
102 /// is always equal to the sign bit (itself), but other cases can give us
103 /// information. For example, immediately after an "ashr X, 2", we know that
104 /// the top 3 bits are all equal to each other, so we return 3.
106 /// 'Op' must have a scalar integer type.
108 unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
109 unsigned Depth = 0, AssumptionCache *AC = nullptr,
110 const Instruction *CxtI = nullptr,
111 const DominatorTree *DT = nullptr);
113 /// ComputeMultiple - This function computes the integer multiple of Base that
114 /// equals V. If successful, it returns true and returns the multiple in
115 /// Multiple. If unsuccessful, it returns false. Also, if V can be
116 /// simplified to an integer, then the simplified V is returned in Val. Look
117 /// through sext only if LookThroughSExt=true.
118 bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
119 bool LookThroughSExt = false,
122 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
123 /// value is never equal to -0.0.
125 bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
127 /// CannotBeOrderedLessThanZero - Return true if we can prove that the
128 /// specified FP value is either a NaN or never less than 0.0.
130 bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
132 /// isBytewiseValue - If the specified value can be set by repeating the same
133 /// byte in memory, return the i8 value that it is represented with. This is
134 /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
135 /// i16 0xF0F0, double 0.0 etc. If the value can't be handled with a repeated
136 /// byte store (e.g. i16 0x1234), return null.
137 Value *isBytewiseValue(Value *V);
139 /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
140 /// the scalar value indexed is already around as a register, for example if
141 /// it were inserted directly into the aggregrate.
143 /// If InsertBefore is not null, this function will duplicate (modified)
144 /// insertvalues when a part of a nested struct is extracted.
145 Value *FindInsertedValue(Value *V,
146 ArrayRef<unsigned> idx_range,
147 Instruction *InsertBefore = nullptr);
149 /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
150 /// it can be expressed as a base pointer plus a constant offset. Return the
151 /// base and offset to the caller.
152 Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
153 const DataLayout &DL);
154 static inline const Value *
155 GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
156 const DataLayout &DL) {
157 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
161 /// getConstantStringInfo - This function computes the length of a
162 /// null-terminated C string pointed to by V. If successful, it returns true
163 /// and returns the string in Str. If unsuccessful, it returns false. This
164 /// does not include the trailing nul character by default. If TrimAtNul is
165 /// set to false, then this returns any trailing nul characters as well as any
166 /// other characters that come after it.
167 bool getConstantStringInfo(const Value *V, StringRef &Str,
168 uint64_t Offset = 0, bool TrimAtNul = true);
170 /// GetStringLength - If we can compute the length of the string pointed to by
171 /// the specified pointer, return 'len+1'. If we can't, return 0.
172 uint64_t GetStringLength(Value *V);
174 /// GetUnderlyingObject - This method strips off any GEP address adjustments
175 /// and pointer casts from the specified value, returning the original object
176 /// being addressed. Note that the returned value has pointer type if the
177 /// specified value does. If the MaxLookup value is non-zero, it limits the
178 /// number of instructions to be stripped off.
179 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
180 unsigned MaxLookup = 6);
181 static inline const Value *GetUnderlyingObject(const Value *V,
182 const DataLayout &DL,
183 unsigned MaxLookup = 6) {
184 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
187 /// \brief This method is similar to GetUnderlyingObject except that it can
188 /// look through phi and select instructions and return multiple objects.
190 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
191 /// accesses different objects in each iteration, we don't look through the
192 /// phi node. E.g. consider this loop nest:
197 /// A[i][j] = A[i-1][j] * B[j]
200 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
201 /// of the outer loop:
203 /// Curr = A[0]; // Prev_0
205 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
208 /// Curr[j] = Prev[j] * B[j]
212 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
213 /// should not assume that Curr and Prev share the same underlying object thus
214 /// it shouldn't look through the phi above.
215 void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
216 const DataLayout &DL, LoopInfo *LI = nullptr,
217 unsigned MaxLookup = 6);
219 /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
220 /// are lifetime markers.
221 bool onlyUsedByLifetimeMarkers(const Value *V);
223 /// isDereferenceablePointer - Return true if this is always a dereferenceable
224 /// pointer. If the context instruction is specified perform context-sensitive
225 /// analysis and return true if the pointer is dereferenceable at the
226 /// specified instruction.
227 bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
228 const Instruction *CtxI = nullptr,
229 const DominatorTree *DT = nullptr,
230 const TargetLibraryInfo *TLI = nullptr);
232 /// isSafeToSpeculativelyExecute - Return true if the instruction does not
233 /// have any effects besides calculating the result and does not have
234 /// undefined behavior.
236 /// This method never returns true for an instruction that returns true for
237 /// mayHaveSideEffects; however, this method also does some other checks in
238 /// addition. It checks for undefined behavior, like dividing by zero or
239 /// loading from an invalid pointer (but not for undefined results, like a
240 /// shift with a shift amount larger than the width of the result). It checks
241 /// for malloc and alloca because speculatively executing them might cause a
242 /// memory leak. It also returns false for instructions related to control
243 /// flow, specifically terminators and PHI nodes.
245 /// If the CtxI is specified this method performs context-sensitive analysis
246 /// and returns true if it is safe to execute the instruction immediately
249 /// If the CtxI is NOT specified this method only looks at the instruction
250 /// itself and its operands, so if this method returns true, it is safe to
251 /// move the instruction as long as the correct dominance relationships for
252 /// the operands and users hold.
254 /// This method can return true for instructions that read memory;
255 /// for such instructions, moving them may change the resulting value.
256 bool isSafeToSpeculativelyExecute(const Value *V,
257 const Instruction *CtxI = nullptr,
258 const DominatorTree *DT = nullptr,
259 const TargetLibraryInfo *TLI = nullptr);
261 /// Returns true if the result or effects of the given instructions \p I
262 /// depend on or influence global memory.
263 /// Memory dependence arises for example if the the instruction reads from
264 /// memory or may produce effects or undefined behaviour. Memory dependent
265 /// instructions generally cannot be reorderd with respect to other memory
266 /// dependent instructions or moved into non-dominated basic blocks.
267 /// Instructions which just compute a value based on the values of their
268 /// operands are not memory dependent.
269 bool mayBeMemoryDependent(const Instruction &I);
271 /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
272 /// its definition. This returns true for allocas, non-extern-weak globals
273 /// and byval arguments.
274 bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
276 /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
277 /// If the context instruction is specified perform context-sensitive analysis
278 /// and return true if the pointer couldn't possibly be null at the specified
280 bool isKnownNonNullAt(const Value *V,
281 const Instruction *CtxI = nullptr,
282 const DominatorTree *DT = nullptr,
283 const TargetLibraryInfo *TLI = nullptr);
285 /// Return true if it is valid to use the assumptions provided by an
286 /// assume intrinsic, I, at the point in the control-flow identified by the
287 /// context instruction, CxtI.
288 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
289 const DominatorTree *DT = nullptr);
291 enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
292 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
293 const DataLayout &DL,
295 const Instruction *CxtI,
296 const DominatorTree *DT);
297 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
298 const DataLayout &DL,
300 const Instruction *CxtI,
301 const DominatorTree *DT);
303 /// Return true if this function can prove that the instruction I will
304 /// always transfer execution to one of its successors (including the next
305 /// instruction that follows within a basic block). E.g. this is not
306 /// guaranteed for function calls that could loop infinitely.
308 /// In other words, this function returns false for instructions that may
309 /// transfer execution or fail to transfer execution in a way that is not
310 /// captured in the CFG nor in the sequence of instructions within a basic
313 /// Undefined behavior is assumed not to happen, so e.g. division is
314 /// guaranteed to transfer execution to the following instruction even
315 /// though division by zero might cause undefined behavior.
316 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
318 /// Return true if this function can prove that the instruction I
319 /// is executed for every iteration of the loop L.
321 /// Note that this currently only considers the loop header.
322 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
325 /// Return true if this function can prove that I is guaranteed to yield
326 /// full-poison (all bits poison) if at least one of its operands are
327 /// full-poison (all bits poison).
329 /// The exact rules for how poison propagates through instructions have
330 /// not been settled as of 2015-07-10, so this function is conservative
331 /// and only considers poison to be propagated in uncontroversial
332 /// cases. There is no attempt to track values that may be only partially
334 bool propagatesFullPoison(const Instruction *I);
336 /// Return either nullptr or an operand of I such that I will trigger
337 /// undefined behavior if I is executed and that operand has a full-poison
338 /// value (all bits poison).
339 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
341 /// Return true if this function can prove that if PoisonI is executed
342 /// and yields a full-poison value (all bits poison), then that will
343 /// trigger undefined behavior.
345 /// Note that this currently only considers the basic block that is
347 bool isKnownNotFullPoison(const Instruction *PoisonI);
349 /// \brief Specific patterns of select instructions we can match.
350 enum SelectPatternFlavor {
352 SPF_SMIN, // Signed minimum
353 SPF_UMIN, // Unsigned minimum
354 SPF_SMAX, // Signed maximum
355 SPF_UMAX, // Unsigned maximum
356 SPF_ABS, // Absolute value
357 SPF_NABS // Negated absolute value
359 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
360 /// and providing the out parameter results if we successfully match.
362 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
363 /// not match that of the original select. If this is the case, the cast
364 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
365 /// type of LHS and RHS into the type of V is returned in CastOp.
368 /// %1 = icmp slt i32 %a, i32 4
369 /// %2 = sext i32 %a to i64
370 /// %3 = select i1 %1, i64 %2, i64 4
372 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
374 SelectPatternFlavor matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
375 Instruction::CastOps *CastOp = nullptr);
377 } // end namespace llvm