LLVM 24.0.0git
ValueTracking.h
Go to the documentation of this file.
1//===- llvm/Analysis/ValueTracking.h - Walk computations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains routines that help analyze properties that chains of
10// computations have.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ANALYSIS_VALUETRACKING_H
15#define LLVM_ANALYSIS_VALUETRACKING_H
16
19#include "llvm/IR/Constants.h"
20#include "llvm/IR/DataLayout.h"
21#include "llvm/IR/FMF.h"
22#include "llvm/IR/InstrTypes.h"
24#include "llvm/IR/Intrinsics.h"
26#include <cassert>
27#include <cstdint>
28#include <optional>
29
30namespace llvm {
31
32class Operator;
33class AddOperator;
34class AssumptionCache;
35class DominatorTree;
36class GEPOperator;
38struct KnownBits;
39struct KnownFPClass;
40class Loop;
41class LoopInfo;
42class MDNode;
43class StringRef;
45class IntrinsicInst;
46template <typename T> class ArrayRef;
47
48constexpr unsigned MaxAnalysisRecursionDepth = 6;
49
50/// The max limit of the search depth in DecomposeGEPExpression() and
51/// getUnderlyingObject().
52constexpr unsigned MaxLookupSearchDepth = 10;
53
54/// Determine which bits of V are known to be either zero or one and return
55/// them in the KnownZero/KnownOne bit sets.
56///
57/// This function is defined on values with integer type, values with pointer
58/// type, and vectors of integers. In the case
59/// where V is a vector, the known zero and known one values are the
60/// same width as the vector element, and the bit is set only if it is true
61/// for all of the elements in the vector.
63 const DataLayout &DL,
64 AssumptionCache *AC = nullptr,
65 const Instruction *CxtI = nullptr,
66 const DominatorTree *DT = nullptr,
67 bool UseInstrInfo = true, unsigned Depth = 0);
68
69/// Returns the known bits rather than passing by reference.
71 AssumptionCache *AC = nullptr,
72 const Instruction *CxtI = nullptr,
73 const DominatorTree *DT = nullptr,
74 bool UseInstrInfo = true,
75 unsigned Depth = 0);
76
77/// Returns the known bits rather than passing by reference.
78LLVM_ABI KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
79 const DataLayout &DL,
80 AssumptionCache *AC = nullptr,
81 const Instruction *CxtI = nullptr,
82 const DominatorTree *DT = nullptr,
83 bool UseInstrInfo = true,
84 unsigned Depth = 0);
85
86LLVM_ABI KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
87 const SimplifyQuery &Q, unsigned Depth = 0);
88
90 unsigned Depth = 0);
91
93 const SimplifyQuery &Q, unsigned Depth = 0);
94
95/// Compute known bits from the range metadata.
96/// \p KnownZero the set of bits that are known to be zero
97/// \p KnownOne the set of bits that are known to be one
100
101/// Merge bits known from context-dependent facts into Known.
103 const SimplifyQuery &Q,
104 unsigned Depth = 0);
105
106/// Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
108 const KnownBits &KnownLHS,
109 const KnownBits &KnownRHS,
110 const SimplifyQuery &SQ,
111 unsigned Depth = 0);
112
113/// Adjust \p Known for the given select \p Arm to include information from the
114/// select \p Cond.
116 Value *Arm, bool Invert,
117 const SimplifyQuery &Q,
118 unsigned Depth = 0);
119
120/// Adjust \p Known for the given select \p Arm to include information from the
121/// select \p Cond.
123 Value *Arm, bool Invert,
124 const SimplifyQuery &Q,
125 unsigned Depth = 0);
126
128 /// Not known to have no common set bits.
130
131 /// Known to have no common set bits only if undef values are ignored.
133
134 /// Known to have no common set bits.
136};
137
138/// Return how strongly LHS and RHS are known to have no common set bits.
140 const WithCache<const Value *> &LHSCache,
141 const WithCache<const Value *> &RHSCache, const SimplifyQuery &SQ);
142
143/// Return true if LHS and RHS have no common bits set.
144LLVM_ABI bool haveNoCommonBitsSet(const WithCache<const Value *> &LHSCache,
145 const WithCache<const Value *> &RHSCache,
146 const SimplifyQuery &SQ);
147
148/// Return true if the given value is known to have exactly one bit set when
149/// defined. For vectors return true if every element is known to be a power
150/// of two when defined. Supports values with integer or pointer type and
151/// vectors of integers. If 'OrZero' is set, then return true if the given
152/// value is either a power of two or zero.
153LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
154 bool OrZero = false,
155 AssumptionCache *AC = nullptr,
156 const Instruction *CxtI = nullptr,
157 const DominatorTree *DT = nullptr,
158 bool UseInstrInfo = true,
159 unsigned Depth = 0);
160
161LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, bool OrZero,
162 const SimplifyQuery &Q,
163 unsigned Depth = 0);
164
165LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI);
166
167LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
168
169/// Return true if the given value is known to be non-zero when defined. For
170/// vectors, return true if every element is known to be non-zero when
171/// defined. For pointers, if the context instruction and dominator tree are
172/// specified, perform context-sensitive analysis and return true if the
173/// pointer couldn't possibly be null at the specified instruction.
174/// Supports values with integer or pointer type and vectors of integers.
175LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q,
176 unsigned Depth = 0);
177
178/// Return true if the two given values are negation.
179/// Currently can recoginze Value pair:
180/// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
181/// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
182LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y,
183 bool NeedNSW = false, bool AllowPoison = true);
184
185/// Return true iff:
186/// 1. X is poison implies Y is poison.
187/// 2. X is true implies Y is false.
188/// 3. X is false implies Y is true.
189/// Otherwise, return false.
190LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y);
191
192/// Returns true if the give value is known to be non-negative.
193LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ,
194 unsigned Depth = 0);
195
196/// Returns true if the given value is known be positive (i.e. non-negative
197/// and non-zero).
198LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ,
199 unsigned Depth = 0);
200
201/// Returns true if the given value is known be negative (i.e. non-positive
202/// and non-zero).
203LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ,
204 unsigned Depth = 0);
205
206/// Return true if the given values are known to be non-equal when defined.
207/// Supports scalar integer types only.
208LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2,
209 const SimplifyQuery &SQ, unsigned Depth = 0);
210
211/// Return true if 'V & Mask' is known to be zero. We use this predicate to
212/// simplify operations downstream. Mask is known to be zero for bits that V
213/// cannot have.
214///
215/// This function is defined on values with integer type, values with pointer
216/// type, and vectors of integers. In the case
217/// where V is a vector, the mask, known zero, and known one values are the
218/// same width as the vector element, and the bit is set only if it is true
219/// for all of the elements in the vector.
220LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask,
221 const SimplifyQuery &SQ, unsigned Depth = 0);
222
223/// Return the number of times the sign bit of the register is replicated into
224/// the other bits. We know that at least 1 bit is always equal to the sign
225/// bit (itself), but other cases can give us information. For example,
226/// immediately after an "ashr X, 2", we know that the top 3 bits are all
227/// equal to each other, so we return 3. For vectors, return the number of
228/// sign bits for the vector element with the mininum number of known sign
229/// bits.
230LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
231 AssumptionCache *AC = nullptr,
232 const Instruction *CxtI = nullptr,
233 const DominatorTree *DT = nullptr,
234 bool UseInstrInfo = true,
235 unsigned Depth = 0);
236
237/// Get the upper bound on bit size for this Value \p Op as a signed integer.
238/// i.e. x == sext(trunc(x to MaxSignificantBits) to bitwidth(x)).
239/// Similar to the APInt::getSignificantBits function.
240LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op,
241 const DataLayout &DL,
242 AssumptionCache *AC = nullptr,
243 const Instruction *CxtI = nullptr,
244 const DominatorTree *DT = nullptr,
245 unsigned Depth = 0);
246
247/// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
248/// intrinsics are treated as-if they were intrinsics.
250 const TargetLibraryInfo *TLI);
251
252/// Given an exploded icmp instruction, return true if the comparison only
253/// checks the sign bit. If it only checks the sign bit, set TrueIfSigned if
254/// the result of the comparison is true when the input value is signed.
255LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS,
256 bool &TrueIfSigned);
257
258/// Determine which floating-point classes are valid for \p V, and return them
259/// in KnownFPClass bit sets.
260///
261/// This function is defined on values with floating-point type, values vectors
262/// of floating-point type, and arrays of floating-point type.
263
264/// \p InterestedClasses is a compile time optimization hint for which floating
265/// point classes should be queried. Queries not specified in \p
266/// InterestedClasses should be reliable if they are determined during the
267/// query.
268LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V,
269 const APInt &DemandedElts,
270 FPClassTest InterestedClasses,
271 const SimplifyQuery &SQ,
272 unsigned Depth = 0);
273
274LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V,
275 FPClassTest InterestedClasses,
276 const SimplifyQuery &SQ,
277 unsigned Depth = 0);
278
279LLVM_ABI KnownFPClass computeKnownFPClass(
280 const Value *V, const DataLayout &DL,
281 FPClassTest InterestedClasses = fcAllFlags,
282 const TargetLibraryInfo *TLI = nullptr, AssumptionCache *AC = nullptr,
283 const Instruction *CxtI = nullptr, const DominatorTree *DT = nullptr,
284 bool UseInstrInfo = true, unsigned Depth = 0);
285
286/// Wrapper to account for known fast math flags at the use instruction.
287LLVM_ABI KnownFPClass computeKnownFPClass(
288 const Value *V, const APInt &DemandedElts, FastMathFlags FMF,
289 FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth = 0);
290
291LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, FastMathFlags FMF,
292 FPClassTest InterestedClasses,
293 const SimplifyQuery &SQ,
294 unsigned Depth = 0);
295
296/// Return true if we can prove that the specified FP value is never equal to
297/// -0.0. Users should use caution when considering PreserveSign
298/// denormal-fp-math.
299LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ,
300 unsigned Depth = 0);
301
302/// Return true if we can prove that the specified FP value is either NaN or
303/// never less than -0.0.
304///
305/// NaN --> true
306/// +0 --> true
307/// -0 --> true
308/// x > +0 --> true
309/// x < -0 --> false
310LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V,
311 const SimplifyQuery &SQ,
312 unsigned Depth = 0);
313
314/// Return true if the floating-point scalar value is not an infinity or if
315/// the floating-point vector value has no infinities. Return false if a value
316/// could ever be infinity.
317LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ,
318 unsigned Depth = 0);
319
320/// Return true if the floating-point value can never contain a NaN or infinity.
321LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ,
322 unsigned Depth = 0);
323
324/// Return true if the floating-point scalar value is not a NaN or if the
325/// floating-point vector value has no NaN elements. Return false if a value
326/// could ever be NaN.
327LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ,
328 unsigned Depth = 0);
329
330/// Return false if we can prove that the specified FP value's sign bit is 0.
331/// Return true if we can prove that the specified FP value's sign bit is 1.
332/// Otherwise return std::nullopt.
333LLVM_ABI std::optional<bool> computeKnownFPSignBit(const Value *V,
334 const SimplifyQuery &SQ,
335 unsigned Depth = 0);
336
337/// Return true if the sign bit of the FP value can be ignored by the user when
338/// the value is zero.
339LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U);
340
341/// Return true if the sign bit of the FP value can be ignored by the user when
342/// the value is NaN.
343LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U);
344
345/// Return true if the floating-point value \p V is known to be an integer
346/// value.
347LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ,
348 FastMathFlags FMF);
349
350/// If the specified value can be set by repeating the same byte in memory,
351/// return the i8 value that it is represented with. This is true for all i8
352/// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
353/// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
354/// i16 0x1234), return null. If the value is entirely undef and padding,
355/// return undef.
356LLVM_ABI Value *isBytewiseValue(Value *V, const DataLayout &DL);
357
358/// Given an aggregate and an sequence of indices, see if the scalar value
359/// indexed is already around as a register, for example if it were inserted
360/// directly into the aggregate.
361///
362/// If InsertBefore is not empty, this function will duplicate (modified)
363/// insertvalues when a part of a nested struct is extracted.
365 Value *V, ArrayRef<unsigned> idx_range,
366 std::optional<BasicBlock::iterator> InsertBefore = std::nullopt);
367
368/// Analyze the specified pointer to see if it can be expressed as a base
369/// pointer plus a constant offset. Return the base and offset to the caller.
370///
371/// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
372/// creates and later unpacks the required APInt.
374 const DataLayout &DL,
375 bool AllowNonInbounds = true) {
376 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
377 Value *Base =
378 Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
379
380 std::optional<int64_t> OffsetInt64 = OffsetAPInt.trySExtValue();
381 if (!OffsetInt64) {
382 Offset = 0;
383 return Ptr;
384 }
385
386 Offset = *OffsetInt64;
387 return Base;
388}
389inline const Value *
391 const DataLayout &DL,
392 bool AllowNonInbounds = true) {
393 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
394 AllowNonInbounds);
395}
396
397/// Represents offset+length into a ConstantDataArray.
399 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
400 /// initializer, it just doesn't fit the ConstantDataArray interface).
402
403 /// Slice starts at this Offset.
405
406 /// Length of the slice.
408
409 /// Moves the Offset and adjusts Length accordingly.
410 void move(uint64_t Delta) {
411 assert(Delta < Length);
412 Offset += Delta;
413 Length -= Delta;
414 }
415
416 /// Convenience accessor for elements in the slice.
417 uint64_t operator[](unsigned I) const {
418 return Array == nullptr ? 0 : Array->getElementAsInteger(I + Offset);
419 }
420};
421
422/// Returns true if the value \p V is a pointer into a ConstantDataArray.
423/// If successful \p Slice will point to a ConstantDataArray info object
424/// with an appropriate offset.
425LLVM_ABI bool getConstantDataArrayInfo(const Value *V,
426 ConstantDataArraySlice &Slice,
427 unsigned ElementSize,
428 uint64_t Offset = 0);
429
430/// This function computes the length of a null-terminated C string pointed to
431/// by V. If successful, it returns true and returns the string in Str. If
432/// unsuccessful, it returns false. This does not include the trailing null
433/// character by default. If TrimAtNul is set to false, then this returns any
434/// trailing null characters as well as any other characters that come after
435/// it.
436LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str,
437 bool TrimAtNul = true);
438
439/// If we can compute the length of the string pointed to by the specified
440/// pointer, return 'len+1'. If we can't, return 0.
441LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
442
443/// This function returns call pointer argument that is considered the same by
444/// aliasing rules. You CAN'T use it to replace one value with another. If
445/// \p MustPreserveOffset is true, the call must preserve the byte offset of
446/// the pointer within its underlying object. Offset preservation implies
447/// nullness preservation; pass true when callers reason about either offset or
448/// null equality (e.g. GEP decomposition, dereferenceability, isKnownNonZero).
449LLVM_ABI const Value *
451 bool MustPreserveOffset);
453 bool MustPreserveOffset) {
454 return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
455 const_cast<const CallBase *>(Call), MustPreserveOffset));
456}
457
458/// {launder,strip}.invariant.group returns pointer that aliases its argument,
459/// and it only captures pointer by returning it.
460/// These intrinsics are not marked as nocapture, because returning is
461/// considered as capture. The arguments are not marked as returned neither,
462/// because it would make it useless. If \p MustPreserveOffset is true, the
463/// intrinsic must preserve the byte offset of the pointer within its
464/// underlying object (which excludes `llvm.ptrmask`, since masking off low
465/// bits changes the byte offset while still aliasing the same object).
467 const CallBase *Call, bool MustPreserveOffset);
468
469/// This method strips off any GEP address adjustments, pointer casts
470/// or `llvm.threadlocal.address` from the specified value \p V, returning the
471/// original object being addressed. Note that the returned value has pointer
472/// type if the specified value does. If the \p MaxLookup value is non-zero, it
473/// limits the number of instructions to be stripped off.
474LLVM_ABI const Value *
475getUnderlyingObject(const Value *V, unsigned MaxLookup = MaxLookupSearchDepth);
477 unsigned MaxLookup = MaxLookupSearchDepth) {
478 // Force const to avoid infinite recursion.
479 const Value *VConst = V;
480 return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
481}
482
483/// Like getUnderlyingObject(), but will try harder to find a single underlying
484/// object. In particular, this function also looks through selects and phis.
485LLVM_ABI const Value *getUnderlyingObjectAggressive(const Value *V);
486
487/// This method is similar to getUnderlyingObject except that it can
488/// look through phi and select instructions and return multiple objects.
489///
490/// If LoopInfo is passed, loop phis are further analyzed. If a pointer
491/// accesses different objects in each iteration, we don't look through the
492/// phi node. E.g. consider this loop nest:
493///
494/// int **A;
495/// for (i)
496/// for (j) {
497/// A[i][j] = A[i-1][j] * B[j]
498/// }
499///
500/// This is transformed by Load-PRE to stash away A[i] for the next iteration
501/// of the outer loop:
502///
503/// Curr = A[0]; // Prev_0
504/// for (i: 1..N) {
505/// Prev = Curr; // Prev = PHI (Prev_0, Curr)
506/// Curr = A[i];
507/// for (j: 0..N) {
508/// Curr[j] = Prev[j] * B[j]
509/// }
510/// }
511///
512/// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
513/// should not assume that Curr and Prev share the same underlying object thus
514/// it shouldn't look through the phi above.
515LLVM_ABI void getUnderlyingObjects(const Value *V,
516 SmallVectorImpl<const Value *> &Objects,
517 const LoopInfo *LI = nullptr,
518 unsigned MaxLookup = MaxLookupSearchDepth);
519
520/// This is a wrapper around getUnderlyingObjects and adds support for basic
521/// ptrtoint+arithmetic+inttoptr sequences.
522LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V,
523 SmallVectorImpl<Value *> &Objects);
524
525/// Returns unique alloca where the value comes from, or nullptr.
526/// If OffsetZero is true check that V points to the begining of the alloca.
527LLVM_ABI AllocaInst *findAllocaForValue(Value *V, bool OffsetZero = false);
528inline const AllocaInst *findAllocaForValue(const Value *V,
529 bool OffsetZero = false) {
530 return findAllocaForValue(const_cast<Value *>(V), OffsetZero);
531}
532
533/// Return true if the only users of this pointer are lifetime markers.
534LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V);
535
536/// Return true if the only users of this pointer are lifetime markers or
537/// droppable instructions.
539
540/// Return true if the instruction doesn't potentially cross vector lanes. This
541/// condition is weaker than checking that the instruction is lanewise: lanewise
542/// means that the same operation is splatted across all lanes, but we also
543/// include the case where there is a different operation on each lane, as long
544/// as the operation only uses data from that lane. An example of an operation
545/// that is not lanewise, but doesn't cross vector lanes is insertelement.
546LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I);
547
548/// Return true if the instruction does not have any effects besides
549/// calculating the result and does not have undefined behavior.
550///
551/// This method never returns true for an instruction that returns true for
552/// mayHaveSideEffects; however, this method also does some other checks in
553/// addition. It checks for undefined behavior, like dividing by zero or
554/// loading from an invalid pointer (but not for undefined results, like a
555/// shift with a shift amount larger than the width of the result). It checks
556/// for malloc and alloca because speculatively executing them might cause a
557/// memory leak. It also returns false for instructions related to control
558/// flow, specifically terminators and PHI nodes.
559///
560/// If the CtxI is specified this method performs context-sensitive analysis
561/// and returns true if it is safe to execute the instruction immediately
562/// before the CtxI. If the instruction has (transitive) operands that don't
563/// dominate CtxI, the analysis is performed under the assumption that these
564/// operands will also be speculated to a point before CxtI.
565///
566/// If the CtxI is NOT specified this method only looks at the instruction
567/// itself and its operands, so if this method returns true, it is safe to
568/// move the instruction as long as the correct dominance relationships for
569/// the operands and users hold.
570///
571/// If \p UseVariableInfo is true, the information from non-constant operands
572/// will be taken into account.
573///
574/// If \p IgnoreUBImplyingAttrs is true, UB-implying attributes will be ignored.
575/// The caller is responsible for correctly propagating them after hoisting.
576///
577/// This method can return true for instructions that read memory;
578/// for such instructions, moving them may change the resulting value.
580 const Instruction *I, const Instruction *CtxI = nullptr,
581 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
582 const TargetLibraryInfo *TLI = nullptr, bool UseVariableInfo = true,
583 bool IgnoreUBImplyingAttrs = true);
584
587 AssumptionCache *AC = nullptr,
588 const DominatorTree *DT = nullptr,
589 const TargetLibraryInfo *TLI = nullptr,
590 bool UseVariableInfo = true,
591 bool IgnoreUBImplyingAttrs = true) {
592 // Take an iterator, and unwrap it into an Instruction *.
593 return isSafeToSpeculativelyExecute(I, &*CtxI, AC, DT, TLI, UseVariableInfo,
594 IgnoreUBImplyingAttrs);
595}
596
597/// Don't use information from its non-constant operands. This helper is used
598/// when its operands are going to be replaced.
600 const Instruction *I, bool IgnoreUBImplyingAttrs = true) {
601 return isSafeToSpeculativelyExecute(I, nullptr, nullptr, nullptr, nullptr,
602 /*UseVariableInfo=*/false,
603 IgnoreUBImplyingAttrs);
604}
605
606/// This returns the same result as isSafeToSpeculativelyExecute if Opcode is
607/// the actual opcode of Inst. If the provided and actual opcode differ, the
608/// function (virtually) overrides the opcode of Inst with the provided
609/// Opcode. There are come constraints in this case:
610/// * If Opcode has a fixed number of operands (eg, as binary operators do),
611/// then Inst has to have at least as many leading operands. The function
612/// will ignore all trailing operands beyond that number.
613/// * If Opcode allows for an arbitrary number of operands (eg, as CallInsts
614/// do), then all operands are considered.
615/// * The virtual instruction has to satisfy all typing rules of the provided
616/// Opcode.
617/// * This function is pessimistic in the following sense: If one actually
618/// materialized the virtual instruction, then isSafeToSpeculativelyExecute
619/// may say that the materialized instruction is speculatable whereas this
620/// function may have said that the instruction wouldn't be speculatable.
621/// This behavior is a shortcoming in the current implementation and not
622/// intentional.
624 unsigned Opcode, const Instruction *Inst, const Instruction *CtxI = nullptr,
625 AssumptionCache *AC = nullptr, const DominatorTree *DT = nullptr,
626 const TargetLibraryInfo *TLI = nullptr, bool UseVariableInfo = true,
627 bool IgnoreUBImplyingAttrs = true);
628
629/// Returns true if the result or effects of the given instructions \p I
630/// depend values not reachable through the def use graph.
631/// * Memory dependence arises for example if the instruction reads from
632/// memory or may produce effects or undefined behaviour. Memory dependent
633/// instructions generally cannot be reorderd with respect to other memory
634/// dependent instructions.
635/// * Control dependence arises for example if the instruction may fault
636/// if lifted above a throwing call or infinite loop.
637LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I);
638
639/// Return true if it is an intrinsic that cannot be speculated but also
640/// cannot trap.
641LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I);
642
643/// Return true if it is valid to use the assumptions provided by an
644/// assume intrinsic, I, at the point in the control-flow identified by the
645/// context instruction, CxtI. By default, ephemeral values of the assumption
646/// are treated as an invalid context, to prevent the assumption from being used
647/// to optimize away its argument. If the caller can ensure that this won't
648/// happen, it can call with AllowEphemerals set to true to get more valid
649/// assumptions.
650LLVM_ABI bool isValidAssumeForContext(const Instruction *I,
651 const Instruction *CxtI,
652 const DominatorTree *DT = nullptr,
653 bool AllowEphemerals = false);
654
656 const SimplifyQuery &Q) {
658}
659
660/// Returns true, if no instruction between \p Assume and \p CtxI may free
661/// (including through synchronization).
662LLVM_ABI bool willNotFreeBetween(const Instruction *Assume,
663 const Instruction *CtxI);
664
665enum class OverflowResult {
666 /// Always overflows in the direction of signed/unsigned min value.
668 /// Always overflows in the direction of signed/unsigned max value.
670 /// May or may not overflow.
672 /// Never overflows.
674};
675
677 const Value *RHS,
678 const SimplifyQuery &SQ,
679 bool IsNSW = false);
681 const Value *RHS,
682 const SimplifyQuery &SQ);
684 const WithCache<const Value *> &LHS, const WithCache<const Value *> &RHS,
685 const SimplifyQuery &SQ);
687 const WithCache<const Value *> &LHS, const WithCache<const Value *> &RHS,
688 const SimplifyQuery &SQ);
689/// This version also leverages the sign bit of Add if known.
691 const SimplifyQuery &SQ);
693 const Value *RHS,
694 const SimplifyQuery &SQ);
696 const Value *RHS,
697 const SimplifyQuery &SQ);
698
699/// Returns true if the arithmetic part of the \p WO 's result is
700/// used only along the paths control dependent on the computation
701/// not overflowing, \p WO being an <op>.with.overflow intrinsic.
702LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
703 const DominatorTree &DT);
704
705/// Determine the possible constant range of vscale with the given bit width,
706/// based on the vscale_range function attribute.
707LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth);
708
709/// Determine the possible constant range of an integer or vector of integer
710/// value. This is intended as a cheap, non-recursive check.
711LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned,
712 const SimplifyQuery &SQ,
713 unsigned Depth = 0);
714
715/// Combine constant ranges from computeConstantRange() and computeKnownBits().
717 const WithCache<const Value *> &V, bool ForSigned, const SimplifyQuery &SQ);
718
719/// Return true if this function can prove that the instruction I will
720/// always transfer execution to one of its successors (including the next
721/// instruction that follows within a basic block). E.g. this is not
722/// guaranteed for function calls that could loop infinitely.
723///
724/// In other words, this function returns false for instructions that may
725/// transfer execution or fail to transfer execution in a way that is not
726/// captured in the CFG nor in the sequence of instructions within a basic
727/// block.
728///
729/// Undefined behavior is assumed not to happen, so e.g. division is
730/// guaranteed to transfer execution to the following instruction even
731/// though division by zero might cause undefined behavior.
733
734/// Returns true if this block does not contain a potential implicit exit.
735/// This is equivelent to saying that all instructions within the basic block
736/// are guaranteed to transfer execution to their successor within the basic
737/// block. This has the same assumptions w.r.t. undefined behavior as the
738/// instruction variant of this function.
740
741/// Return true if every instruction in the range (Begin, End) is
742/// guaranteed to transfer execution to its static successor. \p ScanLimit
743/// bounds the search to avoid scanning huge blocks.
744LLVM_ABI bool
747 unsigned ScanLimit = 32);
748
749/// Same as previous, but with range expressed via iterator_range.
751 iterator_range<BasicBlock::const_iterator> Range, unsigned ScanLimit = 32);
752
753/// Return true if this function can prove that the instruction I
754/// is executed for every iteration of the loop L.
755///
756/// Note that this currently only considers the loop header.
758 const Loop *L);
759
760/// Return true if \p PoisonOp's user yields poison or raises UB if its
761/// operand \p PoisonOp is poison.
762///
763/// If \p PoisonOp is a vector or an aggregate and the operation's result is a
764/// single value, any poison element in /p PoisonOp should make the result
765/// poison or raise UB.
766///
767/// To filter out operands that raise UB on poison, you can use
768/// getGuaranteedNonPoisonOp.
769LLVM_ABI bool propagatesPoison(const Use &PoisonOp);
770
771/// Return whether this intrinsic propagates poison for all operands.
773
774/// Return true if the given instruction must trigger undefined behavior
775/// when I is executed with any operands which appear in KnownPoison holding
776/// a poison value at the point of execution.
777LLVM_ABI bool mustTriggerUB(const Instruction *I,
778 const SmallPtrSetImpl<const Value *> &KnownPoison);
779
780/// Return true if this function can prove that if Inst is executed
781/// and yields a poison value or undef bits, then that will trigger
782/// undefined behavior.
783///
784/// Note that this currently only considers the basic block that is
785/// the parent of Inst.
786LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst);
787LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst);
788
789/// canCreateUndefOrPoison returns true if Op can create undef or poison from
790/// non-undef & non-poison operands.
791/// For vectors, canCreateUndefOrPoison returns true if there is potential
792/// poison or undef in any element of the result when vectors without
793/// undef/poison poison are given as operands.
794/// For example, given `Op = shl <2 x i32> %x, <0, 32>`, this function returns
795/// true. If Op raises immediate UB but never creates poison or undef
796/// (e.g. sdiv I, 0), canCreatePoison returns false.
797///
798/// \p ConsiderFlagsAndMetadata controls whether poison producing flags and
799/// metadata on the instruction are considered. This can be used to see if the
800/// instruction could still introduce undef or poison even without poison
801/// generating flags and metadata which might be on the instruction.
802/// (i.e. could the result of Op->dropPoisonGeneratingFlags() still create
803/// poison or undef)
804///
805/// canCreatePoison returns true if Op can create poison from non-poison
806/// operands.
807LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op,
808 bool ConsiderFlagsAndMetadata = true);
809LLVM_ABI bool canCreatePoison(const Operator *Op,
810 bool ConsiderFlagsAndMetadata = true);
811
812/// Return true if V is poison given that ValAssumedPoison is already poison.
813/// For example, if ValAssumedPoison is `icmp X, 10` and V is `icmp X, 5`,
814/// impliesPoison returns true.
815LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V);
816
817/// Return true if this function can prove that V does not have undef bits
818/// and is never poison. If V is an aggregate value or vector, check whether
819/// all elements (except padding) are not undef or poison.
820/// Note that this is different from canCreateUndefOrPoison because the
821/// function assumes Op's operands are not poison/undef.
822///
823/// If CtxI and DT are specified this method performs flow-sensitive analysis
824/// and returns true if it is guaranteed to be never undef or poison
825/// immediately before the CtxI.
826LLVM_ABI bool
827isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC = nullptr,
828 const Instruction *CtxI = nullptr,
829 const DominatorTree *DT = nullptr,
830 unsigned Depth = 0);
831
832/// Returns true if V cannot be poison, but may be undef.
833LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V,
834 AssumptionCache *AC = nullptr,
835 const Instruction *CtxI = nullptr,
836 const DominatorTree *DT = nullptr,
837 unsigned Depth = 0);
838
841 const DominatorTree *DT = nullptr,
842 unsigned Depth = 0) {
843 // Takes an iterator as a position, passes down to Instruction *
844 // implementation.
845 return isGuaranteedNotToBePoison(V, AC, &*CtxI, DT, Depth);
846}
847
848/// Returns true if V cannot be undef, but may be poison.
849LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V,
850 AssumptionCache *AC = nullptr,
851 const Instruction *CtxI = nullptr,
852 const DominatorTree *DT = nullptr,
853 unsigned Depth = 0);
854
855/// Return true if undefined behavior would provable be executed on the path to
856/// OnPathTo if Root produced a posion result. Note that this doesn't say
857/// anything about whether OnPathTo is actually executed or whether Root is
858/// actually poison. This can be used to assess whether a new use of Root can
859/// be added at a location which is control equivalent with OnPathTo (such as
860/// immediately before it) without introducing UB which didn't previously
861/// exist. Note that a false result conveys no information.
862LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root,
863 Instruction *OnPathTo,
864 DominatorTree *DT);
865
866/// Convert an integer comparison with a constant RHS into an equivalent
867/// form with the strictness flipped predicate. Return the new predicate and
868/// corresponding constant RHS if possible. Otherwise return std::nullopt.
869/// E.g., (icmp sgt X, 0) -> (icmp sle X, 1).
870/// For a samesign predicate, fail if adjusting the constant would change its
871/// sign bit, because that would change the comparison's poison domain.
872LLVM_ABI std::optional<std::pair<CmpPredicate, Constant *>>
873getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C);
874
875/// Specific patterns of select instructions we can match.
878 SPF_SMIN, /// Signed minimum
879 SPF_UMIN, /// Unsigned minimum
880 SPF_SMAX, /// Signed maximum
881 SPF_UMAX, /// Unsigned maximum
882 SPF_FMINNUM, /// Floating point minnum
883 SPF_FMAXNUM, /// Floating point maxnum
884 SPF_ABS, /// Absolute value
885 SPF_NABS /// Negated absolute value
886};
887
888/// Behavior when a floating point min/max is given one NaN and one
889/// non-NaN as input.
891 SPNB_NA = 0, /// NaN behavior not applicable.
892 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
893 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
894 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
895 /// it has been determined that no operands can
896 /// be NaN).
897};
898
901 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
902 /// SPF_FMINNUM or SPF_FMAXNUM.
903 bool Ordered; /// When implementing this min/max pattern as
904 /// fcmp; select, does the fcmp have to be
905 /// ordered?
906
907 /// Return true if \p SPF is a min or a max pattern.
909 return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
910 }
911};
912
913/// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
914/// and providing the out parameter results if we successfully match.
915///
916/// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
917/// the negation instruction from the idiom.
918///
919/// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
920/// not match that of the original select. If this is the case, the cast
921/// operation (one of Trunc,SExt,Zext) that must be done to transform the
922/// type of LHS and RHS into the type of V is returned in CastOp.
923///
924/// For example:
925/// %1 = icmp slt i32 %a, i32 4
926/// %2 = sext i32 %a to i64
927/// %3 = select i1 %1, i64 %2, i64 4
928///
929/// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
930///
931LLVM_ABI SelectPatternResult
932matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
933 Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
934
936 const Value *&RHS) {
937 Value *L = const_cast<Value *>(LHS);
938 Value *R = const_cast<Value *>(RHS);
939 auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
940 LHS = L;
941 RHS = R;
942 return Result;
943}
944
945/// Determine the pattern that a select with the given compare as its
946/// predicate and given values as its true/false operands would match.
947LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(
948 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
949 FastMathFlags FMF = FastMathFlags(), Instruction::CastOps *CastOp = nullptr,
950 unsigned Depth = 0);
951
952/// Determine the pattern for predicate `X Pred Y ? X : Y`.
953LLVM_ABI SelectPatternResult getSelectPattern(
954 CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior = SPNB_NA,
955 bool Ordered = false);
956
957/// Return the canonical comparison predicate for the specified
958/// minimum/maximum flavor.
959LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF,
960 bool Ordered = false);
961
962/// Convert given `SPF` to equivalent min/max intrinsic.
963/// Caller must ensure `SPF` is an integer min or max pattern.
964LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF);
965
966/// Return the inverse minimum/maximum flavor of the specified flavor.
967/// For example, signed minimum is the inverse of signed maximum.
968LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF);
969
971
972/// Return the minimum or maximum constant value for the specified integer
973/// min/max flavor and type.
974LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth);
975
976/// Check if the values in \p VL are select instructions that can be converted
977/// to a min or max (vector) intrinsic. Returns the intrinsic ID, if such a
978/// conversion is possible, together with a bool indicating whether all select
979/// conditions are only used by the selects. Otherwise return
980/// Intrinsic::not_intrinsic.
981LLVM_ABI std::pair<Intrinsic::ID, bool>
983
984/// Attempt to match a simple first order recurrence cycle of the form:
985/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
986/// %inc = binop %iv, %step
987/// OR
988/// %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
989/// %inc = binop %step, %iv
990///
991/// A first order recurrence is a formula with the form: X_n = f(X_(n-1))
992///
993/// A couple of notes on subtleties in that definition:
994/// * The Step does not have to be loop invariant. In math terms, it can
995/// be a free variable. We allow recurrences with both constant and
996/// variable coefficients. Callers may wish to filter cases where Step
997/// does not dominate P.
998/// * For non-commutative operators, we will match both forms. This
999/// results in some odd recurrence structures. Callers may wish to filter
1000/// out recurrences where the phi is not the LHS of the returned operator.
1001/// * Because of the structure matched, the caller can assume as a post
1002/// condition of the match the presence of a Loop with P's parent as it's
1003/// header *except* in unreachable code. (Dominance decays in unreachable
1004/// code.)
1005///
1006/// NOTE: This is intentional simple. If you want the ability to analyze
1007/// non-trivial loop conditons, see ScalarEvolution instead.
1008LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
1009 Value *&Start, Value *&Step);
1010
1011/// Analogous to the above, but starting from the binary operator
1012LLVM_ABI bool matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
1013 Value *&Start, Value *&Step);
1014
1015/// Attempt to match a simple value-accumulating recurrence of the form:
1016/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1017/// %llvm.intrinsic = call Ty @llvm.intrinsic(%OtherOp, %llvm.intrinsic.acc)
1018/// OR
1019/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1020/// %llvm.intrinsic = call Ty @llvm.intrinsic(%llvm.intrinsic.acc, %OtherOp)
1021///
1022/// The recurrence relation is of kind:
1023/// X_0 = %a (initial value),
1024/// X_i = call @llvm.binary.intrinsic(X_i-1, %b)
1025/// Where %b is not required to be loop-invariant.
1026LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I,
1027 PHINode *&P, Value *&Init,
1028 Value *&OtherOp);
1029
1030/// Attempt to match a simple value-accumulating recurrence of the form:
1031/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1032/// %llvm.intrinsic = call Ty @llvm.intrinsic(%OtherOp0, %OtherOp1,
1033/// %llvm.intrinsic.acc)
1034/// OR
1035/// %llvm.intrinsic.acc = phi Ty [%Init, %Entry], [%llvm.intrinsic, %backedge]
1036/// %llvm.intrinsic = call Ty @llvm.intrinsic(%llvm.intrinsic.acc, %OtherOp0,
1037/// %OtherOp1)
1038///
1039/// The recurrence relation is of kind:
1040/// X_0 = %a (initial value),
1041/// X_i = call @llvm.ternary.intrinsic(X_i-1, %b, %c)
1042/// Where %b, %c are not required to be loop-invariant.
1043LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I,
1044 PHINode *&P, Value *&Init,
1045 Value *&OtherOp0,
1046 Value *&OtherOp1);
1047
1048/// Return true if RHS is known to be implied true by LHS. Return false if
1049/// RHS is known to be implied false by LHS. Otherwise, return std::nullopt if
1050/// no implication can be made. A & B must be i1 (boolean) values or a vector of
1051/// such values. Note that the truth table for implication is the same as <=u on
1052/// i1 values (but not
1053/// <=s!). The truth table for both is:
1054/// | T | F (B)
1055/// T | T | F
1056/// F | T | T
1057/// (A)
1058LLVM_ABI std::optional<bool>
1059isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL,
1060 bool LHSIsTrue = true, unsigned Depth = 0);
1061LLVM_ABI std::optional<bool>
1062isImpliedCondition(const Value *LHS, CmpPredicate RHSPred, const Value *RHSOp0,
1063 const Value *RHSOp1, const DataLayout &DL,
1064 bool LHSIsTrue = true, unsigned Depth = 0);
1065
1066/// Return the boolean condition value in the context of the given instruction
1067/// if it is known based on dominating conditions.
1068LLVM_ABI std::optional<bool>
1069isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI,
1070 const DataLayout &DL);
1071LLVM_ABI std::optional<bool>
1072isImpliedByDomCondition(CmpPredicate Pred, const Value *LHS, const Value *RHS,
1073 const Instruction *ContextI, const DataLayout &DL);
1074
1075/// Call \p InsertAffected on all Values whose known bits / value may be
1076/// affected by the condition \p Cond. Used by AssumptionCache and
1077/// DomConditionCache.
1078LLVM_ABI void
1079findValuesAffectedByCondition(Value *Cond, bool IsAssume,
1080 function_ref<void(Value *)> InsertAffected);
1081
1082/// Returns the inner value X if the expression has the form f(X)
1083/// where f(X) == 0 if and only if X == 0, otherwise returns nullptr.
1084LLVM_ABI Value *stripNullTest(Value *V);
1085LLVM_ABI const Value *stripNullTest(const Value *V);
1086
1087/// Enumerates all possible immediate values of V and inserts them into the set
1088/// \p Constants. If \p AllowUndefOrPoison is false, it fails when V may contain
1089/// undef/poison elements. Returns true if the result is complete. Otherwise,
1090/// the result is incomplete (more than MaxCount values).
1091/// NOTE: The constant values are not distinct.
1092LLVM_ABI bool
1093collectPossibleValues(const Value *V,
1094 SmallPtrSetImpl<const Constant *> &Constants,
1095 unsigned MaxCount, bool AllowUndefOrPoison = true);
1096
1097} // end namespace llvm
1098
1099#endif // LLVM_ANALYSIS_VALUETRACKING_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:857
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:215
This file contains the declarations for the subclasses of Constant, which represent the different fla...
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
const uint64_t BitWidth
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
const SmallVectorImpl< MachineOperand > & Cond
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition APInt.h:78
std::optional< int64_t > trySExtValue() const
Get sign extended value if possible.
Definition APInt.h:1595
an instruction to allocate memory on the stack
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A cache of @llvm.assume calls within a function.
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
An array constant whose element type is a simple 1/2/4/8-byte integer, bytes or float/double,...
Definition Constants.h:865
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
A wrapper class for inspecting calls to intrinsic functions.
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1069
This is a utility class that provides an abstraction for the common functionality between Instruction...
Definition Operator.h:33
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Provides information about what library functions are available for the current target.
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * stripAndAccumulateConstantOffsets(const DataLayout &DL, APInt &Offset, bool AllowNonInbounds, bool AllowInvariantGroup=false, function_ref< bool(Value &Value, APInt &Offset)> ExternalAnalysis=nullptr, bool LookThroughIntToPtr=false) const
Accumulate the constant offset this value has compared to a base pointer.
Represents an op.with.overflow intrinsic.
CallInst * Call
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool haveNoCommonBitsSet(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return true if LHS and RHS have no common bits set.
LLVM_ABI bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
LLVM_ABI Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID)
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
@ Offset
Definition DWP.cpp:577
@ NeverOverflows
Never overflows.
@ AlwaysOverflowsHigh
Always overflows in the direction of signed/unsigned max value.
@ AlwaysOverflowsLow
Always overflows in the direction of signed/unsigned min value.
@ MayOverflow
May or may not overflow.
LLVM_ABI KnownFPClass computeKnownFPClass(const Value *V, const APInt &DemandedElts, FPClassTest InterestedClasses, const SimplifyQuery &SQ, unsigned Depth=0)
Determine which floating-point classes are valid for V, and return them in KnownFPClass bit sets.
LLVM_ABI bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI, const DominatorTree *DT=nullptr, bool AllowEphemerals=false)
Return true if it is valid to use the assumptions provided by an assume intrinsic,...
LLVM_ABI bool canCreatePoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
LLVM_ABI bool mustTriggerUB(const Instruction *I, const SmallPtrSetImpl< const Value * > &KnownPoison)
Return true if the given instruction must trigger undefined behavior when I is executed with any oper...
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
LLVM_ABI void computeKnownBitsFromContext(const Value *V, KnownBits &Known, const SimplifyQuery &Q, unsigned Depth=0)
Merge bits known from context-dependent facts into Known.
LLVM_ABI bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI)
LLVM_ABI bool isSignBitCheck(ICmpInst::Predicate Pred, const APInt &RHS, bool &TrueIfSigned)
Given an exploded icmp instruction, return true if the comparison only checks the sign bit.
NoCommonBitsSetResult
@ Known
Known to have no common set bits.
@ Unknown
Not known to have no common set bits.
@ OnlyIfUndefIgnored
Known to have no common set bits only if undef values are ignored.
LLVM_ABI bool isAssumeLikeIntrinsic(const Instruction *I)
Return true if it is an intrinsic that cannot be speculated but also cannot trap.
LLVM_ABI AllocaInst * findAllocaForValue(Value *V, bool OffsetZero=false)
Returns unique alloca where the value comes from, or nullptr.
LLVM_ABI APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth)
Return the minimum or maximum constant value for the specified integer min/max flavor and type.
LLVM_ABI bool isOnlyUsedInZeroComparison(const Instruction *CxtI)
LLVM_ABI bool getConstantStringInfo(const Value *V, StringRef &Str, bool TrimAtNul=true)
This function computes the length of a null-terminated C string pointed to by V.
LLVM_ABI bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V)
Return true if the only users of this pointer are lifetime markers or droppable instructions.
LLVM_ABI Value * stripNullTest(Value *V)
Returns the inner value X if the expression has the form f(X) where f(X) == 0 if and only if X == 0,...
LLVM_ABI bool getUnderlyingObjectsForCodeGen(const Value *V, SmallVectorImpl< Value * > &Objects)
This is a wrapper around getUnderlyingObjects and adds support for basic ptrtoint+arithmetic+inttoptr...
LLVM_ABI std::pair< Intrinsic::ID, bool > canConvertToMinOrMaxIntrinsic(ArrayRef< Value * > VL)
Check if the values in VL are select instructions that can be converted to a min or max (vector) intr...
LLVM_ABI bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice, unsigned ElementSize, uint64_t Offset=0)
Returns true if the value V is a pointer into a ConstantDataArray.
LLVM_ABI bool isGuaranteedToExecuteForEveryIteration(const Instruction *I, const Loop *L)
Return true if this function can prove that the instruction I is executed for every iteration of the ...
Value * GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset, const DataLayout &DL, bool AllowNonInbounds=true)
Analyze the specified pointer to see if it can be expressed as a base pointer plus a constant offset.
LLVM_ABI bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(const CallBase *Call, bool MustPreserveOffset)
{launder,strip}.invariant.group returns pointer that aliases its argument, and it only captures point...
LLVM_ABI const Value * getArgumentAliasingToReturnedPointer(const CallBase *Call, bool MustPreserveOffset)
This function returns call pointer argument that is considered the same by aliasing rules.
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
LLVM_ABI bool canIgnoreSignBitOfZero(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is zero.
LLVM_ABI bool isGuaranteedNotToBeUndef(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be undef, but may be poison.
LLVM_ABI bool MaskedValueIsZero(const Value *V, const APInt &Mask, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if 'V & Mask' is known to be zero.
LLVM_ABI bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO, const DominatorTree &DT)
Returns true if the arithmetic part of the WO 's result is used only along the paths control dependen...
LLVM_ABI bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO, Value *&Start, Value *&Step)
Attempt to match a simple first order recurrence cycle of the form: iv = phi Ty [Start,...
LLVM_ABI OverflowResult computeOverflowForUnsignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ, bool IsNSW=false)
LLVM_ABI SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
constexpr unsigned MaxAnalysisRecursionDepth
LLVM_ABI void adjustKnownBitsForSelectArm(KnownBits &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool isKnownNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be negative (i.e.
LLVM_ABI NoCommonBitsSetResult getNoCommonBitsSetResult(const WithCache< const Value * > &LHSCache, const WithCache< const Value * > &RHSCache, const SimplifyQuery &SQ)
Return how strongly LHS and RHS are known to have no common set bits.
LLVM_ABI OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
SelectPatternFlavor
Specific patterns of select instructions we can match.
@ SPF_ABS
Floating point maxnum.
@ SPF_NABS
Absolute value.
@ SPF_FMAXNUM
Floating point minnum.
@ SPF_UMIN
Signed minimum.
@ SPF_UMAX
Signed maximum.
@ SPF_SMAX
Unsigned minimum.
@ SPF_UNKNOWN
@ SPF_FMINNUM
Unsigned maximum.
LLVM_ABI bool impliesPoison(const Value *ValAssumedPoison, const Value *V)
Return true if V is poison given that ValAssumedPoison is already poison.
LLVM_ABI SelectPatternResult getSelectPattern(CmpInst::Predicate Pred, SelectPatternNaNBehavior NaNBehavior=SPNB_NA, bool Ordered=false)
Determine the pattern for predicate X Pred Y ? X : Y.
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
LLVM_ABI bool matchSimpleBinaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool cannotBeNegativeZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
LLVM_ABI bool programUndefinedIfUndefOrPoison(const Instruction *Inst)
Return true if this function can prove that if Inst is executed and yields a poison value or undef bi...
LLVM_ABI void adjustKnownFPClassForSelectArm(KnownFPClass &Known, Value *Cond, Value *Arm, bool Invert, const SimplifyQuery &Q, unsigned Depth=0)
Adjust Known for the given select Arm to include information from the select Cond.
LLVM_ABI bool collectPossibleValues(const Value *V, SmallPtrSetImpl< const Constant * > &Constants, unsigned MaxCount, bool AllowUndefOrPoison=true)
Enumerates all possible immediate values of V and inserts them into the set Constants.
constexpr unsigned MaxLookupSearchDepth
The max limit of the search depth in DecomposeGEPExpression() and getUnderlyingObject().
LLVM_ABI uint64_t GetStringLength(const Value *V, unsigned CharSize=8)
If we can compute the length of the string pointed to by the specified pointer, return 'len+1'.
LLVM_ABI OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI ConstantRange getVScaleRange(const Function *F, unsigned BitWidth)
Determine the possible constant range of vscale with the given bit width, based on the vscale_range f...
LLVM_ABI bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlagsAndMetadata=true)
canCreateUndefOrPoison returns true if Op can create undef or poison from non-undef & non-poison oper...
LLVM_ABI bool matchSimpleTernaryIntrinsicRecurrence(const IntrinsicInst *I, PHINode *&P, Value *&Init, Value *&OtherOp0, Value *&OtherOp1)
Attempt to match a simple value-accumulating recurrence of the form: llvm.intrinsic....
LLVM_ABI bool isKnownInversion(const Value *X, const Value *Y)
Return true iff:
LLVM_ABI bool intrinsicPropagatesPoison(Intrinsic::ID IID)
Return whether this intrinsic propagates poison for all operands.
LLVM_ABI bool isNotCrossLaneOperation(const Instruction *I)
Return true if the instruction doesn't potentially cross vector lanes.
LLVM_ABI bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
LLVM_ABI bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
LLVM_ABI bool onlyUsedByLifetimeMarkers(const Value *V)
Return true if the only users of this pointer are lifetime markers.
LLVM_ABI Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB, const TargetLibraryInfo *TLI)
Map a call instruction to an intrinsic ID.
LLVM_ABI const Value * getUnderlyingObjectAggressive(const Value *V)
Like getUnderlyingObject(), but will try harder to find a single underlying object.
LLVM_ABI Intrinsic::ID getMinMaxIntrinsic(SelectPatternFlavor SPF)
Convert given SPF to equivalent min/max intrinsic.
LLVM_ABI SelectPatternResult matchDecomposedSelectPattern(CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS, FastMathFlags FMF=FastMathFlags(), Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Determine the pattern that a select with the given compare as its predicate and given values as its t...
LLVM_ABI OverflowResult computeOverflowForSignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool propagatesPoison(const Use &PoisonOp)
Return true if PoisonOp's user yields poison or raises UB if its operand PoisonOp is poison.
@ Add
Sum of integers.
LLVM_ABI ConstantRange computeConstantRangeIncludingKnownBits(const WithCache< const Value * > &V, bool ForSigned, const SimplifyQuery &SQ)
Combine constant ranges from computeConstantRange() and computeKnownBits().
SelectPatternNaNBehavior
Behavior when a floating point min/max is given one NaN and one non-NaN as input.
@ SPNB_RETURNS_NAN
NaN behavior not applicable.
@ SPNB_RETURNS_OTHER
Given one NaN input, returns the NaN.
@ SPNB_RETURNS_ANY
Given one NaN input, returns the non-NaN.
LLVM_ABI bool isKnownNonEqual(const Value *V1, const Value *V2, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the given values are known to be non-equal when defined.
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
LLVM_ABI KnownBits analyzeKnownBitsFromAndXorOr(const Operator *I, const KnownBits &KnownLHS, const KnownBits &KnownRHS, const SimplifyQuery &SQ, unsigned Depth=0)
Using KnownBits LHS/RHS produce the known bits for logic op (and/xor/or).
LLVM_ABI OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool isKnownNeverInfOrNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point value can never contain a NaN or infinity.
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
LLVM_ABI Value * isBytewiseValue(Value *V, const DataLayout &DL)
If the specified value can be set by repeating the same byte in memory, return the i8 value that it i...
LLVM_ABI std::optional< std::pair< CmpPredicate, Constant * > > getFlippedStrictnessPredicateAndConstant(CmpPredicate Pred, Constant *C)
Convert an integer comparison with a constant RHS into an equivalent form with the strictness flipped...
LLVM_ABI unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Get the upper bound on bit size for this Value Op as a signed integer.
LLVM_ABI bool isKnownIntegral(const Value *V, const SimplifyQuery &SQ, FastMathFlags FMF)
Return true if the floating-point value V is known to be an integer value.
LLVM_ABI OverflowResult computeOverflowForUnsignedAdd(const WithCache< const Value * > &LHS, const WithCache< const Value * > &RHS, const SimplifyQuery &SQ)
LLVM_ABI bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL, bool OrZero=false, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return true if the given value is known to have exactly one bit set when defined.
LLVM_ABI std::optional< bool > isImpliedByDomCondition(const Value *Cond, const Instruction *ContextI, const DataLayout &DL)
Return the boolean condition value in the context of the given instruction if it is known based on do...
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI void computeKnownBitsFromRangeMetadata(const MDNode &Ranges, KnownBits &Known)
Compute known bits from the range metadata.
LLVM_ABI Value * FindInsertedValue(Value *V, ArrayRef< unsigned > idx_range, std::optional< BasicBlock::iterator > InsertBefore=std::nullopt)
Given an aggregate and an sequence of indices, see if the scalar value indexed is already around as a...
LLVM_ABI bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false, bool AllowPoison=true)
Return true if the two given values are negation.
LLVM_ABI const Value * getUnderlyingObject(const Value *V, unsigned MaxLookup=MaxLookupSearchDepth)
This method strips off any GEP address adjustments, pointer casts or llvm.threadlocal....
LLVM_ABI bool isKnownPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the given value is known be positive (i.e.
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool cannotBeOrderedLessThanZero(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if we can prove that the specified FP value is either NaN or never less than -0....
LLVM_ABI void getUnderlyingObjects(const Value *V, SmallVectorImpl< const Value * > &Objects, const LoopInfo *LI=nullptr, unsigned MaxLookup=MaxLookupSearchDepth)
This method is similar to getUnderlyingObject except that it can look through phi and select instruct...
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI std::optional< bool > computeKnownFPSignBit(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return false if we can prove that the specified FP value's sign bit is 0.
LLVM_ABI bool canIgnoreSignBitOfNaN(const Use &U)
Return true if the sign bit of the FP value can be ignored by the user when the value is NaN.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
LLVM_ABI void findValuesAffectedByCondition(Value *Cond, bool IsAssume, function_ref< void(Value *)> InsertAffected)
Call InsertAffected on all Values whose known bits / value may be affected by the condition Cond.
Represents offset+length into a ConstantDataArray.
uint64_t Length
Length of the slice.
uint64_t Offset
Slice starts at this Offset.
uint64_t operator[](unsigned I) const
Convenience accessor for elements in the slice.
void move(uint64_t Delta)
Moves the Offset and adjusts Length accordingly.
const ConstantDataArray * Array
ConstantDataArray pointer.
SelectPatternFlavor Flavor
bool Ordered
Only applicable if Flavor is SPF_FMINNUM or SPF_FMAXNUM.
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
SelectPatternNaNBehavior NaNBehavior
const Instruction * CxtI
const DominatorTree * DT