]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/ADT/BitVector.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r302418, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/ADT/ArrayRef.h"
18 #include "llvm/Support/MathExtras.h"
19 #include <algorithm>
20 #include <cassert>
21 #include <climits>
22 #include <cstdint>
23 #include <cstdlib>
24 #include <cstring>
25 #include <utility>
26
27 namespace llvm {
28
29 class BitVector {
30   typedef unsigned long BitWord;
31
32   enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
33
34   static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
35                 "Unsupported word size");
36
37   MutableArrayRef<BitWord> Bits; // Actual bits.
38   unsigned Size;                 // Size of bitvector in bits.
39
40 public:
41   typedef unsigned size_type;
42   // Encapsulation of a single bit.
43   class reference {
44     friend class BitVector;
45
46     BitWord *WordRef;
47     unsigned BitPos;
48
49   public:
50     reference(BitVector &b, unsigned Idx) {
51       WordRef = &b.Bits[Idx / BITWORD_SIZE];
52       BitPos = Idx % BITWORD_SIZE;
53     }
54
55     reference() = delete;
56     reference(const reference&) = default;
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)) != 0;
73     }
74   };
75
76
77   /// BitVector default ctor - Creates an empty bitvector.
78   BitVector() : Size(0) {}
79
80   /// BitVector ctor - Creates a bitvector of specified number of bits. All
81   /// bits are initialized to the specified value.
82   explicit BitVector(unsigned s, bool t = false) : Size(s) {
83     size_t Capacity = NumBitWords(s);
84     Bits = allocate(Capacity);
85     init_words(Bits, t);
86     if (t)
87       clear_unused_bits();
88   }
89
90   /// BitVector copy ctor.
91   BitVector(const BitVector &RHS) : Size(RHS.size()) {
92     if (Size == 0) {
93       Bits = MutableArrayRef<BitWord>();
94       return;
95     }
96
97     size_t Capacity = NumBitWords(RHS.size());
98     Bits = allocate(Capacity);
99     std::memcpy(Bits.data(), RHS.Bits.data(), Capacity * sizeof(BitWord));
100   }
101
102   BitVector(BitVector &&RHS) : Bits(RHS.Bits), Size(RHS.Size) {
103     RHS.Bits = MutableArrayRef<BitWord>();
104     RHS.Size = 0;
105   }
106
107   ~BitVector() { std::free(Bits.data()); }
108
109   /// empty - Tests whether there are no bits in this bitvector.
110   bool empty() const { return Size == 0; }
111
112   /// size - Returns the number of bits in this bitvector.
113   size_type size() const { return Size; }
114
115   /// count - Returns the number of bits which are set.
116   size_type count() const {
117     unsigned NumBits = 0;
118     for (unsigned i = 0; i < NumBitWords(size()); ++i)
119       NumBits += countPopulation(Bits[i]);
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     for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
134       if (Bits[i] != ~0UL)
135         return false;
136
137     // If bits remain check that they are ones. The unused bits are always zero.
138     if (unsigned Remainder = Size % BITWORD_SIZE)
139       return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1;
140
141     return true;
142   }
143
144   /// none - Returns true if none of the bits are set.
145   bool none() const {
146     return !any();
147   }
148
149   /// find_first - Returns the index of the first set bit, -1 if none
150   /// of the bits are set.
151   int find_first() const {
152     for (unsigned i = 0; i < NumBitWords(size()); ++i)
153       if (Bits[i] != 0)
154         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
155     return -1;
156   }
157
158   /// find_last - Returns the index of the last set bit, -1 if none of the bits
159   /// are set.
160   int find_last() const {
161     if (Size == 0)
162       return -1;
163
164     unsigned N = NumBitWords(size());
165     assert(N > 0);
166
167     unsigned i = N - 1;
168     while (i > 0 && Bits[i] == BitWord(0))
169       --i;
170
171     return int((i + 1) * BITWORD_SIZE - countLeadingZeros(Bits[i])) - 1;
172   }
173
174   /// find_first_unset - Returns the index of the first unset bit, -1 if all
175   /// of the bits are set.
176   int find_first_unset() const {
177     for (unsigned i = 0; i < NumBitWords(size()); ++i)
178       if (Bits[i] != ~0UL) {
179         unsigned Result = i * BITWORD_SIZE + countTrailingOnes(Bits[i]);
180         return Result < size() ? Result : -1;
181       }
182     return -1;
183   }
184
185   /// find_last_unset - Returns the index of the last unset bit, -1 if all of
186   /// the bits are set.
187   int find_last_unset() const {
188     if (Size == 0)
189       return -1;
190
191     const unsigned N = NumBitWords(size());
192     assert(N > 0);
193
194     unsigned i = N - 1;
195     BitWord W = Bits[i];
196
197     // The last word in the BitVector has some unused bits, so we need to set
198     // them all to 1 first.  Set them all to 1 so they don't get treated as
199     // valid unset bits.
200     unsigned UnusedCount = BITWORD_SIZE - size() % BITWORD_SIZE;
201     W |= maskLeadingOnes<BitWord>(UnusedCount);
202
203     while (W == ~BitWord(0) && --i > 0)
204       W = Bits[i];
205
206     return int((i + 1) * BITWORD_SIZE - countLeadingOnes(W)) - 1;
207   }
208
209   /// find_next - Returns the index of the next set bit following the
210   /// "Prev" bit. Returns -1 if the next set bit is not found.
211   int find_next(unsigned Prev) const {
212     ++Prev;
213     if (Prev >= Size)
214       return -1;
215
216     unsigned WordPos = Prev / BITWORD_SIZE;
217     unsigned BitPos = Prev % BITWORD_SIZE;
218     BitWord Copy = Bits[WordPos];
219     // Mask off previous bits.
220     Copy &= maskTrailingZeros<BitWord>(BitPos);
221
222     if (Copy != 0)
223       return WordPos * BITWORD_SIZE + countTrailingZeros(Copy);
224
225     // Check subsequent words.
226     for (unsigned i = WordPos+1; i < NumBitWords(size()); ++i)
227       if (Bits[i] != 0)
228         return i * BITWORD_SIZE + countTrailingZeros(Bits[i]);
229     return -1;
230   }
231
232   /// find_next_unset - Returns the index of the next unset bit following the
233   /// "Prev" bit.  Returns -1 if all remaining bits are set.
234   int find_next_unset(unsigned Prev) const {
235     ++Prev;
236     if (Prev >= Size)
237       return -1;
238
239     unsigned WordPos = Prev / BITWORD_SIZE;
240     unsigned BitPos = Prev % BITWORD_SIZE;
241     BitWord Copy = Bits[WordPos];
242     // Mask in previous bits.
243     BitWord Mask = (1 << BitPos) - 1;
244     Copy |= Mask;
245
246     if (Copy != ~0UL)
247       return next_unset_in_word(WordPos, Copy);
248
249     // Check subsequent words.
250     for (unsigned i = WordPos + 1; i < NumBitWords(size()); ++i)
251       if (Bits[i] != ~0UL)
252         return next_unset_in_word(i, Bits[i]);
253     return -1;
254   }
255
256   /// find_prev - Returns the index of the first set bit that precedes the
257   /// the bit at \p PriorTo.  Returns -1 if all previous bits are unset.
258   int find_prev(unsigned PriorTo) {
259     if (PriorTo == 0)
260       return -1;
261
262     --PriorTo;
263
264     unsigned WordPos = PriorTo / BITWORD_SIZE;
265     unsigned BitPos = PriorTo % BITWORD_SIZE;
266     BitWord Copy = Bits[WordPos];
267     // Mask off next bits.
268     Copy &= maskTrailingOnes<BitWord>(BitPos + 1);
269
270     if (Copy != 0)
271       return (WordPos + 1) * BITWORD_SIZE - countLeadingZeros(Copy) - 1;
272
273     // Check previous words.
274     for (unsigned i = 1; i <= WordPos; ++i) {
275       unsigned Index = WordPos - i;
276       if (Bits[Index] == 0)
277         continue;
278       return (Index + 1) * BITWORD_SIZE - countLeadingZeros(Bits[Index]) - 1;
279     }
280     return -1;
281   }
282
283   /// clear - Removes all bits from the bitvector. Does not change capacity.
284   void clear() {
285     Size = 0;
286   }
287
288   /// resize - Grow or shrink the bitvector.
289   void resize(unsigned N, bool t = false) {
290     if (N > getBitCapacity()) {
291       unsigned OldCapacity = Bits.size();
292       grow(N);
293       init_words(Bits.drop_front(OldCapacity), t);
294     }
295
296     // Set any old unused bits that are now included in the BitVector. This
297     // may set bits that are not included in the new vector, but we will clear
298     // them back out below.
299     if (N > Size)
300       set_unused_bits(t);
301
302     // Update the size, and clear out any bits that are now unused
303     unsigned OldSize = Size;
304     Size = N;
305     if (t || N < OldSize)
306       clear_unused_bits();
307   }
308
309   void reserve(unsigned N) {
310     if (N > getBitCapacity())
311       grow(N);
312   }
313
314   // Set, reset, flip
315   BitVector &set() {
316     init_words(Bits, true);
317     clear_unused_bits();
318     return *this;
319   }
320
321   BitVector &set(unsigned Idx) {
322     assert(Bits.data() && "Bits never allocated");
323     Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
324     return *this;
325   }
326
327   /// set - Efficiently set a range of bits in [I, E)
328   BitVector &set(unsigned I, unsigned E) {
329     assert(I <= E && "Attempted to set backwards range!");
330     assert(E <= size() && "Attempted to set out-of-bounds range!");
331
332     if (I == E) return *this;
333
334     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
335       BitWord EMask = 1UL << (E % BITWORD_SIZE);
336       BitWord IMask = 1UL << (I % BITWORD_SIZE);
337       BitWord Mask = EMask - IMask;
338       Bits[I / BITWORD_SIZE] |= Mask;
339       return *this;
340     }
341
342     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
343     Bits[I / BITWORD_SIZE] |= PrefixMask;
344     I = alignTo(I, BITWORD_SIZE);
345
346     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
347       Bits[I / BITWORD_SIZE] = ~0UL;
348
349     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
350     if (I < E)
351       Bits[I / BITWORD_SIZE] |= PostfixMask;
352
353     return *this;
354   }
355
356   BitVector &reset() {
357     init_words(Bits, false);
358     return *this;
359   }
360
361   BitVector &reset(unsigned Idx) {
362     Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
363     return *this;
364   }
365
366   /// reset - Efficiently reset a range of bits in [I, E)
367   BitVector &reset(unsigned I, unsigned E) {
368     assert(I <= E && "Attempted to reset backwards range!");
369     assert(E <= size() && "Attempted to reset out-of-bounds range!");
370
371     if (I == E) return *this;
372
373     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
374       BitWord EMask = 1UL << (E % BITWORD_SIZE);
375       BitWord IMask = 1UL << (I % BITWORD_SIZE);
376       BitWord Mask = EMask - IMask;
377       Bits[I / BITWORD_SIZE] &= ~Mask;
378       return *this;
379     }
380
381     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
382     Bits[I / BITWORD_SIZE] &= ~PrefixMask;
383     I = alignTo(I, BITWORD_SIZE);
384
385     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
386       Bits[I / BITWORD_SIZE] = 0UL;
387
388     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
389     if (I < E)
390       Bits[I / BITWORD_SIZE] &= ~PostfixMask;
391
392     return *this;
393   }
394
395   BitVector &flip() {
396     for (unsigned i = 0; i < NumBitWords(size()); ++i)
397       Bits[i] = ~Bits[i];
398     clear_unused_bits();
399     return *this;
400   }
401
402   BitVector &flip(unsigned Idx) {
403     Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
404     return *this;
405   }
406
407   // Indexing.
408   reference operator[](unsigned Idx) {
409     assert (Idx < Size && "Out-of-bounds Bit access.");
410     return reference(*this, Idx);
411   }
412
413   bool operator[](unsigned Idx) const {
414     assert (Idx < Size && "Out-of-bounds Bit access.");
415     BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
416     return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
417   }
418
419   bool test(unsigned Idx) const {
420     return (*this)[Idx];
421   }
422
423   /// Test if any common bits are set.
424   bool anyCommon(const BitVector &RHS) const {
425     unsigned ThisWords = NumBitWords(size());
426     unsigned RHSWords  = NumBitWords(RHS.size());
427     for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
428       if (Bits[i] & RHS.Bits[i])
429         return true;
430     return false;
431   }
432
433   // Comparison operators.
434   bool operator==(const BitVector &RHS) const {
435     unsigned ThisWords = NumBitWords(size());
436     unsigned RHSWords  = NumBitWords(RHS.size());
437     unsigned i;
438     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
439       if (Bits[i] != RHS.Bits[i])
440         return false;
441
442     // Verify that any extra words are all zeros.
443     if (i != ThisWords) {
444       for (; i != ThisWords; ++i)
445         if (Bits[i])
446           return false;
447     } else if (i != RHSWords) {
448       for (; i != RHSWords; ++i)
449         if (RHS.Bits[i])
450           return false;
451     }
452     return true;
453   }
454
455   bool operator!=(const BitVector &RHS) const {
456     return !(*this == RHS);
457   }
458
459   /// Intersection, union, disjoint union.
460   BitVector &operator&=(const BitVector &RHS) {
461     unsigned ThisWords = NumBitWords(size());
462     unsigned RHSWords  = NumBitWords(RHS.size());
463     unsigned i;
464     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
465       Bits[i] &= RHS.Bits[i];
466
467     // Any bits that are just in this bitvector become zero, because they aren't
468     // in the RHS bit vector.  Any words only in RHS are ignored because they
469     // are already zero in the LHS.
470     for (; i != ThisWords; ++i)
471       Bits[i] = 0;
472
473     return *this;
474   }
475
476   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
477   BitVector &reset(const BitVector &RHS) {
478     unsigned ThisWords = NumBitWords(size());
479     unsigned RHSWords  = NumBitWords(RHS.size());
480     unsigned i;
481     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
482       Bits[i] &= ~RHS.Bits[i];
483     return *this;
484   }
485
486   /// test - Check if (This - RHS) is zero.
487   /// This is the same as reset(RHS) and any().
488   bool test(const BitVector &RHS) const {
489     unsigned ThisWords = NumBitWords(size());
490     unsigned RHSWords  = NumBitWords(RHS.size());
491     unsigned i;
492     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
493       if ((Bits[i] & ~RHS.Bits[i]) != 0)
494         return true;
495
496     for (; i != ThisWords ; ++i)
497       if (Bits[i] != 0)
498         return true;
499
500     return false;
501   }
502
503   BitVector &operator|=(const BitVector &RHS) {
504     if (size() < RHS.size())
505       resize(RHS.size());
506     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
507       Bits[i] |= RHS.Bits[i];
508     return *this;
509   }
510
511   BitVector &operator^=(const BitVector &RHS) {
512     if (size() < RHS.size())
513       resize(RHS.size());
514     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
515       Bits[i] ^= RHS.Bits[i];
516     return *this;
517   }
518
519   BitVector &operator>>=(unsigned N) {
520     assert(N <= Size);
521     if (LLVM_UNLIKELY(empty() || N == 0))
522       return *this;
523
524     unsigned NumWords = NumBitWords(Size);
525     assert(NumWords >= 1);
526
527     wordShr(N / BITWORD_SIZE);
528
529     unsigned BitDistance = N % BITWORD_SIZE;
530     if (BitDistance == 0)
531       return *this;
532
533     // When the shift size is not a multiple of the word size, then we have
534     // a tricky situation where each word in succession needs to extract some
535     // of the bits from the next word and or them into this word while
536     // shifting this word to make room for the new bits.  This has to be done
537     // for every word in the array.
538
539     // Since we're shifting each word right, some bits will fall off the end
540     // of each word to the right, and empty space will be created on the left.
541     // The final word in the array will lose bits permanently, so starting at
542     // the beginning, work forwards shifting each word to the right, and
543     // OR'ing in the bits from the end of the next word to the beginning of
544     // the current word.
545
546     // Example:
547     //   Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting right
548     //   by 4 bits.
549     // Step 1: Word[0] >>= 4           ; 0x0ABBCCDD
550     // Step 2: Word[0] |= 0x10000000   ; 0x1ABBCCDD
551     // Step 3: Word[1] >>= 4           ; 0x0EEFF001
552     // Step 4: Word[1] |= 0x50000000   ; 0x5EEFF001
553     // Step 5: Word[2] >>= 4           ; 0x02334455
554     // Result: { 0x1ABBCCDD, 0x5EEFF001, 0x02334455 }
555     const BitWord Mask = maskTrailingOnes<BitWord>(BitDistance);
556     const unsigned LSH = BITWORD_SIZE - BitDistance;
557
558     for (unsigned I = 0; I < NumWords - 1; ++I) {
559       Bits[I] >>= BitDistance;
560       Bits[I] |= (Bits[I + 1] & Mask) << LSH;
561     }
562
563     Bits[NumWords - 1] >>= BitDistance;
564
565     return *this;
566   }
567
568   BitVector &operator<<=(unsigned N) {
569     assert(N <= Size);
570     if (LLVM_UNLIKELY(empty() || N == 0))
571       return *this;
572
573     unsigned NumWords = NumBitWords(Size);
574     assert(NumWords >= 1);
575
576     wordShl(N / BITWORD_SIZE);
577
578     unsigned BitDistance = N % BITWORD_SIZE;
579     if (BitDistance == 0)
580       return *this;
581
582     // When the shift size is not a multiple of the word size, then we have
583     // a tricky situation where each word in succession needs to extract some
584     // of the bits from the previous word and or them into this word while
585     // shifting this word to make room for the new bits.  This has to be done
586     // for every word in the array.  This is similar to the algorithm outlined
587     // in operator>>=, but backwards.
588
589     // Since we're shifting each word left, some bits will fall off the end
590     // of each word to the left, and empty space will be created on the right.
591     // The first word in the array will lose bits permanently, so starting at
592     // the end, work backwards shifting each word to the left, and OR'ing
593     // in the bits from the end of the next word to the beginning of the
594     // current word.
595
596     // Example:
597     //   Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting left
598     //   by 4 bits.
599     // Step 1: Word[2] <<= 4           ; 0x23344550
600     // Step 2: Word[2] |= 0x0000000E   ; 0x2334455E
601     // Step 3: Word[1] <<= 4           ; 0xEFF00110
602     // Step 4: Word[1] |= 0x0000000A   ; 0xEFF0011A
603     // Step 5: Word[0] <<= 4           ; 0xABBCCDD0
604     // Result: { 0xABBCCDD0, 0xEFF0011A, 0x2334455E }
605     const BitWord Mask = maskLeadingOnes<BitWord>(BitDistance);
606     const unsigned RSH = BITWORD_SIZE - BitDistance;
607
608     for (int I = NumWords - 1; I > 0; --I) {
609       Bits[I] <<= BitDistance;
610       Bits[I] |= (Bits[I - 1] & Mask) >> RSH;
611     }
612     Bits[0] <<= BitDistance;
613     clear_unused_bits();
614
615     return *this;
616   }
617
618   // Assignment operator.
619   const BitVector &operator=(const BitVector &RHS) {
620     if (this == &RHS) return *this;
621
622     Size = RHS.size();
623     unsigned RHSWords = NumBitWords(Size);
624     if (Size <= getBitCapacity()) {
625       if (Size)
626         std::memcpy(Bits.data(), RHS.Bits.data(), RHSWords * sizeof(BitWord));
627       clear_unused_bits();
628       return *this;
629     }
630
631     // Grow the bitvector to have enough elements.
632     unsigned NewCapacity = RHSWords;
633     assert(NewCapacity > 0 && "negative capacity?");
634     auto NewBits = allocate(NewCapacity);
635     std::memcpy(NewBits.data(), RHS.Bits.data(), NewCapacity * sizeof(BitWord));
636
637     // Destroy the old bits.
638     std::free(Bits.data());
639     Bits = NewBits;
640
641     return *this;
642   }
643
644   const BitVector &operator=(BitVector &&RHS) {
645     if (this == &RHS) return *this;
646
647     std::free(Bits.data());
648     Bits = RHS.Bits;
649     Size = RHS.Size;
650
651     RHS.Bits = MutableArrayRef<BitWord>();
652     RHS.Size = 0;
653
654     return *this;
655   }
656
657   void swap(BitVector &RHS) {
658     std::swap(Bits, RHS.Bits);
659     std::swap(Size, RHS.Size);
660   }
661
662   //===--------------------------------------------------------------------===//
663   // Portable bit mask operations.
664   //===--------------------------------------------------------------------===//
665   //
666   // These methods all operate on arrays of uint32_t, each holding 32 bits. The
667   // fixed word size makes it easier to work with literal bit vector constants
668   // in portable code.
669   //
670   // The LSB in each word is the lowest numbered bit.  The size of a portable
671   // bit mask is always a whole multiple of 32 bits.  If no bit mask size is
672   // given, the bit mask is assumed to cover the entire BitVector.
673
674   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
675   /// This computes "*this |= Mask".
676   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
677     applyMask<true, false>(Mask, MaskWords);
678   }
679
680   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
681   /// Don't resize. This computes "*this &= ~Mask".
682   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
683     applyMask<false, false>(Mask, MaskWords);
684   }
685
686   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
687   /// Don't resize.  This computes "*this |= ~Mask".
688   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
689     applyMask<true, true>(Mask, MaskWords);
690   }
691
692   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
693   /// Don't resize.  This computes "*this &= Mask".
694   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
695     applyMask<false, true>(Mask, MaskWords);
696   }
697
698 private:
699   /// \brief Perform a logical left shift of \p Count words by moving everything
700   /// \p Count words to the right in memory.
701   ///
702   /// While confusing, words are stored from least significant at Bits[0] to
703   /// most significant at Bits[NumWords-1].  A logical shift left, however,
704   /// moves the current least significant bit to a higher logical index, and
705   /// fills the previous least significant bits with 0.  Thus, we actually
706   /// need to move the bytes of the memory to the right, not to the left.
707   /// Example:
708   ///   Words = [0xBBBBAAAA, 0xDDDDFFFF, 0x00000000, 0xDDDD0000]
709   /// represents a BitVector where 0xBBBBAAAA contain the least significant
710   /// bits.  So if we want to shift the BitVector left by 2 words, we need to
711   /// turn this into 0x00000000 0x00000000 0xBBBBAAAA 0xDDDDFFFF by using a
712   /// memmove which moves right, not left.
713   void wordShl(uint32_t Count) {
714     if (Count == 0)
715       return;
716
717     uint32_t NumWords = NumBitWords(Size);
718
719     auto Src = Bits.take_front(NumWords).drop_back(Count);
720     auto Dest = Bits.take_front(NumWords).drop_front(Count);
721
722     // Since we always move Word-sized chunks of data with src and dest both
723     // aligned to a word-boundary, we don't need to worry about endianness
724     // here.
725     std::memmove(Dest.begin(), Src.begin(), Dest.size() * sizeof(BitWord));
726     std::memset(Bits.data(), 0, Count * sizeof(BitWord));
727     clear_unused_bits();
728   }
729
730   /// \brief Perform a logical right shift of \p Count words by moving those
731   /// words to the left in memory.  See wordShl for more information.
732   ///
733   void wordShr(uint32_t Count) {
734     if (Count == 0)
735       return;
736
737     uint32_t NumWords = NumBitWords(Size);
738
739     auto Src = Bits.take_front(NumWords).drop_front(Count);
740     auto Dest = Bits.take_front(NumWords).drop_back(Count);
741     assert(Dest.size() == Src.size());
742
743     std::memmove(Dest.begin(), Src.begin(), Dest.size() * sizeof(BitWord));
744     std::memset(Dest.end(), 0, Count * sizeof(BitWord));
745   }
746
747   MutableArrayRef<BitWord> allocate(size_t NumWords) {
748     BitWord *RawBits = (BitWord *)std::malloc(NumWords * sizeof(BitWord));
749     return MutableArrayRef<BitWord>(RawBits, NumWords);
750   }
751
752   int next_unset_in_word(int WordIndex, BitWord Word) const {
753     unsigned Result = WordIndex * BITWORD_SIZE + countTrailingOnes(Word);
754     return Result < size() ? Result : -1;
755   }
756
757   unsigned NumBitWords(unsigned S) const {
758     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
759   }
760
761   // Set the unused bits in the high words.
762   void set_unused_bits(bool t = true) {
763     //  Set high words first.
764     unsigned UsedWords = NumBitWords(Size);
765     if (Bits.size() > UsedWords)
766       init_words(Bits.drop_front(UsedWords), t);
767
768     //  Then set any stray high bits of the last used word.
769     unsigned ExtraBits = Size % BITWORD_SIZE;
770     if (ExtraBits) {
771       BitWord ExtraBitMask = ~0UL << ExtraBits;
772       if (t)
773         Bits[UsedWords-1] |= ExtraBitMask;
774       else
775         Bits[UsedWords-1] &= ~ExtraBitMask;
776     }
777   }
778
779   // Clear the unused bits in the high words.
780   void clear_unused_bits() {
781     set_unused_bits(false);
782   }
783
784   void grow(unsigned NewSize) {
785     size_t NewCapacity = std::max<size_t>(NumBitWords(NewSize), Bits.size() * 2);
786     assert(NewCapacity > 0 && "realloc-ing zero space");
787     BitWord *NewBits =
788         (BitWord *)std::realloc(Bits.data(), NewCapacity * sizeof(BitWord));
789     Bits = MutableArrayRef<BitWord>(NewBits, NewCapacity);
790     clear_unused_bits();
791   }
792
793   void init_words(MutableArrayRef<BitWord> B, bool t) {
794     if (B.size() > 0)
795       memset(B.data(), 0 - (int)t, B.size() * sizeof(BitWord));
796   }
797
798   template<bool AddBits, bool InvertMask>
799   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
800     static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
801     MaskWords = std::min(MaskWords, (size() + 31) / 32);
802     const unsigned Scale = BITWORD_SIZE / 32;
803     unsigned i;
804     for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
805       BitWord BW = Bits[i];
806       // This inner loop should unroll completely when BITWORD_SIZE > 32.
807       for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
808         uint32_t M = *Mask++;
809         if (InvertMask) M = ~M;
810         if (AddBits) BW |=   BitWord(M) << b;
811         else         BW &= ~(BitWord(M) << b);
812       }
813       Bits[i] = BW;
814     }
815     for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
816       uint32_t M = *Mask++;
817       if (InvertMask) M = ~M;
818       if (AddBits) Bits[i] |=   BitWord(M) << b;
819       else         Bits[i] &= ~(BitWord(M) << b);
820     }
821     if (AddBits)
822       clear_unused_bits();
823   }
824
825 public:
826   /// Return the size (in bytes) of the bit vector.
827   size_t getMemorySize() const { return Bits.size() * sizeof(BitWord); }
828   size_t getBitCapacity() const { return Bits.size() * BITWORD_SIZE; }
829 };
830
831 static inline size_t capacity_in_bytes(const BitVector &X) {
832   return X.getMemorySize();
833 }
834
835 } // end namespace llvm
836
837 namespace std {
838   /// Implement std::swap in terms of BitVector swap.
839   inline void
840   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
841     LHS.swap(RHS);
842   }
843 } // end namespace std
844
845 #endif // LLVM_ADT_BITVECTOR_H