ConstantRange.cpp revision fc33d30446843009b0eadf63c0bfca35ae2baac6
1//===-- ConstantRange.cpp - ConstantRange implementation ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source 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 (other integral ranges use min/max values for special range values):
16//
17//  [F, F) = {}     = Empty set
18//  [T, F) = {T}
19//  [F, T) = {F}
20//  [T, T) = {F, T} = Full set
21//
22//===----------------------------------------------------------------------===//
23
24#include "llvm/Support/ConstantRange.h"
25#include "llvm/Constants.h"
26#include "llvm/Instruction.h"
27#include "llvm/Type.h"
28using namespace llvm;
29
30static ConstantIntegral *Next(ConstantIntegral *CI) {
31  if (CI->getType() == Type::BoolTy)
32    return CI == ConstantBool::True ? ConstantBool::False : ConstantBool::True;
33
34  Constant *Result = ConstantExpr::getAdd(CI,
35                                          ConstantInt::get(CI->getType(), 1));
36  return cast<ConstantIntegral>(Result);
37}
38
39static bool LT(ConstantIntegral *A, ConstantIntegral *B) {
40  Constant *C = ConstantExpr::getSetLT(A, B);
41  assert(isa<ConstantBool>(C) && "Constant folding of integrals not impl??");
42  return cast<ConstantBool>(C)->getValue();
43}
44
45static bool LTE(ConstantIntegral *A, ConstantIntegral *B) {
46  Constant *C = ConstantExpr::getSetLE(A, B);
47  assert(isa<ConstantBool>(C) && "Constant folding of integrals not impl??");
48  return cast<ConstantBool>(C)->getValue();
49}
50
51static bool GT(ConstantIntegral *A, ConstantIntegral *B) { return LT(B, A); }
52
53static ConstantIntegral *Min(ConstantIntegral *A, ConstantIntegral *B) {
54  return LT(A, B) ? A : B;
55}
56static ConstantIntegral *Max(ConstantIntegral *A, ConstantIntegral *B) {
57  return GT(A, B) ? A : B;
58}
59
60/// Initialize a full (the default) or empty set for the specified type.
61///
62ConstantRange::ConstantRange(const Type *Ty, bool Full) {
63  assert(Ty->isIntegral() &&
64         "Cannot make constant range of non-integral type!");
65  if (Full)
66    Lower = Upper = ConstantIntegral::getMaxValue(Ty);
67  else
68    Lower = Upper = ConstantIntegral::getMinValue(Ty);
69}
70
71/// Initialize a range to hold the single specified value.
72///
73ConstantRange::ConstantRange(Constant *V)
74  : Lower(cast<ConstantIntegral>(V)), Upper(Next(cast<ConstantIntegral>(V))) {
75}
76
77/// Initialize a range of values explicitly... this will assert out if
78/// Lower==Upper and Lower != Min or Max for its type (or if the two constants
79/// have different types)
80///
81ConstantRange::ConstantRange(Constant *L, Constant *U)
82  : Lower(cast<ConstantIntegral>(L)), Upper(cast<ConstantIntegral>(U)) {
83  assert(Lower->getType() == Upper->getType() &&
84         "Incompatible types for ConstantRange!");
85
86  // Make sure that if L & U are equal that they are either Min or Max...
87  assert((L != U || (L == ConstantIntegral::getMaxValue(L->getType()) ||
88                     L == ConstantIntegral::getMinValue(L->getType()))) &&
89         "Lower == Upper, but they aren't min or max for type!");
90}
91
92/// Initialize a set of values that all satisfy the condition with C.
93///
94ConstantRange::ConstantRange(unsigned SetCCOpcode, ConstantIntegral *C) {
95  switch (SetCCOpcode) {
96  default: assert(0 && "Invalid SetCC opcode to ConstantRange ctor!");
97  case Instruction::SetEQ: Lower = C; Upper = Next(C); return;
98  case Instruction::SetNE: Upper = C; Lower = Next(C); return;
99  case Instruction::SetLT:
100    Lower = ConstantIntegral::getMinValue(C->getType());
101    Upper = C;
102    return;
103  case Instruction::SetGT:
104    Lower = Next(C);
105    Upper = ConstantIntegral::getMinValue(C->getType());  // Min = Next(Max)
106    return;
107  case Instruction::SetLE:
108    Lower = ConstantIntegral::getMinValue(C->getType());
109    Upper = Next(C);
110    return;
111  case Instruction::SetGE:
112    Lower = C;
113    Upper = ConstantIntegral::getMinValue(C->getType());  // Min = Next(Max)
114    return;
115  }
116}
117
118/// getType - Return the LLVM data type of this range.
119///
120const Type *ConstantRange::getType() const { return Lower->getType(); }
121
122/// isFullSet - Return true if this set contains all of the elements possible
123/// for this data-type
124bool ConstantRange::isFullSet() const {
125  return Lower == Upper && Lower == ConstantIntegral::getMaxValue(getType());
126}
127
128/// isEmptySet - Return true if this set contains no members.
129///
130bool ConstantRange::isEmptySet() const {
131  return Lower == Upper && Lower == ConstantIntegral::getMinValue(getType());
132}
133
134/// isWrappedSet - Return true if this set wraps around the top of the range,
135/// for example: [100, 8)
136///
137bool ConstantRange::isWrappedSet() const {
138  return GT(Lower, Upper);
139}
140
141
142/// getSingleElement - If this set contains a single element, return it,
143/// otherwise return null.
144ConstantIntegral *ConstantRange::getSingleElement() const {
145  if (Upper == Next(Lower))  // Is it a single element range?
146    return Lower;
147  return 0;
148}
149
150/// getSetSize - Return the number of elements in this set.
151///
152uint64_t ConstantRange::getSetSize() const {
153  if (isEmptySet()) return 0;
154  if (getType() == Type::BoolTy) {
155    if (Lower != Upper)  // One of T or F in the set...
156      return 1;
157    return 2;            // Must be full set...
158  }
159
160  // Simply subtract the bounds...
161  Constant *Result = ConstantExpr::getSub(Upper, Lower);
162  return cast<ConstantInt>(Result)->getRawValue();
163}
164
165/// contains - Return true if the specified value is in the set.
166///
167bool ConstantRange::contains(ConstantInt *Val) const {
168  if (Lower == Upper) {
169    if (isFullSet()) return true;
170    return false;
171  }
172
173  if (!isWrappedSet())
174    return LTE(Lower, Val) && LT(Val, Upper);
175  return LTE(Lower, Val) || LT(Val, Upper);
176}
177
178
179
180/// subtract - Subtract the specified constant from the endpoints of this
181/// constant range.
182ConstantRange ConstantRange::subtract(ConstantInt *CI) const {
183  assert(CI->getType() == getType() && getType()->isInteger() &&
184         "Cannot subtract from different type range or non-integer!");
185  // If the set is empty or full, don't modify the endpoints.
186  if (Lower == Upper) return *this;
187  return ConstantRange(ConstantExpr::getSub(Lower, CI),
188                       ConstantExpr::getSub(Upper, CI));
189}
190
191
192// intersect1Wrapped - This helper function is used to intersect two ranges when
193// it is known that LHS is wrapped and RHS isn't.
194//
195static ConstantRange intersect1Wrapped(const ConstantRange &LHS,
196                                       const ConstantRange &RHS) {
197  assert(LHS.isWrappedSet() && !RHS.isWrappedSet());
198
199  // Check to see if we overlap on the Left side of RHS...
200  //
201  if (LT(RHS.getLower(), LHS.getUpper())) {
202    // We do overlap on the left side of RHS, see if we overlap on the right of
203    // RHS...
204    if (GT(RHS.getUpper(), LHS.getLower())) {
205      // Ok, the result overlaps on both the left and right sides.  See if the
206      // resultant interval will be smaller if we wrap or not...
207      //
208      if (LHS.getSetSize() < RHS.getSetSize())
209        return LHS;
210      else
211        return RHS;
212
213    } else {
214      // No overlap on the right, just on the left.
215      return ConstantRange(RHS.getLower(), LHS.getUpper());
216    }
217
218  } else {
219    // We don't overlap on the left side of RHS, see if we overlap on the right
220    // of RHS...
221    if (GT(RHS.getUpper(), LHS.getLower())) {
222      // Simple overlap...
223      return ConstantRange(LHS.getLower(), RHS.getUpper());
224    } else {
225      // No overlap...
226      return ConstantRange(LHS.getType(), false);
227    }
228  }
229}
230
231/// intersect - Return the range that results from the intersection of this
232/// range with another range.
233///
234ConstantRange ConstantRange::intersectWith(const ConstantRange &CR) const {
235  assert(getType() == CR.getType() && "ConstantRange types don't agree!");
236  // Handle common special cases
237  if (isEmptySet() || CR.isFullSet())  return *this;
238  if (isFullSet()  || CR.isEmptySet()) return CR;
239
240  if (!isWrappedSet()) {
241    if (!CR.isWrappedSet()) {
242      ConstantIntegral *L = Max(Lower, CR.Lower);
243      ConstantIntegral *U = Min(Upper, CR.Upper);
244
245      if (LT(L, U))  // If range isn't empty...
246        return ConstantRange(L, U);
247      else
248        return ConstantRange(getType(), false);  // Otherwise, return empty set
249    } else
250      return intersect1Wrapped(CR, *this);
251  } else {   // We know "this" is wrapped...
252    if (!CR.isWrappedSet())
253      return intersect1Wrapped(*this, CR);
254    else {
255      // Both ranges are wrapped...
256      ConstantIntegral *L = Max(Lower, CR.Lower);
257      ConstantIntegral *U = Min(Upper, CR.Upper);
258      return ConstantRange(L, U);
259    }
260  }
261  return *this;
262}
263
264/// union - Return the range that results from the union of this range with
265/// another range.  The resultant range is guaranteed to include the elements of
266/// both sets, but may contain more.  For example, [3, 9) union [12,15) is [3,
267/// 15), which includes 9, 10, and 11, which were not included in either set
268/// before.
269///
270ConstantRange ConstantRange::unionWith(const ConstantRange &CR) const {
271  assert(getType() == CR.getType() && "ConstantRange types don't agree!");
272
273  assert(0 && "Range union not implemented yet!");
274
275  return *this;
276}
277
278/// zeroExtend - Return a new range in the specified integer type, which must
279/// be strictly larger than the current type.  The returned range will
280/// correspond to the possible range of values if the source range had been
281/// zero extended.
282ConstantRange ConstantRange::zeroExtend(const Type *Ty) const {
283  assert(getLower()->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
284         "Not a value extension");
285  if (isFullSet()) {
286    // Change a source full set into [0, 1 << 8*numbytes)
287    unsigned SrcTySize = getLower()->getType()->getPrimitiveSize();
288    return ConstantRange(Constant::getNullValue(Ty),
289                         ConstantUInt::get(Ty, 1ULL << SrcTySize*8));
290  }
291
292  Constant *Lower = getLower();
293  Constant *Upper = getUpper();
294  if (Lower->getType()->isInteger() && !Lower->getType()->isUnsigned()) {
295    // Ensure we are doing a ZERO extension even if the input range is signed.
296    Lower = ConstantExpr::getCast(Lower, Ty->getUnsignedVersion());
297    Upper = ConstantExpr::getCast(Upper, Ty->getUnsignedVersion());
298  }
299
300  return ConstantRange(ConstantExpr::getCast(Lower, Ty),
301                       ConstantExpr::getCast(Upper, Ty));
302}
303
304/// truncate - Return a new range in the specified integer type, which must be
305/// strictly smaller than the current type.  The returned range will
306/// correspond to the possible range of values if the source range had been
307/// truncated to the specified type.
308ConstantRange ConstantRange::truncate(const Type *Ty) const {
309  assert(getLower()->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
310         "Not a value truncation");
311  uint64_t Size = 1ULL << Ty->getPrimitiveSize()*8;
312  if (isFullSet() || getSetSize() >= Size)
313    return ConstantRange(getType());
314
315  return ConstantRange(ConstantExpr::getCast(getLower(), Ty),
316                       ConstantExpr::getCast(getUpper(), Ty));
317}
318
319
320/// print - Print out the bounds to a stream...
321///
322void ConstantRange::print(std::ostream &OS) const {
323  OS << "[" << Lower << "," << Upper << " )";
324}
325
326/// dump - Allow printing from a debugger easily...
327///
328void ConstantRange::dump() const {
329  print(std::cerr);
330}
331