444f47471c369a70b6915f6719a0e258221b1ba0
[oota-llvm.git] / include / llvm / ADT / BitVector.h
1 //===- llvm/ADT/BitVector.h - 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 BitVector class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_BITVECTOR_H
15 #define LLVM_ADT_BITVECTOR_H
16
17 #include "llvm/Support/Compiler.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
20 #include <algorithm>
21 #include <cassert>
22 #include <climits>
23 #include <cstdlib>
24
25 namespace llvm {
26
27 class BitVector {
28   typedef unsigned long BitWord;
29
30   enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
31
32   static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
33                 "Unsupported word size");
34
35   BitWord  *Bits;        // Actual bits.
36   unsigned Size;         // Size of bitvector in bits.
37   unsigned Capacity;     // Size of allocated memory in BitWord.
38
39 public:
40   typedef unsigned size_type;
41   // Encapsulation of a single bit.
42   class reference {
43     friend class BitVector;
44
45     BitWord *WordRef;
46     unsigned BitPos;
47
48     reference();  // Undefined
49
50   public:
51     reference(BitVector &b, unsigned Idx) {
52       WordRef = &b.Bits[Idx / BITWORD_SIZE];
53       BitPos = Idx % BITWORD_SIZE;
54     }
55
56     ~reference() {}
57
58     reference &operator=(reference t) {
59       *this = bool(t);
60       return *this;
61     }
62
63     reference& operator=(bool t) {
64       if (t)
65         *WordRef |= BitWord(1) << BitPos;
66       else
67         *WordRef &= ~(BitWord(1) << BitPos);
68       return *this;
69     }
70
71     operator bool() const {
72       return ((*WordRef) & (BitWord(1) << BitPos)) ? true : false;
73     }
74   };
75
76
77   /// BitVector default ctor - Creates an empty bitvector.
78   BitVector() : Size(0), Capacity(0) {
79     Bits = nullptr;
80   }
81
82   /// BitVector ctor - Creates a bitvector of specified number of bits. All
83   /// bits are initialized to the specified value.
84   explicit BitVector(unsigned s, bool t = false) : Size(s) {
85     Capacity = NumBitWords(s);
86     Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
87     init_words(Bits, Capacity, t);
88     if (t)
89       clear_unused_bits();
90   }
91
92   /// BitVector copy ctor.
93   BitVector(const BitVector &RHS) : Size(RHS.size()) {
94     if (Size == 0) {
95       Bits = nullptr;
96       Capacity = 0;
97       return;
98     }
99
100     Capacity = NumBitWords(RHS.size());
101     Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
102     std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
103   }
104
105   BitVector(BitVector &&RHS)
106     : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) {
107     RHS.Bits = nullptr;
108   }
109
110   ~BitVector() {
111     std::free(Bits);
112   }
113
114   /// empty - Tests whether there are no bits in this bitvector.
115   bool empty() const { return Size == 0; }
116
117   /// size - Returns the number of bits in this bitvector.
118   size_type size() const { return Size; }
119
120   /// count - Returns the number of bits which are set.
121   size_type count() const {
122     unsigned NumBits = 0;
123     for (unsigned i = 0; i < NumBitWords(size()); ++i)
124       if (sizeof(BitWord) == 4)
125         NumBits += CountPopulation_32((uint32_t)Bits[i]);
126       else if (sizeof(BitWord) == 8)
127         NumBits += CountPopulation_64(Bits[i]);
128       else
129         llvm_unreachable("Unsupported!");
130     return NumBits;
131   }
132
133   /// any - Returns true if any bit is set.
134   bool any() const {
135     for (unsigned i = 0; i < NumBitWords(size()); ++i)
136       if (Bits[i] != 0)
137         return true;
138     return false;
139   }
140
141   /// all - Returns true if all bits are set.
142   bool all() const {
143     for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
144       if (Bits[i] != ~0UL)
145         return false;
146
147     // If bits remain check that they are ones. The unused bits are always zero.
148     if (unsigned Remainder = Size % BITWORD_SIZE)
149       return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1;
150
151     return true;
152   }
153
154   /// none - Returns true if none of the bits are set.
155   bool none() const {
156     return !any();
157   }
158
159   /// find_first - Returns the index of the first set bit, -1 if none
160   /// of the bits are set.
161   int find_first() const {
162     for (unsigned i = 0; i < NumBitWords(size()); ++i)
163       if (Bits[i] != 0)
164         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
165     return -1;
166   }
167
168   /// find_next - Returns the index of the next set bit following the
169   /// "Prev" bit. Returns -1 if the next set bit is not found.
170   int find_next(unsigned Prev) const {
171     ++Prev;
172     if (Prev >= Size)
173       return -1;
174
175     unsigned WordPos = Prev / BITWORD_SIZE;
176     unsigned BitPos = Prev % BITWORD_SIZE;
177     BitWord Copy = Bits[WordPos];
178     // Mask off previous bits.
179     Copy &= ~0UL << BitPos;
180
181     if (Copy != 0)
182       return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
183
184     // Check subsequent words.
185     for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
186       if (Bits[i] != 0)
187         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
188     return -1;
189   }
190
191   /// clear - Clear all bits.
192   void clear() {
193     Size = 0;
194   }
195
196   /// resize - Grow or shrink the bitvector.
197   void resize(unsigned N, bool t = false) {
198     if (N > Capacity * BITWORD_SIZE) {
199       unsigned OldCapacity = Capacity;
200       grow(N);
201       init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
202     }
203
204     // Set any old unused bits that are now included in the BitVector. This
205     // may set bits that are not included in the new vector, but we will clear
206     // them back out below.
207     if (N > Size)
208       set_unused_bits(t);
209
210     // Update the size, and clear out any bits that are now unused
211     unsigned OldSize = Size;
212     Size = N;
213     if (t || N < OldSize)
214       clear_unused_bits();
215   }
216
217   void reserve(unsigned N) {
218     if (N > Capacity * BITWORD_SIZE)
219       grow(N);
220   }
221
222   // Set, reset, flip
223   BitVector &set() {
224     init_words(Bits, Capacity, true);
225     clear_unused_bits();
226     return *this;
227   }
228
229   BitVector &set(unsigned Idx) {
230     assert(Bits && "Bits never allocated");
231     Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
232     return *this;
233   }
234
235   /// set - Efficiently set a range of bits in [I, E)
236   BitVector &set(unsigned I, unsigned E) {
237     assert(I <= E && "Attempted to set backwards range!");
238     assert(E <= size() && "Attempted to set out-of-bounds range!");
239
240     if (I == E) return *this;
241
242     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
243       BitWord EMask = 1UL << (E % BITWORD_SIZE);
244       BitWord IMask = 1UL << (I % BITWORD_SIZE);
245       BitWord Mask = EMask - IMask;
246       Bits[I / BITWORD_SIZE] |= Mask;
247       return *this;
248     }
249
250     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
251     Bits[I / BITWORD_SIZE] |= PrefixMask;
252     I = RoundUpToAlignment(I, BITWORD_SIZE);
253
254     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
255       Bits[I / BITWORD_SIZE] = ~0UL;
256
257     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
258     if (I < E)
259       Bits[I / BITWORD_SIZE] |= PostfixMask;
260
261     return *this;
262   }
263
264   BitVector &reset() {
265     init_words(Bits, Capacity, false);
266     return *this;
267   }
268
269   BitVector &reset(unsigned Idx) {
270     Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
271     return *this;
272   }
273
274   /// reset - Efficiently reset a range of bits in [I, E)
275   BitVector &reset(unsigned I, unsigned E) {
276     assert(I <= E && "Attempted to reset backwards range!");
277     assert(E <= size() && "Attempted to reset out-of-bounds range!");
278
279     if (I == E) return *this;
280
281     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
282       BitWord EMask = 1UL << (E % BITWORD_SIZE);
283       BitWord IMask = 1UL << (I % BITWORD_SIZE);
284       BitWord Mask = EMask - IMask;
285       Bits[I / BITWORD_SIZE] &= ~Mask;
286       return *this;
287     }
288
289     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
290     Bits[I / BITWORD_SIZE] &= ~PrefixMask;
291     I = RoundUpToAlignment(I, BITWORD_SIZE);
292
293     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
294       Bits[I / BITWORD_SIZE] = 0UL;
295
296     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
297     if (I < E)
298       Bits[I / BITWORD_SIZE] &= ~PostfixMask;
299
300     return *this;
301   }
302
303   BitVector &flip() {
304     for (unsigned i = 0; i < NumBitWords(size()); ++i)
305       Bits[i] = ~Bits[i];
306     clear_unused_bits();
307     return *this;
308   }
309
310   BitVector &flip(unsigned Idx) {
311     Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
312     return *this;
313   }
314
315   // Indexing.
316   reference operator[](unsigned Idx) {
317     assert (Idx < Size && "Out-of-bounds Bit access.");
318     return reference(*this, Idx);
319   }
320
321   bool operator[](unsigned Idx) const {
322     assert (Idx < Size && "Out-of-bounds Bit access.");
323     BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
324     return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
325   }
326
327   bool test(unsigned Idx) const {
328     return (*this)[Idx];
329   }
330
331   /// Test if any common bits are set.
332   bool anyCommon(const BitVector &RHS) const {
333     unsigned ThisWords = NumBitWords(size());
334     unsigned RHSWords  = NumBitWords(RHS.size());
335     for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
336       if (Bits[i] & RHS.Bits[i])
337         return true;
338     return false;
339   }
340
341   // Comparison operators.
342   bool operator==(const BitVector &RHS) const {
343     unsigned ThisWords = NumBitWords(size());
344     unsigned RHSWords  = NumBitWords(RHS.size());
345     unsigned i;
346     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
347       if (Bits[i] != RHS.Bits[i])
348         return false;
349
350     // Verify that any extra words are all zeros.
351     if (i != ThisWords) {
352       for (; i != ThisWords; ++i)
353         if (Bits[i])
354           return false;
355     } else if (i != RHSWords) {
356       for (; i != RHSWords; ++i)
357         if (RHS.Bits[i])
358           return false;
359     }
360     return true;
361   }
362
363   bool operator!=(const BitVector &RHS) const {
364     return !(*this == RHS);
365   }
366
367   /// Intersection, union, disjoint union.
368   BitVector &operator&=(const BitVector &RHS) {
369     unsigned ThisWords = NumBitWords(size());
370     unsigned RHSWords  = NumBitWords(RHS.size());
371     unsigned i;
372     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
373       Bits[i] &= RHS.Bits[i];
374
375     // Any bits that are just in this bitvector become zero, because they aren't
376     // in the RHS bit vector.  Any words only in RHS are ignored because they
377     // are already zero in the LHS.
378     for (; i != ThisWords; ++i)
379       Bits[i] = 0;
380
381     return *this;
382   }
383
384   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
385   BitVector &reset(const BitVector &RHS) {
386     unsigned ThisWords = NumBitWords(size());
387     unsigned RHSWords  = NumBitWords(RHS.size());
388     unsigned i;
389     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
390       Bits[i] &= ~RHS.Bits[i];
391     return *this;
392   }
393
394   /// test - Check if (This - RHS) is zero.
395   /// This is the same as reset(RHS) and any().
396   bool test(const BitVector &RHS) const {
397     unsigned ThisWords = NumBitWords(size());
398     unsigned RHSWords  = NumBitWords(RHS.size());
399     unsigned i;
400     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
401       if ((Bits[i] & ~RHS.Bits[i]) != 0)
402         return true;
403
404     for (; i != ThisWords ; ++i)
405       if (Bits[i] != 0)
406         return true;
407
408     return false;
409   }
410
411   BitVector &operator|=(const BitVector &RHS) {
412     if (size() < RHS.size())
413       resize(RHS.size());
414     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
415       Bits[i] |= RHS.Bits[i];
416     return *this;
417   }
418
419   BitVector &operator^=(const BitVector &RHS) {
420     if (size() < RHS.size())
421       resize(RHS.size());
422     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
423       Bits[i] ^= RHS.Bits[i];
424     return *this;
425   }
426
427   // Assignment operator.
428   const BitVector &operator=(const BitVector &RHS) {
429     if (this == &RHS) return *this;
430
431     Size = RHS.size();
432     unsigned RHSWords = NumBitWords(Size);
433     if (Size <= Capacity * BITWORD_SIZE) {
434       if (Size)
435         std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
436       clear_unused_bits();
437       return *this;
438     }
439
440     // Grow the bitvector to have enough elements.
441     Capacity = RHSWords;
442     assert(Capacity > 0 && "negative capacity?");
443     BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
444     std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
445
446     // Destroy the old bits.
447     std::free(Bits);
448     Bits = NewBits;
449
450     return *this;
451   }
452
453   const BitVector &operator=(BitVector &&RHS) {
454     if (this == &RHS) return *this;
455
456     std::free(Bits);
457     Bits = RHS.Bits;
458     Size = RHS.Size;
459     Capacity = RHS.Capacity;
460
461     RHS.Bits = nullptr;
462
463     return *this;
464   }
465
466   void swap(BitVector &RHS) {
467     std::swap(Bits, RHS.Bits);
468     std::swap(Size, RHS.Size);
469     std::swap(Capacity, RHS.Capacity);
470   }
471
472   //===--------------------------------------------------------------------===//
473   // Portable bit mask operations.
474   //===--------------------------------------------------------------------===//
475   //
476   // These methods all operate on arrays of uint32_t, each holding 32 bits. The
477   // fixed word size makes it easier to work with literal bit vector constants
478   // in portable code.
479   //
480   // The LSB in each word is the lowest numbered bit.  The size of a portable
481   // bit mask is always a whole multiple of 32 bits.  If no bit mask size is
482   // given, the bit mask is assumed to cover the entire BitVector.
483
484   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
485   /// This computes "*this |= Mask".
486   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
487     applyMask<true, false>(Mask, MaskWords);
488   }
489
490   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
491   /// Don't resize. This computes "*this &= ~Mask".
492   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
493     applyMask<false, false>(Mask, MaskWords);
494   }
495
496   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
497   /// Don't resize.  This computes "*this |= ~Mask".
498   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
499     applyMask<true, true>(Mask, MaskWords);
500   }
501
502   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
503   /// Don't resize.  This computes "*this &= Mask".
504   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
505     applyMask<false, true>(Mask, MaskWords);
506   }
507
508 private:
509   unsigned NumBitWords(unsigned S) const {
510     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
511   }
512
513   // Set the unused bits in the high words.
514   void set_unused_bits(bool t = true) {
515     //  Set high words first.
516     unsigned UsedWords = NumBitWords(Size);
517     if (Capacity > UsedWords)
518       init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
519
520     //  Then set any stray high bits of the last used word.
521     unsigned ExtraBits = Size % BITWORD_SIZE;
522     if (ExtraBits) {
523       BitWord ExtraBitMask = ~0UL << ExtraBits;
524       if (t)
525         Bits[UsedWords-1] |= ExtraBitMask;
526       else
527         Bits[UsedWords-1] &= ~ExtraBitMask;
528     }
529   }
530
531   // Clear the unused bits in the high words.
532   void clear_unused_bits() {
533     set_unused_bits(false);
534   }
535
536   void grow(unsigned NewSize) {
537     Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
538     assert(Capacity > 0 && "realloc-ing zero space");
539     Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
540
541     clear_unused_bits();
542   }
543
544   void init_words(BitWord *B, unsigned NumWords, bool t) {
545     memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
546   }
547
548   template<bool AddBits, bool InvertMask>
549   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
550     static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
551     MaskWords = std::min(MaskWords, (size() + 31) / 32);
552     const unsigned Scale = BITWORD_SIZE / 32;
553     unsigned i;
554     for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
555       BitWord BW = Bits[i];
556       // This inner loop should unroll completely when BITWORD_SIZE > 32.
557       for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
558         uint32_t M = *Mask++;
559         if (InvertMask) M = ~M;
560         if (AddBits) BW |=   BitWord(M) << b;
561         else         BW &= ~(BitWord(M) << b);
562       }
563       Bits[i] = BW;
564     }
565     for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
566       uint32_t M = *Mask++;
567       if (InvertMask) M = ~M;
568       if (AddBits) Bits[i] |=   BitWord(M) << b;
569       else         Bits[i] &= ~(BitWord(M) << b);
570     }
571     if (AddBits)
572       clear_unused_bits();
573   }
574 };
575
576 } // End llvm namespace
577
578 namespace std {
579   /// Implement std::swap in terms of BitVector swap.
580   inline void
581   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
582     LHS.swap(RHS);
583   }
584 }
585
586 #endif