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