MathExtras: Bring Count(Trailing|Leading)Ones and CountPopulation in line with countT...
[oota-llvm.git] / include / llvm / ADT / SmallBitVector.h
1 //===- llvm/ADT/SmallBitVector.h - 'Normally small' bit vectors -*- 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 // This file implements the SmallBitVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_SMALLBITVECTOR_H
15 #define LLVM_ADT_SMALLBITVECTOR_H
16
17 #include "llvm/ADT/BitVector.h"
18 #include "llvm/Support/Compiler.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <cassert>
21
22 namespace llvm {
23
24 /// SmallBitVector - This is a 'bitvector' (really, a variable-sized bit array),
25 /// optimized for the case when the array is small.  It contains one
26 /// pointer-sized field, which is directly used as a plain collection of bits
27 /// when possible, or as a pointer to a larger heap-allocated array when
28 /// necessary.  This allows normal "small" cases to be fast without losing
29 /// generality for large inputs.
30 ///
31 class SmallBitVector {
32   // TODO: In "large" mode, a pointer to a BitVector is used, leading to an
33   // unnecessary level of indirection. It would be more efficient to use a
34   // pointer to memory containing size, allocation size, and the array of bits.
35   uintptr_t X;
36
37   enum {
38     // The number of bits in this class.
39     NumBaseBits = sizeof(uintptr_t) * CHAR_BIT,
40
41     // One bit is used to discriminate between small and large mode. The
42     // remaining bits are used for the small-mode representation.
43     SmallNumRawBits = NumBaseBits - 1,
44
45     // A few more bits are used to store the size of the bit set in small mode.
46     // Theoretically this is a ceil-log2. These bits are encoded in the most
47     // significant bits of the raw bits.
48     SmallNumSizeBits = (NumBaseBits == 32 ? 5 :
49                         NumBaseBits == 64 ? 6 :
50                         SmallNumRawBits),
51
52     // The remaining bits are used to store the actual set in small mode.
53     SmallNumDataBits = SmallNumRawBits - SmallNumSizeBits
54   };
55
56   static_assert(NumBaseBits == 64 || NumBaseBits == 32,
57                 "Unsupported word size");
58
59 public:
60   typedef unsigned size_type;
61   // Encapsulation of a single bit.
62   class reference {
63     SmallBitVector &TheVector;
64     unsigned BitPos;
65
66   public:
67     reference(SmallBitVector &b, unsigned Idx) : TheVector(b), BitPos(Idx) {}
68
69     reference& operator=(reference t) {
70       *this = bool(t);
71       return *this;
72     }
73
74     reference& operator=(bool t) {
75       if (t)
76         TheVector.set(BitPos);
77       else
78         TheVector.reset(BitPos);
79       return *this;
80     }
81
82     operator bool() const {
83       return const_cast<const SmallBitVector &>(TheVector).operator[](BitPos);
84     }
85   };
86
87 private:
88   bool isSmall() const {
89     return X & uintptr_t(1);
90   }
91
92   BitVector *getPointer() const {
93     assert(!isSmall());
94     return reinterpret_cast<BitVector *>(X);
95   }
96
97   void switchToSmall(uintptr_t NewSmallBits, size_t NewSize) {
98     X = 1;
99     setSmallSize(NewSize);
100     setSmallBits(NewSmallBits);
101   }
102
103   void switchToLarge(BitVector *BV) {
104     X = reinterpret_cast<uintptr_t>(BV);
105     assert(!isSmall() && "Tried to use an unaligned pointer");
106   }
107
108   // Return all the bits used for the "small" representation; this includes
109   // bits for the size as well as the element bits.
110   uintptr_t getSmallRawBits() const {
111     assert(isSmall());
112     return X >> 1;
113   }
114
115   void setSmallRawBits(uintptr_t NewRawBits) {
116     assert(isSmall());
117     X = (NewRawBits << 1) | uintptr_t(1);
118   }
119
120   // Return the size.
121   size_t getSmallSize() const {
122     return getSmallRawBits() >> SmallNumDataBits;
123   }
124
125   void setSmallSize(size_t Size) {
126     setSmallRawBits(getSmallBits() | (Size << SmallNumDataBits));
127   }
128
129   // Return the element bits.
130   uintptr_t getSmallBits() const {
131     return getSmallRawBits() & ~(~uintptr_t(0) << getSmallSize());
132   }
133
134   void setSmallBits(uintptr_t NewBits) {
135     setSmallRawBits((NewBits & ~(~uintptr_t(0) << getSmallSize())) |
136                     (getSmallSize() << SmallNumDataBits));
137   }
138
139 public:
140   /// SmallBitVector default ctor - Creates an empty bitvector.
141   SmallBitVector() : X(1) {}
142
143   /// SmallBitVector ctor - Creates a bitvector of specified number of bits. All
144   /// bits are initialized to the specified value.
145   explicit SmallBitVector(unsigned s, bool t = false) {
146     if (s <= SmallNumDataBits)
147       switchToSmall(t ? ~uintptr_t(0) : 0, s);
148     else
149       switchToLarge(new BitVector(s, t));
150   }
151
152   /// SmallBitVector copy ctor.
153   SmallBitVector(const SmallBitVector &RHS) {
154     if (RHS.isSmall())
155       X = RHS.X;
156     else
157       switchToLarge(new BitVector(*RHS.getPointer()));
158   }
159
160   SmallBitVector(SmallBitVector &&RHS) : X(RHS.X) {
161     RHS.X = 1;
162   }
163
164   ~SmallBitVector() {
165     if (!isSmall())
166       delete getPointer();
167   }
168
169   /// empty - Tests whether there are no bits in this bitvector.
170   bool empty() const {
171     return isSmall() ? getSmallSize() == 0 : getPointer()->empty();
172   }
173
174   /// size - Returns the number of bits in this bitvector.
175   size_t size() const {
176     return isSmall() ? getSmallSize() : getPointer()->size();
177   }
178
179   /// count - Returns the number of bits which are set.
180   size_type count() const {
181     if (isSmall()) {
182       uintptr_t Bits = getSmallBits();
183       return countPopulation(Bits);
184     }
185     return getPointer()->count();
186   }
187
188   /// any - Returns true if any bit is set.
189   bool any() const {
190     if (isSmall())
191       return getSmallBits() != 0;
192     return getPointer()->any();
193   }
194
195   /// all - Returns true if all bits are set.
196   bool all() const {
197     if (isSmall())
198       return getSmallBits() == (uintptr_t(1) << getSmallSize()) - 1;
199     return getPointer()->all();
200   }
201
202   /// none - Returns true if none of the bits are set.
203   bool none() const {
204     if (isSmall())
205       return getSmallBits() == 0;
206     return getPointer()->none();
207   }
208
209   /// find_first - Returns the index of the first set bit, -1 if none
210   /// of the bits are set.
211   int find_first() const {
212     if (isSmall()) {
213       uintptr_t Bits = getSmallBits();
214       if (Bits == 0)
215         return -1;
216       return countTrailingZeros(Bits);
217     }
218     return getPointer()->find_first();
219   }
220
221   /// find_next - Returns the index of the next set bit following the
222   /// "Prev" bit. Returns -1 if the next set bit is not found.
223   int find_next(unsigned Prev) const {
224     if (isSmall()) {
225       uintptr_t Bits = getSmallBits();
226       // Mask off previous bits.
227       Bits &= ~uintptr_t(0) << (Prev + 1);
228       if (Bits == 0 || Prev + 1 >= getSmallSize())
229         return -1;
230       return countTrailingZeros(Bits);
231     }
232     return getPointer()->find_next(Prev);
233   }
234
235   /// clear - Clear all bits.
236   void clear() {
237     if (!isSmall())
238       delete getPointer();
239     switchToSmall(0, 0);
240   }
241
242   /// resize - Grow or shrink the bitvector.
243   void resize(unsigned N, bool t = false) {
244     if (!isSmall()) {
245       getPointer()->resize(N, t);
246     } else if (SmallNumDataBits >= N) {
247       uintptr_t NewBits = t ? ~uintptr_t(0) << getSmallSize() : 0;
248       setSmallSize(N);
249       setSmallBits(NewBits | getSmallBits());
250     } else {
251       BitVector *BV = new BitVector(N, t);
252       uintptr_t OldBits = getSmallBits();
253       for (size_t i = 0, e = getSmallSize(); i != e; ++i)
254         (*BV)[i] = (OldBits >> i) & 1;
255       switchToLarge(BV);
256     }
257   }
258
259   void reserve(unsigned N) {
260     if (isSmall()) {
261       if (N > SmallNumDataBits) {
262         uintptr_t OldBits = getSmallRawBits();
263         size_t SmallSize = getSmallSize();
264         BitVector *BV = new BitVector(SmallSize);
265         for (size_t i = 0; i < SmallSize; ++i)
266           if ((OldBits >> i) & 1)
267             BV->set(i);
268         BV->reserve(N);
269         switchToLarge(BV);
270       }
271     } else {
272       getPointer()->reserve(N);
273     }
274   }
275
276   // Set, reset, flip
277   SmallBitVector &set() {
278     if (isSmall())
279       setSmallBits(~uintptr_t(0));
280     else
281       getPointer()->set();
282     return *this;
283   }
284
285   SmallBitVector &set(unsigned Idx) {
286     if (isSmall()) {
287       assert(Idx <= static_cast<unsigned>(
288                         std::numeric_limits<uintptr_t>::digits) &&
289              "undefined behavior");
290       setSmallBits(getSmallBits() | (uintptr_t(1) << Idx));
291     }
292     else
293       getPointer()->set(Idx);
294     return *this;
295   }
296
297   /// set - Efficiently set a range of bits in [I, E)
298   SmallBitVector &set(unsigned I, unsigned E) {
299     assert(I <= E && "Attempted to set backwards range!");
300     assert(E <= size() && "Attempted to set out-of-bounds range!");
301     if (I == E) return *this;
302     if (isSmall()) {
303       uintptr_t EMask = ((uintptr_t)1) << E;
304       uintptr_t IMask = ((uintptr_t)1) << I;
305       uintptr_t Mask = EMask - IMask;
306       setSmallBits(getSmallBits() | Mask);
307     } else
308       getPointer()->set(I, E);
309     return *this;
310   }
311
312   SmallBitVector &reset() {
313     if (isSmall())
314       setSmallBits(0);
315     else
316       getPointer()->reset();
317     return *this;
318   }
319
320   SmallBitVector &reset(unsigned Idx) {
321     if (isSmall())
322       setSmallBits(getSmallBits() & ~(uintptr_t(1) << Idx));
323     else
324       getPointer()->reset(Idx);
325     return *this;
326   }
327
328   /// reset - Efficiently reset a range of bits in [I, E)
329   SmallBitVector &reset(unsigned I, unsigned E) {
330     assert(I <= E && "Attempted to reset backwards range!");
331     assert(E <= size() && "Attempted to reset out-of-bounds range!");
332     if (I == E) return *this;
333     if (isSmall()) {
334       uintptr_t EMask = ((uintptr_t)1) << E;
335       uintptr_t IMask = ((uintptr_t)1) << I;
336       uintptr_t Mask = EMask - IMask;
337       setSmallBits(getSmallBits() & ~Mask);
338     } else
339       getPointer()->reset(I, E);
340     return *this;
341   }
342
343   SmallBitVector &flip() {
344     if (isSmall())
345       setSmallBits(~getSmallBits());
346     else
347       getPointer()->flip();
348     return *this;
349   }
350
351   SmallBitVector &flip(unsigned Idx) {
352     if (isSmall())
353       setSmallBits(getSmallBits() ^ (uintptr_t(1) << Idx));
354     else
355       getPointer()->flip(Idx);
356     return *this;
357   }
358
359   // No argument flip.
360   SmallBitVector operator~() const {
361     return SmallBitVector(*this).flip();
362   }
363
364   // Indexing.
365   reference operator[](unsigned Idx) {
366     assert(Idx < size() && "Out-of-bounds Bit access.");
367     return reference(*this, Idx);
368   }
369
370   bool operator[](unsigned Idx) const {
371     assert(Idx < size() && "Out-of-bounds Bit access.");
372     if (isSmall())
373       return ((getSmallBits() >> Idx) & 1) != 0;
374     return getPointer()->operator[](Idx);
375   }
376
377   bool test(unsigned Idx) const {
378     return (*this)[Idx];
379   }
380
381   /// Test if any common bits are set.
382   bool anyCommon(const SmallBitVector &RHS) const {
383     if (isSmall() && RHS.isSmall())
384       return (getSmallBits() & RHS.getSmallBits()) != 0;
385     if (!isSmall() && !RHS.isSmall())
386       return getPointer()->anyCommon(*RHS.getPointer());
387
388     for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
389       if (test(i) && RHS.test(i))
390         return true;
391     return false;
392   }
393
394   // Comparison operators.
395   bool operator==(const SmallBitVector &RHS) const {
396     if (size() != RHS.size())
397       return false;
398     if (isSmall())
399       return getSmallBits() == RHS.getSmallBits();
400     else
401       return *getPointer() == *RHS.getPointer();
402   }
403
404   bool operator!=(const SmallBitVector &RHS) const {
405     return !(*this == RHS);
406   }
407
408   // Intersection, union, disjoint union.
409   SmallBitVector &operator&=(const SmallBitVector &RHS) {
410     resize(std::max(size(), RHS.size()));
411     if (isSmall())
412       setSmallBits(getSmallBits() & RHS.getSmallBits());
413     else if (!RHS.isSmall())
414       getPointer()->operator&=(*RHS.getPointer());
415     else {
416       SmallBitVector Copy = RHS;
417       Copy.resize(size());
418       getPointer()->operator&=(*Copy.getPointer());
419     }
420     return *this;
421   }
422
423   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
424   SmallBitVector &reset(const SmallBitVector &RHS) {
425     if (isSmall() && RHS.isSmall())
426       setSmallBits(getSmallBits() & ~RHS.getSmallBits());
427     else if (!isSmall() && !RHS.isSmall())
428       getPointer()->reset(*RHS.getPointer());
429     else
430       for (unsigned i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
431         if (RHS.test(i))
432           reset(i);
433
434     return *this;
435   }
436
437   /// test - Check if (This - RHS) is zero.
438   /// This is the same as reset(RHS) and any().
439   bool test(const SmallBitVector &RHS) const {
440     if (isSmall() && RHS.isSmall())
441       return (getSmallBits() & ~RHS.getSmallBits()) != 0;
442     if (!isSmall() && !RHS.isSmall())
443       return getPointer()->test(*RHS.getPointer());
444
445     unsigned i, e;
446     for (i = 0, e = std::min(size(), RHS.size()); i != e; ++i)
447       if (test(i) && !RHS.test(i))
448         return true;
449
450     for (e = size(); i != e; ++i)
451       if (test(i))
452         return true;
453
454     return false;
455   }
456
457   SmallBitVector &operator|=(const SmallBitVector &RHS) {
458     resize(std::max(size(), RHS.size()));
459     if (isSmall())
460       setSmallBits(getSmallBits() | RHS.getSmallBits());
461     else if (!RHS.isSmall())
462       getPointer()->operator|=(*RHS.getPointer());
463     else {
464       SmallBitVector Copy = RHS;
465       Copy.resize(size());
466       getPointer()->operator|=(*Copy.getPointer());
467     }
468     return *this;
469   }
470
471   SmallBitVector &operator^=(const SmallBitVector &RHS) {
472     resize(std::max(size(), RHS.size()));
473     if (isSmall())
474       setSmallBits(getSmallBits() ^ RHS.getSmallBits());
475     else if (!RHS.isSmall())
476       getPointer()->operator^=(*RHS.getPointer());
477     else {
478       SmallBitVector Copy = RHS;
479       Copy.resize(size());
480       getPointer()->operator^=(*Copy.getPointer());
481     }
482     return *this;
483   }
484
485   // Assignment operator.
486   const SmallBitVector &operator=(const SmallBitVector &RHS) {
487     if (isSmall()) {
488       if (RHS.isSmall())
489         X = RHS.X;
490       else
491         switchToLarge(new BitVector(*RHS.getPointer()));
492     } else {
493       if (!RHS.isSmall())
494         *getPointer() = *RHS.getPointer();
495       else {
496         delete getPointer();
497         X = RHS.X;
498       }
499     }
500     return *this;
501   }
502
503   const SmallBitVector &operator=(SmallBitVector &&RHS) {
504     if (this != &RHS) {
505       clear();
506       swap(RHS);
507     }
508     return *this;
509   }
510
511   void swap(SmallBitVector &RHS) {
512     std::swap(X, RHS.X);
513   }
514
515   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
516   /// This computes "*this |= Mask".
517   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
518     if (isSmall())
519       applyMask<true, false>(Mask, MaskWords);
520     else
521       getPointer()->setBitsInMask(Mask, MaskWords);
522   }
523
524   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
525   /// Don't resize. This computes "*this &= ~Mask".
526   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
527     if (isSmall())
528       applyMask<false, false>(Mask, MaskWords);
529     else
530       getPointer()->clearBitsInMask(Mask, MaskWords);
531   }
532
533   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
534   /// Don't resize.  This computes "*this |= ~Mask".
535   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
536     if (isSmall())
537       applyMask<true, true>(Mask, MaskWords);
538     else
539       getPointer()->setBitsNotInMask(Mask, MaskWords);
540   }
541
542   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
543   /// Don't resize.  This computes "*this &= Mask".
544   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
545     if (isSmall())
546       applyMask<false, true>(Mask, MaskWords);
547     else
548       getPointer()->clearBitsNotInMask(Mask, MaskWords);
549   }
550
551 private:
552   template<bool AddBits, bool InvertMask>
553   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
554     if (NumBaseBits == 64 && MaskWords >= 2) {
555       uint64_t M = Mask[0] | (uint64_t(Mask[1]) << 32);
556       if (InvertMask) M = ~M;
557       if (AddBits) setSmallBits(getSmallBits() | M);
558       else         setSmallBits(getSmallBits() & ~M);
559     } else {
560       uint32_t M = Mask[0];
561       if (InvertMask) M = ~M;
562       if (AddBits) setSmallBits(getSmallBits() | M);
563       else         setSmallBits(getSmallBits() & ~M);
564     }
565   }
566 };
567
568 inline SmallBitVector
569 operator&(const SmallBitVector &LHS, const SmallBitVector &RHS) {
570   SmallBitVector Result(LHS);
571   Result &= RHS;
572   return Result;
573 }
574
575 inline SmallBitVector
576 operator|(const SmallBitVector &LHS, const SmallBitVector &RHS) {
577   SmallBitVector Result(LHS);
578   Result |= RHS;
579   return Result;
580 }
581
582 inline SmallBitVector
583 operator^(const SmallBitVector &LHS, const SmallBitVector &RHS) {
584   SmallBitVector Result(LHS);
585   Result ^= RHS;
586   return Result;
587 }
588
589 } // End llvm namespace
590
591 namespace std {
592   /// Implement std::swap in terms of BitVector swap.
593   inline void
594   swap(llvm::SmallBitVector &LHS, llvm::SmallBitVector &RHS) {
595     LHS.swap(RHS);
596   }
597 }
598
599 #endif