Recommit [NFC] Better encapsulation of llvm::Optional Storage
[llvm-complete.git] / include / llvm / IR / ConstantRange.h
blob86c8c30f5e4039a5307ca9ad6ead09371ea8a576
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: :
16 // [F, F) = {} = Empty set
17 // [T, F) = {T}
18 // [F, T) = {F}
19 // [T, T) = {F, T} = Full set
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
26 // Note that ConstantRange can be used to represent either signed or
27 // unsigned ranges.
29 //===----------------------------------------------------------------------===//
31 #ifndef LLVM_IR_CONSTANTRANGE_H
32 #define LLVM_IR_CONSTANTRANGE_H
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>
40 namespace llvm {
42 class MDNode;
43 class raw_ostream;
45 /// This class represents a range of values.
46 class LLVM_NODISCARD ConstantRange {
47 APInt Lower, Upper;
49 public:
50 /// Initialize a full (the default) or empty set for the specified bit width.
51 explicit ConstantRange(uint32_t BitWidth, bool isFullSet = true);
53 /// Initialize a range to hold the single specified value.
54 ConstantRange(APInt Value);
56 /// Initialize a range of values explicitly. This will assert out if
57 /// Lower==Upper and Lower != Min or Max value for its type. It will also
58 /// assert out if the two APInt's are not the same bit width.
59 ConstantRange(APInt Lower, APInt Upper);
61 /// Produce the smallest range such that all values that may satisfy the given
62 /// predicate with any value contained within Other is contained in the
63 /// returned range. Formally, this returns a superset of
64 /// 'union over all y in Other . { x : icmp op x y is true }'. If the exact
65 /// answer is not representable as a ConstantRange, the return value will be a
66 /// proper superset of the above.
67 ///
68 /// Example: Pred = ult and Other = i8 [2, 5) returns Result = [0, 4)
69 static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred,
70 const ConstantRange &Other);
72 /// Produce the largest range such that all values in the returned range
73 /// satisfy the given predicate with all values contained within Other.
74 /// Formally, this returns a subset of
75 /// 'intersection over all y in Other . { x : icmp op x y is true }'. If the
76 /// exact answer is not representable as a ConstantRange, the return value
77 /// will be a proper subset of the above.
78 ///
79 /// Example: Pred = ult and Other = i8 [2, 5) returns [0, 2)
80 static ConstantRange makeSatisfyingICmpRegion(CmpInst::Predicate Pred,
81 const ConstantRange &Other);
83 /// Produce the exact range such that all values in the returned range satisfy
84 /// the given predicate with any value contained within Other. Formally, this
85 /// returns the exact answer when the superset of 'union over all y in Other
86 /// is exactly same as the subset of intersection over all y in Other.
87 /// { x : icmp op x y is true}'.
88 ///
89 /// Example: Pred = ult and Other = i8 3 returns [0, 3)
90 static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred,
91 const APInt &Other);
93 /// Return the largest range containing all X such that "X BinOpC Y" is
94 /// guaranteed not to wrap (overflow) for all Y in Other.
95 ///
96 /// NB! The returned set does *not* contain **all** possible values of X for
97 /// which "X BinOpC Y" does not wrap -- some viable values of X may be
98 /// missing, so you cannot use this to constrain X's range. E.g. in the
99 /// fourth example, "(-2) + 1" is both nsw and nuw (so the "X" could be -2),
100 /// but (-2) is not in the set returned.
102 /// Examples:
103 /// typedef OverflowingBinaryOperator OBO;
104 /// #define MGNR makeGuaranteedNoWrapRegion
105 /// MGNR(Add, [i8 1, 2), OBO::NoSignedWrap) == [-128, 127)
106 /// MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap) == [0, -1)
107 /// MGNR(Add, [i8 0, 1), OBO::NoUnsignedWrap) == Full Set
108 /// MGNR(Add, [i8 1, 2), OBO::NoUnsignedWrap | OBO::NoSignedWrap)
109 /// == [0,INT_MAX)
110 /// MGNR(Add, [i8 -1, 6), OBO::NoSignedWrap) == [INT_MIN+1, INT_MAX-4)
111 /// MGNR(Sub, [i8 1, 2), OBO::NoSignedWrap) == [-127, 128)
112 /// MGNR(Sub, [i8 1, 2), OBO::NoUnsignedWrap) == [1, 0)
113 /// MGNR(Sub, [i8 1, 2), OBO::NoUnsignedWrap | OBO::NoSignedWrap)
114 /// == [1,INT_MAX)
115 static ConstantRange makeGuaranteedNoWrapRegion(Instruction::BinaryOps BinOp,
116 const ConstantRange &Other,
117 unsigned NoWrapKind);
119 /// Set up \p Pred and \p RHS such that
120 /// ConstantRange::makeExactICmpRegion(Pred, RHS) == *this. Return true if
121 /// successful.
122 bool getEquivalentICmp(CmpInst::Predicate &Pred, APInt &RHS) const;
124 /// Return the lower value for this range.
125 const APInt &getLower() const { return Lower; }
127 /// Return the upper value for this range.
128 const APInt &getUpper() const { return Upper; }
130 /// Get the bit width of this ConstantRange.
131 uint32_t getBitWidth() const { return Lower.getBitWidth(); }
133 /// Return true if this set contains all of the elements possible
134 /// for this data-type.
135 bool isFullSet() const;
137 /// Return true if this set contains no members.
138 bool isEmptySet() const;
140 /// Return true if this set wraps around the top of the range.
141 /// For example: [100, 8).
142 bool isWrappedSet() const;
144 /// Return true if this set wraps around the INT_MIN of
145 /// its bitwidth. For example: i8 [120, 140).
146 bool isSignWrappedSet() const;
148 /// Return true if the specified value is in the set.
149 bool contains(const APInt &Val) const;
151 /// Return true if the other range is a subset of this one.
152 bool contains(const ConstantRange &CR) const;
154 /// If this set contains a single element, return it, otherwise return null.
155 const APInt *getSingleElement() const {
156 if (Upper == Lower + 1)
157 return &Lower;
158 return nullptr;
161 /// If this set contains all but a single element, return it, otherwise return
162 /// null.
163 const APInt *getSingleMissingElement() const {
164 if (Lower == Upper + 1)
165 return &Upper;
166 return nullptr;
169 /// Return true if this set contains exactly one member.
170 bool isSingleElement() const { return getSingleElement() != nullptr; }
172 /// Return the number of elements in this set.
173 APInt getSetSize() const;
175 /// Compare set size of this range with the range CR.
176 bool isSizeStrictlySmallerThan(const ConstantRange &CR) const;
178 // Compare set size of this range with Value.
179 bool isSizeLargerThan(uint64_t MaxSize) const;
181 /// Return the largest unsigned value contained in the ConstantRange.
182 APInt getUnsignedMax() const;
184 /// Return the smallest unsigned value contained in the ConstantRange.
185 APInt getUnsignedMin() const;
187 /// Return the largest signed value contained in the ConstantRange.
188 APInt getSignedMax() const;
190 /// Return the smallest signed value contained in the ConstantRange.
191 APInt getSignedMin() const;
193 /// Return true if this range is equal to another range.
194 bool operator==(const ConstantRange &CR) const {
195 return Lower == CR.Lower && Upper == CR.Upper;
197 bool operator!=(const ConstantRange &CR) const {
198 return !operator==(CR);
201 /// Subtract the specified constant from the endpoints of this constant range.
202 ConstantRange subtract(const APInt &CI) const;
204 /// Subtract the specified range from this range (aka relative complement of
205 /// the sets).
206 ConstantRange difference(const ConstantRange &CR) const;
208 /// Return the range that results from the intersection of
209 /// this range with another range. The resultant range is guaranteed to
210 /// include all elements contained in both input ranges, and to have the
211 /// smallest possible set size that does so. Because there may be two
212 /// intersections with the same set size, A.intersectWith(B) might not
213 /// be equal to B.intersectWith(A).
214 ConstantRange intersectWith(const ConstantRange &CR) const;
216 /// Return the range that results from the union of this range
217 /// with another range. The resultant range is guaranteed to include the
218 /// elements of both sets, but may contain more. For example, [3, 9) union
219 /// [12,15) is [3, 15), which includes 9, 10, and 11, which were not included
220 /// in either set before.
221 ConstantRange unionWith(const ConstantRange &CR) const;
223 /// Return a new range representing the possible values resulting
224 /// from an application of the specified cast operator to this range. \p
225 /// BitWidth is the target bitwidth of the cast. For casts which don't
226 /// change bitwidth, it must be the same as the source bitwidth. For casts
227 /// which do change bitwidth, the bitwidth must be consistent with the
228 /// requested cast and source bitwidth.
229 ConstantRange castOp(Instruction::CastOps CastOp,
230 uint32_t BitWidth) const;
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 /// zero extended to BitWidth.
236 ConstantRange zeroExtend(uint32_t BitWidth) const;
238 /// Return a new range in the specified integer type, which must
239 /// be strictly larger than the current type. The returned range will
240 /// correspond to the possible range of values if the source range had been
241 /// sign extended to BitWidth.
242 ConstantRange signExtend(uint32_t BitWidth) const;
244 /// Return a new range in the specified integer type, which must be
245 /// strictly smaller than the current type. The returned range will
246 /// correspond to the possible range of values if the source range had been
247 /// truncated to the specified type.
248 ConstantRange truncate(uint32_t BitWidth) const;
250 /// Make this range have the bit width given by \p BitWidth. The
251 /// value is zero extended, truncated, or left alone to make it that width.
252 ConstantRange zextOrTrunc(uint32_t BitWidth) const;
254 /// Make this range have the bit width given by \p BitWidth. The
255 /// value is sign extended, truncated, or left alone to make it that width.
256 ConstantRange sextOrTrunc(uint32_t BitWidth) const;
258 /// Return a new range representing the possible values resulting
259 /// from an application of the specified binary operator to an left hand side
260 /// of this range and a right hand side of \p Other.
261 ConstantRange binaryOp(Instruction::BinaryOps BinOp,
262 const ConstantRange &Other) const;
264 /// Return a new range representing the possible values resulting
265 /// from an addition of a value in this range and a value in \p Other.
266 ConstantRange add(const ConstantRange &Other) const;
268 /// Return a new range representing the possible values resulting from a
269 /// known NSW addition of a value in this range and \p Other constant.
270 ConstantRange addWithNoSignedWrap(const APInt &Other) const;
272 /// Return a new range representing the possible values resulting
273 /// from a subtraction of a value in this range and a value in \p Other.
274 ConstantRange sub(const ConstantRange &Other) const;
276 /// Return a new range representing the possible values resulting
277 /// from a multiplication of a value in this range and a value in \p Other,
278 /// treating both this and \p Other as unsigned ranges.
279 ConstantRange multiply(const ConstantRange &Other) const;
281 /// Return a new range representing the possible values resulting
282 /// from a signed maximum of a value in this range and a value in \p Other.
283 ConstantRange smax(const ConstantRange &Other) const;
285 /// Return a new range representing the possible values resulting
286 /// from an unsigned maximum of a value in this range and a value in \p Other.
287 ConstantRange umax(const ConstantRange &Other) const;
289 /// Return a new range representing the possible values resulting
290 /// from a signed minimum of a value in this range and a value in \p Other.
291 ConstantRange smin(const ConstantRange &Other) const;
293 /// Return a new range representing the possible values resulting
294 /// from an unsigned minimum of a value in this range and a value in \p Other.
295 ConstantRange umin(const ConstantRange &Other) const;
297 /// Return a new range representing the possible values resulting
298 /// from an unsigned division of a value in this range and a value in
299 /// \p Other.
300 ConstantRange udiv(const ConstantRange &Other) const;
302 /// Return a new range representing the possible values resulting
303 /// from a binary-and of a value in this range by a value in \p Other.
304 ConstantRange binaryAnd(const ConstantRange &Other) const;
306 /// Return a new range representing the possible values resulting
307 /// from a binary-or of a value in this range by a value in \p Other.
308 ConstantRange binaryOr(const ConstantRange &Other) const;
310 /// Return a new range representing the possible values resulting
311 /// from a left shift of a value in this range by a value in \p Other.
312 /// TODO: This isn't fully implemented yet.
313 ConstantRange shl(const ConstantRange &Other) const;
315 /// Return a new range representing the possible values resulting from a
316 /// logical right shift of a value in this range and a value in \p Other.
317 ConstantRange lshr(const ConstantRange &Other) const;
319 /// Return a new range representing the possible values resulting from a
320 /// arithmetic right shift of a value in this range and a value in \p Other.
321 ConstantRange ashr(const ConstantRange &Other) const;
323 /// Return a new range that is the logical not of the current set.
324 ConstantRange inverse() const;
326 /// Print out the bounds to a stream.
327 void print(raw_ostream &OS) const;
329 /// Allow printing from a debugger easily.
330 void dump() const;
333 inline raw_ostream &operator<<(raw_ostream &OS, const ConstantRange &CR) {
334 CR.print(OS);
335 return OS;
338 /// Parse out a conservative ConstantRange from !range metadata.
340 /// E.g. if RangeMD is !{i32 0, i32 10, i32 15, i32 20} then return [0, 20).
341 ConstantRange getConstantRangeFromMetadata(const MDNode &RangeMD);
343 } // end namespace llvm
345 #endif // LLVM_IR_CONSTANTRANGE_H