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 /// Returns true if V is always a dereferenceable pointer with alignment
233 /// greater or equal than requested. If the context instruction is specified
234 /// performs context-sensitive analysis and returns true if the pointer is
235 /// dereferenceable at the specified instruction.
236 bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
237 const DataLayout &DL,
238 const Instruction *CtxI = nullptr,
239 const DominatorTree *DT = nullptr,
240 const TargetLibraryInfo *TLI = nullptr);
242 /// isSafeToSpeculativelyExecute - Return true if the instruction does not
243 /// have any effects besides calculating the result and does not have
244 /// undefined behavior.
246 /// This method never returns true for an instruction that returns true for
247 /// mayHaveSideEffects; however, this method also does some other checks in
248 /// addition. It checks for undefined behavior, like dividing by zero or
249 /// loading from an invalid pointer (but not for undefined results, like a
250 /// shift with a shift amount larger than the width of the result). It checks
251 /// for malloc and alloca because speculatively executing them might cause a
252 /// memory leak. It also returns false for instructions related to control
253 /// flow, specifically terminators and PHI nodes.
255 /// If the CtxI is specified this method performs context-sensitive analysis
256 /// and returns true if it is safe to execute the instruction immediately
259 /// If the CtxI is NOT specified this method only looks at the instruction
260 /// itself and its operands, so if this method returns true, it is safe to
261 /// move the instruction as long as the correct dominance relationships for
262 /// the operands and users hold.
264 /// This method can return true for instructions that read memory;
265 /// for such instructions, moving them may change the resulting value.
266 bool isSafeToSpeculativelyExecute(const Value *V,
267 const Instruction *CtxI = nullptr,
268 const DominatorTree *DT = nullptr,
269 const TargetLibraryInfo *TLI = nullptr);
271 /// Returns true if the result or effects of the given instructions \p I
272 /// depend on or influence global memory.
273 /// Memory dependence arises for example if the the instruction reads from
274 /// memory or may produce effects or undefined behaviour. Memory dependent
275 /// instructions generally cannot be reorderd with respect to other memory
276 /// dependent instructions or moved into non-dominated basic blocks.
277 /// Instructions which just compute a value based on the values of their
278 /// operands are not memory dependent.
279 bool mayBeMemoryDependent(const Instruction &I);
281 /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
282 /// its definition. This returns true for allocas, non-extern-weak globals
283 /// and byval arguments.
284 bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
286 /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
287 /// If the context instruction is specified perform context-sensitive analysis
288 /// and return true if the pointer couldn't possibly be null at the specified
290 bool isKnownNonNullAt(const Value *V,
291 const Instruction *CtxI = nullptr,
292 const DominatorTree *DT = nullptr,
293 const TargetLibraryInfo *TLI = nullptr);
295 /// Return true if it is valid to use the assumptions provided by an
296 /// assume intrinsic, I, at the point in the control-flow identified by the
297 /// context instruction, CxtI.
298 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
299 const DominatorTree *DT = nullptr);
301 enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
302 OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
303 const DataLayout &DL,
305 const Instruction *CxtI,
306 const DominatorTree *DT);
307 OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
308 const DataLayout &DL,
310 const Instruction *CxtI,
311 const DominatorTree *DT);
313 /// Return true if this function can prove that the instruction I will
314 /// always transfer execution to one of its successors (including the next
315 /// instruction that follows within a basic block). E.g. this is not
316 /// guaranteed for function calls that could loop infinitely.
318 /// In other words, this function returns false for instructions that may
319 /// transfer execution or fail to transfer execution in a way that is not
320 /// captured in the CFG nor in the sequence of instructions within a basic
323 /// Undefined behavior is assumed not to happen, so e.g. division is
324 /// guaranteed to transfer execution to the following instruction even
325 /// though division by zero might cause undefined behavior.
326 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
328 /// Return true if this function can prove that the instruction I
329 /// is executed for every iteration of the loop L.
331 /// Note that this currently only considers the loop header.
332 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
335 /// Return true if this function can prove that I is guaranteed to yield
336 /// full-poison (all bits poison) if at least one of its operands are
337 /// full-poison (all bits poison).
339 /// The exact rules for how poison propagates through instructions have
340 /// not been settled as of 2015-07-10, so this function is conservative
341 /// and only considers poison to be propagated in uncontroversial
342 /// cases. There is no attempt to track values that may be only partially
344 bool propagatesFullPoison(const Instruction *I);
346 /// Return either nullptr or an operand of I such that I will trigger
347 /// undefined behavior if I is executed and that operand has a full-poison
348 /// value (all bits poison).
349 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
351 /// Return true if this function can prove that if PoisonI is executed
352 /// and yields a full-poison value (all bits poison), then that will
353 /// trigger undefined behavior.
355 /// Note that this currently only considers the basic block that is
357 bool isKnownNotFullPoison(const Instruction *PoisonI);
359 /// \brief Specific patterns of select instructions we can match.
360 enum SelectPatternFlavor {
362 SPF_SMIN, /// Signed minimum
363 SPF_UMIN, /// Unsigned minimum
364 SPF_SMAX, /// Signed maximum
365 SPF_UMAX, /// Unsigned maximum
366 SPF_FMINNUM, /// Floating point minnum
367 SPF_FMAXNUM, /// Floating point maxnum
368 SPF_ABS, /// Absolute value
369 SPF_NABS /// Negated absolute value
371 /// \brief Behavior when a floating point min/max is given one NaN and one
372 /// non-NaN as input.
373 enum SelectPatternNaNBehavior {
374 SPNB_NA = 0, /// NaN behavior not applicable.
375 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
376 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
377 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
378 /// it has been determined that no operands can
381 struct SelectPatternResult {
382 SelectPatternFlavor Flavor;
383 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
384 /// SPF_FMINNUM or SPF_FMAXNUM.
385 bool Ordered; /// When implementing this min/max pattern as
386 /// fcmp; select, does the fcmp have to be
389 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
390 /// and providing the out parameter results if we successfully match.
392 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
393 /// not match that of the original select. If this is the case, the cast
394 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
395 /// type of LHS and RHS into the type of V is returned in CastOp.
398 /// %1 = icmp slt i32 %a, i32 4
399 /// %2 = sext i32 %a to i64
400 /// %3 = select i1 %1, i64 %2, i64 4
402 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
404 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
405 Instruction::CastOps *CastOp = nullptr);
407 } // end namespace llvm