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