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/Compiler.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/MathExtras.h"
28 typedef unsigned long BitWord;
30 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
32 BitWord *Bits; // Actual bits.
33 unsigned Size; // Size of bitvector in bits.
34 unsigned Capacity; // Size of allocated memory in BitWord.
37 // Encapsulation of a single bit.
39 friend class BitVector;
44 reference(); // Undefined
47 reference(BitVector &b, unsigned Idx) {
48 WordRef = &b.Bits[Idx / BITWORD_SIZE];
49 BitPos = Idx % BITWORD_SIZE;
54 reference &operator=(reference t) {
59 reference& operator=(bool t) {
61 *WordRef |= 1L << BitPos;
63 *WordRef &= ~(1L << BitPos);
67 operator bool() const {
68 return ((*WordRef) & (1L << BitPos)) ? true : false;
73 /// BitVector default ctor - Creates an empty bitvector.
74 BitVector() : Size(0), Capacity(0) {
78 /// BitVector ctor - Creates a bitvector of specified number of bits. All
79 /// bits are initialized to the specified value.
80 explicit BitVector(unsigned s, bool t = false) : Size(s) {
81 Capacity = NumBitWords(s);
82 Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
83 init_words(Bits, Capacity, t);
88 /// BitVector copy ctor.
89 BitVector(const BitVector &RHS) : Size(RHS.size()) {
96 Capacity = NumBitWords(RHS.size());
97 Bits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
98 std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord));
101 #if LLVM_HAS_RVALUE_REFERENCES
102 BitVector(BitVector &&RHS)
103 : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) {
112 /// empty - Tests whether there are no bits in this bitvector.
113 bool empty() const { return Size == 0; }
115 /// size - Returns the number of bits in this bitvector.
116 unsigned size() const { return Size; }
118 /// count - Returns the number of bits which are set.
119 unsigned count() const {
120 unsigned NumBits = 0;
121 for (unsigned i = 0; i < NumBitWords(size()); ++i)
122 if (sizeof(BitWord) == 4)
123 NumBits += CountPopulation_32((uint32_t)Bits[i]);
124 else if (sizeof(BitWord) == 8)
125 NumBits += CountPopulation_64(Bits[i]);
127 llvm_unreachable("Unsupported!");
131 /// any - Returns true if any bit is set.
133 for (unsigned i = 0; i < NumBitWords(size()); ++i)
139 /// all - Returns true if all bits are set.
141 for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
145 // If bits remain check that they are ones. The unused bits are always zero.
146 if (unsigned Remainder = Size % BITWORD_SIZE)
147 return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1;
152 /// none - Returns true if none of the bits are set.
157 /// find_first - Returns the index of the first set bit, -1 if none
158 /// of the bits are set.
159 int find_first() const {
160 for (unsigned i = 0; i < NumBitWords(size()); ++i)
162 if (sizeof(BitWord) == 4)
163 return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
164 if (sizeof(BitWord) == 8)
165 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
166 llvm_unreachable("Unsupported!");
171 /// find_next - Returns the index of the next set bit following the
172 /// "Prev" bit. Returns -1 if the next set bit is not found.
173 int find_next(unsigned Prev) const {
178 unsigned WordPos = Prev / BITWORD_SIZE;
179 unsigned BitPos = Prev % BITWORD_SIZE;
180 BitWord Copy = Bits[WordPos];
181 // Mask off previous bits.
182 Copy &= ~0UL << BitPos;
185 if (sizeof(BitWord) == 4)
186 return WordPos * BITWORD_SIZE + countTrailingZeros((uint32_t)Copy);
187 if (sizeof(BitWord) == 8)
188 return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
189 llvm_unreachable("Unsupported!");
192 // Check subsequent words.
193 for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
195 if (sizeof(BitWord) == 4)
196 return i * BITWORD_SIZE + countTrailingZeros((uint32_t)Bits[i]);
197 if (sizeof(BitWord) == 8)
198 return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
199 llvm_unreachable("Unsupported!");
204 /// clear - Clear all bits.
209 /// resize - Grow or shrink the bitvector.
210 void resize(unsigned N, bool t = false) {
211 if (N > Capacity * BITWORD_SIZE) {
212 unsigned OldCapacity = Capacity;
214 init_words(&Bits[OldCapacity], (Capacity-OldCapacity), t);
217 // Set any old unused bits that are now included in the BitVector. This
218 // may set bits that are not included in the new vector, but we will clear
219 // them back out below.
223 // Update the size, and clear out any bits that are now unused
224 unsigned OldSize = Size;
226 if (t || N < OldSize)
230 void reserve(unsigned N) {
231 if (N > Capacity * BITWORD_SIZE)
237 init_words(Bits, Capacity, true);
242 BitVector &set(unsigned Idx) {
243 Bits[Idx / BITWORD_SIZE] |= 1L << (Idx % BITWORD_SIZE);
247 /// set - Efficiently set a range of bits in [I, E)
248 BitVector &set(unsigned I, unsigned E) {
249 assert(I <= E && "Attempted to set backwards range!");
250 assert(E <= size() && "Attempted to set out-of-bounds range!");
252 if (I == E) return *this;
254 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
255 BitWord EMask = 1UL << (E % BITWORD_SIZE);
256 BitWord IMask = 1UL << (I % BITWORD_SIZE);
257 BitWord Mask = EMask - IMask;
258 Bits[I / BITWORD_SIZE] |= Mask;
262 BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
263 Bits[I / BITWORD_SIZE] |= PrefixMask;
264 I = RoundUpToAlignment(I, BITWORD_SIZE);
266 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
267 Bits[I / BITWORD_SIZE] = ~0UL;
269 BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
270 Bits[I / BITWORD_SIZE] |= PostfixMask;
276 init_words(Bits, Capacity, false);
280 BitVector &reset(unsigned Idx) {
281 Bits[Idx / BITWORD_SIZE] &= ~(1L << (Idx % BITWORD_SIZE));
285 /// reset - Efficiently reset a range of bits in [I, E)
286 BitVector &reset(unsigned I, unsigned E) {
287 assert(I <= E && "Attempted to reset backwards range!");
288 assert(E <= size() && "Attempted to reset out-of-bounds range!");
290 if (I == E) return *this;
292 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
293 BitWord EMask = 1UL << (E % BITWORD_SIZE);
294 BitWord IMask = 1UL << (I % BITWORD_SIZE);
295 BitWord Mask = EMask - IMask;
296 Bits[I / BITWORD_SIZE] &= ~Mask;
300 BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
301 Bits[I / BITWORD_SIZE] &= ~PrefixMask;
302 I = RoundUpToAlignment(I, BITWORD_SIZE);
304 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
305 Bits[I / BITWORD_SIZE] = 0UL;
307 BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
308 Bits[I / BITWORD_SIZE] &= ~PostfixMask;
314 for (unsigned i = 0; i < NumBitWords(size()); ++i)
320 BitVector &flip(unsigned Idx) {
321 Bits[Idx / BITWORD_SIZE] ^= 1L << (Idx % BITWORD_SIZE);
326 reference operator[](unsigned Idx) {
327 assert (Idx < Size && "Out-of-bounds Bit access.");
328 return reference(*this, Idx);
331 bool operator[](unsigned Idx) const {
332 assert (Idx < Size && "Out-of-bounds Bit access.");
333 BitWord Mask = 1L << (Idx % BITWORD_SIZE);
334 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
337 bool test(unsigned Idx) const {
341 /// Test if any common bits are set.
342 bool anyCommon(const BitVector &RHS) const {
343 unsigned ThisWords = NumBitWords(size());
344 unsigned RHSWords = NumBitWords(RHS.size());
345 for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
346 if (Bits[i] & RHS.Bits[i])
351 // Comparison operators.
352 bool operator==(const BitVector &RHS) const {
353 unsigned ThisWords = NumBitWords(size());
354 unsigned RHSWords = NumBitWords(RHS.size());
356 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
357 if (Bits[i] != RHS.Bits[i])
360 // Verify that any extra words are all zeros.
361 if (i != ThisWords) {
362 for (; i != ThisWords; ++i)
365 } else if (i != RHSWords) {
366 for (; i != RHSWords; ++i)
373 bool operator!=(const BitVector &RHS) const {
374 return !(*this == RHS);
377 /// Intersection, union, disjoint union.
378 BitVector &operator&=(const BitVector &RHS) {
379 unsigned ThisWords = NumBitWords(size());
380 unsigned RHSWords = NumBitWords(RHS.size());
382 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
383 Bits[i] &= RHS.Bits[i];
385 // Any bits that are just in this bitvector become zero, because they aren't
386 // in the RHS bit vector. Any words only in RHS are ignored because they
387 // are already zero in the LHS.
388 for (; i != ThisWords; ++i)
394 /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
395 BitVector &reset(const BitVector &RHS) {
396 unsigned ThisWords = NumBitWords(size());
397 unsigned RHSWords = NumBitWords(RHS.size());
399 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
400 Bits[i] &= ~RHS.Bits[i];
404 /// test - Check if (This - RHS) is zero.
405 /// This is the same as reset(RHS) and any().
406 bool test(const BitVector &RHS) const {
407 unsigned ThisWords = NumBitWords(size());
408 unsigned RHSWords = NumBitWords(RHS.size());
410 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
411 if ((Bits[i] & ~RHS.Bits[i]) != 0)
414 for (; i != ThisWords ; ++i)
421 BitVector &operator|=(const BitVector &RHS) {
422 if (size() < RHS.size())
424 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
425 Bits[i] |= RHS.Bits[i];
429 BitVector &operator^=(const BitVector &RHS) {
430 if (size() < RHS.size())
432 for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
433 Bits[i] ^= RHS.Bits[i];
437 // Assignment operator.
438 const BitVector &operator=(const BitVector &RHS) {
439 if (this == &RHS) return *this;
442 unsigned RHSWords = NumBitWords(Size);
443 if (Size <= Capacity * BITWORD_SIZE) {
445 std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
450 // Grow the bitvector to have enough elements.
452 BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
453 std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
455 // Destroy the old bits.
462 #if LLVM_HAS_RVALUE_REFERENCES
463 const BitVector &operator=(BitVector &&RHS) {
464 if (this == &RHS) return *this;
469 Capacity = RHS.Capacity;
477 void swap(BitVector &RHS) {
478 std::swap(Bits, RHS.Bits);
479 std::swap(Size, RHS.Size);
480 std::swap(Capacity, RHS.Capacity);
483 //===--------------------------------------------------------------------===//
484 // Portable bit mask operations.
485 //===--------------------------------------------------------------------===//
487 // These methods all operate on arrays of uint32_t, each holding 32 bits. The
488 // fixed word size makes it easier to work with literal bit vector constants
491 // The LSB in each word is the lowest numbered bit. The size of a portable
492 // bit mask is always a whole multiple of 32 bits. If no bit mask size is
493 // given, the bit mask is assumed to cover the entire BitVector.
495 /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
496 /// This computes "*this |= Mask".
497 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
498 applyMask<true, false>(Mask, MaskWords);
501 /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
502 /// Don't resize. This computes "*this &= ~Mask".
503 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
504 applyMask<false, false>(Mask, MaskWords);
507 /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
508 /// Don't resize. This computes "*this |= ~Mask".
509 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
510 applyMask<true, true>(Mask, MaskWords);
513 /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
514 /// Don't resize. This computes "*this &= Mask".
515 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
516 applyMask<false, true>(Mask, MaskWords);
520 unsigned NumBitWords(unsigned S) const {
521 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
524 // Set the unused bits in the high words.
525 void set_unused_bits(bool t = true) {
526 // Set high words first.
527 unsigned UsedWords = NumBitWords(Size);
528 if (Capacity > UsedWords)
529 init_words(&Bits[UsedWords], (Capacity-UsedWords), t);
531 // Then set any stray high bits of the last used word.
532 unsigned ExtraBits = Size % BITWORD_SIZE;
534 BitWord ExtraBitMask = ~0UL << ExtraBits;
536 Bits[UsedWords-1] |= ExtraBitMask;
538 Bits[UsedWords-1] &= ~ExtraBitMask;
542 // Clear the unused bits in the high words.
543 void clear_unused_bits() {
544 set_unused_bits(false);
547 void grow(unsigned NewSize) {
548 Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
549 Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
554 void init_words(BitWord *B, unsigned NumWords, bool t) {
555 memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
558 template<bool AddBits, bool InvertMask>
559 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
560 assert(BITWORD_SIZE % 32 == 0 && "Unsupported BitWord size.");
561 MaskWords = std::min(MaskWords, (size() + 31) / 32);
562 const unsigned Scale = BITWORD_SIZE / 32;
564 for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
565 BitWord BW = Bits[i];
566 // This inner loop should unroll completely when BITWORD_SIZE > 32.
567 for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
568 uint32_t M = *Mask++;
569 if (InvertMask) M = ~M;
570 if (AddBits) BW |= BitWord(M) << b;
571 else BW &= ~(BitWord(M) << b);
575 for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
576 uint32_t M = *Mask++;
577 if (InvertMask) M = ~M;
578 if (AddBits) Bits[i] |= BitWord(M) << b;
579 else Bits[i] &= ~(BitWord(M) << b);
586 } // End llvm namespace
589 /// Implement std::swap in terms of BitVector swap.
591 swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {