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