LLVM  9.0.0svn
ConstantRange.h
Go to the documentation of this file.
1 //===- ConstantRange.h - Represent a range ----------------------*- 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 // Represent a range of possible values that may occur when the program is run
10 // for an integral value. This keeps track of a lower and upper bound for the
11 // constant, which MAY wrap around the end of the numeric range. To do this, it
12 // keeps track of a [lower, upper) bound, which specifies an interval just like
13 // STL iterators. When used with boolean values, the following are important
14 // ranges: :
15 //
16 // [F, F) = {} = Empty set
17 // [T, F) = {T}
18 // [F, T) = {F}
19 // [T, T) = {F, T} = Full set
20 //
21 // The other integral ranges use min/max values for special range values. For
22 // example, for 8-bit types, it uses:
23 // [0, 0) = {} = Empty set
24 // [255, 255) = {0..255} = Full Set
25 //
26 // Note that ConstantRange can be used to represent either signed or
27 // unsigned ranges.
28 //
29 //===----------------------------------------------------------------------===//
30 
31 #ifndef LLVM_IR_CONSTANTRANGE_H
32 #define LLVM_IR_CONSTANTRANGE_H
33 
34 #include "llvm/ADT/APInt.h"
35 #include "llvm/IR/InstrTypes.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/Support/Compiler.h"
38 #include <cstdint>
39 
40 namespace llvm {
41 
42 class MDNode;
43 class raw_ostream;
44 struct KnownBits;
45 
46 /// This class represents a range of values.
48  APInt Lower, Upper;
49 
50  /// Create empty constant range with same bitwidth.
51  ConstantRange getEmpty() const {
52  return ConstantRange(getBitWidth(), false);
53  }
54 
55  /// Create full constant range with same bitwidth.
56  ConstantRange getFull() const {
57  return ConstantRange(getBitWidth(), true);
58  }
59 
60 public:
61  /// Initialize a full or empty set for the specified bit width.
62  explicit ConstantRange(uint32_t BitWidth, bool isFullSet);
63 
64  /// Initialize a range to hold the single specified value.
66 
67  /// Initialize a range of values explicitly. This will assert out if
68  /// Lower==Upper and Lower != Min or Max value for its type. It will also
69  /// assert out if the two APInt's are not the same bit width.
70  ConstantRange(APInt Lower, APInt Upper);
71 
72  /// Create empty constant range with the given bit width.
73  static ConstantRange getEmpty(uint32_t BitWidth) {
74  return ConstantRange(BitWidth, false);
75  }
76 
77  /// Create full constant range with the given bit width.
78  static ConstantRange getFull(uint32_t BitWidth) {
79  return ConstantRange(BitWidth, true);
80  }
81 
82  /// Initialize a range based on a known bits constraint. The IsSigned flag
83  /// indicates whether the constant range should not wrap in the signed or
84  /// unsigned domain.
85  static ConstantRange fromKnownBits(const KnownBits &Known, bool IsSigned);
86 
87  /// Produce the smallest range such that all values that may satisfy the given
88  /// predicate with any value contained within Other is contained in the
89  /// returned range. Formally, this returns a superset of
90  /// 'union over all y in Other . { x : icmp op x y is true }'. If the exact
91  /// answer is not representable as a ConstantRange, the return value will be a
92  /// proper superset of the above.
93  ///
94  /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
95  static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
96  const ConstantRange &Other);
97 
98  /// Produce the largest range such that all values in the returned range
99  /// satisfy the given predicate with all values contained within Other.
100  /// Formally, this returns a subset of
101  /// 'intersection over all y in Other . { x : icmp op x y is true }'. If the
102  /// exact answer is not representable as a ConstantRange, the return value
103  /// will be a proper subset of the above.
104  ///
105  /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
106  static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
107  const ConstantRange &Other);
108 
109  /// Produce the exact range such that all values in the returned range satisfy
110  /// the given predicate with any value contained within Other. Formally, this
111  /// returns the exact answer when the superset of 'union over all y in Other
112  /// is exactly same as the subset of intersection over all y in Other.
113  /// { x : icmp op x y is true}'.
114  ///
115  /// Example: Pred = ult and Other = i8 3 returns [0, 3)
116  static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
117  const APInt &Other);
118 
119  /// Return the exact range containing all X such that "X BinOpC Y" is
120  /// guaranteed not to wrap (overflow) for all Y in Other.
121  ///
122  /// NoWrapKind must be one of OBO::NoUnsignedWrap or OBO::NoSignedWrap.
123  ///
124  /// Examples:
125  /// typedef OverflowingBinaryOperator OBO;
126  /// #define MGNR makeGuaranteedNoWrapRegion
127  /// MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
128  /// MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
129  /// MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
130  /// MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
131  /// MGNR(Sub, [i8 1, 2), OBO::NoSignedWrap) == [-127, 128)
132  /// MGNR(Sub, [i8 1, 2), OBO::NoUnsignedWrap) == [1, 0)
133  static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
134  const ConstantRange &Other,
135  unsigned NoWrapKind);
136 
137  /// Set up \p Pred and \p RHS such that
138  /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this. Return true if
139  /// successful.
140  bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
141 
142  /// Return the lower value for this range.
143  const APInt &getLower() const { return Lower; }
144 
145  /// Return the upper value for this range.
146  const APInt &getUpper() const { return Upper; }
147 
148  /// Get the bit width of this ConstantRange.
149  uint32_t getBitWidth() const { return Lower.getBitWidth(); }
150 
151  /// Return true if this set contains all of the elements possible
152  /// for this data-type.
153  bool isFullSet() const;
154 
155  /// Return true if this set contains no members.
156  bool isEmptySet() const;
157 
158  /// Return true if this set wraps around the unsigned domain. Special cases:
159  /// * Empty set: Not wrapped.
160  /// * Full set: Not wrapped.
161  /// * [X, 0) == [X, Max]: Not wrapped.
162  bool isWrappedSet() const;
163 
164  /// Return true if the exclusive upper bound wraps around the unsigned
165  /// domain. Special cases:
166  /// * Empty set: Not wrapped.
167  /// * Full set: Not wrapped.
168  /// * [X, 0): Wrapped.
169  bool isUpperWrapped() const;
170 
171  /// Return true if this set wraps around the signed domain. Special cases:
172  /// * Empty set: Not wrapped.
173  /// * Full set: Not wrapped.
174  /// * [X, SignedMin) == [X, SignedMax]: Not wrapped.
175  bool isSignWrappedSet() const;
176 
177  /// Return true if the (exclusive) upper bound wraps around the signed
178  /// domain. Special cases:
179  /// * Empty set: Not wrapped.
180  /// * Full set: Not wrapped.
181  /// * [X, SignedMin): Wrapped.
182  bool isUpperSignWrapped() const;
183 
184  /// Return true if the specified value is in the set.
185  bool contains(const APInt &Val) const;
186 
187  /// Return true if the other range is a subset of this one.
188  bool contains(const ConstantRange &CR) const;
189 
190  /// If this set contains a single element, return it, otherwise return null.
191  const APInt *getSingleElement() const {
192  if (Upper == Lower + 1)
193  return &Lower;
194  return nullptr;
195  }
196 
197  /// If this set contains all but a single element, return it, otherwise return
198  /// null.
200  if (Lower == Upper + 1)
201  return &Upper;
202  return nullptr;
203  }
204 
205  /// Return true if this set contains exactly one member.
206  bool isSingleElement() const { return getSingleElement() != nullptr; }
207 
208  /// Compare set size of this range with the range CR.
209  bool isSizeStrictlySmallerThan(const ConstantRange &CR) const;
210 
211  /// Compare set size of this range with Value.
212  bool isSizeLargerThan(uint64_t MaxSize) const;
213 
214  /// Return true if all values in this range are negative.
215  bool isAllNegative() const;
216 
217  /// Return true if all values in this range are non-negative.
218  bool isAllNonNegative() const;
219 
220  /// Return the largest unsigned value contained in the ConstantRange.
221  APInt getUnsignedMax() const;
222 
223  /// Return the smallest unsigned value contained in the ConstantRange.
224  APInt getUnsignedMin() const;
225 
226  /// Return the largest signed value contained in the ConstantRange.
227  APInt getSignedMax() const;
228 
229  /// Return the smallest signed value contained in the ConstantRange.
230  APInt getSignedMin() const;
231 
232  /// Return true if this range is equal to another range.
233  bool operator==(const ConstantRange &CR) const {
234  return Lower == CR.Lower && Upper == CR.Upper;
235  }
236  bool operator!=(const ConstantRange &CR) const {
237  return !operator==(CR);
238  }
239 
240  /// Subtract the specified constant from the endpoints of this constant range.
241  ConstantRange subtract(const APInt &CI) const;
242 
243  /// Subtract the specified range from this range (aka relative complement of
244  /// the sets).
245  ConstantRange difference(const ConstantRange &CR) const;
246 
247  /// If represented precisely, the result of some range operations may consist
248  /// of multiple disjoint ranges. As only a single range may be returned, any
249  /// range covering these disjoint ranges constitutes a valid result, but some
250  /// may be more useful than others depending on context. The preferred range
251  /// type specifies whether a range that is non-wrapping in the unsigned or
252  /// signed domain, or has the smallest size, is preferred. If a signedness is
253  /// preferred but all ranges are non-wrapping or all wrapping, then the
254  /// smallest set size is preferred. If there are multiple smallest sets, any
255  /// one of them may be returned.
256  enum PreferredRangeType { Smallest, Unsigned, Signed };
257 
258  /// Return the range that results from the intersection of this range with
259  /// another range. If the intersection is disjoint, such that two results
260  /// are possible, the preferred range is determined by the PreferredRangeType.
261  ConstantRange intersectWith(const ConstantRange &CR,
262  PreferredRangeType Type = Smallest) const;
263 
264  /// Return the range that results from the union of this range
265  /// with another range. The resultant range is guaranteed to include the
266  /// elements of both sets, but may contain more. For example, [3, 9) union
267  /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
268  /// in either set before.
269  ConstantRange unionWith(const ConstantRange &CR,
270  PreferredRangeType Type = Smallest) const;
271 
272  /// Return a new range representing the possible values resulting
273  /// from an application of the specified cast operator to this range. \p
274  /// BitWidth is the target bitwidth of the cast. For casts which don't
275  /// change bitwidth, it must be the same as the source bitwidth. For casts
276  /// which do change bitwidth, the bitwidth must be consistent with the
277  /// requested cast and source bitwidth.
278  ConstantRange castOp(Instruction::CastOps CastOp,
279  uint32_t BitWidth) const;
280 
281  /// Return a new range in the specified integer type, which must
282  /// be strictly larger than the current type. The returned range will
283  /// correspond to the possible range of values if the source range had been
284  /// zero extended to BitWidth.
285  ConstantRange zeroExtend(uint32_t BitWidth) const;
286 
287  /// Return a new range in the specified integer type, which must
288  /// be strictly larger than the current type. The returned range will
289  /// correspond to the possible range of values if the source range had been
290  /// sign extended to BitWidth.
291  ConstantRange signExtend(uint32_t BitWidth) const;
292 
293  /// Return a new range in the specified integer type, which must be
294  /// strictly smaller than the current type. The returned range will
295  /// correspond to the possible range of values if the source range had been
296  /// truncated to the specified type.
297  ConstantRange truncate(uint32_t BitWidth) const;
298 
299  /// Make this range have the bit width given by \p BitWidth. The
300  /// value is zero extended, truncated, or left alone to make it that width.
301  ConstantRange zextOrTrunc(uint32_t BitWidth) const;
302 
303  /// Make this range have the bit width given by \p BitWidth. The
304  /// value is sign extended, truncated, or left alone to make it that width.
305  ConstantRange sextOrTrunc(uint32_t BitWidth) const;
306 
307  /// Return a new range representing the possible values resulting
308  /// from an application of the specified binary operator to an left hand side
309  /// of this range and a right hand side of \p Other.
310  ConstantRange binaryOp(Instruction::BinaryOps BinOp,
311  const ConstantRange &Other) const;
312 
313  /// Return a new range representing the possible values resulting
314  /// from an addition of a value in this range and a value in \p Other.
315  ConstantRange add(const ConstantRange &Other) const;
316 
317  /// Return a new range representing the possible values resulting from a
318  /// known NSW addition of a value in this range and \p Other constant.
319  ConstantRange addWithNoSignedWrap(const APInt &Other) const;
320 
321  /// Return a new range representing the possible values resulting
322  /// from a subtraction of a value in this range and a value in \p Other.
323  ConstantRange sub(const ConstantRange &Other) const;
324 
325  /// Return a new range representing the possible values resulting
326  /// from a multiplication of a value in this range and a value in \p Other,
327  /// treating both this and \p Other as unsigned ranges.
328  ConstantRange multiply(const ConstantRange &Other) const;
329 
330  /// Return a new range representing the possible values resulting
331  /// from a signed maximum of a value in this range and a value in \p Other.
332  ConstantRange smax(const ConstantRange &Other) const;
333 
334  /// Return a new range representing the possible values resulting
335  /// from an unsigned maximum of a value in this range and a value in \p Other.
336  ConstantRange umax(const ConstantRange &Other) const;
337 
338  /// Return a new range representing the possible values resulting
339  /// from a signed minimum of a value in this range and a value in \p Other.
340  ConstantRange smin(const ConstantRange &Other) const;
341 
342  /// Return a new range representing the possible values resulting
343  /// from an unsigned minimum of a value in this range and a value in \p Other.
344  ConstantRange umin(const ConstantRange &Other) const;
345 
346  /// Return a new range representing the possible values resulting
347  /// from an unsigned division of a value in this range and a value in
348  /// \p Other.
349  ConstantRange udiv(const ConstantRange &Other) const;
350 
351  /// Return a new range representing the possible values resulting
352  /// from a binary-and of a value in this range by a value in \p Other.
353  ConstantRange binaryAnd(const ConstantRange &Other) const;
354 
355  /// Return a new range representing the possible values resulting
356  /// from a binary-or of a value in this range by a value in \p Other.
357  ConstantRange binaryOr(const ConstantRange &Other) const;
358 
359  /// Return a new range representing the possible values resulting
360  /// from a left shift of a value in this range by a value in \p Other.
361  /// TODO: This isn't fully implemented yet.
362  ConstantRange shl(const ConstantRange &Other) const;
363 
364  /// Return a new range representing the possible values resulting from a
365  /// logical right shift of a value in this range and a value in \p Other.
366  ConstantRange lshr(const ConstantRange &Other) const;
367 
368  /// Return a new range representing the possible values resulting from a
369  /// arithmetic right shift of a value in this range and a value in \p Other.
370  ConstantRange ashr(const ConstantRange &Other) const;
371 
372  /// Return a new range that is the logical not of the current set.
373  ConstantRange inverse() const;
374 
375  /// Represents whether an operation on the given constant range is known to
376  /// always or never overflow.
378 
379  /// Return whether unsigned add of the two ranges always/never overflows.
380  OverflowResult unsignedAddMayOverflow(const ConstantRange &Other) const;
381 
382  /// Return whether signed add of the two ranges always/never overflows.
383  OverflowResult signedAddMayOverflow(const ConstantRange &Other) const;
384 
385  /// Return whether unsigned sub of the two ranges always/never overflows.
386  OverflowResult unsignedSubMayOverflow(const ConstantRange &Other) const;
387 
388  /// Return whether signed sub of the two ranges always/never overflows.
389  OverflowResult signedSubMayOverflow(const ConstantRange &Other) const;
390 
391  /// Return whether unsigned mul of the two ranges always/never overflows.
392  OverflowResult unsignedMulMayOverflow(const ConstantRange &Other) const;
393 
394  /// Print out the bounds to a stream.
395  void print(raw_ostream &OS) const;
396 
397  /// Allow printing from a debugger easily.
398  void dump() const;
399 };
400 
402  CR.print(OS);
403  return OS;
404 }
405 
406 /// Parse out a conservative ConstantRange from !range metadata.
407 ///
408 /// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
410 
411 } // end namespace llvm
412 
413 #endif // LLVM_IR_CONSTANTRANGE_H
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
const APInt & getUpper() const
Return the upper value for this range.
const APInt * getSingleElement() const
If this set contains a single element, return it, otherwise return null.
Metadata node.
Definition: Metadata.h:863
static ConstantRange getEmpty(uint32_t BitWidth)
Create empty constant range with the given bit width.
Definition: ConstantRange.h:73
void print(raw_ostream &OS) const
Print out the bounds to a stream.
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
return AArch64::GPR64RegClass contains(Reg)
uint32_t getBitWidth() const
Get the bit width of this ConstantRange.
ELFYAML::ELF_STO Other
Definition: ELFYAML.cpp:849
This file implements a class to represent arbitrary precision integral constant values and operations...
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition: APInt.h:2109
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2104
static ConstantRange getFull(uint32_t BitWidth)
Create full constant range with the given bit width.
Definition: ConstantRange.h:78
OverflowResult
Represents whether an operation on the given constant range is known to always or never overflow...
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD)
Parse out a conservative ConstantRange from !range metadata.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
bool operator!=(const ConstantRange &CR) const
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition: APInt.h:2114
This class represents a range of values.
Definition: ConstantRange.h:47
Class for arbitrary precision integers.
Definition: APInt.h:69
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition: APInt.h:2119
const APInt * getSingleMissingElement() const
If this set contains all but a single element, return it, otherwise return null.
const APInt & getLower() const
Return the lower value for this range.
raw_ostream & operator<<(raw_ostream &OS, const APInt &I)
Definition: APInt.h:2038
#define LLVM_NODISCARD
LLVM_NODISCARD - Warn if a type or return value is discarded.
Definition: Compiler.h:128
bool isSingleElement() const
Return true if this set contains exactly one member.
LLVM Value Representation.
Definition: Value.h:72
PreferredRangeType
If represented precisely, the result of some range operations may consist of multiple disjoint ranges...
bool operator==(const ConstantRange &CR) const
Return true if this range is equal to another range.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
bool operator==(uint64_t V1, const APInt &V2)
Definition: APInt.h:1966