Exploit dereferenceable_or_null attribute in LICM pass
[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 Value;
24   class Instruction;
25   class APInt;
26   class DataLayout;
27   class StringRef;
28   class MDNode;
29   class AssumptionCache;
30   class DominatorTree;
31   class TargetLibraryInfo;
32   class LoopInfo;
33
34   /// Determine which bits of V are known to be either zero or one and return
35   /// them in the KnownZero/KnownOne bit sets.
36   ///
37   /// This function is defined on values with integer type, values with pointer
38   /// type, and vectors of integers.  In the case
39   /// where V is a vector, the known zero and known one values are the
40   /// same width as the vector element, and the bit is set only if it is true
41   /// for all of the elements in the vector.
42   void computeKnownBits(Value *V, APInt &KnownZero, APInt &KnownOne,
43                         const DataLayout &DL, unsigned Depth = 0,
44                         AssumptionCache *AC = nullptr,
45                         const Instruction *CxtI = nullptr,
46                         const DominatorTree *DT = nullptr);
47   /// Compute known bits from the range metadata.
48   /// \p KnownZero the set of bits that are known to be zero
49   void computeKnownBitsFromRangeMetadata(const MDNode &Ranges,
50                                          APInt &KnownZero);
51   /// Returns true if LHS and RHS have no common bits set.
52   bool haveNoCommonBitsSet(Value *LHS, Value *RHS, const DataLayout &DL,
53                            AssumptionCache *AC = nullptr,
54                            const Instruction *CxtI = nullptr,
55                            const DominatorTree *DT = nullptr);
56
57   /// ComputeSignBit - Determine whether the sign bit is known to be zero or
58   /// one.  Convenience wrapper around computeKnownBits.
59   void ComputeSignBit(Value *V, bool &KnownZero, bool &KnownOne,
60                       const DataLayout &DL, unsigned Depth = 0,
61                       AssumptionCache *AC = nullptr,
62                       const Instruction *CxtI = nullptr,
63                       const DominatorTree *DT = nullptr);
64
65   /// isKnownToBeAPowerOfTwo - Return true if the given value is known to have
66   /// exactly one bit set when defined. For vectors return true if every
67   /// element is known to be a power of two when defined.  Supports values with
68   /// integer or pointer type and vectors of integers.  If 'OrZero' is set then
69   /// returns true if the given value is either a power of two or zero.
70   bool isKnownToBeAPowerOfTwo(Value *V, const DataLayout &DL,
71                               bool OrZero = false, unsigned Depth = 0,
72                               AssumptionCache *AC = nullptr,
73                               const Instruction *CxtI = nullptr,
74                               const DominatorTree *DT = nullptr);
75
76   /// isKnownNonZero - Return true if the given value is known to be non-zero
77   /// when defined.  For vectors return true if every element is known to be
78   /// non-zero when defined.  Supports values with integer or pointer type and
79   /// vectors of integers.
80   bool isKnownNonZero(Value *V, const DataLayout &DL, unsigned Depth = 0,
81                       AssumptionCache *AC = nullptr,
82                       const Instruction *CxtI = nullptr,
83                       const DominatorTree *DT = nullptr);
84
85   /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
86   /// this predicate to simplify operations downstream.  Mask is known to be
87   /// zero for bits that V cannot have.
88   ///
89   /// This function is defined on values with integer type, values with pointer
90   /// type, and vectors of integers.  In the case
91   /// where V is a vector, the mask, known zero, and known one values are the
92   /// same width as the vector element, and the bit is set only if it is true
93   /// for all of the elements in the vector.
94   bool MaskedValueIsZero(Value *V, const APInt &Mask, const DataLayout &DL,
95                          unsigned Depth = 0, AssumptionCache *AC = nullptr,
96                          const Instruction *CxtI = nullptr,
97                          const DominatorTree *DT = nullptr);
98
99   /// ComputeNumSignBits - Return the number of times the sign bit of the
100   /// register is replicated into the other bits.  We know that at least 1 bit
101   /// is always equal to the sign bit (itself), but other cases can give us
102   /// information.  For example, immediately after an "ashr X, 2", we know that
103   /// the top 3 bits are all equal to each other, so we return 3.
104   ///
105   /// 'Op' must have a scalar integer type.
106   ///
107   unsigned ComputeNumSignBits(Value *Op, const DataLayout &DL,
108                               unsigned Depth = 0, AssumptionCache *AC = nullptr,
109                               const Instruction *CxtI = nullptr,
110                               const DominatorTree *DT = nullptr);
111
112   /// ComputeMultiple - This function computes the integer multiple of Base that
113   /// equals V.  If successful, it returns true and returns the multiple in
114   /// Multiple.  If unsuccessful, it returns false.  Also, if V can be
115   /// simplified to an integer, then the simplified V is returned in Val.  Look
116   /// through sext only if LookThroughSExt=true.
117   bool ComputeMultiple(Value *V, unsigned Base, Value *&Multiple,
118                        bool LookThroughSExt = false,
119                        unsigned Depth = 0);
120
121   /// CannotBeNegativeZero - Return true if we can prove that the specified FP 
122   /// value is never equal to -0.0.
123   ///
124   bool CannotBeNegativeZero(const Value *V, unsigned Depth = 0);
125
126   /// CannotBeOrderedLessThanZero - Return true if we can prove that the 
127   /// specified FP value is either a NaN or never less than 0.0.
128   ///
129   bool CannotBeOrderedLessThanZero(const Value *V, unsigned Depth = 0);
130
131   /// isBytewiseValue - If the specified value can be set by repeating the same
132   /// byte in memory, return the i8 value that it is represented with.  This is
133   /// true for all i8 values obviously, but is also true for i32 0, i32 -1,
134   /// i16 0xF0F0, double 0.0 etc.  If the value can't be handled with a repeated
135   /// byte store (e.g. i16 0x1234), return null.
136   Value *isBytewiseValue(Value *V);
137     
138   /// FindInsertedValue - Given an aggregrate and an sequence of indices, see if
139   /// the scalar value indexed is already around as a register, for example if
140   /// it were inserted directly into the aggregrate.
141   ///
142   /// If InsertBefore is not null, this function will duplicate (modified)
143   /// insertvalues when a part of a nested struct is extracted.
144   Value *FindInsertedValue(Value *V,
145                            ArrayRef<unsigned> idx_range,
146                            Instruction *InsertBefore = nullptr);
147
148   /// GetPointerBaseWithConstantOffset - Analyze the specified pointer to see if
149   /// it can be expressed as a base pointer plus a constant offset.  Return the
150   /// base and offset to the caller.
151   Value *GetPointerBaseWithConstantOffset(Value *Ptr, int64_t &Offset,
152                                           const DataLayout &DL);
153   static inline const Value *
154   GetPointerBaseWithConstantOffset(const Value *Ptr, int64_t &Offset,
155                                    const DataLayout &DL) {
156     return GetPointerBaseWithConstantOffset(const_cast<Value *>(Ptr), Offset,
157                                             DL);
158   }
159   
160   /// getConstantStringInfo - This function computes the length of a
161   /// null-terminated C string pointed to by V.  If successful, it returns true
162   /// and returns the string in Str.  If unsuccessful, it returns false.  This
163   /// does not include the trailing nul character by default.  If TrimAtNul is
164   /// set to false, then this returns any trailing nul characters as well as any
165   /// other characters that come after it.
166   bool getConstantStringInfo(const Value *V, StringRef &Str,
167                              uint64_t Offset = 0, bool TrimAtNul = true);
168
169   /// GetStringLength - If we can compute the length of the string pointed to by
170   /// the specified pointer, return 'len+1'.  If we can't, return 0.
171   uint64_t GetStringLength(Value *V);
172
173   /// GetUnderlyingObject - This method strips off any GEP address adjustments
174   /// and pointer casts from the specified value, returning the original object
175   /// being addressed.  Note that the returned value has pointer type if the
176   /// specified value does.  If the MaxLookup value is non-zero, it limits the
177   /// number of instructions to be stripped off.
178   Value *GetUnderlyingObject(Value *V, const DataLayout &DL,
179                              unsigned MaxLookup = 6);
180   static inline const Value *GetUnderlyingObject(const Value *V,
181                                                  const DataLayout &DL,
182                                                  unsigned MaxLookup = 6) {
183     return GetUnderlyingObject(const_cast<Value *>(V), DL, MaxLookup);
184   }
185
186   /// \brief This method is similar to GetUnderlyingObject except that it can
187   /// look through phi and select instructions and return multiple objects.
188   ///
189   /// If LoopInfo is passed, loop phis are further analyzed.  If a pointer
190   /// accesses different objects in each iteration, we don't look through the
191   /// phi node. E.g. consider this loop nest:
192   ///
193   ///   int **A;
194   ///   for (i)
195   ///     for (j) {
196   ///        A[i][j] = A[i-1][j] * B[j]
197   ///     }
198   ///
199   /// This is transformed by Load-PRE to stash away A[i] for the next iteration
200   /// of the outer loop:
201   ///
202   ///   Curr = A[0];          // Prev_0
203   ///   for (i: 1..N) {
204   ///     Prev = Curr;        // Prev = PHI (Prev_0, Curr)
205   ///     Curr = A[i];
206   ///     for (j: 0..N) {
207   ///        Curr[j] = Prev[j] * B[j]
208   ///     }
209   ///   }
210   ///
211   /// Since A[i] and A[i-1] are independent pointers, getUnderlyingObjects
212   /// should not assume that Curr and Prev share the same underlying object thus
213   /// it shouldn't look through the phi above.
214   void GetUnderlyingObjects(Value *V, SmallVectorImpl<Value *> &Objects,
215                             const DataLayout &DL, LoopInfo *LI = nullptr,
216                             unsigned MaxLookup = 6);
217
218   /// onlyUsedByLifetimeMarkers - Return true if the only users of this pointer
219   /// are lifetime markers.
220   bool onlyUsedByLifetimeMarkers(const Value *V);
221
222   /// isDereferenceablePointer - Return true if this is always a dereferenceable
223   /// pointer. If the context instruction is specified perform context-sensitive
224   /// analysis and return true if the pointer is dereferenceable at the
225   /// specified instruction.
226   bool isDereferenceablePointer(const Value *V, const DataLayout &DL,
227                                 const Instruction *CtxI = nullptr,
228                                 const DominatorTree *DT = nullptr,
229                                 const TargetLibraryInfo *TLI = nullptr);
230   
231   /// isSafeToSpeculativelyExecute - Return true if the instruction does not
232   /// have any effects besides calculating the result and does not have
233   /// undefined behavior.
234   ///
235   /// This method never returns true for an instruction that returns true for
236   /// mayHaveSideEffects; however, this method also does some other checks in
237   /// addition. It checks for undefined behavior, like dividing by zero or
238   /// loading from an invalid pointer (but not for undefined results, like a
239   /// shift with a shift amount larger than the width of the result). It checks
240   /// for malloc and alloca because speculatively executing them might cause a
241   /// memory leak. It also returns false for instructions related to control
242   /// flow, specifically terminators and PHI nodes.
243   ///
244   /// If the CtxI is specified this method performs context-sensitive analysis
245   /// and returns true if it is safe to execute the instruction immediately
246   /// before the CtxI.
247   ///
248   /// If the CtxI is NOT specified this method only looks at the instruction
249   /// itself and its operands, so if this method returns true, it is safe to
250   /// move the instruction as long as the correct dominance relationships for
251   /// the operands and users hold.
252   ///
253   /// This method can return true for instructions that read memory;
254   /// for such instructions, moving them may change the resulting value.
255   bool isSafeToSpeculativelyExecute(const Value *V,
256                                     const Instruction *CtxI = nullptr,
257                                     const DominatorTree *DT = nullptr,
258                                     const TargetLibraryInfo *TLI = nullptr);
259
260   /// isKnownNonNull - Return true if this pointer couldn't possibly be null by
261   /// its definition.  This returns true for allocas, non-extern-weak globals
262   /// and byval arguments.
263   bool isKnownNonNull(const Value *V, const TargetLibraryInfo *TLI = nullptr);
264
265   /// isKnownNonNullAt - Return true if this pointer couldn't possibly be null.
266   /// If the context instruction is specified perform context-sensitive analysis
267   /// and return true if the pointer couldn't possibly be null at the specified
268   /// instruction.
269   bool isKnownNonNullAt(const Value *V,
270                         const Instruction *CtxI = nullptr,
271                         const DominatorTree *DT  = nullptr,
272                         const TargetLibraryInfo *TLI = nullptr);
273
274   /// Return true if it is valid to use the assumptions provided by an
275   /// assume intrinsic, I, at the point in the control-flow identified by the
276   /// context instruction, CxtI.
277   bool isValidAssumeForContext(const Instruction *I, const Instruction *CxtI,
278                                const DominatorTree *DT = nullptr);
279
280   enum class OverflowResult { AlwaysOverflows, MayOverflow, NeverOverflows };
281   OverflowResult computeOverflowForUnsignedMul(Value *LHS, Value *RHS,
282                                                const DataLayout &DL,
283                                                AssumptionCache *AC,
284                                                const Instruction *CxtI,
285                                                const DominatorTree *DT);
286   OverflowResult computeOverflowForUnsignedAdd(Value *LHS, Value *RHS,
287                                                const DataLayout &DL,
288                                                AssumptionCache *AC,
289                                                const Instruction *CxtI,
290                                                const DominatorTree *DT);
291   
292   /// \brief Specific patterns of select instructions we can match.
293   enum SelectPatternFlavor {
294     SPF_UNKNOWN = 0,
295     SPF_SMIN,                   // Signed minimum
296     SPF_UMIN,                   // Unsigned minimum
297     SPF_SMAX,                   // Signed maximum
298     SPF_UMAX,                   // Unsigned maximum
299     SPF_ABS,                    // Absolute value
300     SPF_NABS                    // Negated absolute value
301   };
302   /// Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind
303   /// and providing the out parameter results if we successfully match.
304   ///
305   /// If CastOp is not nullptr, also match MIN/MAX idioms where the type does
306   /// not match that of the original select. If this is the case, the cast
307   /// operation (one of Trunc,SExt,Zext) that must be done to transform the
308   /// type of LHS and RHS into the type of V is returned in CastOp.
309   ///
310   /// For example:
311   ///   %1 = icmp slt i32 %a, i32 4
312   ///   %2 = sext i32 %a to i64
313   ///   %3 = select i1 %1, i64 %2, i64 4
314   ///
315   /// -> LHS = %a, RHS = i32 4, *CastOp = Instruction::SExt
316   ///
317   SelectPatternFlavor matchSelectPattern(Value *V, Value *&LHS, Value *&RHS,
318                                          Instruction::CastOps *CastOp = nullptr);
319
320 } // end namespace llvm
321
322 #endif