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 
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/InstrTypes.h"
23 #include "llvm/IR/Intrinsics.h"
24 #include <cassert>
25 #include <cstdint>
26 
27 namespace llvm {
28 
29 class Operator;
30 class AddOperator;
31 class AllocaInst;
32 class APInt;
33 class AssumptionCache;
34 class DominatorTree;
35 class GEPOperator;
36 class LoadInst;
37 class WithOverflowInst;
38 struct KnownBits;
39 class Loop;
40 class LoopInfo;
41 class MDNode;
42 class OptimizationRemarkEmitter;
43 class StringRef;
44 class TargetLibraryInfo;
45 class Value;
46 
47 constexpr unsigned MaxAnalysisRecursionDepth = 6;
48 
49   /// Determine which bits of V are known to be either zero or one and return
50   /// them in the KnownZero/KnownOne bit sets.
51   ///
52   /// This function is defined on values with integer type, values with pointer
53   /// type, and vectors of integers.  In the case
54   /// where V is a vector, the known zero and known one values are the
55   /// same width as the vector element, and the bit is set only if it is true
56   /// for all of the elements in the vector.
57   void computeKnownBits(const Value *V, KnownBits &Known,
58                         const DataLayout &DL, unsigned Depth = 0,
59                         AssumptionCache *AC = nullptr,
60                         const Instruction *CxtI = nullptr,
61                         const DominatorTree *DT = nullptr,
62                         OptimizationRemarkEmitter *ORE = nullptr,
63                         bool UseInstrInfo = true);
64 
65   /// Determine which bits of V are known to be either zero or one and return
66   /// them in the KnownZero/KnownOne bit sets.
67   ///
68   /// This function is defined on values with integer type, values with pointer
69   /// type, and vectors of integers.  In the case
70   /// where V is a vector, the known zero and known one values are the
71   /// same width as the vector element, and the bit is set only if it is true
72   /// for all of the demanded elements in the vector.
73   void computeKnownBits(const Value *V, const APInt &DemandedElts,
74                         KnownBits &Known, const DataLayout &DL,
75                         unsigned Depth = 0, AssumptionCache *AC = nullptr,
76                         const Instruction *CxtI = nullptr,
77                         const DominatorTree *DT = nullptr,
78                         OptimizationRemarkEmitter *ORE = nullptr,
79                         bool UseInstrInfo = true);
80 
81   /// Returns the known bits rather than passing by reference.
82   KnownBits computeKnownBits(const Value *V, const DataLayout &DL,
83                              unsigned Depth = 0, AssumptionCache *AC = nullptr,
84                              const Instruction *CxtI = nullptr,
85                              const DominatorTree *DT = nullptr,
86                              OptimizationRemarkEmitter *ORE = nullptr,
87                              bool UseInstrInfo = true);
88 
89   /// Returns the known bits rather than passing by reference.
90   KnownBits computeKnownBits(const Value *V, const APInt &DemandedElts,
91                              const DataLayout &DL, unsigned Depth = 0,
92                              AssumptionCache *AC = nullptr,
93                              const Instruction *CxtI = nullptr,
94                              const DominatorTree *DT = nullptr,
95                              OptimizationRemarkEmitter *ORE = nullptr,
96                              bool UseInstrInfo = true);
97 
98   /// Compute known bits from the range metadata.
99   /// \p KnownZero the set of bits that are known to be zero
100   /// \p KnownOne the set of bits that are known to be one
101   void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
102                                          KnownBits &Known);
103 
104   /// Return true if LHS and RHS have no common bits set.
105   bool haveNoCommonBitsSet(const Value *LHS, const Value *RHS,
106                            const DataLayout &DL,
107                            AssumptionCache *AC = nullptr,
108                            const Instruction *CxtI = nullptr,
109                            const DominatorTree *DT = nullptr,
110                            bool UseInstrInfo = true);
111 
112   /// Return true if the given value is known to have exactly one bit set when
113   /// defined. For vectors return true if every element is known to be a power
114   /// of two when defined. Supports values with integer or pointer type and
115   /// vectors of integers. If 'OrZero' is set, then return true if the given
116   /// value is either a power of two or zero.
117   bool isKnownToBeAPowerOfTwo(const Value *V, const DataLayout &DL,
118                               bool OrZero = false, unsigned Depth = 0,
119                               AssumptionCache *AC = nullptr,
120                               const Instruction *CxtI = nullptr,
121                               const DominatorTree *DT = nullptr,
122                               bool UseInstrInfo = true);
123 
124   bool isOnlyUsedInZeroEqualityComparison(const Instruction *CxtI);
125 
126   /// Return true if the given value is known to be non-zero when defined. For
127   /// vectors, return true if every element is known to be non-zero when
128   /// defined. For pointers, if the context instruction and dominator tree are
129   /// specified, perform context-sensitive analysis and return true if the
130   /// pointer couldn't possibly be null at the specified instruction.
131   /// Supports values with integer or pointer type and vectors of integers.
132   bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth = 0,
133                       AssumptionCache *AC = nullptr,
134                       const Instruction *CxtI = nullptr,
135                       const DominatorTree *DT = nullptr,
136                       bool UseInstrInfo = true);
137 
138   /// Return true if the two given values are negation.
139   /// Currently can recoginze Value pair:
140   /// 1: <X, Y> if X = sub (0, Y) or Y = sub (0, X)
141   /// 2: <X, Y> if X = sub (A, B) and Y = sub (B, A)
142   bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW = false);
143 
144   /// Returns true if the give value is known to be non-negative.
145   bool isKnownNonNegative(const Value *V, const DataLayout &DL,
146                           unsigned Depth = 0,
147                           AssumptionCache *AC = nullptr,
148                           const Instruction *CxtI = nullptr,
149                           const DominatorTree *DT = nullptr,
150                           bool UseInstrInfo = true);
151 
152   /// Returns true if the given value is known be positive (i.e. non-negative
153   /// and non-zero).
154   bool isKnownPositive(const Value *V, const DataLayout &DL, unsigned Depth = 0,
155                        AssumptionCache *AC = nullptr,
156                        const Instruction *CxtI = nullptr,
157                        const DominatorTree *DT = nullptr,
158                        bool UseInstrInfo = true);
159 
160   /// Returns true if the given value is known be negative (i.e. non-positive
161   /// and non-zero).
162   bool isKnownNegative(const Value *V, const DataLayout &DL, unsigned Depth = 0,
163                        AssumptionCache *AC = nullptr,
164                        const Instruction *CxtI = nullptr,
165                        const DominatorTree *DT = nullptr,
166                        bool UseInstrInfo = true);
167 
168   /// Return true if the given values are known to be non-equal when defined.
169   /// Supports scalar integer types only.
170   bool isKnownNonEqual(const Value *V1, const Value *V2, const DataLayout &DL,
171                        AssumptionCache *AC = nullptr,
172                        const Instruction *CxtI = nullptr,
173                        const DominatorTree *DT = nullptr,
174                        bool UseInstrInfo = true);
175 
176   /// Return true if 'V & Mask' is known to be zero. We use this predicate to
177   /// simplify operations downstream. Mask is known to be zero for bits that V
178   /// cannot have.
179   ///
180   /// This function is defined on values with integer type, values with pointer
181   /// type, and vectors of integers.  In the case
182   /// where V is a vector, the mask, known zero, and known one values are the
183   /// same width as the vector element, and the bit is set only if it is true
184   /// for all of the elements in the vector.
185   bool MaskedValueIsZero(const Value *V, const APInt &Mask,
186                          const DataLayout &DL,
187                          unsigned Depth = 0, AssumptionCache *AC = nullptr,
188                          const Instruction *CxtI = nullptr,
189                          const DominatorTree *DT = nullptr,
190                          bool UseInstrInfo = true);
191 
192   /// Return the number of times the sign bit of the register is replicated into
193   /// the other bits. We know that at least 1 bit is always equal to the sign
194   /// bit (itself), but other cases can give us information. For example,
195   /// immediately after an "ashr X, 2", we know that the top 3 bits are all
196   /// equal to each other, so we return 3. For vectors, return the number of
197   /// sign bits for the vector element with the mininum number of known sign
198   /// bits.
199   unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL,
200                               unsigned Depth = 0, AssumptionCache *AC = nullptr,
201                               const Instruction *CxtI = nullptr,
202                               const DominatorTree *DT = nullptr,
203                               bool UseInstrInfo = true);
204 
205   /// Get the upper bound on bit size for this Value \p Op as a signed integer.
206   /// i.e.  x == sext(trunc(x to MaxSignificantBits) to bitwidth(x)).
207   /// Similar to the APInt::getSignificantBits function.
208   unsigned ComputeMaxSignificantBits(const Value *Op, const DataLayout &DL,
209                                      unsigned Depth = 0,
210                                      AssumptionCache *AC = nullptr,
211                                      const Instruction *CxtI = nullptr,
212                                      const DominatorTree *DT = nullptr);
213 
214   /// Map a call instruction to an intrinsic ID.  Libcalls which have equivalent
215   /// intrinsics are treated as-if they were intrinsics.
216   Intrinsic::ID getIntrinsicForCallSite(const CallBase &CB,
217                                         const TargetLibraryInfo *TLI);
218 
219   /// Return true if we can prove that the specified FP value is never equal to
220   /// -0.0.
221   bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI,
222                             unsigned Depth = 0);
223 
224   /// Return true if we can prove that the specified FP value is either NaN or
225   /// never less than -0.0.
226   ///
227   ///      NaN --> true
228   ///       +0 --> true
229   ///       -0 --> true
230   ///   x > +0 --> true
231   ///   x < -0 --> false
232   bool CannotBeOrderedLessThanZero(const Value *V, const TargetLibraryInfo *TLI);
233 
234   /// Return true if the floating-point scalar value is not an infinity or if
235   /// the floating-point vector value has no infinities. Return false if a value
236   /// could ever be infinity.
237   bool isKnownNeverInfinity(const Value *V, const TargetLibraryInfo *TLI,
238                             unsigned Depth = 0);
239 
240   /// Return true if the floating-point scalar value is not a NaN or if the
241   /// floating-point vector value has no NaN elements. Return false if a value
242   /// could ever be NaN.
243   bool isKnownNeverNaN(const Value *V, const TargetLibraryInfo *TLI,
244                        unsigned Depth = 0);
245 
246   /// Return true if we can prove that the specified FP value's sign bit is 0.
247   ///
248   ///      NaN --> true/false (depending on the NaN's sign bit)
249   ///       +0 --> true
250   ///       -0 --> false
251   ///   x > +0 --> true
252   ///   x < -0 --> false
253   bool SignBitMustBeZero(const Value *V, const TargetLibraryInfo *TLI);
254 
255   /// If the specified value can be set by repeating the same byte in memory,
256   /// return the i8 value that it is represented with. This is true for all i8
257   /// values obviously, but is also true for i32 0, i32 -1, i16 0xF0F0, double
258   /// 0.0 etc. If the value can't be handled with a repeated byte store (e.g.
259   /// i16 0x1234), return null. If the value is entirely undef and padding,
260   /// return undef.
261   Value *isBytewiseValue(Value *V, const DataLayout &DL);
262 
263   /// Given an aggregate and an sequence of indices, see if the scalar value
264   /// indexed is already around as a register, for example if it were inserted
265   /// directly into the aggregate.
266   ///
267   /// If InsertBefore is not null, this function will duplicate (modified)
268   /// insertvalues when a part of a nested struct is extracted.
269   Value *FindInsertedValue(Value *V,
270                            ArrayRef<unsigned> idx_range,
271                            Instruction *InsertBefore = nullptr);
272 
273   /// Analyze the specified pointer to see if it can be expressed as a base
274   /// pointer plus a constant offset. Return the base and offset to the caller.
275   ///
276   /// This is a wrapper around Value::stripAndAccumulateConstantOffsets that
277   /// creates and later unpacks the required APInt.
278   inline Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
279                                                  const DataLayout &DL,
280                                                  bool AllowNonInbounds = true) {
281     APInt OffsetAPInt(DL.getIndexTypeSizeInBits(Ptr->getType()), 0);
282     Value *Base =
283         Ptr->stripAndAccumulateConstantOffsets(DL, OffsetAPInt, AllowNonInbounds);
284 
285     Offset = OffsetAPInt.getSExtValue();
286     return Base;
287   }
288   inline const Value *
289   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
290                                    const DataLayout &DL,
291                                    bool AllowNonInbounds = true) {
292     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset, DL,
293                                             AllowNonInbounds);
294   }
295 
296   /// Returns true if the GEP is based on a pointer to a string (array of
297   // \p CharSize integers) and is indexing into this string.
298   bool isGEPBasedOnPointerToString(const GEPOperator *GEP,
299                                    unsigned CharSize = 8);
300 
301   /// Represents offset+length into a ConstantDataArray.
302   struct ConstantDataArraySlice {
303     /// ConstantDataArray pointer. nullptr indicates a zeroinitializer (a valid
304     /// initializer, it just doesn't fit the ConstantDataArray interface).
305     const ConstantDataArray *Array;
306 
307     /// Slice starts at this Offset.
308     uint64_t Offset;
309 
310     /// Length of the slice.
311     uint64_t Length;
312 
313     /// Moves the Offset and adjusts Length accordingly.
314     void move(uint64_t Delta) {
315       assert(Delta < Length);
316       Offset += Delta;
317       Length -= Delta;
318     }
319 
320     /// Convenience accessor for elements in the slice.
321     uint64_t operator[](unsigned I) const {
322       return Array==nullptr ? 0 : Array->getElementAsInteger(I + Offset);
323     }
324   };
325 
326   /// Returns true if the value \p V is a pointer into a ConstantDataArray.
327   /// If successful \p Slice will point to a ConstantDataArray info object
328   /// with an appropriate offset.
329   bool getConstantDataArrayInfo(const Value *V, ConstantDataArraySlice &Slice,
330                                 unsigned ElementSize, uint64_t Offset = 0);
331 
332   /// This function computes the length of a null-terminated C string pointed to
333   /// by V. If successful, it returns true and returns the string in Str. If
334   /// unsuccessful, it returns false. This does not include the trailing null
335   /// character by default. If TrimAtNul is set to false, then this returns any
336   /// trailing null characters as well as any other characters that come after
337   /// it.
338   bool getConstantStringInfo(const Value *V, StringRef &Str,
339                              uint64_t Offset = 0, bool TrimAtNul = true);
340 
341   /// If we can compute the length of the string pointed to by the specified
342   /// pointer, return 'len+1'.  If we can't, return 0.
343   uint64_t GetStringLength(const Value *V, unsigned CharSize = 8);
344 
345   /// This function returns call pointer argument that is considered the same by
346   /// aliasing rules. You CAN'T use it to replace one value with another. If
347   /// \p MustPreserveNullness is true, the call must preserve the nullness of
348   /// the pointer.
349   const Value *getArgumentAliasingToReturnedPointer(const CallBase *Call,
350                                                     bool MustPreserveNullness);
351   inline Value *
352   getArgumentAliasingToReturnedPointer(CallBase *Call,
353                                        bool MustPreserveNullness) {
354     return const_cast<Value *>(getArgumentAliasingToReturnedPointer(
355         const_cast<const CallBase *>(Call), MustPreserveNullness));
356   }
357 
358   /// {launder,strip}.invariant.group returns pointer that aliases its argument,
359   /// and it only captures pointer by returning it.
360   /// These intrinsics are not marked as nocapture, because returning is
361   /// considered as capture. The arguments are not marked as returned neither,
362   /// because it would make it useless. If \p MustPreserveNullness is true,
363   /// the intrinsic must preserve the nullness of the pointer.
364   bool isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(
365       const CallBase *Call, bool MustPreserveNullness);
366 
367   /// This method strips off any GEP address adjustments and pointer casts from
368   /// the specified value, returning the original object being addressed. Note
369   /// that the returned value has pointer type if the specified value does. If
370   /// the MaxLookup value is non-zero, it limits the number of instructions to
371   /// be stripped off.
372   const Value *getUnderlyingObject(const Value *V, unsigned MaxLookup = 6);
373   inline Value *getUnderlyingObject(Value *V, unsigned MaxLookup = 6) {
374     // Force const to avoid infinite recursion.
375     const Value *VConst = V;
376     return const_cast<Value *>(getUnderlyingObject(VConst, MaxLookup));
377   }
378 
379   /// This method is similar to getUnderlyingObject except that it can
380   /// look through phi and select instructions and return multiple objects.
381   ///
382   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
383   /// accesses different objects in each iteration, we don't look through the
384   /// phi node. E.g. consider this loop nest:
385   ///
386   ///   int **A;
387   ///   for (i)
388   ///     for (j) {
389   ///        A[i][j] = A[i-1][j] * B[j]
390   ///     }
391   ///
392   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
393   /// of the outer loop:
394   ///
395   ///   Curr = A[0];          // Prev_0
396   ///   for (i: 1..N) {
397   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
398   ///     Curr = A[i];
399   ///     for (j: 0..N) {
400   ///        Curr[j] = Prev[j] * B[j]
401   ///     }
402   ///   }
403   ///
404   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
405   /// should not assume that Curr and Prev share the same underlying object thus
406   /// it shouldn't look through the phi above.
407   void getUnderlyingObjects(const Value *V,
408                             SmallVectorImpl<const Value *> &Objects,
409                             LoopInfo *LI = nullptr, unsigned MaxLookup = 6);
410 
411   /// This is a wrapper around getUnderlyingObjects and adds support for basic
412   /// ptrtoint+arithmetic+inttoptr sequences.
413   bool getUnderlyingObjectsForCodeGen(const Value *V,
414                                       SmallVectorImpl<Value *> &Objects);
415 
416   /// Returns unique alloca where the value comes from, or nullptr.
417   /// If OffsetZero is true check that V points to the begining of the alloca.
418   AllocaInst *findAllocaForValue(Value *V, bool OffsetZero = false);
419   inline const AllocaInst *findAllocaForValue(const Value *V,
420                                               bool OffsetZero = false) {
421     return findAllocaForValue(const_cast<Value *>(V), OffsetZero);
422   }
423 
424   /// Return true if the only users of this pointer are lifetime markers.
425   bool onlyUsedByLifetimeMarkers(const Value *V);
426 
427   /// Return true if the only users of this pointer are lifetime markers or
428   /// droppable instructions.
429   bool onlyUsedByLifetimeMarkersOrDroppableInsts(const Value *V);
430 
431   /// Return true if speculation of the given load must be suppressed to avoid
432   /// ordering or interfering with an active sanitizer.  If not suppressed,
433   /// dereferenceability and alignment must be proven separately.  Note: This
434   /// is only needed for raw reasoning; if you use the interface below
435   /// (isSafeToSpeculativelyExecute), this is handled internally.
436   bool mustSuppressSpeculation(const LoadInst &LI);
437 
438   /// Return true if the instruction does not have any effects besides
439   /// calculating the result and does not have undefined behavior.
440   ///
441   /// This method never returns true for an instruction that returns true for
442   /// mayHaveSideEffects; however, this method also does some other checks in
443   /// addition. It checks for undefined behavior, like dividing by zero or
444   /// loading from an invalid pointer (but not for undefined results, like a
445   /// shift with a shift amount larger than the width of the result). It checks
446   /// for malloc and alloca because speculatively executing them might cause a
447   /// memory leak. It also returns false for instructions related to control
448   /// flow, specifically terminators and PHI nodes.
449   ///
450   /// If the CtxI is specified this method performs context-sensitive analysis
451   /// and returns true if it is safe to execute the instruction immediately
452   /// before the CtxI.
453   ///
454   /// If the CtxI is NOT specified this method only looks at the instruction
455   /// itself and its operands, so if this method returns true, it is safe to
456   /// move the instruction as long as the correct dominance relationships for
457   /// the operands and users hold.
458   ///
459   /// This method can return true for instructions that read memory;
460   /// for such instructions, moving them may change the resulting value.
461   bool isSafeToSpeculativelyExecute(const Instruction *I,
462                                     const Instruction *CtxI = nullptr,
463                                     const DominatorTree *DT = nullptr,
464                                     const TargetLibraryInfo *TLI = nullptr);
465 
466   /// This returns the same result as isSafeToSpeculativelyExecute if Opcode is
467   /// the actual opcode of Inst. If the provided and actual opcode differ, the
468   /// function (virtually) overrides the opcode of Inst with the provided
469   /// Opcode. There are come constraints in this case:
470   /// * If Opcode has a fixed number of operands (eg, as binary operators do),
471   ///   then Inst has to have at least as many leading operands. The function
472   ///   will ignore all trailing operands beyond that number.
473   /// * If Opcode allows for an arbitrary number of operands (eg, as CallInsts
474   ///   do), then all operands are considered.
475   /// * The virtual instruction has to satisfy all typing rules of the provided
476   ///   Opcode.
477   /// * This function is pessimistic in the following sense: If one actually
478   ///   materialized the virtual instruction, then isSafeToSpeculativelyExecute
479   ///   may say that the materialized instruction is speculatable whereas this
480   ///   function may have said that the instruction wouldn't be speculatable.
481   ///   This behavior is a shortcoming in the current implementation and not
482   ///   intentional.
483   bool isSafeToSpeculativelyExecuteWithOpcode(
484       unsigned Opcode, const Instruction *Inst,
485       const Instruction *CtxI = nullptr, const DominatorTree *DT = nullptr,
486       const TargetLibraryInfo *TLI = nullptr);
487 
488   /// Returns true if the result or effects of the given instructions \p I
489   /// depend values not reachable through the def use graph.
490   /// * Memory dependence arises for example if the instruction reads from
491   ///   memory or may produce effects or undefined behaviour. Memory dependent
492   ///   instructions generally cannot be reorderd with respect to other memory
493   ///   dependent instructions.
494   /// * Control dependence arises for example if the instruction may fault
495   ///   if lifted above a throwing call or infinite loop.
496   bool mayHaveNonDefUseDependency(const Instruction &I);
497 
498   /// Return true if it is an intrinsic that cannot be speculated but also
499   /// cannot trap.
500   bool isAssumeLikeIntrinsic(const Instruction *I);
501 
502   /// Return true if it is valid to use the assumptions provided by an
503   /// assume intrinsic, I, at the point in the control-flow identified by the
504   /// context instruction, CxtI.
505   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
506                                const DominatorTree *DT = nullptr);
507 
508   enum class OverflowResult {
509     /// Always overflows in the direction of signed/unsigned min value.
510     AlwaysOverflowsLow,
511     /// Always overflows in the direction of signed/unsigned max value.
512     AlwaysOverflowsHigh,
513     /// May or may not overflow.
514     MayOverflow,
515     /// Never overflows.
516     NeverOverflows,
517   };
518 
519   OverflowResult computeOverflowForUnsignedMul(const Value *LHS,
520                                                const Value *RHS,
521                                                const DataLayout &DL,
522                                                AssumptionCache *AC,
523                                                const Instruction *CxtI,
524                                                const DominatorTree *DT,
525                                                bool UseInstrInfo = true);
526   OverflowResult computeOverflowForSignedMul(const Value *LHS, const Value *RHS,
527                                              const DataLayout &DL,
528                                              AssumptionCache *AC,
529                                              const Instruction *CxtI,
530                                              const DominatorTree *DT,
531                                              bool UseInstrInfo = true);
532   OverflowResult computeOverflowForUnsignedAdd(const Value *LHS,
533                                                const Value *RHS,
534                                                const DataLayout &DL,
535                                                AssumptionCache *AC,
536                                                const Instruction *CxtI,
537                                                const DominatorTree *DT,
538                                                bool UseInstrInfo = true);
539   OverflowResult computeOverflowForSignedAdd(const Value *LHS, const Value *RHS,
540                                              const DataLayout &DL,
541                                              AssumptionCache *AC = nullptr,
542                                              const Instruction *CxtI = nullptr,
543                                              const DominatorTree *DT = nullptr);
544   /// This version also leverages the sign bit of Add if known.
545   OverflowResult computeOverflowForSignedAdd(const AddOperator *Add,
546                                              const DataLayout &DL,
547                                              AssumptionCache *AC = nullptr,
548                                              const Instruction *CxtI = nullptr,
549                                              const DominatorTree *DT = nullptr);
550   OverflowResult computeOverflowForUnsignedSub(const Value *LHS, const Value *RHS,
551                                                const DataLayout &DL,
552                                                AssumptionCache *AC,
553                                                const Instruction *CxtI,
554                                                const DominatorTree *DT);
555   OverflowResult computeOverflowForSignedSub(const Value *LHS, const Value *RHS,
556                                              const DataLayout &DL,
557                                              AssumptionCache *AC,
558                                              const Instruction *CxtI,
559                                              const DominatorTree *DT);
560 
561   /// Returns true if the arithmetic part of the \p WO 's result is
562   /// used only along the paths control dependent on the computation
563   /// not overflowing, \p WO being an <op>.with.overflow intrinsic.
564   bool isOverflowIntrinsicNoWrap(const WithOverflowInst *WO,
565                                  const DominatorTree &DT);
566 
567 
568   /// Determine the possible constant range of an integer or vector of integer
569   /// value. This is intended as a cheap, non-recursive check.
570   ConstantRange computeConstantRange(const Value *V, bool ForSigned,
571                                      bool UseInstrInfo = true,
572                                      AssumptionCache *AC = nullptr,
573                                      const Instruction *CtxI = nullptr,
574                                      const DominatorTree *DT = nullptr,
575                                      unsigned Depth = 0);
576 
577   /// Return true if this function can prove that the instruction I will
578   /// always transfer execution to one of its successors (including the next
579   /// instruction that follows within a basic block). E.g. this is not
580   /// guaranteed for function calls that could loop infinitely.
581   ///
582   /// In other words, this function returns false for instructions that may
583   /// transfer execution or fail to transfer execution in a way that is not
584   /// captured in the CFG nor in the sequence of instructions within a basic
585   /// block.
586   ///
587   /// Undefined behavior is assumed not to happen, so e.g. division is
588   /// guaranteed to transfer execution to the following instruction even
589   /// though division by zero might cause undefined behavior.
590   bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
591 
592   /// Returns true if this block does not contain a potential implicit exit.
593   /// This is equivelent to saying that all instructions within the basic block
594   /// are guaranteed to transfer execution to their successor within the basic
595   /// block. This has the same assumptions w.r.t. undefined behavior as the
596   /// instruction variant of this function.
597   bool isGuaranteedToTransferExecutionToSuccessor(const BasicBlock *BB);
598 
599   /// Return true if every instruction in the range (Begin, End) is
600   /// guaranteed to transfer execution to its static successor. \p ScanLimit
601   /// bounds the search to avoid scanning huge blocks.
602   bool isGuaranteedToTransferExecutionToSuccessor(
603      BasicBlock::const_iterator Begin, BasicBlock::const_iterator End,
604      unsigned ScanLimit = 32);
605 
606   /// Same as previous, but with range expressed via iterator_range.
607   bool isGuaranteedToTransferExecutionToSuccessor(
608      iterator_range<BasicBlock::const_iterator> Range,
609      unsigned ScanLimit = 32);
610 
611   /// Return true if this function can prove that the instruction I
612   /// is executed for every iteration of the loop L.
613   ///
614   /// Note that this currently only considers the loop header.
615   bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
616                                               const Loop *L);
617 
618   /// Return true if I yields poison or raises UB if any of its operands is
619   /// poison.
620   /// Formally, given I = `r = op v1 v2 .. vN`, propagatesPoison returns true
621   /// if, for all i, r is evaluated to poison or op raises UB if vi = poison.
622   /// If vi is a vector or an aggregate and r is a single value, any poison
623   /// element in vi should make r poison or raise UB.
624   /// To filter out operands that raise UB on poison, you can use
625   /// getGuaranteedNonPoisonOp.
626   bool propagatesPoison(const Operator *I);
627 
628   /// Insert operands of I into Ops such that I will trigger undefined behavior
629   /// if I is executed and that operand has a poison value.
630   void getGuaranteedNonPoisonOps(const Instruction *I,
631                                  SmallPtrSetImpl<const Value *> &Ops);
632   /// Insert operands of I into Ops such that I will trigger undefined behavior
633   /// if I is executed and that operand is not a well-defined value
634   /// (i.e. has undef bits or poison).
635   void getGuaranteedWellDefinedOps(const Instruction *I,
636                                    SmallPtrSetImpl<const Value *> &Ops);
637 
638   /// Return true if the given instruction must trigger undefined behavior
639   /// when I is executed with any operands which appear in KnownPoison holding
640   /// a poison value at the point of execution.
641   bool mustTriggerUB(const Instruction *I,
642                      const SmallSet<const Value *, 16>& KnownPoison);
643 
644   /// Return true if this function can prove that if Inst is executed
645   /// and yields a poison value or undef bits, then that will trigger
646   /// undefined behavior.
647   ///
648   /// Note that this currently only considers the basic block that is
649   /// the parent of Inst.
650   bool programUndefinedIfUndefOrPoison(const Instruction *Inst);
651   bool programUndefinedIfPoison(const Instruction *Inst);
652 
653   /// canCreateUndefOrPoison returns true if Op can create undef or poison from
654   /// non-undef & non-poison operands.
655   /// For vectors, canCreateUndefOrPoison returns true if there is potential
656   /// poison or undef in any element of the result when vectors without
657   /// undef/poison poison are given as operands.
658   /// For example, given `Op = shl <2 x i32> %x, <0, 32>`, this function returns
659   /// true. If Op raises immediate UB but never creates poison or undef
660   /// (e.g. sdiv I, 0), canCreatePoison returns false.
661   ///
662   /// \p ConsiderFlags controls whether poison producing flags on the
663   /// instruction are considered.  This can be used to see if the instruction
664   /// could still introduce undef or poison even without poison generating flags
665   /// which might be on the instruction.  (i.e. could the result of
666   /// Op->dropPoisonGeneratingFlags() still create poison or undef)
667   ///
668   /// canCreatePoison returns true if Op can create poison from non-poison
669   /// operands.
670   bool canCreateUndefOrPoison(const Operator *Op, bool ConsiderFlags = true);
671   bool canCreatePoison(const Operator *Op, bool ConsiderFlags = true);
672 
673   /// Return true if V is poison given that ValAssumedPoison is already poison.
674   /// For example, if ValAssumedPoison is `icmp X, 10` and V is `icmp X, 5`,
675   /// impliesPoison returns true.
676   bool impliesPoison(const Value *ValAssumedPoison, const Value *V);
677 
678   /// Return true if this function can prove that V does not have undef bits
679   /// and is never poison. If V is an aggregate value or vector, check whether
680   /// all elements (except padding) are not undef or poison.
681   /// Note that this is different from canCreateUndefOrPoison because the
682   /// function assumes Op's operands are not poison/undef.
683   ///
684   /// If CtxI and DT are specified this method performs flow-sensitive analysis
685   /// and returns true if it is guaranteed to be never undef or poison
686   /// immediately before the CtxI.
687   bool isGuaranteedNotToBeUndefOrPoison(const Value *V,
688                                         AssumptionCache *AC = nullptr,
689                                         const Instruction *CtxI = nullptr,
690                                         const DominatorTree *DT = nullptr,
691                                         unsigned Depth = 0);
692   bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC = nullptr,
693                                  const Instruction *CtxI = nullptr,
694                                  const DominatorTree *DT = nullptr,
695                                  unsigned Depth = 0);
696 
697   /// Specific patterns of select instructions we can match.
698   enum SelectPatternFlavor {
699     SPF_UNKNOWN = 0,
700     SPF_SMIN,                   /// Signed minimum
701     SPF_UMIN,                   /// Unsigned minimum
702     SPF_SMAX,                   /// Signed maximum
703     SPF_UMAX,                   /// Unsigned maximum
704     SPF_FMINNUM,                /// Floating point minnum
705     SPF_FMAXNUM,                /// Floating point maxnum
706     SPF_ABS,                    /// Absolute value
707     SPF_NABS                    /// Negated absolute value
708   };
709 
710   /// Behavior when a floating point min/max is given one NaN and one
711   /// non-NaN as input.
712   enum SelectPatternNaNBehavior {
713     SPNB_NA = 0,                /// NaN behavior not applicable.
714     SPNB_RETURNS_NAN,           /// Given one NaN input, returns the NaN.
715     SPNB_RETURNS_OTHER,         /// Given one NaN input, returns the non-NaN.
716     SPNB_RETURNS_ANY            /// Given one NaN input, can return either (or
717                                 /// it has been determined that no operands can
718                                 /// be NaN).
719   };
720 
721   struct SelectPatternResult {
722     SelectPatternFlavor Flavor;
723     SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
724                                           /// SPF_FMINNUM or SPF_FMAXNUM.
725     bool Ordered;               /// When implementing this min/max pattern as
726                                 /// fcmp; select, does the fcmp have to be
727                                 /// ordered?
728 
729     /// Return true if \p SPF is a min or a max pattern.
730     static bool isMinOrMax(SelectPatternFlavor SPF) {
731       return SPF != SPF_UNKNOWN && SPF != SPF_ABS && SPF != SPF_NABS;
732     }
733   };
734 
735   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
736   /// and providing the out parameter results if we successfully match.
737   ///
738   /// For ABS/NABS, LHS will be set to the input to the abs idiom. RHS will be
739   /// the negation instruction from the idiom.
740   ///
741   /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
742   /// not match that of the original select. If this is the case, the cast
743   /// operation (one of Trunc,SExt,Zext) that must be done to transform the
744   /// type of LHS and RHS into the type of V is returned in CastOp.
745   ///
746   /// For example:
747   ///   %1 = icmp slt i32 %a, i32 4
748   ///   %2 = sext i32 %a to i64
749   ///   %3 = select i1 %1, i64 %2, i64 4
750   ///
751   /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
752   ///
753   SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
754                                          Instruction::CastOps *CastOp = nullptr,
755                                          unsigned Depth = 0);
756 
757   inline SelectPatternResult
758   matchSelectPattern(const Value *V, const Value *&LHS, const Value *&RHS) {
759     Value *L = const_cast<Value *>(LHS);
760     Value *R = const_cast<Value *>(RHS);
761     auto Result = matchSelectPattern(const_cast<Value *>(V), L, R);
762     LHS = L;
763     RHS = R;
764     return Result;
765   }
766 
767   /// Determine the pattern that a select with the given compare as its
768   /// predicate and given values as its true/false operands would match.
769   SelectPatternResult matchDecomposedSelectPattern(
770       CmpInst *CmpI, Value *TrueVal, Value *FalseVal, Value *&LHS, Value *&RHS,
771       Instruction::CastOps *CastOp = nullptr, unsigned Depth = 0);
772 
773   /// Return the canonical comparison predicate for the specified
774   /// minimum/maximum flavor.
775   CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF,
776                                    bool Ordered = false);
777 
778   /// Return the inverse minimum/maximum flavor of the specified flavor.
779   /// For example, signed minimum is the inverse of signed maximum.
780   SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF);
781 
782   Intrinsic::ID getInverseMinMaxIntrinsic(Intrinsic::ID MinMaxID);
783 
784   /// Return the canonical inverse comparison predicate for the specified
785   /// minimum/maximum flavor.
786   CmpInst::Predicate getInverseMinMaxPred(SelectPatternFlavor SPF);
787 
788   /// Return the minimum or maximum constant value for the specified integer
789   /// min/max flavor and type.
790   APInt getMinMaxLimit(SelectPatternFlavor SPF, unsigned BitWidth);
791 
792   /// Check if the values in \p VL are select instructions that can be converted
793   /// to a min or max (vector) intrinsic. Returns the intrinsic ID, if such a
794   /// conversion is possible, together with a bool indicating whether all select
795   /// conditions are only used by the selects. Otherwise return
796   /// Intrinsic::not_intrinsic.
797   std::pair<Intrinsic::ID, bool>
798   canConvertToMinOrMaxIntrinsic(ArrayRef<Value *> VL);
799 
800   /// Attempt to match a simple first order recurrence cycle of the form:
801   ///   %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
802   ///   %inc = binop %iv, %step
803   /// OR
804   ///   %iv = phi Ty [%Start, %Entry], [%Inc, %backedge]
805   ///   %inc = binop %step, %iv
806   ///
807   /// A first order recurrence is a formula with the form: X_n = f(X_(n-1))
808   ///
809   /// A couple of notes on subtleties in that definition:
810   /// * The Step does not have to be loop invariant.  In math terms, it can
811   ///   be a free variable.  We allow recurrences with both constant and
812   ///   variable coefficients. Callers may wish to filter cases where Step
813   ///   does not dominate P.
814   /// * For non-commutative operators, we will match both forms.  This
815   ///   results in some odd recurrence structures.  Callers may wish to filter
816   ///   out recurrences where the phi is not the LHS of the returned operator.
817   /// * Because of the structure matched, the caller can assume as a post
818   ///   condition of the match the presence of a Loop with P's parent as it's
819   ///   header *except* in unreachable code.  (Dominance decays in unreachable
820   ///   code.)
821   ///
822   /// NOTE: This is intentional simple.  If you want the ability to analyze
823   /// non-trivial loop conditons, see ScalarEvolution instead.
824   bool matchSimpleRecurrence(const PHINode *P, BinaryOperator *&BO,
825                              Value *&Start, Value *&Step);
826 
827   /// Analogous to the above, but starting from the binary operator
828   bool matchSimpleRecurrence(const BinaryOperator *I, PHINode *&P,
829                                     Value *&Start, Value *&Step);
830 
831   /// Return true if RHS is known to be implied true by LHS.  Return false if
832   /// RHS is known to be implied false by LHS.  Otherwise, return None if no
833   /// implication can be made.
834   /// A & B must be i1 (boolean) values or a vector of such values. Note that
835   /// the truth table for implication is the same as <=u on i1 values (but not
836   /// <=s!).  The truth table for both is:
837   ///    | T | F (B)
838   ///  T | T | F
839   ///  F | T | T
840   /// (A)
841   Optional<bool> isImpliedCondition(const Value *LHS, const Value *RHS,
842                                     const DataLayout &DL, bool LHSIsTrue = true,
843                                     unsigned Depth = 0);
844   Optional<bool> isImpliedCondition(const Value *LHS,
845                                     CmpInst::Predicate RHSPred,
846                                     const Value *RHSOp0, const Value *RHSOp1,
847                                     const DataLayout &DL, bool LHSIsTrue = true,
848                                     unsigned Depth = 0);
849 
850   /// Return the boolean condition value in the context of the given instruction
851   /// if it is known based on dominating conditions.
852   Optional<bool> isImpliedByDomCondition(const Value *Cond,
853                                          const Instruction *ContextI,
854                                          const DataLayout &DL);
855   Optional<bool> isImpliedByDomCondition(CmpInst::Predicate Pred,
856                                          const Value *LHS, const Value *RHS,
857                                          const Instruction *ContextI,
858                                          const DataLayout &DL);
859 
860   /// If Ptr1 is provably equal to Ptr2 plus a constant offset, return that
861   /// offset. For example, Ptr1 might be &A[42], and Ptr2 might be &A[40]. In
862   /// this case offset would be -8.
863   Optional<int64_t> isPointerOffset(const Value *Ptr1, const Value *Ptr2,
864                                     const DataLayout &DL);
865 } // end namespace llvm
866 
867 #endif // LLVM_ANALYSIS_VALUETRACKING_H
868