[LLVM][NFC] Removing unused functions
[llvm-complete.git] / include / llvm / Analysis / ValueTracking.h
blob182cad22f6953a9488645808db165c5e6b1c39db
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.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ANALYSIS_VALUETRACKING_H
15 #define LLVM_ANALYSIS_VALUETRACKING_H
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/IR/CallSite.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DataLayout.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/Intrinsics.h"
25 #include <cassert>
26 #include <cstdint>
28 namespace llvm {
30 class AddOperator;
31 class APInt;
32 class AssumptionCache;
33 class DominatorTree;
34 class GEPOperator;
35 class IntrinsicInst;
36 class WithOverflowInst;
37 struct KnownBits;
38 class Loop;
39 class LoopInfo;
40 class MDNode;
41 class OptimizationRemarkEmitter;
42 class StringRef;
43 class TargetLibraryInfo;
44 class Value;
46 /// Determine which bits of V are known to be either zero or one and return
47 /// them in the KnownZero/KnownOne bit sets.
48 ///
49 /// This function is defined on values with integer type, values with pointer
50 /// type, and vectors of integers. In the case
51 /// where V is a vector, the known zero and known one values are the
52 /// same width as the vector element, and the bit is set only if it is true
53 /// for all of the elements in the vector.
54 void computeKnownBits(const Value *V, KnownBits &Known,
55 const DataLayout &DL, unsigned Depth = 0,
56 AssumptionCache *AC = nullptr,
57 const Instruction *CxtI = nullptr,
58 const DominatorTree *DT = nullptr,
59 OptimizationRemarkEmitter *ORE = nullptr,
60 bool UseInstrInfo = true);
62 /// Returns the known bits rather than passing by reference.
63 KnownBits computeKnownBits(const Value *V, const DataLayout &DL,
64 unsigned Depth = 0, AssumptionCache *AC = nullptr,
65 const Instruction *CxtI = nullptr,
66 const DominatorTree *DT = nullptr,
67 OptimizationRemarkEmitter *ORE = nullptr,
68 bool UseInstrInfo = true);
70 /// Compute known bits from the range metadata.
71 /// \p KnownZero the set of bits that are known to be zero
72 /// \p KnownOne the set of bits that are known to be one
73 void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
74 KnownBits &Known);
76 /// Return true if LHS and RHS have no common bits set.
77 bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
78 const DataLayout &DL,
79 AssumptionCache *AC = nullptr,
80 const Instruction *CxtI = nullptr,
81 const DominatorTree *DT = nullptr,
82 bool UseInstrInfo = true);
84 /// Return true if the given value is known to have exactly one bit set when
85 /// defined. For vectors return true if every element is known to be a power
86 /// of two when defined. Supports values with integer or pointer type and
87 /// vectors of integers. If 'OrZero' is set, then return true if the given
88 /// value is either a power of two or zero.
89 bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
90 bool OrZero = false, unsigned Depth = 0,
91 AssumptionCache *AC = nullptr,
92 const Instruction *CxtI = nullptr,
93 const DominatorTree *DT = nullptr,
94 bool UseInstrInfo = true);
96 bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
98 /// Return true if the given value is known to be non-zero when defined. For
99 /// vectors, return true if every element is known to be non-zero when
100 /// defined. For pointers, if the context instruction and dominator tree are
101 /// specified, perform context-sensitive analysis and return true if the
102 /// pointer couldn't possibly be null at the specified instruction.
103 /// Supports values with integer or pointer type and vectors of integers.
104 bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
105 AssumptionCache *AC = nullptr,
106 const Instruction *CxtI = nullptr,
107 const DominatorTree *DT = nullptr,
108 bool UseInstrInfo = true);
110 /// Return true if the two given values are negation.
111 /// Currently can recoginze Value pair:
112 /// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
113 /// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
114 bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW = false);
116 /// Returns true if the give value is known to be non-negative.
117 bool isKnownNonNegative(const Value *V, const DataLayout &DL,
118 unsigned Depth = 0,
119 AssumptionCache *AC = nullptr,
120 const Instruction *CxtI = nullptr,
121 const DominatorTree *DT = nullptr,
122 bool UseInstrInfo = true);
124 /// Returns true if the given value is known be positive (i.e. non-negative
125 /// and non-zero).
126 bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
127 AssumptionCache *AC = nullptr,
128 const Instruction *CxtI = nullptr,
129 const DominatorTree *DT = nullptr,
130 bool UseInstrInfo = true);
132 /// Returns true if the given value is known be negative (i.e. non-positive
133 /// and non-zero).
134 bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
135 AssumptionCache *AC = nullptr,
136 const Instruction *CxtI = nullptr,
137 const DominatorTree *DT = nullptr,
138 bool UseInstrInfo = true);
140 /// Return true if the given values are known to be non-equal when defined.
141 /// Supports scalar integer types only.
142 bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
143 AssumptionCache *AC = nullptr,
144 const Instruction *CxtI = nullptr,
145 const DominatorTree *DT = nullptr,
146 bool UseInstrInfo = true);
148 /// Return true if 'V & Mask' is known to be zero. We use this predicate to
149 /// simplify operations downstream. Mask is known to be zero for bits that V
150 /// cannot have.
152 /// This function is defined on values with integer type, values with pointer
153 /// type, and vectors of integers. In the case
154 /// where V is a vector, the mask, known zero, and known one values are the
155 /// same width as the vector element, and the bit is set only if it is true
156 /// for all of the elements in the vector.
157 bool MaskedValueIsZero(const Value *V, const APInt &Mask,
158 const DataLayout &DL,
159 unsigned Depth = 0, AssumptionCache *AC = nullptr,
160 const Instruction *CxtI = nullptr,
161 const DominatorTree *DT = nullptr,
162 bool UseInstrInfo = true);
164 /// Return the number of times the sign bit of the register is replicated into
165 /// the other bits. We know that at least 1 bit is always equal to the sign
166 /// bit (itself), but other cases can give us information. For example,
167 /// immediately after an "ashr X, 2", we know that the top 3 bits are all
168 /// equal to each other, so we return 3. For vectors, return the number of
169 /// sign bits for the vector element with the mininum number of known sign
170 /// bits.
171 unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
172 unsigned Depth = 0, AssumptionCache *AC = nullptr,
173 const Instruction *CxtI = nullptr,
174 const DominatorTree *DT = nullptr,
175 bool UseInstrInfo = true);
177 /// This function computes the integer multiple of Base that equals V. If
178 /// successful, it returns true and returns the multiple in Multiple. If
179 /// unsuccessful, it returns false. Also, if V can be simplified to an
180 /// integer, then the simplified V is returned in Val. Look through sext only
181 /// if LookThroughSExt=true.
182 bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
183 bool LookThroughSExt = false,
184 unsigned Depth = 0);
186 /// Map a call instruction to an intrinsic ID. Libcalls which have equivalent
187 /// intrinsics are treated as-if they were intrinsics.
188 Intrinsic::ID getIntrinsicForCallSite(ImmutableCallSite ICS,
189 const TargetLibraryInfo *TLI);
191 /// Return true if we can prove that the specified FP value is never equal to
192 /// -0.0.
193 bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
194 unsigned Depth = 0);
196 /// Return true if we can prove that the specified FP value is either NaN or
197 /// never less than -0.0.
199 /// NaN --> true
200 /// +0 --> true
201 /// -0 --> true
202 /// x > +0 --> true
203 /// x < -0 --> false
204 bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
206 /// Return true if the floating-point scalar value is not a NaN or if the
207 /// floating-point vector value has no NaN elements. Return false if a value
208 /// could ever be NaN.
209 bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
210 unsigned Depth = 0);
212 /// Return true if we can prove that the specified FP value's sign bit is 0.
214 /// NaN --> true/false (depending on the NaN's sign bit)
215 /// +0 --> true
216 /// -0 --> false
217 /// x > +0 --> true
218 /// x < -0 --> false
219 bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
221 /// If the specified value can be set by repeating the same byte in memory,
222 /// return the i8 value that it is represented with. This is true for all i8
223 /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
224 /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
225 /// i16 0x1234), return null. If the value is entirely undef and padding,
226 /// return undef.
227 Value *isBytewiseValue(Value *V, const DataLayout &DL);
229 /// Given an aggregrate and an sequence of indices, see if the scalar value
230 /// indexed is already around as a register, for example if it were inserted
231 /// directly into the aggregrate.
233 /// If InsertBefore is not null, this function will duplicate (modified)
234 /// insertvalues when a part of a nested struct is extracted.
235 Value *FindInsertedValue(Value *V,
236 ArrayRef<unsigned> idx_range,
237 Instruction *InsertBefore = nullptr);
239 /// Analyze the specified pointer to see if it can be expressed as a base
240 /// pointer plus a constant offset. Return the base and offset to the caller.
242 /// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
243 /// creates and later unpacks the required APInt.
244 inline Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
245 const DataLayout &DL) {
246 APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
247 Value *Base =
248 Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt,
249 /* AllowNonInbounds */ true);
250 Offset = OffsetAPInt.getSExtValue();
251 return Base;
253 inline const Value *GetPointerBaseWithConstantOffset(const Value *Ptr,
254 int64_t &Offset,
255 const DataLayout &DL) {
256 return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
257 DL);
260 /// Returns true if the GEP is based on a pointer to a string (array of
261 // \p CharSize integers) and is indexing into this string.
262 bool isGEPBasedOnPointerToString(const GEPOperator *GEP,
263 unsigned CharSize = 8);
265 /// Represents offset+length into a ConstantDataArray.
266 struct ConstantDataArraySlice {
267 /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
268 /// initializer, it just doesn't fit the ConstantDataArray interface).
269 const ConstantDataArray *Array;
271 /// Slice starts at this Offset.
272 uint64_t Offset;
274 /// Length of the slice.
275 uint64_t Length;
277 /// Moves the Offset and adjusts Length accordingly.
278 void move(uint64_t Delta) {
279 assert(Delta < Length);
280 Offset += Delta;
281 Length -= Delta;
284 /// Convenience accessor for elements in the slice.
285 uint64_t operator[](unsigned I) const {
286 return Array==nullptr ? 0 : Array->getElementAsInteger(I + Offset);
290 /// Returns true if the value \p V is a pointer into a ConstantDataArray.
291 /// If successful \p Slice will point to a ConstantDataArray info object
292 /// with an appropriate offset.
293 bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
294 unsigned ElementSize, uint64_t Offset = 0);
296 /// This function computes the length of a null-terminated C string pointed to
297 /// by V. If successful, it returns true and returns the string in Str. If
298 /// unsuccessful, it returns false. This does not include the trailing null
299 /// character by default. If TrimAtNul is set to false, then this returns any
300 /// trailing null characters as well as any other characters that come after
301 /// it.
302 bool getConstantStringInfo(const Value *V, StringRef &Str,
303 uint64_t Offset = 0, bool TrimAtNul = true);
305 /// If we can compute the length of the string pointed to by the specified
306 /// pointer, return 'len+1'. If we can't, return 0.
307 uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
309 /// This function returns call pointer argument that is considered the same by
310 /// aliasing rules. You CAN'T use it to replace one value with another. If
311 /// \p MustPreserveNullness is true, the call must preserve the nullness of
312 /// the pointer.
313 const Value *getArgumentAliasingToReturnedPointer(const CallBase *Call,
314 bool MustPreserveNullness);
315 inline Value *
316 getArgumentAliasingToReturnedPointer(CallBase *Call,
317 bool MustPreserveNullness) {
318 return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
319 const_cast<const CallBase *>(Call), MustPreserveNullness));
322 /// {launder,strip}.invariant.group returns pointer that aliases its argument,
323 /// and it only captures pointer by returning it.
324 /// These intrinsics are not marked as nocapture, because returning is
325 /// considered as capture. The arguments are not marked as returned neither,
326 /// because it would make it useless. If \p MustPreserveNullness is true,
327 /// the intrinsic must preserve the nullness of the pointer.
328 bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
329 const CallBase *Call, bool MustPreserveNullness);
331 /// This method strips off any GEP address adjustments and pointer casts from
332 /// the specified value, returning the original object being addressed. Note
333 /// that the returned value has pointer type if the specified value does. If
334 /// the MaxLookup value is non-zero, it limits the number of instructions to
335 /// be stripped off.
336 Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
337 unsigned MaxLookup = 6);
338 inline const Value *GetUnderlyingObject(const Value *V, const DataLayout &DL,
339 unsigned MaxLookup = 6) {
340 return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
343 /// This method is similar to GetUnderlyingObject except that it can
344 /// look through phi and select instructions and return multiple objects.
346 /// If LoopInfo is passed, loop phis are further analyzed. If a pointer
347 /// accesses different objects in each iteration, we don't look through the
348 /// phi node. E.g. consider this loop nest:
350 /// int **A;
351 /// for (i)
352 /// for (j) {
353 /// A[i][j] = A[i-1][j] * B[j]
354 /// }
356 /// This is transformed by Load-PRE to stash away A[i] for the next iteration
357 /// of the outer loop:
359 /// Curr = A[0]; // Prev_0
360 /// for (i: 1..N) {
361 /// Prev = Curr; // Prev = PHI (Prev_0, Curr)
362 /// Curr = A[i];
363 /// for (j: 0..N) {
364 /// Curr[j] = Prev[j] * B[j]
365 /// }
366 /// }
368 /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
369 /// should not assume that Curr and Prev share the same underlying object thus
370 /// it shouldn't look through the phi above.
371 void GetUnderlyingObjects(const Value *V,
372 SmallVectorImpl<const Value *> &Objects,
373 const DataLayout &DL, LoopInfo *LI = nullptr,
374 unsigned MaxLookup = 6);
376 /// This is a wrapper around GetUnderlyingObjects and adds support for basic
377 /// ptrtoint+arithmetic+inttoptr sequences.
378 bool getUnderlyingObjectsForCodeGen(const Value *V,
379 SmallVectorImpl<Value *> &Objects,
380 const DataLayout &DL);
382 /// Return true if the only users of this pointer are lifetime markers.
383 bool onlyUsedByLifetimeMarkers(const Value *V);
385 /// Return true if the instruction does not have any effects besides
386 /// calculating the result and does not have undefined behavior.
388 /// This method never returns true for an instruction that returns true for
389 /// mayHaveSideEffects; however, this method also does some other checks in
390 /// addition. It checks for undefined behavior, like dividing by zero or
391 /// loading from an invalid pointer (but not for undefined results, like a
392 /// shift with a shift amount larger than the width of the result). It checks
393 /// for malloc and alloca because speculatively executing them might cause a
394 /// memory leak. It also returns false for instructions related to control
395 /// flow, specifically terminators and PHI nodes.
397 /// If the CtxI is specified this method performs context-sensitive analysis
398 /// and returns true if it is safe to execute the instruction immediately
399 /// before the CtxI.
401 /// If the CtxI is NOT specified this method only looks at the instruction
402 /// itself and its operands, so if this method returns true, it is safe to
403 /// move the instruction as long as the correct dominance relationships for
404 /// the operands and users hold.
406 /// This method can return true for instructions that read memory;
407 /// for such instructions, moving them may change the resulting value.
408 bool isSafeToSpeculativelyExecute(const Value *V,
409 const Instruction *CtxI = nullptr,
410 const DominatorTree *DT = nullptr);
412 /// Returns true if the result or effects of the given instructions \p I
413 /// depend on or influence global memory.
414 /// Memory dependence arises for example if the instruction reads from
415 /// memory or may produce effects or undefined behaviour. Memory dependent
416 /// instructions generally cannot be reorderd with respect to other memory
417 /// dependent instructions or moved into non-dominated basic blocks.
418 /// Instructions which just compute a value based on the values of their
419 /// operands are not memory dependent.
420 bool mayBeMemoryDependent(const Instruction &I);
422 /// Return true if it is an intrinsic that cannot be speculated but also
423 /// cannot trap.
424 bool isAssumeLikeIntrinsic(const Instruction *I);
426 /// Return true if it is valid to use the assumptions provided by an
427 /// assume intrinsic, I, at the point in the control-flow identified by the
428 /// context instruction, CxtI.
429 bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
430 const DominatorTree *DT = nullptr);
432 enum class OverflowResult {
433 /// Always overflows in the direction of signed/unsigned min value.
434 AlwaysOverflowsLow,
435 /// Always overflows in the direction of signed/unsigned max value.
436 AlwaysOverflowsHigh,
437 /// May or may not overflow.
438 MayOverflow,
439 /// Never overflows.
440 NeverOverflows,
443 OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
444 const Value *RHS,
445 const DataLayout &DL,
446 AssumptionCache *AC,
447 const Instruction *CxtI,
448 const DominatorTree *DT,
449 bool UseInstrInfo = true);
450 OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
451 const DataLayout &DL,
452 AssumptionCache *AC,
453 const Instruction *CxtI,
454 const DominatorTree *DT,
455 bool UseInstrInfo = true);
456 OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
457 const Value *RHS,
458 const DataLayout &DL,
459 AssumptionCache *AC,
460 const Instruction *CxtI,
461 const DominatorTree *DT,
462 bool UseInstrInfo = true);
463 OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
464 const DataLayout &DL,
465 AssumptionCache *AC = nullptr,
466 const Instruction *CxtI = nullptr,
467 const DominatorTree *DT = nullptr);
468 /// This version also leverages the sign bit of Add if known.
469 OverflowResult computeOverflowForSignedAdd(const AddOperator *Add,
470 const DataLayout &DL,
471 AssumptionCache *AC = nullptr,
472 const Instruction *CxtI = nullptr,
473 const DominatorTree *DT = nullptr);
474 OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS,
475 const DataLayout &DL,
476 AssumptionCache *AC,
477 const Instruction *CxtI,
478 const DominatorTree *DT);
479 OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
480 const DataLayout &DL,
481 AssumptionCache *AC,
482 const Instruction *CxtI,
483 const DominatorTree *DT);
485 /// Returns true if the arithmetic part of the \p WO 's result is
486 /// used only along the paths control dependent on the computation
487 /// not overflowing, \p WO being an <op>.with.overflow intrinsic.
488 bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
489 const DominatorTree &DT);
492 /// Determine the possible constant range of an integer or vector of integer
493 /// value. This is intended as a cheap, non-recursive check.
494 ConstantRange computeConstantRange(const Value *V, bool UseInstrInfo = true);
496 /// Return true if this function can prove that the instruction I will
497 /// always transfer execution to one of its successors (including the next
498 /// instruction that follows within a basic block). E.g. this is not
499 /// guaranteed for function calls that could loop infinitely.
501 /// In other words, this function returns false for instructions that may
502 /// transfer execution or fail to transfer execution in a way that is not
503 /// captured in the CFG nor in the sequence of instructions within a basic
504 /// block.
506 /// Undefined behavior is assumed not to happen, so e.g. division is
507 /// guaranteed to transfer execution to the following instruction even
508 /// though division by zero might cause undefined behavior.
509 bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
511 /// Returns true if this block does not contain a potential implicit exit.
512 /// This is equivelent to saying that all instructions within the basic block
513 /// are guaranteed to transfer execution to their successor within the basic
514 /// block. This has the same assumptions w.r.t. undefined behavior as the
515 /// instruction variant of this function.
516 bool isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB);
518 /// Return true if this function can prove that the instruction I
519 /// is executed for every iteration of the loop L.
521 /// Note that this currently only considers the loop header.
522 bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
523 const Loop *L);
525 /// Return true if this function can prove that I is guaranteed to yield
526 /// full-poison (all bits poison) if at least one of its operands are
527 /// full-poison (all bits poison).
529 /// The exact rules for how poison propagates through instructions have
530 /// not been settled as of 2015-07-10, so this function is conservative
531 /// and only considers poison to be propagated in uncontroversial
532 /// cases. There is no attempt to track values that may be only partially
533 /// poison.
534 bool propagatesFullPoison(const Instruction *I);
536 /// Return either nullptr or an operand of I such that I will trigger
537 /// undefined behavior if I is executed and that operand has a full-poison
538 /// value (all bits poison).
539 const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
541 /// Return true if the given instruction must trigger undefined behavior.
542 /// when I is executed with any operands which appear in KnownPoison holding
543 /// a full-poison value at the point of execution.
544 bool mustTriggerUB(const Instruction *I,
545 const SmallSet<const Value *, 16>& KnownPoison);
547 /// Return true if this function can prove that if PoisonI is executed
548 /// and yields a full-poison value (all bits poison), then that will
549 /// trigger undefined behavior.
551 /// Note that this currently only considers the basic block that is
552 /// the parent of I.
553 bool programUndefinedIfFullPoison(const Instruction *PoisonI);
555 /// Specific patterns of select instructions we can match.
556 enum SelectPatternFlavor {
557 SPF_UNKNOWN = 0,
558 SPF_SMIN, /// Signed minimum
559 SPF_UMIN, /// Unsigned minimum
560 SPF_SMAX, /// Signed maximum
561 SPF_UMAX, /// Unsigned maximum
562 SPF_FMINNUM, /// Floating point minnum
563 SPF_FMAXNUM, /// Floating point maxnum
564 SPF_ABS, /// Absolute value
565 SPF_NABS /// Negated absolute value
568 /// Behavior when a floating point min/max is given one NaN and one
569 /// non-NaN as input.
570 enum SelectPatternNaNBehavior {
571 SPNB_NA = 0, /// NaN behavior not applicable.
572 SPNB_RETURNS_NAN, /// Given one NaN input, returns the NaN.
573 SPNB_RETURNS_OTHER, /// Given one NaN input, returns the non-NaN.
574 SPNB_RETURNS_ANY /// Given one NaN input, can return either (or
575 /// it has been determined that no operands can
576 /// be NaN).
579 struct SelectPatternResult {
580 SelectPatternFlavor Flavor;
581 SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
582 /// SPF_FMINNUM or SPF_FMAXNUM.
583 bool Ordered; /// When implementing this min/max pattern as
584 /// fcmp; select, does the fcmp have to be
585 /// ordered?
587 /// Return true if \p SPF is a min or a max pattern.
588 static bool isMinOrMax(SelectPatternFlavor SPF) {
589 return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
593 /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
594 /// and providing the out parameter results if we successfully match.
596 /// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
597 /// the negation instruction from the idiom.
599 /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
600 /// not match that of the original select. If this is the case, the cast
601 /// operation (one of Trunc,SExt,Zext) that must be done to transform the
602 /// type of LHS and RHS into the type of V is returned in CastOp.
604 /// For example:
605 /// %1 = icmp slt i32 %a, i32 4
606 /// %2 = sext i32 %a to i64
607 /// %3 = select i1 %1, i64 %2, i64 4
609 /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
611 SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
612 Instruction::CastOps *CastOp = nullptr,
613 unsigned Depth = 0);
614 inline SelectPatternResult
615 matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS,
616 Instruction::CastOps *CastOp = nullptr) {
617 Value *L = const_cast<Value*>(LHS);
618 Value *R = const_cast<Value*>(RHS);
619 auto Result = matchSelectPattern(const_cast<Value*>(V), L, R);
620 LHS = L;
621 RHS = R;
622 return Result;
625 /// Determine the pattern that a select with the given compare as its
626 /// predicate and given values as its true/false operands would match.
627 SelectPatternResult matchDecomposedSelectPattern(
628 CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
629 Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
631 /// Return the canonical comparison predicate for the specified
632 /// minimum/maximum flavor.
633 CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF,
634 bool Ordered = false);
636 /// Return the inverse minimum/maximum flavor of the specified flavor.
637 /// For example, signed minimum is the inverse of signed maximum.
638 SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF);
640 /// Return the canonical inverse comparison predicate for the specified
641 /// minimum/maximum flavor.
642 CmpInst::Predicate getInverseMinMaxPred(SelectPatternFlavor SPF);
644 /// Return true if RHS is known to be implied true by LHS. Return false if
645 /// RHS is known to be implied false by LHS. Otherwise, return None if no
646 /// implication can be made.
647 /// A & B must be i1 (boolean) values or a vector of such values. Note that
648 /// the truth table for implication is the same as <=u on i1 values (but not
649 /// <=s!). The truth table for both is:
650 /// | T | F (B)
651 /// T | T | F
652 /// F | T | T
653 /// (A)
654 Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
655 const DataLayout &DL, bool LHSIsTrue = true,
656 unsigned Depth = 0);
658 /// Return the boolean condition value in the context of the given instruction
659 /// if it is known based on dominating conditions.
660 Optional<bool> isImpliedByDomCondition(const Value *Cond,
661 const Instruction *ContextI,
662 const DataLayout &DL);
664 /// If Ptr1 is provably equal to Ptr2 plus a constant offset, return that
665 /// offset. For example, Ptr1 might be &A[42], and Ptr2 might be &A[40]. In
666 /// this case offset would be -8.
667 Optional<int64_t> isPointerOffset(const Value *Ptr1, const Value *Ptr2,
668 const DataLayout &DL);
669 } // end namespace llvm
671 #endif // LLVM_ANALYSIS_VALUETRACKING_H