[ValueTracking] Add a new predicate: isKnownNonEqual()
[oota-llvm.git] / include / llvm / Analysis / ValueTracking.h
1 //===- 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/IR/Instruction.h"
20 #include "llvm/Support/DataTypes.h"
21
22 namespace llvm {
23   class APInt;
24   class AddOperator;
25   class AssumptionCache;
26   class DataLayout;
27   class DominatorTree;
28   class Instruction;
29   class Loop;
30   class LoopInfo;
31   class MDNode;
32   class StringRef;
33   class TargetLibraryInfo;
34   class Value;
35
36   /// Determine which bits of V are known to be either zero or one and return
37   /// them in the KnownZero/KnownOne bit sets.
38   ///
39   /// This function is defined on values with integer type, values with pointer
40   /// type, and vectors of integers.  In the case
41   /// where V is a vector, the known zero and known one values are the
42   /// same width as the vector element, and the bit is set only if it is true
43   /// for all of the elements in the vector.
44   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
45                         const DataLayout &DL, unsigned Depth = 0,
46                         AssumptionCache *AC = nullptr,
47                         const Instruction *CxtI = nullptr,
48                         const DominatorTree *DT = nullptr);
49   /// Compute known bits from the range metadata.
50   /// \p KnownZero the set of bits that are known to be zero
51   void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
52                                          APInt &KnownZero);
53   /// Return true if LHS and RHS have no common bits set.
54   bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
55                            AssumptionCache *AC = nullptr,
56                            const Instruction *CxtI = nullptr,
57                            const DominatorTree *DT = nullptr);
58
59   /// ComputeSignBit - Determine whether the sign bit is known to be zero or
60   /// one.  Convenience wrapper around computeKnownBits.
61   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
62                       const DataLayout &DL, unsigned Depth = 0,
63                       AssumptionCache *AC = nullptr,
64                       const Instruction *CxtI = nullptr,
65                       const DominatorTree *DT = nullptr);
66
67   /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
68   /// exactly one bit set when defined. For vectors return true if every
69   /// element is known to be a power of two when defined.  Supports values with
70   /// integer or pointer type and vectors of integers.  If 'OrZero' is set then
71   /// return true if the given value is either a power of two or zero.
72   bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
73                               bool OrZero = false, unsigned Depth = 0,
74                               AssumptionCache *AC = nullptr,
75                               const Instruction *CxtI = nullptr,
76                               const DominatorTree *DT = nullptr);
77
78   /// isKnownNonZero - Return true if the given value is known to be non-zero
79   /// when defined.  For vectors return true if every element is known to be
80   /// non-zero when defined.  Supports values with integer or pointer type and
81   /// vectors of integers.
82   bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
83                       AssumptionCache *AC = nullptr,
84                       const Instruction *CxtI = nullptr,
85                       const DominatorTree *DT = nullptr);
86
87   /// Returns true if the give value is known to be non-negative.
88   bool isKnownNonNegative(Value *V, const DataLayout &DL, unsigned Depth = 0,
89                           AssumptionCache *AC = nullptr,
90                           const Instruction *CxtI = nullptr,
91                           const DominatorTree *DT = nullptr);
92
93   /// isKnownNonEqual - Return true if the given values are known to be
94   /// non-equal when defined. Supports scalar integer types only.
95   bool isKnownNonEqual(Value *V1, Value *V2, const DataLayout &DL,
96                       AssumptionCache *AC = nullptr,
97                       const Instruction *CxtI = nullptr,
98                       const DominatorTree *DT = nullptr);
99
100   /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
101   /// this predicate to simplify operations downstream.  Mask is known to be
102   /// zero for bits that V cannot have.
103   ///
104   /// This function is defined on values with integer type, values with pointer
105   /// type, and vectors of integers.  In the case
106   /// where V is a vector, the mask, known zero, and known one values are the
107   /// same width as the vector element, and the bit is set only if it is true
108   /// for all of the elements in the vector.
109   bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
110                          unsigned Depth = 0, AssumptionCache *AC = nullptr,
111                          const Instruction *CxtI = nullptr,
112                          const DominatorTree *DT = nullptr);
113
114   /// ComputeNumSignBits - Return the number of times the sign bit of the
115   /// register is replicated into the other bits.  We know that at least 1 bit
116   /// is always equal to the sign bit (itself), but other cases can give us
117   /// information.  For example, immediately after an "ashr X, 2", we know that
118   /// the top 3 bits are all equal to each other, so we return 3.
119   ///
120   /// 'Op' must have a scalar integer type.
121   ///
122   unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
123                               unsigned Depth = 0, AssumptionCache *AC = nullptr,
124                               const Instruction *CxtI = nullptr,
125                               const DominatorTree *DT = nullptr);
126
127   /// ComputeMultiple - This function computes the integer multiple of Base that
128   /// equals V.  If successful, it returns true and returns the multiple in
129   /// Multiple.  If unsuccessful, it returns false.  Also, if V can be
130   /// simplified to an integer, then the simplified V is returned in Val.  Look
131   /// through sext only if LookThroughSExt=true.
132   bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
133                        bool LookThroughSExt = false,
134                        unsigned Depth = 0);
135
136   /// CannotBeNegativeZero - Return true if we can prove that the specified FP
137   /// value is never equal to -0.0.
138   ///
139   bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
140
141   /// CannotBeOrderedLessThanZero - Return true if we can prove that the
142   /// specified FP value is either a NaN or never less than 0.0.
143   ///
144   bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
145
146   /// isBytewiseValue - If the specified value can be set by repeating the same
147   /// byte in memory, return the i8 value that it is represented with.  This is
148   /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
149   /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
150   /// byte store (e.g. i16 0x1234), return null.
151   Value *isBytewiseValue(Value *V);
152
153   /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
154   /// the scalar value indexed is already around as a register, for example if
155   /// it were inserted directly into the aggregrate.
156   ///
157   /// If InsertBefore is not null, this function will duplicate (modified)
158   /// insertvalues when a part of a nested struct is extracted.
159   Value *FindInsertedValue(Value *V,
160                            ArrayRef<unsigned> idx_range,
161                            Instruction *InsertBefore = nullptr);
162
163   /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
164   /// it can be expressed as a base pointer plus a constant offset.  Return the
165   /// base and offset to the caller.
166   Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
167                                           const DataLayout &DL);
168   static inline const Value *
169   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
170                                    const DataLayout &DL) {
171     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
172                                             DL);
173   }
174
175   /// getConstantStringInfo - This function computes the length of a
176   /// null-terminated C string pointed to by V.  If successful, it returns true
177   /// and returns the string in Str.  If unsuccessful, it returns false.  This
178   /// does not include the trailing nul character by default.  If TrimAtNul is
179   /// set to false, then this returns any trailing nul characters as well as any
180   /// other characters that come after it.
181   bool getConstantStringInfo(const Value *V, StringRef &Str,
182                              uint64_t Offset = 0, bool TrimAtNul = true);
183
184   /// GetStringLength - If we can compute the length of the string pointed to by
185   /// the specified pointer, return 'len+1'.  If we can't, return 0.
186   uint64_t GetStringLength(Value *V);
187
188   /// GetUnderlyingObject - This method strips off any GEP address adjustments
189   /// and pointer casts from the specified value, returning the original object
190   /// being addressed.  Note that the returned value has pointer type if the
191   /// specified value does.  If the MaxLookup value is non-zero, it limits the
192   /// number of instructions to be stripped off.
193   Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
194                              unsigned MaxLookup = 6);
195   static inline const Value *GetUnderlyingObject(const Value *V,
196                                                  const DataLayout &DL,
197                                                  unsigned MaxLookup = 6) {
198     return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
199   }
200
201   /// \brief This method is similar to GetUnderlyingObject except that it can
202   /// look through phi and select instructions and return multiple objects.
203   ///
204   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
205   /// accesses different objects in each iteration, we don't look through the
206   /// phi node. E.g. consider this loop nest:
207   ///
208   ///   int **A;
209   ///   for (i)
210   ///     for (j) {
211   ///        A[i][j] = A[i-1][j] * B[j]
212   ///     }
213   ///
214   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
215   /// of the outer loop:
216   ///
217   ///   Curr = A[0];          // Prev_0
218   ///   for (i: 1..N) {
219   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
220   ///     Curr = A[i];
221   ///     for (j: 0..N) {
222   ///        Curr[j] = Prev[j] * B[j]
223   ///     }
224   ///   }
225   ///
226   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
227   /// should not assume that Curr and Prev share the same underlying object thus
228   /// it shouldn't look through the phi above.
229   void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
230                             const DataLayout &DL, LoopInfo *LI = nullptr,
231                             unsigned MaxLookup = 6);
232
233   /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
234   /// are lifetime markers.
235   bool onlyUsedByLifetimeMarkers(const Value *V);
236
237   /// isDereferenceablePointer - Return true if this is always a dereferenceable
238   /// pointer. If the context instruction is specified perform context-sensitive
239   /// analysis and return true if the pointer is dereferenceable at the
240   /// specified instruction.
241   bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
242                                 const Instruction *CtxI = nullptr,
243                                 const DominatorTree *DT = nullptr,
244                                 const TargetLibraryInfo *TLI = nullptr);
245
246   /// Returns true if V is always a dereferenceable pointer with alignment
247   /// greater or equal than requested. If the context instruction is specified
248   /// performs context-sensitive analysis and returns true if the pointer is
249   /// dereferenceable at the specified instruction.
250   bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align,
251                                           const DataLayout &DL,
252                                           const Instruction *CtxI = nullptr,
253                                           const DominatorTree *DT = nullptr,
254                                           const TargetLibraryInfo *TLI = nullptr);
255
256   /// isSafeToSpeculativelyExecute - Return true if the instruction does not
257   /// have any effects besides calculating the result and does not have
258   /// undefined behavior.
259   ///
260   /// This method never returns true for an instruction that returns true for
261   /// mayHaveSideEffects; however, this method also does some other checks in
262   /// addition. It checks for undefined behavior, like dividing by zero or
263   /// loading from an invalid pointer (but not for undefined results, like a
264   /// shift with a shift amount larger than the width of the result). It checks
265   /// for malloc and alloca because speculatively executing them might cause a
266   /// memory leak. It also returns false for instructions related to control
267   /// flow, specifically terminators and PHI nodes.
268   ///
269   /// If the CtxI is specified this method performs context-sensitive analysis
270   /// and returns true if it is safe to execute the instruction immediately
271   /// before the CtxI.
272   ///
273   /// If the CtxI is NOT specified this method only looks at the instruction
274   /// itself and its operands, so if this method returns true, it is safe to
275   /// move the instruction as long as the correct dominance relationships for
276   /// the operands and users hold.
277   ///
278   /// This method can return true for instructions that read memory;
279   /// for such instructions, moving them may change the resulting value.
280   bool isSafeToSpeculativelyExecute(const Value *V,
281                                     const Instruction *CtxI = nullptr,
282                                     const DominatorTree *DT = nullptr,
283                                     const TargetLibraryInfo *TLI = nullptr);
284
285   /// Returns true if the result or effects of the given instructions \p I
286   /// depend on or influence global memory.
287   /// Memory dependence arises for example if the the instruction reads from
288   /// memory or may produce effects or undefined behaviour. Memory dependent
289   /// instructions generally cannot be reorderd with respect to other memory
290   /// dependent instructions or moved into non-dominated basic blocks.
291   /// Instructions which just compute a value based on the values of their
292   /// operands are not memory dependent.
293   bool mayBeMemoryDependent(const Instruction &I);
294
295   /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
296   /// its definition.  This returns true for allocas, non-extern-weak globals
297   /// and byval arguments.
298   bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
299
300   /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
301   /// If the context instruction is specified perform context-sensitive analysis
302   /// and return true if the pointer couldn't possibly be null at the specified
303   /// instruction.
304   bool isKnownNonNullAt(const Value *V,
305                         const Instruction *CtxI = nullptr,
306                         const DominatorTree *DT  = nullptr,
307                         const TargetLibraryInfo *TLI = nullptr);
308
309   /// Return true if it is valid to use the assumptions provided by an
310   /// assume intrinsic, I, at the point in the control-flow identified by the
311   /// context instruction, CxtI.
312   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
313                                const DominatorTree *DT = nullptr);
314
315   enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
316   OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
317                                                const DataLayout &DL,
318                                                AssumptionCache *AC,
319                                                const Instruction *CxtI,
320                                                const DominatorTree *DT);
321   OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
322                                                const DataLayout &DL,
323                                                AssumptionCache *AC,
324                                                const Instruction *CxtI,
325                                                const DominatorTree *DT);
326   OverflowResult computeOverflowForSignedAdd(Value *LHS, Value *RHS,
327                                              const DataLayout &DL,
328                                              AssumptionCache *AC = nullptr,
329                                              const Instruction *CxtI = nullptr,
330                                              const DominatorTree *DT = nullptr);
331   /// This version also leverages the sign bit of Add if known.
332   OverflowResult computeOverflowForSignedAdd(AddOperator *Add,
333                                              const DataLayout &DL,
334                                              AssumptionCache *AC = nullptr,
335                                              const Instruction *CxtI = nullptr,
336                                              const DominatorTree *DT = nullptr);
337
338   /// Return true if this function can prove that the instruction I will
339   /// always transfer execution to one of its successors (including the next
340   /// instruction that follows within a basic block). E.g. this is not
341   /// guaranteed for function calls that could loop infinitely.
342   ///
343   /// In other words, this function returns false for instructions that may
344   /// transfer execution or fail to transfer execution in a way that is not
345   /// captured in the CFG nor in the sequence of instructions within a basic
346   /// block.
347   ///
348   /// Undefined behavior is assumed not to happen, so e.g. division is
349   /// guaranteed to transfer execution to the following instruction even
350   /// though division by zero might cause undefined behavior.
351   bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I);
352
353   /// Return true if this function can prove that the instruction I
354   /// is executed for every iteration of the loop L.
355   ///
356   /// Note that this currently only considers the loop header.
357   bool isGuaranteedToExecuteForEveryIteration(const Instruction *I,
358                                               const Loop *L);
359
360   /// Return true if this function can prove that I is guaranteed to yield
361   /// full-poison (all bits poison) if at least one of its operands are
362   /// full-poison (all bits poison).
363   ///
364   /// The exact rules for how poison propagates through instructions have
365   /// not been settled as of 2015-07-10, so this function is conservative
366   /// and only considers poison to be propagated in uncontroversial
367   /// cases. There is no attempt to track values that may be only partially
368   /// poison.
369   bool propagatesFullPoison(const Instruction *I);
370
371   /// Return either nullptr or an operand of I such that I will trigger
372   /// undefined behavior if I is executed and that operand has a full-poison
373   /// value (all bits poison).
374   const Value *getGuaranteedNonFullPoisonOp(const Instruction *I);
375
376   /// Return true if this function can prove that if PoisonI is executed
377   /// and yields a full-poison value (all bits poison), then that will
378   /// trigger undefined behavior.
379   ///
380   /// Note that this currently only considers the basic block that is
381   /// the parent of I.
382   bool isKnownNotFullPoison(const Instruction *PoisonI);
383
384   /// \brief Specific patterns of select instructions we can match.
385   enum SelectPatternFlavor {
386     SPF_UNKNOWN = 0,
387     SPF_SMIN,                   /// Signed minimum
388     SPF_UMIN,                   /// Unsigned minimum
389     SPF_SMAX,                   /// Signed maximum
390     SPF_UMAX,                   /// Unsigned maximum
391     SPF_FMINNUM,                /// Floating point minnum
392     SPF_FMAXNUM,                /// Floating point maxnum
393     SPF_ABS,                    /// Absolute value
394     SPF_NABS                    /// Negated absolute value
395   };
396   /// \brief Behavior when a floating point min/max is given one NaN and one
397   /// non-NaN as input.
398   enum SelectPatternNaNBehavior {
399     SPNB_NA = 0,                /// NaN behavior not applicable.
400     SPNB_RETURNS_NAN,           /// Given one NaN input, returns the NaN.
401     SPNB_RETURNS_OTHER,         /// Given one NaN input, returns the non-NaN.
402     SPNB_RETURNS_ANY            /// Given one NaN input, can return either (or
403                                 /// it has been determined that no operands can
404                                 /// be NaN).
405   };
406   struct SelectPatternResult {
407     SelectPatternFlavor Flavor;
408     SelectPatternNaNBehavior NaNBehavior; /// Only applicable if Flavor is
409                                           /// SPF_FMINNUM or SPF_FMAXNUM.
410     bool Ordered;               /// When implementing this min/max pattern as
411                                 /// fcmp; select, does the fcmp have to be
412                                 /// ordered?
413   };
414   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
415   /// and providing the out parameter results if we successfully match.
416   ///
417   /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
418   /// not match that of the original select. If this is the case, the cast
419   /// operation (one of Trunc,SExt,Zext) that must be done to transform the
420   /// type of LHS and RHS into the type of V is returned in CastOp.
421   ///
422   /// For example:
423   ///   %1 = icmp slt i32 %a, i32 4
424   ///   %2 = sext i32 %a to i64
425   ///   %3 = select i1 %1, i64 %2, i64 4
426   ///
427   /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
428   ///
429   SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
430                                          Instruction::CastOps *CastOp = nullptr);
431
432 } // end namespace llvm
433
434 #endif