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