Implement review feedback for the ConstantBool->ConstantInt merge. Chris
[oota-llvm.git] / lib / Support / ConstantRange.cpp
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/Instructions.h"
28 #include "llvm/Type.h"
29 #include "llvm/Support/Streams.h"
30 #include <ostream>
31 using namespace llvm;
32
33 static ConstantInt *getMaxValue(const Type *Ty, bool isSigned = false) {
34   if (Ty == Type::Int1Ty)
35     return ConstantInt::getTrue();
36   if (Ty->isInteger()) {
37     if (isSigned) {
38       // Calculate 011111111111111...
39       unsigned TypeBits = Ty->getPrimitiveSizeInBits();
40       int64_t Val = INT64_MAX;             // All ones
41       Val >>= 64-TypeBits;                 // Shift out unwanted 1 bits...
42       return ConstantInt::get(Ty, Val);
43     }
44     return ConstantInt::getAllOnesValue(Ty);
45   }
46   return 0;
47 }
48
49 // Static constructor to create the minimum constant for an integral type...
50 static ConstantInt *getMinValue(const Type *Ty, bool isSigned = false) {
51   if (Ty == Type::Int1Ty)
52     return ConstantInt::getFalse();
53   if (Ty->isInteger()) {
54     if (isSigned) {
55       // Calculate 1111111111000000000000
56       unsigned TypeBits = Ty->getPrimitiveSizeInBits();
57       int64_t Val = -1;                    // All ones
58       Val <<= TypeBits-1;                  // Shift over to the right spot
59       return ConstantInt::get(Ty, Val);
60     }
61     return ConstantInt::get(Ty, 0);
62   }
63   return 0;
64 }
65 static ConstantInt *Next(ConstantInt *CI) {
66   if (CI->getType() == Type::Int1Ty)
67     return ConstantInt::get(Type::Int1Ty, !CI->getZExtValue());
68
69   Constant *Result = ConstantExpr::getAdd(CI,
70                                           ConstantInt::get(CI->getType(), 1));
71   return cast<ConstantInt>(Result);
72 }
73
74 static bool LT(ConstantInt *A, ConstantInt *B, bool isSigned) {
75   Constant *C = ConstantExpr::getICmp(
76     (isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT), A, B);
77   assert(isa<ConstantInt>(C) && "Constant folding of integrals not impl??");
78   return cast<ConstantInt>(C)->getZExtValue();
79 }
80
81 static bool LTE(ConstantInt *A, ConstantInt *B, bool isSigned) {
82   Constant *C = ConstantExpr::getICmp(
83     (isSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE), A, B);
84   assert(isa<ConstantInt>(C) && "Constant folding of integrals not impl??");
85   return cast<ConstantInt>(C)->getZExtValue();
86 }
87
88 static bool GT(ConstantInt *A, ConstantInt *B, bool isSigned) { 
89   return LT(B, A, isSigned); }
90
91 static ConstantInt *Min(ConstantInt *A, ConstantInt *B, 
92                              bool isSigned) {
93   return LT(A, B, isSigned) ? A : B;
94 }
95 static ConstantInt *Max(ConstantInt *A, ConstantInt *B,
96                              bool isSigned) {
97   return GT(A, B, isSigned) ? A : B;
98 }
99
100 /// Initialize a full (the default) or empty set for the specified type.
101 ///
102 ConstantRange::ConstantRange(const Type *Ty, bool Full) {
103   assert(Ty->isIntegral() &&
104          "Cannot make constant range of non-integral type!");
105   if (Full)
106     Lower = Upper = getMaxValue(Ty);
107   else
108     Lower = Upper = getMinValue(Ty);
109 }
110
111 /// Initialize a range to hold the single specified value.
112 ///
113 ConstantRange::ConstantRange(Constant *V) 
114   : Lower(cast<ConstantInt>(V)), Upper(Next(cast<ConstantInt>(V))) { }
115
116 /// Initialize a range of values explicitly... this will assert out if
117 /// Lower==Upper and Lower != Min or Max for its type (or if the two constants
118 /// have different types)
119 ///
120 ConstantRange::ConstantRange(Constant *L, Constant *U) 
121   : Lower(cast<ConstantInt>(L)), Upper(cast<ConstantInt>(U)) {
122   assert(Lower->getType() == Upper->getType() &&
123          "Incompatible types for ConstantRange!");
124
125   // Make sure that if L & U are equal that they are either Min or Max...
126   assert((L != U || (L == getMaxValue(L->getType()) ||
127                      L == getMinValue(L->getType())))
128           && "Lower == Upper, but they aren't min or max for type!");
129 }
130
131 /// Initialize a set of values that all satisfy the condition with C.
132 ///
133 ConstantRange::ConstantRange(unsigned short ICmpOpcode, ConstantInt *C) {
134   switch (ICmpOpcode) {
135   default: assert(0 && "Invalid ICmp opcode to ConstantRange ctor!");
136   case ICmpInst::ICMP_EQ: Lower = C; Upper = Next(C); return;
137   case ICmpInst::ICMP_NE: Upper = C; Lower = Next(C); return;
138   case ICmpInst::ICMP_ULT:
139     Lower = getMinValue(C->getType());
140     Upper = C;
141     return;
142   case ICmpInst::ICMP_SLT:
143     Lower = getMinValue(C->getType(), true);
144     Upper = C;
145     return;
146   case ICmpInst::ICMP_UGT:
147     Lower = Next(C);
148     Upper = getMinValue(C->getType());        // Min = Next(Max)
149     return;
150   case ICmpInst::ICMP_SGT:
151     Lower = Next(C);
152     Upper = getMinValue(C->getType(), true);  // Min = Next(Max)
153     return;
154   case ICmpInst::ICMP_ULE:
155     Lower = getMinValue(C->getType());
156     Upper = Next(C);
157     return;
158   case ICmpInst::ICMP_SLE:
159     Lower = getMinValue(C->getType(), true);
160     Upper = Next(C);
161     return;
162   case ICmpInst::ICMP_UGE:
163     Lower = C;
164     Upper = getMinValue(C->getType());        // Min = Next(Max)
165     return;
166   case ICmpInst::ICMP_SGE:
167     Lower = C;
168     Upper = getMinValue(C->getType(), true);  // Min = Next(Max)
169     return;
170   }
171 }
172
173 /// getType - Return the LLVM data type of this range.
174 ///
175 const Type *ConstantRange::getType() const { return Lower->getType(); }
176
177 /// isFullSet - Return true if this set contains all of the elements possible
178 /// for this data-type
179 bool ConstantRange::isFullSet() const {
180   return Lower == Upper && Lower == getMaxValue(getType());
181 }
182
183 /// isEmptySet - Return true if this set contains no members.
184 ///
185 bool ConstantRange::isEmptySet() const {
186   return Lower == Upper && Lower == getMinValue(getType());
187 }
188
189 /// isWrappedSet - Return true if this set wraps around the top of the range,
190 /// for example: [100, 8)
191 ///
192 bool ConstantRange::isWrappedSet(bool isSigned) const {
193   return GT(Lower, Upper, isSigned);
194 }
195
196 /// getSingleElement - If this set contains a single element, return it,
197 /// otherwise return null.
198 ConstantInt *ConstantRange::getSingleElement() const {
199   if (Upper == Next(Lower))  // Is it a single element range?
200     return Lower;
201   return 0;
202 }
203
204 /// getSetSize - Return the number of elements in this set.
205 ///
206 uint64_t ConstantRange::getSetSize() const {
207   if (isEmptySet()) return 0;
208   if (getType() == Type::Int1Ty) {
209     if (Lower != Upper)  // One of T or F in the set...
210       return 1;
211     return 2;            // Must be full set...
212   }
213
214   // Simply subtract the bounds...
215   Constant *Result = ConstantExpr::getSub(Upper, Lower);
216   return cast<ConstantInt>(Result)->getZExtValue();
217 }
218
219 /// contains - Return true if the specified value is in the set.
220 ///
221 bool ConstantRange::contains(ConstantInt *Val, bool isSigned) const {
222   if (Lower == Upper) {
223     if (isFullSet()) return true;
224     return false;
225   }
226
227   if (!isWrappedSet(isSigned))
228     return LTE(Lower, Val, isSigned) && LT(Val, Upper, isSigned);
229   return LTE(Lower, Val, isSigned) || LT(Val, Upper, isSigned);
230 }
231
232 /// subtract - Subtract the specified constant from the endpoints of this
233 /// constant range.
234 ConstantRange ConstantRange::subtract(ConstantInt *CI) const {
235   assert(CI->getType() == getType() && getType()->isInteger() &&
236          "Cannot subtract from different type range or non-integer!");
237   // If the set is empty or full, don't modify the endpoints.
238   if (Lower == Upper) return *this;
239   return ConstantRange(ConstantExpr::getSub(Lower, CI),
240                        ConstantExpr::getSub(Upper, CI));
241 }
242
243
244 // intersect1Wrapped - This helper function is used to intersect two ranges when
245 // it is known that LHS is wrapped and RHS isn't.
246 //
247 static ConstantRange intersect1Wrapped(const ConstantRange &LHS,
248                                        const ConstantRange &RHS,
249                                        bool isSigned) {
250   assert(LHS.isWrappedSet(isSigned) && !RHS.isWrappedSet(isSigned));
251
252   // Check to see if we overlap on the Left side of RHS...
253   //
254   if (LT(RHS.getLower(), LHS.getUpper(), isSigned)) {
255     // We do overlap on the left side of RHS, see if we overlap on the right of
256     // RHS...
257     if (GT(RHS.getUpper(), LHS.getLower(), isSigned)) {
258       // Ok, the result overlaps on both the left and right sides.  See if the
259       // resultant interval will be smaller if we wrap or not...
260       //
261       if (LHS.getSetSize() < RHS.getSetSize())
262         return LHS;
263       else
264         return RHS;
265
266     } else {
267       // No overlap on the right, just on the left.
268       return ConstantRange(RHS.getLower(), LHS.getUpper());
269     }
270   } else {
271     // We don't overlap on the left side of RHS, see if we overlap on the right
272     // of RHS...
273     if (GT(RHS.getUpper(), LHS.getLower(), isSigned)) {
274       // Simple overlap...
275       return ConstantRange(LHS.getLower(), RHS.getUpper());
276     } else {
277       // No overlap...
278       return ConstantRange(LHS.getType(), false);
279     }
280   }
281 }
282
283 /// intersect - Return the range that results from the intersection of this
284 /// range with another range.
285 ///
286 ConstantRange ConstantRange::intersectWith(const ConstantRange &CR,
287                                            bool isSigned) const {
288   assert(getType() == CR.getType() && "ConstantRange types don't agree!");
289   // Handle common special cases
290   if (isEmptySet() || CR.isFullSet())  return *this;
291   if (isFullSet()  || CR.isEmptySet()) return CR;
292
293   if (!isWrappedSet(isSigned)) {
294     if (!CR.isWrappedSet(isSigned)) {
295       ConstantInt *L = Max(Lower, CR.Lower, isSigned);
296       ConstantInt *U = Min(Upper, CR.Upper, isSigned);
297
298       if (LT(L, U, isSigned))  // If range isn't empty...
299         return ConstantRange(L, U);
300       else
301         return ConstantRange(getType(), false);  // Otherwise, return empty set
302     } else
303       return intersect1Wrapped(CR, *this, isSigned);
304   } else {   // We know "this" is wrapped...
305     if (!CR.isWrappedSet(isSigned))
306       return intersect1Wrapped(*this, CR, isSigned);
307     else {
308       // Both ranges are wrapped...
309       ConstantInt *L = Max(Lower, CR.Lower, isSigned);
310       ConstantInt *U = Min(Upper, CR.Upper, isSigned);
311       return ConstantRange(L, U);
312     }
313   }
314   return *this;
315 }
316
317 /// union - Return the range that results from the union of this range with
318 /// another range.  The resultant range is guaranteed to include the elements of
319 /// both sets, but may contain more.  For example, [3, 9) union [12,15) is [3,
320 /// 15), which includes 9, 10, and 11, which were not included in either set
321 /// before.
322 ///
323 ConstantRange ConstantRange::unionWith(const ConstantRange &CR,
324                                        bool isSigned) const {
325   assert(getType() == CR.getType() && "ConstantRange types don't agree!");
326
327   assert(0 && "Range union not implemented yet!");
328
329   return *this;
330 }
331
332 /// zeroExtend - Return a new range in the specified integer type, which must
333 /// be strictly larger than the current type.  The returned range will
334 /// correspond to the possible range of values as if the source range had been
335 /// zero extended.
336 ConstantRange ConstantRange::zeroExtend(const Type *Ty) const {
337   unsigned SrcTySize = getLower()->getType()->getPrimitiveSizeInBits();
338   assert(SrcTySize < Ty->getPrimitiveSizeInBits() && "Not a value extension");
339   if (isFullSet()) {
340     // Change a source full set into [0, 1 << 8*numbytes)
341     return ConstantRange(Constant::getNullValue(Ty),
342                          ConstantInt::get(Ty, 1ULL << SrcTySize));
343   }
344
345   Constant *Lower = getLower();
346   Constant *Upper = getUpper();
347
348   return ConstantRange(ConstantExpr::getZExt(Lower, Ty),
349                        ConstantExpr::getZExt(Upper, Ty));
350 }
351
352 /// truncate - Return a new range in the specified integer type, which must be
353 /// strictly smaller than the current type.  The returned range will
354 /// correspond to the possible range of values as if the source range had been
355 /// truncated to the specified type.
356 ConstantRange ConstantRange::truncate(const Type *Ty) const {
357   unsigned SrcTySize = getLower()->getType()->getPrimitiveSizeInBits();
358   assert(SrcTySize > Ty->getPrimitiveSizeInBits() && "Not a value truncation");
359   uint64_t Size = 1ULL << Ty->getPrimitiveSizeInBits();
360   if (isFullSet() || getSetSize() >= Size)
361     return ConstantRange(getType());
362
363   return ConstantRange(
364       ConstantExpr::getTrunc(getLower(), Ty),
365       ConstantExpr::getTrunc(getUpper(), Ty));
366 }
367
368 /// print - Print out the bounds to a stream...
369 ///
370 void ConstantRange::print(std::ostream &OS) const {
371   OS << "[" << *Lower << "," << *Upper << " )";
372 }
373
374 /// dump - Allow printing from a debugger easily...
375 ///
376 void ConstantRange::dump() const {
377   print(cerr);
378 }