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