SwitchInst cosmetics: renamed "Hash" method to "hash"
[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/ErrorHandling.h"
18 #include "llvm/Support/MathExtras.h"
19 #include <algorithm>
20 #include <cassert>
21 #include <climits>
22 #include <cstdlib>
23
24 namespace llvm {
25
26 class 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
35 public:
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   // No argument flip.
255   BitVector operator~() const {
256     return BitVector(*this).flip();
257   }
258
259   // Indexing.
260   reference operator[](unsigned Idx) {
261     assert (Idx < Size && "Out-of-bounds Bit access.");
262     return reference(*this, Idx);
263   }
264
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;
269   }
270
271   bool test(unsigned Idx) const {
272     return (*this)[Idx];
273   }
274
275   // Comparison operators.
276   bool operator==(const BitVector &RHS) const {
277     unsigned ThisWords = NumBitWords(size());
278     unsigned RHSWords  = NumBitWords(RHS.size());
279     unsigned i;
280     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
281       if (Bits[i] != RHS.Bits[i])
282         return false;
283
284     // Verify that any extra words are all zeros.
285     if (i != ThisWords) {
286       for (; i != ThisWords; ++i)
287         if (Bits[i])
288           return false;
289     } else if (i != RHSWords) {
290       for (; i != RHSWords; ++i)
291         if (RHS.Bits[i])
292           return false;
293     }
294     return true;
295   }
296
297   bool operator!=(const BitVector &RHS) const {
298     return !(*this == RHS);
299   }
300
301   // Intersection, union, disjoint union.
302   BitVector &operator&=(const BitVector &RHS) {
303     unsigned ThisWords = NumBitWords(size());
304     unsigned RHSWords  = NumBitWords(RHS.size());
305     unsigned i;
306     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
307       Bits[i] &= RHS.Bits[i];
308
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)
313       Bits[i] = 0;
314
315     return *this;
316   }
317
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());
322     unsigned i;
323     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
324       Bits[i] &= ~RHS.Bits[i];
325     return *this;
326   }
327
328   BitVector &operator|=(const BitVector &RHS) {
329     if (size() < RHS.size())
330       resize(RHS.size());
331     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
332       Bits[i] |= RHS.Bits[i];
333     return *this;
334   }
335
336   BitVector &operator^=(const BitVector &RHS) {
337     if (size() < RHS.size())
338       resize(RHS.size());
339     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
340       Bits[i] ^= RHS.Bits[i];
341     return *this;
342   }
343
344   // Assignment operator.
345   const BitVector &operator=(const BitVector &RHS) {
346     if (this == &RHS) return *this;
347
348     Size = RHS.size();
349     unsigned RHSWords = NumBitWords(Size);
350     if (Size <= Capacity * BITWORD_SIZE) {
351       if (Size)
352         std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord));
353       clear_unused_bits();
354       return *this;
355     }
356
357     // Grow the bitvector to have enough elements.
358     Capacity = RHSWords;
359     BitWord *NewBits = (BitWord *)std::malloc(Capacity * sizeof(BitWord));
360     std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord));
361
362     // Destroy the old bits.
363     std::free(Bits);
364     Bits = NewBits;
365
366     return *this;
367   }
368
369   void swap(BitVector &RHS) {
370     std::swap(Bits, RHS.Bits);
371     std::swap(Size, RHS.Size);
372     std::swap(Capacity, RHS.Capacity);
373   }
374
375   //===--------------------------------------------------------------------===//
376   // Portable bit mask operations.
377   //===--------------------------------------------------------------------===//
378   //
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
381   // in portable code.
382   //
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.
386
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);
391   }
392
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);
397   }
398
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);
403   }
404
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);
409   }
410
411 private:
412   unsigned NumBitWords(unsigned S) const {
413     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
414   }
415
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);
422
423     //  Then set any stray high bits of the last used word.
424     unsigned ExtraBits = Size % BITWORD_SIZE;
425     if (ExtraBits) {
426       Bits[UsedWords-1] &= ~(~0L << ExtraBits);
427       Bits[UsedWords-1] |= (0 - (BitWord)t) << ExtraBits;
428     }
429   }
430
431   // Clear the unused bits in the high words.
432   void clear_unused_bits() {
433     set_unused_bits(false);
434   }
435
436   void grow(unsigned NewSize) {
437     Capacity = std::max(NumBitWords(NewSize), Capacity * 2);
438     Bits = (BitWord *)std::realloc(Bits, Capacity * sizeof(BitWord));
439
440     clear_unused_bits();
441   }
442
443   void init_words(BitWord *B, unsigned NumWords, bool t) {
444     memset(B, 0 - (int)t, NumWords*sizeof(BitWord));
445   }
446
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;
452     unsigned i;
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);
461       }
462       Bits[i] = BW;
463     }
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);
469     }
470     if (AddBits)
471       clear_unused_bits();
472   }
473 };
474
475 inline BitVector operator&(const BitVector &LHS, const BitVector &RHS) {
476   BitVector Result(LHS);
477   Result &= RHS;
478   return Result;
479 }
480
481 inline BitVector operator|(const BitVector &LHS, const BitVector &RHS) {
482   BitVector Result(LHS);
483   Result |= RHS;
484   return Result;
485 }
486
487 inline BitVector operator^(const BitVector &LHS, const BitVector &RHS) {
488   BitVector Result(LHS);
489   Result ^= RHS;
490   return Result;
491 }
492
493 } // End llvm namespace
494
495 namespace std {
496   /// Implement std::swap in terms of BitVector swap.
497   inline void
498   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
499     LHS.swap(RHS);
500   }
501 }
502
503 #endif