1 //===- ConstantRange.h - Represent a range ----------------------*- 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 // Represent a range of possible values that may occur when the program is run
11 // for an integral value.  This keeps track of a lower and upper bound for the
12 // constant, which MAY wrap around the end of the numeric range.  To do this, it
13 // keeps track of a [lower, upper) bound, which specifies an interval just like
14 // STL iterators.  When used with boolean values, the following are important
15 // ranges: :
16 //
17 //  [F, F) = {}     = Empty set
18 //  [T, F) = {T}
19 //  [F, T) = {F}
20 //  [T, T) = {F, T} = Full set
21 //
22 // The other integral ranges use min/max values for special range values. For
23 // example, for 8-bit types, it uses:
24 // [0, 0)     = {}       = Empty set
25 // [255, 255) = {0..255} = Full Set
26 //
27 // Note that ConstantRange can be used to represent either signed or
28 // unsigned ranges.
29 //
30 //===----------------------------------------------------------------------===//
31 
32 #ifndef LLVM_IR_CONSTANTRANGE_H
33 #define LLVM_IR_CONSTANTRANGE_H
34 
35 #include "llvm/ADT/APInt.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/Support/DataTypes.h"
38 
39 namespace llvm {
40 
41 /// This class represents a range of values.
42 ///
43 class ConstantRange {
44   APInt Lower, Upper;
45 
46   // If we have move semantics, pass APInts by value and move them into place.
47   typedef APInt APIntMoveTy;
48 
49 public:
50   /// Initialize a full (the default) or empty set for the specified bit width.
51   ///
52   explicit ConstantRange(uint32_t BitWidth, bool isFullSet = true);
53 
54   /// Initialize a range to hold the single specified value.
55   ///
56   ConstantRange(APIntMoveTy Value);
57 
58   /// @brief Initialize a range of values explicitly. This will assert out if
59   /// Lower==Upper and Lower != Min or Max value for its type. It will also
60   /// assert out if the two APInt's are not the same bit width.
61   ConstantRange(APIntMoveTy Lower, APIntMoveTy Upper);
62 
63   /// Produce the smallest range such that all values that may satisfy the given
64   /// predicate with any value contained within Other is contained in the
65   /// returned range.  Formally, this returns a superset of
66   /// 'union over all y in Other . { x : icmp op x y is true }'.  If the exact
67   /// answer is not representable as a ConstantRange, the return value will be a
68   /// proper superset of the above.
69   ///
70   /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
71   static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
72                                              const ConstantRange &Other);
73 
74   /// Produce the largest range such that all values in the returned range
75   /// satisfy the given predicate with all values contained within Other.
76   /// Formally, this returns a subset of
77   /// 'intersection over all y in Other . { x : icmp op x y is true }'.  If the
78   /// exact answer is not representable as a ConstantRange, the return value
79   /// will be a proper subset of the above.
80   ///
81   /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
82   static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
83                                                 const ConstantRange &Other);
84 
85   /// Produce the exact range such that all values in the returned range satisfy
86   /// the given predicate with any value contained within Other. Formally, this
87   /// returns the exact answer when the superset of 'union over all y in Other
88   /// is exactly same as the subset of intersection over all y in Other.
89   /// { x : icmp op x y is true}'.
90   ///
91   /// Example: Pred = ult and Other = i8 3 returns [0, 3)
92   static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
93                                            const APInt &Other);
94 
95   /// Return the largest range containing all X such that "X BinOpC Y" is
96   /// guaranteed not to wrap (overflow) for all Y in Other.
97   ///
98   /// NB! The returned set does *not* contain **all** possible values of X for
99   /// which "X BinOpC Y" does not wrap -- some viable values of X may be
100   /// missing, so you cannot use this to contrain X's range.  E.g. in the last
101   /// example, "(-2) + 1" is both nsw and nuw (so the "X" could be -2), but (-2)
102   /// is not in the set returned.
103   ///
104   /// Examples:
105   ///  typedef OverflowingBinaryOperator OBO;
106   ///  #define MGNR makeGuaranteedNoWrapRegion
107   ///  MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
108   ///  MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
109   ///  MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
110   ///  MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap | OBO::NoSignedWrap)
111   ///    == [0,INT_MAX)
112   ///  MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
113   static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
114                                                   const ConstantRange &Other,
115                                                   unsigned NoWrapKind);
116 
117   /// Set up \p Pred and \p RHS such that
118   /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this.  Return true if
119   /// successful.
120   bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
121 
122   /// Return the lower value for this range.
123   ///
getLower()124   const APInt &getLower() const { return Lower; }
125 
126   /// Return the upper value for this range.
127   ///
getUpper()128   const APInt &getUpper() const { return Upper; }
129 
130   /// Get the bit width of this ConstantRange.
131   ///
getBitWidth()132   uint32_t getBitWidth() const { return Lower.getBitWidth(); }
133 
134   /// Return true if this set contains all of the elements possible
135   /// for this data-type.
136   ///
137   bool isFullSet() const;
138 
139   /// Return true if this set contains no members.
140   ///
141   bool isEmptySet() const;
142 
143   /// Return true if this set wraps around the top of the range.
144   /// For example: [100, 8).
145   ///
146   bool isWrappedSet() const;
147 
148   /// Return true if this set wraps around the INT_MIN of
149   /// its bitwidth. For example: i8 [120, 140).
150   ///
151   bool isSignWrappedSet() const;
152 
153   /// Return true if the specified value is in the set.
154   ///
155   bool contains(const APInt &Val) const;
156 
157   /// Return true if the other range is a subset of this one.
158   ///
159   bool contains(const ConstantRange &CR) const;
160 
161   /// If this set contains a single element, return it, otherwise return null.
162   ///
getSingleElement()163   const APInt *getSingleElement() const {
164     if (Upper == Lower + 1)
165       return &Lower;
166     return nullptr;
167   }
168 
169   /// Return true if this set contains exactly one member.
170   ///
isSingleElement()171   bool isSingleElement() const { return getSingleElement() != nullptr; }
172 
173   /// Return the number of elements in this set.
174   ///
175   APInt getSetSize() const;
176 
177   /// Return the largest unsigned value contained in the ConstantRange.
178   ///
179   APInt getUnsignedMax() const;
180 
181   /// Return the smallest unsigned value contained in the ConstantRange.
182   ///
183   APInt getUnsignedMin() const;
184 
185   /// Return the largest signed value contained in the ConstantRange.
186   ///
187   APInt getSignedMax() const;
188 
189   /// Return the smallest signed value contained in the ConstantRange.
190   ///
191   APInt getSignedMin() const;
192 
193   /// Return true if this range is equal to another range.
194   ///
195   bool operator==(const ConstantRange &CR) const {
196     return Lower == CR.Lower && Upper == CR.Upper;
197   }
198   bool operator!=(const ConstantRange &CR) const {
199     return !operator==(CR);
200   }
201 
202   /// Subtract the specified constant from the endpoints of this constant range.
203   ConstantRange subtract(const APInt &CI) const;
204 
205   /// \brief Subtract the specified range from this range (aka relative
206   /// complement of the sets).
207   ConstantRange difference(const ConstantRange &CR) const;
208 
209   /// Return the range that results from the intersection of
210   /// this range with another range.  The resultant range is guaranteed to
211   /// include all elements contained in both input ranges, and to have the
212   /// smallest possible set size that does so.  Because there may be two
213   /// intersections with the same set size, A.intersectWith(B) might not
214   /// be equal to B.intersectWith(A).
215   ///
216   ConstantRange intersectWith(const ConstantRange &CR) const;
217 
218   /// Return the range that results from the union of this range
219   /// with another range.  The resultant range is guaranteed to include the
220   /// elements of both sets, but may contain more.  For example, [3, 9) union
221   /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
222   /// in either set before.
223   ///
224   ConstantRange unionWith(const ConstantRange &CR) const;
225 
226   /// Return a new range in the specified integer type, which must
227   /// be strictly larger than the current type.  The returned range will
228   /// correspond to the possible range of values if the source range had been
229   /// zero extended to BitWidth.
230   ConstantRange zeroExtend(uint32_t BitWidth) const;
231 
232   /// Return a new range in the specified integer type, which must
233   /// be strictly larger than the current type.  The returned range will
234   /// correspond to the possible range of values if the source range had been
235   /// sign extended to BitWidth.
236   ConstantRange signExtend(uint32_t BitWidth) const;
237 
238   /// Return a new range in the specified integer type, which must be
239   /// strictly smaller than the current type.  The returned range will
240   /// correspond to the possible range of values if the source range had been
241   /// truncated to the specified type.
242   ConstantRange truncate(uint32_t BitWidth) const;
243 
244   /// Make this range have the bit width given by \p BitWidth. The
245   /// value is zero extended, truncated, or left alone to make it that width.
246   ConstantRange zextOrTrunc(uint32_t BitWidth) const;
247 
248   /// Make this range have the bit width given by \p BitWidth. The
249   /// value is sign extended, truncated, or left alone to make it that width.
250   ConstantRange sextOrTrunc(uint32_t BitWidth) const;
251 
252   /// Return a new range representing the possible values resulting
253   /// from an addition of a value in this range and a value in \p Other.
254   ConstantRange add(const ConstantRange &Other) const;
255 
256   /// Return a new range representing the possible values resulting
257   /// from a subtraction of a value in this range and a value in \p Other.
258   ConstantRange sub(const ConstantRange &Other) const;
259 
260   /// Return a new range representing the possible values resulting
261   /// from a multiplication of a value in this range and a value in \p Other,
262   /// treating both this and \p Other as unsigned ranges.
263   ConstantRange multiply(const ConstantRange &Other) const;
264 
265   /// Return a new range representing the possible values resulting
266   /// from a signed maximum of a value in this range and a value in \p Other.
267   ConstantRange smax(const ConstantRange &Other) const;
268 
269   /// Return a new range representing the possible values resulting
270   /// from an unsigned maximum of a value in this range and a value in \p Other.
271   ConstantRange umax(const ConstantRange &Other) const;
272 
273   /// Return a new range representing the possible values resulting
274   /// from a signed minimum of a value in this range and a value in \p Other.
275   ConstantRange smin(const ConstantRange &Other) const;
276 
277   /// Return a new range representing the possible values resulting
278   /// from an unsigned minimum of a value in this range and a value in \p Other.
279   ConstantRange umin(const ConstantRange &Other) const;
280 
281   /// Return a new range representing the possible values resulting
282   /// from an unsigned division of a value in this range and a value in
283   /// \p Other.
284   ConstantRange udiv(const ConstantRange &Other) const;
285 
286   /// Return a new range representing the possible values resulting
287   /// from a binary-and of a value in this range by a value in \p Other.
288   ConstantRange binaryAnd(const ConstantRange &Other) const;
289 
290   /// Return a new range representing the possible values resulting
291   /// from a binary-or of a value in this range by a value in \p Other.
292   ConstantRange binaryOr(const ConstantRange &Other) const;
293 
294   /// Return a new range representing the possible values resulting
295   /// from a left shift of a value in this range by a value in \p Other.
296   /// TODO: This isn't fully implemented yet.
297   ConstantRange shl(const ConstantRange &Other) const;
298 
299   /// Return a new range representing the possible values resulting from a
300   /// logical right shift of a value in this range and a value in \p Other.
301   ConstantRange lshr(const ConstantRange &Other) const;
302 
303   /// Return a new range that is the logical not of the current set.
304   ///
305   ConstantRange inverse() const;
306 
307   /// Print out the bounds to a stream.
308   ///
309   void print(raw_ostream &OS) const;
310 
311   /// Allow printing from a debugger easily.
312   ///
313   void dump() const;
314 };
315 
316 inline raw_ostream &operator<<(raw_ostream &OS, const ConstantRange &CR) {
317   CR.print(OS);
318   return OS;
319 }
320 
321 } // End llvm namespace
322 
323 #endif
324