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/IR/CallSite.h"
19 #include "llvm/IR/Instruction.h"
20 #include "llvm/IR/IntrinsicInst.h"
21 #include "llvm/Support/DataTypes.h"
24 template <typename T> class ArrayRef;
27 class AssumptionCache;
34 class OptimizationRemarkEmitter;
37 class TargetLibraryInfo;
44 /// Determine which bits of V are known to be either zero or one and return
45 /// them in the KnownZero/KnownOne bit sets.
47 /// This function is defined on values with integer type, values with pointer
48 /// type, and vectors of integers. In the case
49 /// where V is a vector, the known zero and known one values are the
50 /// same width as the vector element, and the bit is set only if it is true
51 /// for all of the elements in the vector.
52 void computeKnownBits(const Value *V, APInt &KnownZero, APInt &KnownOne,
53 const DataLayout &DL, unsigned Depth = 0,
54 AssumptionCache *AC = nullptr,
55 const Instruction *CxtI = nullptr,
56 const DominatorTree *DT = nullptr,
57 OptimizationRemarkEmitter *ORE = nullptr);
58 /// Compute known bits from the range metadata.
59 /// \p KnownZero the set of bits that are known to be zero
60 /// \p KnownOne the set of bits that are known to be one
61 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
62 APInt &KnownZero, APInt &KnownOne);
63 /// Return true if LHS and RHS have no common bits set.
64 bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
66 AssumptionCache *AC = nullptr,
67 const Instruction *CxtI = nullptr,
68 const DominatorTree *DT = nullptr);
70 /// Determine whether the sign bit is known to be zero or one. Convenience
71 /// wrapper around computeKnownBits.
72 void ComputeSignBit(const Value *V, bool &KnownZero, bool &KnownOne,
73 const DataLayout &DL, unsigned Depth = 0,
74 AssumptionCache *AC = nullptr,
75 const Instruction *CxtI = nullptr,
76 const DominatorTree *DT = nullptr);
78 /// Return true if the given value is known to have exactly one bit set when
79 /// defined. For vectors return true if every element is known to be a power
80 /// of two when defined. Supports values with integer or pointer type and
81 /// vectors of integers. If 'OrZero' is set, then return true if the given
82 /// value is either a power of two or zero.
83 bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
84 bool OrZero = false, unsigned Depth = 0,
85 AssumptionCache *AC = nullptr,
86 const Instruction *CxtI = nullptr,
87 const DominatorTree *DT = nullptr);
89 /// Return true if the given value is known to be non-zero when defined. For
90 /// vectors, return true if every element is known to be non-zero when
91 /// defined. For pointers, if the context instruction and dominator tree are
92 /// specified, perform context-sensitive analysis and return true if the
93 /// pointer couldn't possibly be null at the specified instruction.
94 /// Supports values with integer or pointer type and vectors of integers.
95 bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
96 AssumptionCache *AC = nullptr,
97 const Instruction *CxtI = nullptr,
98 const DominatorTree *DT = nullptr);
100 /// Returns true if the give value is known to be non-negative.
101 bool isKnownNonNegative(const Value *V, const DataLayout &DL,
103 AssumptionCache *AC = nullptr,
104 const Instruction *CxtI = nullptr,
105 const DominatorTree *DT = nullptr);
107 /// Returns true if the given value is known be positive (i.e. non-negative
109 bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
110 AssumptionCache *AC = nullptr,
111 const Instruction *CxtI = nullptr,
112 const DominatorTree *DT = nullptr);
114 /// Returns true if the given value is known be negative (i.e. non-positive
116 bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
117 AssumptionCache *AC = nullptr,
118 const Instruction *CxtI = nullptr,
119 const DominatorTree *DT = nullptr);
121 /// Return true if the given values are known to be non-equal when defined.
122 /// Supports scalar integer types only.
123 bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
124 AssumptionCache *AC = nullptr,
125 const Instruction *CxtI = nullptr,
126 const DominatorTree *DT = nullptr);
128 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
129 /// simplify operations downstream. Mask is known to be zero for bits that V
132 /// This function is defined on values with integer type, values with pointer
133 /// type, and vectors of integers. In the case
134 /// where V is a vector, the mask, known zero, and known one values are the
135 /// same width as the vector element, and the bit is set only if it is true
136 /// for all of the elements in the vector.
137 bool MaskedValueIsZero(const Value *V, const APInt &Mask,
138 const DataLayout &DL,
139 unsigned Depth = 0, AssumptionCache *AC = nullptr,
140 const Instruction *CxtI = nullptr,
141 const DominatorTree *DT = nullptr);
143 /// Return the number of times the sign bit of the register is replicated into
144 /// the other bits. We know that at least 1 bit is always equal to the sign
145 /// bit (itself), but other cases can give us information. For example,
146 /// immediately after an "ashr X, 2", we know that the top 3 bits are all
147 /// equal to each other, so we return 3. For vectors, return the number of
148 /// sign bits for the vector element with the mininum number of known sign
150 unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
151 unsigned Depth = 0, AssumptionCache *AC = nullptr,
152 const Instruction *CxtI = nullptr,
153 const DominatorTree *DT = nullptr);
155 /// This function computes the integer multiple of Base that equals V. If
156 /// successful, it returns true and returns the multiple in Multiple. If
157 /// unsuccessful, it returns false. Also, if V can be simplified to an
158 /// integer, then the simplified V is returned in Val. Look through sext only
159 /// if LookThroughSExt=true.
160 bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
161 bool LookThroughSExt = false,
164 /// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
165 /// intrinsics are treated as-if they were intrinsics.
166 Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS,
167 const TargetLibraryInfo *TLI);
169 /// Return true if we can prove that the specified FP value is never equal to
171 bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
174 /// Return true if we can prove that the specified FP value is either NaN or
175 /// never less than -0.0.
183 bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
185 /// Return true if we can prove that the specified FP value's sign bit is 0.
187 /// NaN --> true/false (depending on the NaN's sign bit)
193 bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
195 /// If the specified value can be set by repeating the same byte in memory,
196 /// return the i8 value that it is represented with. This is true for all i8
197 /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
198 /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
199 /// i16 0x1234), return null.
200 Value *isBytewiseValue(Value *V);
202 /// Given an aggregrate and an sequence of indices, see if the scalar value
203 /// indexed is already around as a register, for example if it were inserted
204 /// directly into the aggregrate.
206 /// If InsertBefore is not null, this function will duplicate (modified)
207 /// insertvalues when a part of a nested struct is extracted.
208 Value *FindInsertedValue(Value *V,
209 ArrayRef<unsigned> idx_range,
210 Instruction *InsertBefore = nullptr);
212 /// Analyze the specified pointer to see if it can be expressed as a base
213 /// pointer plus a constant offset. Return the base and offset to the caller.
214 Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
215 const DataLayout &DL);
216 static inline const Value *
217 GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
218 const DataLayout &DL) {
219 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
223 /// Returns true if the GEP is based on a pointer to a string (array of i8),
224 /// and is indexing into this string.
225 bool isGEPBasedOnPointerToString(const GEPOperator *GEP);
227 /// This function computes the length of a null-terminated C string pointed to
228 /// by V. If successful, it returns true and returns the string in Str. If
229 /// unsuccessful, it returns false. This does not include the trailing null
230 /// character by default. If TrimAtNul is set to false, then this returns any
231 /// trailing null characters as well as any other characters that come after
233 bool getConstantStringInfo(const Value *V, StringRef &Str,
234 uint64_t Offset = 0, bool TrimAtNul = true);
236 /// If we can compute the length of the string pointed to by the specified
237 /// pointer, return 'len+1'. If we can't, return 0.
238 uint64_t GetStringLength(const Value *V);
240 /// This method strips off any GEP address adjustments and pointer casts from
241 /// the specified value, returning the original object being addressed. Note
242 /// that the returned value has pointer type if the specified value does. If
243 /// the MaxLookup value is non-zero, it limits the number of instructions to
245 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
246 unsigned MaxLookup = 6);
247 static inline const Value *GetUnderlyingObject(const Value *V,
248 const DataLayout &DL,
249 unsigned MaxLookup = 6) {
250 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
253 /// \brief This method is similar to GetUnderlyingObject except that it can
254 /// look through phi and select instructions and return multiple objects.
256 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
257 /// accesses different objects in each iteration, we don't look through the
258 /// phi node. E.g. consider this loop nest:
263 /// A[i][j] = A[i-1][j] * B[j]
266 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
267 /// of the outer loop:
269 /// Curr = A[0]; // Prev_0
271 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
274 /// Curr[j] = Prev[j] * B[j]
278 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
279 /// should not assume that Curr and Prev share the same underlying object thus
280 /// it shouldn't look through the phi above.
281 void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
282 const DataLayout &DL, LoopInfo *LI = nullptr,
283 unsigned MaxLookup = 6);
285 /// Return true if the only users of this pointer are lifetime markers.
286 bool onlyUsedByLifetimeMarkers(const Value *V);
288 /// Return true if the instruction does not have any effects besides
289 /// calculating the result and does not have undefined behavior.
291 /// This method never returns true for an instruction that returns true for
292 /// mayHaveSideEffects; however, this method also does some other checks in
293 /// addition. It checks for undefined behavior, like dividing by zero or
294 /// loading from an invalid pointer (but not for undefined results, like a
295 /// shift with a shift amount larger than the width of the result). It checks
296 /// for malloc and alloca because speculatively executing them might cause a
297 /// memory leak. It also returns false for instructions related to control
298 /// flow, specifically terminators and PHI nodes.
300 /// If the CtxI is specified this method performs context-sensitive analysis
301 /// and returns true if it is safe to execute the instruction immediately
304 /// If the CtxI is NOT specified this method only looks at the instruction
305 /// itself and its operands, so if this method returns true, it is safe to
306 /// move the instruction as long as the correct dominance relationships for
307 /// the operands and users hold.
309 /// This method can return true for instructions that read memory;
310 /// for such instructions, moving them may change the resulting value.
311 bool isSafeToSpeculativelyExecute(const Value *V,
312 const Instruction *CtxI = nullptr,
313 const DominatorTree *DT = nullptr);
315 /// Returns true if the result or effects of the given instructions \p I
316 /// depend on or influence global memory.
317 /// Memory dependence arises for example if the instruction reads from
318 /// memory or may produce effects or undefined behaviour. Memory dependent
319 /// instructions generally cannot be reorderd with respect to other memory
320 /// dependent instructions or moved into non-dominated basic blocks.
321 /// Instructions which just compute a value based on the values of their
322 /// operands are not memory dependent.
323 bool mayBeMemoryDependent(const Instruction &I);
325 /// Return true if this pointer couldn't possibly be null by its definition.
326 /// This returns true for allocas, non-extern-weak globals, and byval
328 bool isKnownNonNull(const Value *V);
330 /// Return true if this pointer couldn't possibly be null. If the context
331 /// instruction and dominator tree are specified, perform context-sensitive
332 /// analysis and return true if the pointer couldn't possibly be null at the
333 /// specified instruction.
334 bool isKnownNonNullAt(const Value *V,
335 const Instruction *CtxI = nullptr,
336 const DominatorTree *DT = nullptr);
338 /// Return true if it is valid to use the assumptions provided by an
339 /// assume intrinsic, I, at the point in the control-flow identified by the
340 /// context instruction, CxtI.
341 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
342 const DominatorTree *DT = nullptr);
344 enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
345 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
347 const DataLayout &DL,
349 const Instruction *CxtI,
350 const DominatorTree *DT);
351 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
353 const DataLayout &DL,
355 const Instruction *CxtI,
356 const DominatorTree *DT);
357 OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
358 const DataLayout &DL,
359 AssumptionCache *AC = nullptr,
360 const Instruction *CxtI = nullptr,
361 const DominatorTree *DT = nullptr);
362 /// This version also leverages the sign bit of Add if known.
363 OverflowResult computeOverflowForSignedAdd(const AddOperator *Add,
364 const DataLayout &DL,
365 AssumptionCache *AC = nullptr,
366 const Instruction *CxtI = nullptr,
367 const DominatorTree *DT = nullptr);
369 /// Returns true if the arithmetic part of the \p II 's result is
370 /// used only along the paths control dependent on the computation
371 /// not overflowing, \p II being an <op>.with.overflow intrinsic.
372 bool isOverflowIntrinsicNoWrap(const IntrinsicInst *II,
373 const DominatorTree &DT);
375 /// Return true if this function can prove that the instruction I will
376 /// always transfer execution to one of its successors (including the next
377 /// instruction that follows within a basic block). E.g. this is not
378 /// guaranteed for function calls that could loop infinitely.
380 /// In other words, this function returns false for instructions that may
381 /// transfer execution or fail to transfer execution in a way that is not
382 /// captured in the CFG nor in the sequence of instructions within a basic
385 /// Undefined behavior is assumed not to happen, so e.g. division is
386 /// guaranteed to transfer execution to the following instruction even
387 /// though division by zero might cause undefined behavior.
388 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
390 /// Return true if this function can prove that the instruction I
391 /// is executed for every iteration of the loop L.
393 /// Note that this currently only considers the loop header.
394 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
397 /// Return true if this function can prove that I is guaranteed to yield
398 /// full-poison (all bits poison) if at least one of its operands are
399 /// full-poison (all bits poison).
401 /// The exact rules for how poison propagates through instructions have
402 /// not been settled as of 2015-07-10, so this function is conservative
403 /// and only considers poison to be propagated in uncontroversial
404 /// cases. There is no attempt to track values that may be only partially
406 bool propagatesFullPoison(const Instruction *I);
408 /// Return either nullptr or an operand of I such that I will trigger
409 /// undefined behavior if I is executed and that operand has a full-poison
410 /// value (all bits poison).
411 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
413 /// Return true if this function can prove that if PoisonI is executed
414 /// and yields a full-poison value (all bits poison), then that will
415 /// trigger undefined behavior.
417 /// Note that this currently only considers the basic block that is
419 bool isKnownNotFullPoison(const Instruction *PoisonI);
421 /// \brief Specific patterns of select instructions we can match.
422 enum SelectPatternFlavor {
424 SPF_SMIN, /// Signed minimum
425 SPF_UMIN, /// Unsigned minimum
426 SPF_SMAX, /// Signed maximum
427 SPF_UMAX, /// Unsigned maximum
428 SPF_FMINNUM, /// Floating point minnum
429 SPF_FMAXNUM, /// Floating point maxnum
430 SPF_ABS, /// Absolute value
431 SPF_NABS /// Negated absolute value
433 /// \brief Behavior when a floating point min/max is given one NaN and one
434 /// non-NaN as input.
435 enum SelectPatternNaNBehavior {
436 SPNB_NA = 0, /// NaN behavior not applicable.
437 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
438 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
439 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
440 /// it has been determined that no operands can
443 struct SelectPatternResult {
444 SelectPatternFlavor Flavor;
445 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
446 /// SPF_FMINNUM or SPF_FMAXNUM.
447 bool Ordered; /// When implementing this min/max pattern as
448 /// fcmp; select, does the fcmp have to be
451 /// \brief Return true if \p SPF is a min or a max pattern.
452 static bool isMinOrMax(SelectPatternFlavor SPF) {
453 return !(SPF == SPF_UNKNOWN || SPF == SPF_ABS || SPF == SPF_NABS);
456 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
457 /// and providing the out parameter results if we successfully match.
459 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
460 /// not match that of the original select. If this is the case, the cast
461 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
462 /// type of LHS and RHS into the type of V is returned in CastOp.
465 /// %1 = icmp slt i32 %a, i32 4
466 /// %2 = sext i32 %a to i64
467 /// %3 = select i1 %1, i64 %2, i64 4
469 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
471 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
472 Instruction::CastOps *CastOp = nullptr);
473 static inline SelectPatternResult
474 matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS,
475 Instruction::CastOps *CastOp = nullptr) {
476 Value *L = const_cast<Value*>(LHS);
477 Value *R = const_cast<Value*>(RHS);
478 auto Result = matchSelectPattern(const_cast<Value*>(V), L, R);
484 /// Return true if RHS is known to be implied true by LHS. Return false if
485 /// RHS is known to be implied false by LHS. Otherwise, return None if no
486 /// implication can be made.
487 /// A & B must be i1 (boolean) values or a vector of such values. Note that
488 /// the truth table for implication is the same as <=u on i1 values (but not
489 /// <=s!). The truth table for both is:
494 Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
495 const DataLayout &DL,
496 bool InvertAPred = false,
498 AssumptionCache *AC = nullptr,
499 const Instruction *CxtI = nullptr,
500 const DominatorTree *DT = nullptr);
501 } // end namespace llvm