IntRange:
[oota-llvm.git] / include / llvm / Support / IntegersSubset.h
1 //===-- llvm/IntegersSubset.h - The subset of integers ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// @file
11 /// This file contains class that implements constant set of ranges:
12 /// [<Low0,High0>,...,<LowN,HighN>]. Initially, this class was created for
13 /// SwitchInst and was used for case value representation that may contain
14 /// multiple ranges for a single successor.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #ifndef CONSTANTRANGESSET_H_
19 #define CONSTANTRANGESSET_H_
20
21 #include <list>
22
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/LLVMContext.h"
26
27 namespace llvm {
28
29   // The IntItem is a wrapper for APInt.
30   // 1. It determines sign of integer, it allows to use
31   //    comparison operators >,<,>=,<=, and as result we got shorter and cleaner
32   //    constructions.
33   // 2. It helps to implement PR1255 (case ranges) as a series of small patches.
34   // 3. Currently we can interpret IntItem both as ConstantInt and as APInt.
35   //    It allows to provide SwitchInst methods that works with ConstantInt for
36   //    non-updated passes. And it allows to use APInt interface for new methods.
37   // 4. IntItem can be easily replaced with APInt.
38
39   // The set of macros that allows to propagate APInt operators to the IntItem.
40
41 #define INT_ITEM_DEFINE_COMPARISON(op,func) \
42   bool operator op (const APInt& RHS) const { \
43     return getAPIntValue().func(RHS); \
44   }
45
46 #define INT_ITEM_DEFINE_UNARY_OP(op) \
47   IntItem operator op () const { \
48     APInt res = op(getAPIntValue()); \
49     Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
50     return IntItem(cast<ConstantInt>(NewVal)); \
51   }
52
53 #define INT_ITEM_DEFINE_BINARY_OP(op) \
54   IntItem operator op (const APInt& RHS) const { \
55     APInt res = getAPIntValue() op RHS; \
56     Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
57     return IntItem(cast<ConstantInt>(NewVal)); \
58   }
59
60 #define INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(op) \
61   IntItem& operator op (const APInt& RHS) {\
62     APInt res = getAPIntValue();\
63     res op RHS; \
64     Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
65     ConstantIntVal = cast<ConstantInt>(NewVal); \
66     return *this; \
67   }
68
69 #define INT_ITEM_DEFINE_PREINCDEC(op) \
70     IntItem& operator op () { \
71       APInt res = getAPIntValue(); \
72       op(res); \
73       Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
74       ConstantIntVal = cast<ConstantInt>(NewVal); \
75       return *this; \
76     }
77
78 #define INT_ITEM_DEFINE_POSTINCDEC(op) \
79     IntItem& operator op (int) { \
80       APInt res = getAPIntValue();\
81       op(res); \
82       Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res); \
83       OldConstantIntVal = ConstantIntVal; \
84       ConstantIntVal = cast<ConstantInt>(NewVal); \
85       return IntItem(OldConstantIntVal); \
86     }
87
88 #define INT_ITEM_DEFINE_OP_STANDARD_INT(RetTy, op, IntTy) \
89   RetTy operator op (IntTy RHS) const { \
90     return (*this) op APInt(getAPIntValue().getBitWidth(), RHS); \
91   }
92
93 class IntItem {
94   ConstantInt *ConstantIntVal;
95   const APInt* APIntVal;
96   IntItem(const ConstantInt *V) :
97     ConstantIntVal(const_cast<ConstantInt*>(V)),
98     APIntVal(&ConstantIntVal->getValue()){}
99   const APInt& getAPIntValue() const {
100     return *APIntVal;
101   }
102 public:
103
104   IntItem() {}
105
106   operator const APInt&() const {
107     return getAPIntValue();
108   }
109
110   // Propagate APInt operators.
111   // Note, that
112   // /,/=,>>,>>= are not implemented in APInt.
113   // <<= is implemented for unsigned RHS, but not implemented for APInt RHS.
114
115   INT_ITEM_DEFINE_COMPARISON(<, ult)
116   INT_ITEM_DEFINE_COMPARISON(>, ugt)
117   INT_ITEM_DEFINE_COMPARISON(<=, ule)
118   INT_ITEM_DEFINE_COMPARISON(>=, uge)
119
120   INT_ITEM_DEFINE_COMPARISON(==, eq)
121   INT_ITEM_DEFINE_OP_STANDARD_INT(bool,==,uint64_t)
122
123   INT_ITEM_DEFINE_COMPARISON(!=, ne)
124   INT_ITEM_DEFINE_OP_STANDARD_INT(bool,!=,uint64_t)
125
126   INT_ITEM_DEFINE_BINARY_OP(*)
127   INT_ITEM_DEFINE_BINARY_OP(+)
128   INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,+,uint64_t)
129   INT_ITEM_DEFINE_BINARY_OP(-)
130   INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,-,uint64_t)
131   INT_ITEM_DEFINE_BINARY_OP(<<)
132   INT_ITEM_DEFINE_OP_STANDARD_INT(IntItem,<<,unsigned)
133   INT_ITEM_DEFINE_BINARY_OP(&)
134   INT_ITEM_DEFINE_BINARY_OP(^)
135   INT_ITEM_DEFINE_BINARY_OP(|)
136
137   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(*=)
138   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(+=)
139   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(-=)
140   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(&=)
141   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(^=)
142   INT_ITEM_DEFINE_ASSIGNMENT_BY_OP(|=)
143
144   // Special case for <<=
145   IntItem& operator <<= (unsigned RHS) {
146     APInt res = getAPIntValue();
147     res <<= RHS;
148     Constant *NewVal = ConstantInt::get(ConstantIntVal->getContext(), res);
149     ConstantIntVal = cast<ConstantInt>(NewVal);
150     return *this;
151   }
152
153   INT_ITEM_DEFINE_UNARY_OP(-)
154   INT_ITEM_DEFINE_UNARY_OP(~)
155
156   INT_ITEM_DEFINE_PREINCDEC(++)
157   INT_ITEM_DEFINE_PREINCDEC(--)
158
159   // The set of workarounds, since currently we use ConstantInt implemented
160   // integer.
161
162   static IntItem fromConstantInt(const ConstantInt *V) {
163     return IntItem(V);
164   }
165   static IntItem fromType(Type* Ty, const APInt& V) {
166     ConstantInt *C = cast<ConstantInt>(ConstantInt::get(Ty, V));
167     return fromConstantInt(C);
168   }
169   static IntItem withImplLikeThis(const IntItem& LikeThis, const APInt& V) {
170     ConstantInt *C = cast<ConstantInt>(ConstantInt::get(
171         LikeThis.ConstantIntVal->getContext(), V));
172     return fromConstantInt(C);
173   }
174   ConstantInt *toConstantInt() const {
175     return ConstantIntVal;
176   }
177 };
178
179 template<class IntType>
180 class IntRange {
181 protected:
182     IntType Low;
183     IntType High;
184     bool IsEmpty : 1;
185     enum Type {
186       SINGLE_NUMBER,
187       RANGE,
188       UNKNOWN
189     };
190     Type RangeType;
191
192 public:
193     typedef IntRange<IntType> self;
194     typedef std::pair<self, self> SubRes;
195
196     IntRange() : IsEmpty(true) {}
197     IntRange(const self &RHS) :
198       Low(RHS.Low), High(RHS.High),
199       IsEmpty(RHS.IsEmpty), RangeType(RHS.RangeType) {}
200     IntRange(const IntType &C) :
201       Low(C), High(C), IsEmpty(false), RangeType(SINGLE_NUMBER) {}
202
203     IntRange(const IntType &L, const IntType &H) : Low(L), High(H),
204       IsEmpty(false), RangeType(UNKNOWN) {}
205
206     bool isEmpty() const { return IsEmpty; }
207     bool isSingleNumber() const {
208       switch (RangeType) {
209       case SINGLE_NUMBER:
210         return true;
211       case RANGE:
212         return false;
213       case UNKNOWN:
214       default:
215         if (Low == High) {
216           const_cast<Type&>(RangeType) = SINGLE_NUMBER;
217           return true;
218         }
219         const_cast<Type&>(RangeType) = RANGE;
220         return false;
221       }
222     }
223
224     const IntType& getLow() const {
225       assert(!IsEmpty && "Range is empty.");
226       return Low;
227     }
228     const IntType& getHigh() const {
229       assert(!IsEmpty && "Range is empty.");
230       return High;
231     }
232
233     bool operator<(const self &RHS) const {
234       assert(!IsEmpty && "Left range is empty.");
235       assert(!RHS.IsEmpty && "Right range is empty.");
236       if (Low < RHS.Low)
237         return true;
238       if (Low == RHS.Low) {
239         if (High > RHS.High)
240           return true;
241         return false;
242       }
243       return false;
244     }
245
246     bool operator==(const self &RHS) const {
247       assert(!IsEmpty && "Left range is empty.");
248       assert(!RHS.IsEmpty && "Right range is empty.");
249       return Low == RHS.Low && High == RHS.High;
250     }
251
252     bool operator!=(const self &RHS) const {
253       return !operator ==(RHS);
254     }
255
256     static bool LessBySize(const self &LHS, const self &RHS) {
257       return (LHS.High - LHS.Low) < (RHS.High - RHS.Low);
258     }
259
260     bool isInRange(const IntType &IntVal) const {
261       assert(!IsEmpty && "Range is empty.");
262       return IntVal >= Low && IntVal <= High;
263     }
264
265     SubRes sub(const self &RHS) const {
266       SubRes Res;
267
268       // RHS is either more global and includes this range or
269       // if it doesn't intersected with this range.
270       if (!isInRange(RHS.Low) && !isInRange(RHS.High)) {
271
272         // If RHS more global (it is enough to check
273         // only one border in this case.
274         if (RHS.isInRange(Low))
275           return std::make_pair(self(Low, High), self());
276
277         return Res;
278       }
279
280       if (Low < RHS.Low) {
281         Res.first.Low = Low;
282         IntType NewHigh = RHS.Low;
283         --NewHigh;
284         Res.first.High = NewHigh;
285       }
286       if (High > RHS.High) {
287         IntType NewLow = RHS.High;
288         ++NewLow;
289         Res.second.Low = NewLow;
290         Res.second.High = High;
291       }
292       return Res;
293     }
294   };
295
296 //===----------------------------------------------------------------------===//
297 /// IntegersSubsetGeneric - class that implements the subset of integers. It
298 /// consists from ranges and single numbers.
299 template <class IntTy>
300 class IntegersSubsetGeneric {
301 public:
302   // Use Chris Lattner idea, that was initially described here:
303   // http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20120213/136954.html
304   // In short, for more compact memory consumption we can store flat
305   // numbers collection, and define range as pair of indices.
306   // In that case we can safe some memory on 32 bit machines.
307   typedef std::vector<IntTy> FlatCollectionTy;
308   typedef std::pair<IntTy*, IntTy*> RangeLinkTy;
309   typedef std::vector<RangeLinkTy> RangeLinksTy;
310   typedef typename RangeLinksTy::const_iterator RangeLinksConstIt;
311
312   typedef IntegersSubsetGeneric<IntTy> self;
313
314 protected:
315
316   FlatCollectionTy FlatCollection;
317   RangeLinksTy RangeLinks;
318
319   bool IsSingleNumber;
320   bool IsSingleNumbersOnly;
321
322 public:
323
324   template<class RangesCollectionTy>
325   explicit IntegersSubsetGeneric(const RangesCollectionTy& Links) {
326     assert(Links.size() && "Empty ranges are not allowed.");
327
328     // In case of big set of single numbers consumes additional RAM space,
329     // but allows to avoid additional reallocation.
330     FlatCollection.reserve(Links.size() * 2);
331     RangeLinks.reserve(Links.size());
332     IsSingleNumbersOnly = true;
333     for (typename RangesCollectionTy::const_iterator i = Links.begin(),
334          e = Links.end(); i != e; ++i) {
335       RangeLinkTy RangeLink;
336       FlatCollection.push_back(i->getLow());
337       RangeLink.first = &FlatCollection.back();
338       if (i->getLow() != i->getHigh()) {
339         FlatCollection.push_back(i->getHigh());
340         IsSingleNumbersOnly = false;
341       }
342       RangeLink.second = &FlatCollection.back();
343       RangeLinks.push_back(RangeLink);
344     }
345     IsSingleNumber = IsSingleNumbersOnly && RangeLinks.size() == 1;
346   }
347
348   IntegersSubsetGeneric(const self& RHS) {
349     *this = RHS;
350   }
351
352   self& operator=(const self& RHS) {
353     FlatCollection.clear();
354     RangeLinks.clear();
355     FlatCollection.reserve(RHS.RangeLinks.size() * 2);
356     RangeLinks.reserve(RHS.RangeLinks.size());
357     for (RangeLinksConstIt i = RHS.RangeLinks.begin(), e = RHS.RangeLinks.end();
358          i != e; ++i) {
359       RangeLinkTy RangeLink;
360       FlatCollection.push_back(*(i->first));
361       RangeLink.first = &FlatCollection.back();
362       if (i->first != i->second)
363         FlatCollection.push_back(*(i->second));
364       RangeLink.second = &FlatCollection.back();
365       RangeLinks.push_back(RangeLink);
366     }
367     IsSingleNumber = RHS.IsSingleNumber;
368     IsSingleNumbersOnly = RHS.IsSingleNumbersOnly;
369     return *this;
370   }
371
372   typedef IntRange<IntTy> Range;
373
374   /// Checks is the given constant satisfies this case. Returns
375   /// true if it equals to one of contained values or belongs to the one of
376   /// contained ranges.
377   bool isSatisfies(const IntTy &CheckingVal) const {
378     if (IsSingleNumber)
379       return FlatCollection.front() == CheckingVal;
380     if (IsSingleNumbersOnly)
381       return std::find(FlatCollection.begin(),
382                        FlatCollection.end(),
383                        CheckingVal) != FlatCollection.end();
384
385     for (unsigned i = 0, e = getNumItems(); i < e; ++i) {
386       if (RangeLinks[i].first == RangeLinks[i].second) {
387         if (*RangeLinks[i].first == CheckingVal)
388           return true;
389       } else if (*RangeLinks[i].first <= CheckingVal &&
390                  *RangeLinks[i].second >= CheckingVal)
391         return true;
392     }
393     return false;
394   }
395
396   /// Returns set's item with given index.
397   Range getItem(unsigned idx) const {
398     const RangeLinkTy &Link = RangeLinks[idx];
399     if (Link.first != Link.second)
400       return Range(*Link.first, *Link.second);
401     else
402       return Range(*Link.first);
403   }
404
405   /// Return number of items (ranges) stored in set.
406   unsigned getNumItems() const {
407     return RangeLinks.size();
408   }
409
410   /// Returns true if whole subset contains single element.
411   bool isSingleNumber() const {
412     return IsSingleNumber;
413   }
414
415   /// Returns true if whole subset contains only single numbers, no ranges.
416   bool isSingleNumbersOnly() const {
417     return IsSingleNumbersOnly;
418   }
419
420   /// Does the same like getItem(idx).isSingleNumber(), but
421   /// works faster, since we avoid creation of temporary range object.
422   bool isSingleNumber(unsigned idx) const {
423     return RangeLinks[idx].first == RangeLinks[idx].second;
424   }
425
426   /// Returns set the size, that equals number of all values + sizes of all
427   /// ranges.
428   /// Ranges set is considered as flat numbers collection.
429   /// E.g.: for range [<0>, <1>, <4,8>] the size will 7;
430   ///       for range [<0>, <1>, <5>] the size will 3
431   unsigned getSize() const {
432     APInt sz(((const APInt&)getItem(0).getLow()).getBitWidth(), 0);
433     for (unsigned i = 0, e = getNumItems(); i != e; ++i) {
434       const APInt &Low = getItem(i).getLow();
435       const APInt &High = getItem(i).getHigh();
436       APInt S = High - Low + 1;
437       sz += S;
438     }
439     return sz.getZExtValue();
440   }
441
442   /// Allows to access single value even if it belongs to some range.
443   /// Ranges set is considered as flat numbers collection.
444   /// [<1>, <4,8>] is considered as [1,4,5,6,7,8]
445   /// For range [<1>, <4,8>] getSingleValue(3) returns 6.
446   APInt getSingleValue(unsigned idx) const {
447     APInt sz(((const APInt&)getItem(0).getLow()).getBitWidth(), 0);
448     for (unsigned i = 0, e = getNumItems(); i != e; ++i) {
449       const APInt &Low = getItem(i).getLow();
450       const APInt &High = getItem(i).getHigh();
451       APInt S = High - Low + 1;
452       APInt oldSz = sz;
453       sz += S;
454       if (sz.ugt(idx)) {
455         APInt Res = Low;
456         APInt Offset(oldSz.getBitWidth(), idx);
457         Offset -= oldSz;
458         Res += Offset;
459         return Res;
460       }
461     }
462     assert(0 && "Index exceeds high border.");
463     return sz;
464   }
465
466   /// Does the same as getSingleValue, but works only if subset contains
467   /// single numbers only.
468   const IntTy& getSingleNumber(unsigned idx) const {
469     assert(IsSingleNumbersOnly && "This method works properly if subset "
470                                   "contains single numbers only.");
471     return FlatCollection[idx];
472   }
473 };
474
475 //===----------------------------------------------------------------------===//
476 /// IntegersSubset - currently is extension of IntegersSubsetGeneric
477 /// that also supports conversion to/from Constant* object.
478 class IntegersSubset : public IntegersSubsetGeneric<IntItem> {
479
480   typedef IntegersSubsetGeneric<IntItem> ParentTy;
481
482   Constant *Holder;
483
484   static unsigned getNumItemsFromConstant(Constant *C) {
485     return cast<ArrayType>(C->getType())->getNumElements();
486   }
487
488   static Range getItemFromConstant(Constant *C, unsigned idx) {
489     const Constant *CV = C->getAggregateElement(idx);
490
491     unsigned NumEls = cast<VectorType>(CV->getType())->getNumElements();
492     switch (NumEls) {
493     case 1:
494       return Range(IntItem::fromConstantInt(
495                      cast<ConstantInt>(CV->getAggregateElement(0U))),
496                    IntItem::fromConstantInt(cast<ConstantInt>(
497                      cast<ConstantInt>(CV->getAggregateElement(0U)))));
498     case 2:
499       return Range(IntItem::fromConstantInt(
500                      cast<ConstantInt>(CV->getAggregateElement(0U))),
501                    IntItem::fromConstantInt(
502                    cast<ConstantInt>(CV->getAggregateElement(1))));
503     default:
504       assert(0 && "Only pairs and single numbers are allowed here.");
505       return Range();
506     }
507   }
508
509   std::vector<Range> rangesFromConstant(Constant *C) {
510     unsigned NumItems = getNumItemsFromConstant(C);
511     std::vector<Range> r;
512     r.reserve(NumItems);
513     for (unsigned i = 0, e = NumItems; i != e; ++i)
514       r.push_back(getItemFromConstant(C, i));
515     return r;
516   }
517
518 public:
519
520   explicit IntegersSubset(Constant *C) : ParentTy(rangesFromConstant(C)),
521                           Holder(C) {}
522
523   IntegersSubset(const IntegersSubset& RHS) :
524     ParentTy(*(const ParentTy *)&RHS), // FIXME: tweak for msvc.
525     Holder(RHS.Holder) {}
526
527   template<class RangesCollectionTy>
528   explicit IntegersSubset(const RangesCollectionTy& Src) : ParentTy(Src) {
529     std::vector<Constant*> Elts;
530     Elts.reserve(Src.size());
531     for (typename RangesCollectionTy::const_iterator i = Src.begin(),
532          e = Src.end(); i != e; ++i) {
533       const Range &R = *i;
534       std::vector<Constant*> r;
535       if (!R.isSingleNumber()) {
536         r.reserve(2);
537         // FIXME: Since currently we have ConstantInt based numbers
538         // use hack-conversion of IntItem to ConstantInt
539         r.push_back(R.getLow().toConstantInt());
540         r.push_back(R.getHigh().toConstantInt());
541       } else {
542         r.reserve(1);
543         r.push_back(R.getLow().toConstantInt());
544       }
545       Constant *CV = ConstantVector::get(r);
546       Elts.push_back(CV);
547     }
548     ArrayType *ArrTy =
549         ArrayType::get(Elts.front()->getType(), (uint64_t)Elts.size());
550     Holder = ConstantArray::get(ArrTy, Elts);
551   }
552
553   operator Constant*() { return Holder; }
554   operator const Constant*() const { return Holder; }
555   Constant *operator->() { return Holder; }
556   const Constant *operator->() const { return Holder; }
557 };
558
559 }
560
561 #endif /* CONSTANTRANGESSET_H_ */