1 //===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the BitVector class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_BITVECTOR_H
15 #define LLVM_ADT_BITVECTOR_H
17 #include "llvm/Support/ErrorHandling.h"
18 #include "llvm/Support/MathExtras.h"
27 typedef unsigned long BitWord;
29 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
31 BitWord *Bits; // Actual bits.
32 unsigned Size; // Size of bitvector in bits.
33 unsigned Capacity; // Size of allocated memory in BitWord.
36 // Encapsulation of a single bit.
38 friend class BitVector;
43 reference(); // Undefined
46 reference(BitVector &b, unsigned Idx) {
47 WordRef = &b.Bits[Idx / BITWORD_SIZE];
48 BitPos = Idx % BITWORD_SIZE;
53 reference &operator=(reference t) {
58 reference& operator=(bool t) {
60 *WordRef |= 1L << BitPos;
62 *WordRef &= ~(1L << BitPos);
66 operator bool() const {
67 return ((*WordRef) & (1L << BitPos)) ? true : false;
72 /// BitVector default ctor - Creates an empty bitvector.
73 BitVector() : Size(0), Capacity(0) {
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);
87 /// BitVector copy ctor.
88 BitVector(const BitVector &RHS) : Size(RHS.size()) {
95 Capacity = NumBitWords(RHS.size());
96 Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
97 std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
104 /// empty - Tests whether there are no bits in this bitvector.
105 bool empty() const { return Size == 0; }
107 /// size - Returns the number of bits in this bitvector.
108 unsigned size() const { return Size; }
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]);
119 llvm_unreachable("Unsupported!");
123 /// any - Returns true if any bit is set.
125 for (unsigned i = 0; i < NumBitWords(size()); ++i)
131 /// all - Returns true if all bits are set.
133 // TODO: Optimize this.
134 return count() == size();
137 /// none - Returns true if none of the bits are set.
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)
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!");
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 {
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;
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!");
177 // Check subsequent words.
178 for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
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!");
189 /// clear - Clear all bits.
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;
199 init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
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.
208 // Update the size, and clear out any bits that are now unused
209 unsigned OldSize = Size;
211 if (t || N < OldSize)
215 void reserve(unsigned N) {
216 if (N > Capacity * BITWORD_SIZE)
222 init_words(Bits, Capacity, true);
227 BitVector &set(unsigned Idx) {
228 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
233 init_words(Bits, Capacity, false);
237 BitVector &reset(unsigned Idx) {
238 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
243 for (unsigned i = 0; i < NumBitWords(size()); ++i)
249 BitVector &flip(unsigned Idx) {
250 Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
255 BitVector operator~() const {
256 return BitVector(*this).flip();
260 reference operator[](unsigned Idx) {
261 assert (Idx < Size && "Out-of-bounds Bit access.");
262 return reference(*this, Idx);
265 bool operator[](unsigned Idx) const {
266 assert (Idx < Size && "Out-of-bounds Bit access.");
267 BitWord Mask = 1L << (Idx % BITWORD_SIZE);
268 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
271 bool test(unsigned Idx) const {
275 // Comparison operators.
276 bool operator==(const BitVector &RHS) const {
277 unsigned ThisWords = NumBitWords(size());
278 unsigned RHSWords = NumBitWords(RHS.size());
280 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
281 if (Bits[i] != RHS.Bits[i])
284 // Verify that any extra words are all zeros.
285 if (i != ThisWords) {
286 for (; i != ThisWords; ++i)
289 } else if (i != RHSWords) {
290 for (; i != RHSWords; ++i)
297 bool operator!=(const BitVector &RHS) const {
298 return !(*this == RHS);
301 // Intersection, union, disjoint union.
302 BitVector &operator&=(const BitVector &RHS) {
303 unsigned ThisWords = NumBitWords(size());
304 unsigned RHSWords = NumBitWords(RHS.size());
306 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
307 Bits[i] &= RHS.Bits[i];
309 // Any bits that are just in this bitvector become zero, because they aren't
310 // in the RHS bit vector. Any words only in RHS are ignored because they
311 // are already zero in the LHS.
312 for (; i != ThisWords; ++i)
318 // reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
319 BitVector &reset(const BitVector &RHS) {
320 unsigned ThisWords = NumBitWords(size());
321 unsigned RHSWords = NumBitWords(RHS.size());
323 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
324 Bits[i] &= ~RHS.Bits[i];
328 BitVector &operator|=(const BitVector &RHS) {
329 if (size() < RHS.size())
331 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
332 Bits[i] |= RHS.Bits[i];
336 BitVector &operator^=(const BitVector &RHS) {
337 if (size() < RHS.size())
339 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
340 Bits[i] ^= RHS.Bits[i];
344 // Assignment operator.
345 const BitVector &operator=(const BitVector &RHS) {
346 if (this == &RHS) return *this;
349 unsigned RHSWords = NumBitWords(Size);
350 if (Size <= Capacity * BITWORD_SIZE) {
352 std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
357 // Grow the bitvector to have enough elements.
359 BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
360 std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
362 // Destroy the old bits.
369 void swap(BitVector &RHS) {
370 std::swap(Bits, RHS.Bits);
371 std::swap(Size, RHS.Size);
372 std::swap(Capacity, RHS.Capacity);
375 //===--------------------------------------------------------------------===//
376 // Portable bit mask operations.
377 //===--------------------------------------------------------------------===//
379 // These methods all operate on arrays of uint32_t, each holding 32 bits. The
380 // fixed word size makes it easier to work with literal bit vector constants
383 // The LSB in each word is the lowest numbered bit. The size of a portable
384 // bit mask is always a whole multiple of 32 bits. If no bit mask size is
385 // given, the bit mask is assumed to cover the entire BitVector.
387 /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
388 /// This computes "*this |= Mask".
389 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
390 applyMask<true, false>(Mask, MaskWords);
393 /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
394 /// Don't resize. This computes "*this &= ~Mask".
395 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
396 applyMask<false, false>(Mask, MaskWords);
399 /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
400 /// Don't resize. This computes "*this |= ~Mask".
401 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
402 applyMask<true, true>(Mask, MaskWords);
405 /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
406 /// Don't resize. This computes "*this &= Mask".
407 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
408 applyMask<false, true>(Mask, MaskWords);
412 unsigned NumBitWords(unsigned S) const {
413 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
416 // Set the unused bits in the high words.
417 void set_unused_bits(bool t = true) {
418 // Set high words first.
419 unsigned UsedWords = NumBitWords(Size);
420 if (Capacity > UsedWords)
421 init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
423 // Then set any stray high bits of the last used word.
424 unsigned ExtraBits = Size % BITWORD_SIZE;
426 Bits[UsedWords-1] &= ~(~0L << ExtraBits);
427 Bits[UsedWords-1] |= (0 - (BitWord)t) << ExtraBits;
431 // Clear the unused bits in the high words.
432 void clear_unused_bits() {
433 set_unused_bits(false);
436 void grow(unsigned NewSize) {
437 Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
438 Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
443 void init_words(BitWord *B, unsigned NumWords, bool t) {
444 memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
447 template<bool AddBits, bool InvertMask>
448 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
449 assert(BITWORD_SIZE % 32 == 0 && "Unsupported BitWord size.");
450 MaskWords = std::min(MaskWords, (size() + 31) / 32);
451 const unsigned Scale = BITWORD_SIZE / 32;
453 for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
454 BitWord BW = Bits[i];
455 // This inner loop should unroll completely when BITWORD_SIZE > 32.
456 for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
457 uint32_t M = *Mask++;
458 if (InvertMask) M = ~M;
459 if (AddBits) BW |= BitWord(M) << b;
460 else BW &= ~(BitWord(M) << b);
464 for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
465 uint32_t M = *Mask++;
466 if (InvertMask) M = ~M;
467 if (AddBits) Bits[i] |= BitWord(M) << b;
468 else Bits[i] &= ~(BitWord(M) << b);
475 inline BitVector operator&(const BitVector &LHS, const BitVector &RHS) {
476 BitVector Result(LHS);
481 inline BitVector operator|(const BitVector &LHS, const BitVector &RHS) {
482 BitVector Result(LHS);
487 inline BitVector operator^(const BitVector &LHS, const BitVector &RHS) {
488 BitVector Result(LHS);
493 } // End llvm namespace
496 /// Implement std::swap in terms of BitVector swap.
498 swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {