]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/include/llvm/ADT/BitVector.h
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, 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 &= ~0UL << 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 usnet 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   /// clear - Clear all bits.
257   void clear() {
258     Size = 0;
259   }
260
261   /// resize - Grow or shrink the bitvector.
262   void resize(unsigned N, bool t = false) {
263     if (N > getBitCapacity()) {
264       unsigned OldCapacity = Bits.size();
265       grow(N);
266       init_words(Bits.drop_front(OldCapacity), t);
267     }
268
269     // Set any old unused bits that are now included in the BitVector. This
270     // may set bits that are not included in the new vector, but we will clear
271     // them back out below.
272     if (N > Size)
273       set_unused_bits(t);
274
275     // Update the size, and clear out any bits that are now unused
276     unsigned OldSize = Size;
277     Size = N;
278     if (t || N < OldSize)
279       clear_unused_bits();
280   }
281
282   void reserve(unsigned N) {
283     if (N > getBitCapacity())
284       grow(N);
285   }
286
287   // Set, reset, flip
288   BitVector &set() {
289     init_words(Bits, true);
290     clear_unused_bits();
291     return *this;
292   }
293
294   BitVector &set(unsigned Idx) {
295     assert(Bits.data() && "Bits never allocated");
296     Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
297     return *this;
298   }
299
300   /// set - Efficiently set a range of bits in [I, E)
301   BitVector &set(unsigned I, unsigned E) {
302     assert(I <= E && "Attempted to set backwards range!");
303     assert(E <= size() && "Attempted to set out-of-bounds range!");
304
305     if (I == E) return *this;
306
307     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
308       BitWord EMask = 1UL << (E % BITWORD_SIZE);
309       BitWord IMask = 1UL << (I % BITWORD_SIZE);
310       BitWord Mask = EMask - IMask;
311       Bits[I / BITWORD_SIZE] |= Mask;
312       return *this;
313     }
314
315     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
316     Bits[I / BITWORD_SIZE] |= PrefixMask;
317     I = alignTo(I, BITWORD_SIZE);
318
319     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
320       Bits[I / BITWORD_SIZE] = ~0UL;
321
322     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
323     if (I < E)
324       Bits[I / BITWORD_SIZE] |= PostfixMask;
325
326     return *this;
327   }
328
329   BitVector &reset() {
330     init_words(Bits, false);
331     return *this;
332   }
333
334   BitVector &reset(unsigned Idx) {
335     Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
336     return *this;
337   }
338
339   /// reset - Efficiently reset a range of bits in [I, E)
340   BitVector &reset(unsigned I, unsigned E) {
341     assert(I <= E && "Attempted to reset backwards range!");
342     assert(E <= size() && "Attempted to reset out-of-bounds range!");
343
344     if (I == E) return *this;
345
346     if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
347       BitWord EMask = 1UL << (E % BITWORD_SIZE);
348       BitWord IMask = 1UL << (I % BITWORD_SIZE);
349       BitWord Mask = EMask - IMask;
350       Bits[I / BITWORD_SIZE] &= ~Mask;
351       return *this;
352     }
353
354     BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE);
355     Bits[I / BITWORD_SIZE] &= ~PrefixMask;
356     I = alignTo(I, BITWORD_SIZE);
357
358     for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
359       Bits[I / BITWORD_SIZE] = 0UL;
360
361     BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1;
362     if (I < E)
363       Bits[I / BITWORD_SIZE] &= ~PostfixMask;
364
365     return *this;
366   }
367
368   BitVector &flip() {
369     for (unsigned i = 0; i < NumBitWords(size()); ++i)
370       Bits[i] = ~Bits[i];
371     clear_unused_bits();
372     return *this;
373   }
374
375   BitVector &flip(unsigned Idx) {
376     Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
377     return *this;
378   }
379
380   // Indexing.
381   reference operator[](unsigned Idx) {
382     assert (Idx < Size && "Out-of-bounds Bit access.");
383     return reference(*this, Idx);
384   }
385
386   bool operator[](unsigned Idx) const {
387     assert (Idx < Size && "Out-of-bounds Bit access.");
388     BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
389     return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
390   }
391
392   bool test(unsigned Idx) const {
393     return (*this)[Idx];
394   }
395
396   /// Test if any common bits are set.
397   bool anyCommon(const BitVector &RHS) const {
398     unsigned ThisWords = NumBitWords(size());
399     unsigned RHSWords  = NumBitWords(RHS.size());
400     for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
401       if (Bits[i] & RHS.Bits[i])
402         return true;
403     return false;
404   }
405
406   // Comparison operators.
407   bool operator==(const BitVector &RHS) const {
408     unsigned ThisWords = NumBitWords(size());
409     unsigned RHSWords  = NumBitWords(RHS.size());
410     unsigned i;
411     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
412       if (Bits[i] != RHS.Bits[i])
413         return false;
414
415     // Verify that any extra words are all zeros.
416     if (i != ThisWords) {
417       for (; i != ThisWords; ++i)
418         if (Bits[i])
419           return false;
420     } else if (i != RHSWords) {
421       for (; i != RHSWords; ++i)
422         if (RHS.Bits[i])
423           return false;
424     }
425     return true;
426   }
427
428   bool operator!=(const BitVector &RHS) const {
429     return !(*this == RHS);
430   }
431
432   /// Intersection, union, disjoint union.
433   BitVector &operator&=(const BitVector &RHS) {
434     unsigned ThisWords = NumBitWords(size());
435     unsigned RHSWords  = NumBitWords(RHS.size());
436     unsigned i;
437     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
438       Bits[i] &= RHS.Bits[i];
439
440     // Any bits that are just in this bitvector become zero, because they aren't
441     // in the RHS bit vector.  Any words only in RHS are ignored because they
442     // are already zero in the LHS.
443     for (; i != ThisWords; ++i)
444       Bits[i] = 0;
445
446     return *this;
447   }
448
449   /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
450   BitVector &reset(const BitVector &RHS) {
451     unsigned ThisWords = NumBitWords(size());
452     unsigned RHSWords  = NumBitWords(RHS.size());
453     unsigned i;
454     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
455       Bits[i] &= ~RHS.Bits[i];
456     return *this;
457   }
458
459   /// test - Check if (This - RHS) is zero.
460   /// This is the same as reset(RHS) and any().
461   bool test(const BitVector &RHS) const {
462     unsigned ThisWords = NumBitWords(size());
463     unsigned RHSWords  = NumBitWords(RHS.size());
464     unsigned i;
465     for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
466       if ((Bits[i] & ~RHS.Bits[i]) != 0)
467         return true;
468
469     for (; i != ThisWords ; ++i)
470       if (Bits[i] != 0)
471         return true;
472
473     return false;
474   }
475
476   BitVector &operator|=(const BitVector &RHS) {
477     if (size() < RHS.size())
478       resize(RHS.size());
479     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
480       Bits[i] |= RHS.Bits[i];
481     return *this;
482   }
483
484   BitVector &operator^=(const BitVector &RHS) {
485     if (size() < RHS.size())
486       resize(RHS.size());
487     for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i)
488       Bits[i] ^= RHS.Bits[i];
489     return *this;
490   }
491
492   BitVector &operator>>=(unsigned N) {
493     assert(N <= Size);
494     if (LLVM_UNLIKELY(empty() || N == 0))
495       return *this;
496
497     unsigned NumWords = NumBitWords(Size);
498     assert(NumWords >= 1);
499
500     wordShr(N / BITWORD_SIZE);
501
502     unsigned BitDistance = N % BITWORD_SIZE;
503     if (BitDistance == 0)
504       return *this;
505
506     // When the shift size is not a multiple of the word size, then we have
507     // a tricky situation where each word in succession needs to extract some
508     // of the bits from the next word and or them into this word while
509     // shifting this word to make room for the new bits.  This has to be done
510     // for every word in the array.
511
512     // Since we're shifting each word right, some bits will fall off the end
513     // of each word to the right, and empty space will be created on the left.
514     // The final word in the array will lose bits permanently, so starting at
515     // the beginning, work forwards shifting each word to the right, and
516     // OR'ing in the bits from the end of the next word to the beginning of
517     // the current word.
518
519     // Example:
520     //   Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting right
521     //   by 4 bits.
522     // Step 1: Word[0] >>= 4           ; 0x0ABBCCDD
523     // Step 2: Word[0] |= 0x10000000   ; 0x1ABBCCDD
524     // Step 3: Word[1] >>= 4           ; 0x0EEFF001
525     // Step 4: Word[1] |= 0x50000000   ; 0x5EEFF001
526     // Step 5: Word[2] >>= 4           ; 0x02334455
527     // Result: { 0x1ABBCCDD, 0x5EEFF001, 0x02334455 }
528     const BitWord Mask = maskTrailingOnes<BitWord>(BitDistance);
529     const unsigned LSH = BITWORD_SIZE - BitDistance;
530
531     for (unsigned I = 0; I < NumWords - 1; ++I) {
532       Bits[I] >>= BitDistance;
533       Bits[I] |= (Bits[I + 1] & Mask) << LSH;
534     }
535
536     Bits[NumWords - 1] >>= BitDistance;
537
538     return *this;
539   }
540
541   BitVector &operator<<=(unsigned N) {
542     assert(N <= Size);
543     if (LLVM_UNLIKELY(empty() || N == 0))
544       return *this;
545
546     unsigned NumWords = NumBitWords(Size);
547     assert(NumWords >= 1);
548
549     wordShl(N / BITWORD_SIZE);
550
551     unsigned BitDistance = N % BITWORD_SIZE;
552     if (BitDistance == 0)
553       return *this;
554
555     // When the shift size is not a multiple of the word size, then we have
556     // a tricky situation where each word in succession needs to extract some
557     // of the bits from the previous word and or them into this word while
558     // shifting this word to make room for the new bits.  This has to be done
559     // for every word in the array.  This is similar to the algorithm outlined
560     // in operator>>=, but backwards.
561
562     // Since we're shifting each word left, some bits will fall off the end
563     // of each word to the left, and empty space will be created on the right.
564     // The first word in the array will lose bits permanently, so starting at
565     // the end, work backwards shifting each word to the left, and OR'ing
566     // in the bits from the end of the next word to the beginning of the
567     // current word.
568
569     // Example:
570     //   Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting left
571     //   by 4 bits.
572     // Step 1: Word[2] <<= 4           ; 0x23344550
573     // Step 2: Word[2] |= 0x0000000E   ; 0x2334455E
574     // Step 3: Word[1] <<= 4           ; 0xEFF00110
575     // Step 4: Word[1] |= 0x0000000A   ; 0xEFF0011A
576     // Step 5: Word[0] <<= 4           ; 0xABBCCDD0
577     // Result: { 0xABBCCDD0, 0xEFF0011A, 0x2334455E }
578     const BitWord Mask = maskLeadingOnes<BitWord>(BitDistance);
579     const unsigned RSH = BITWORD_SIZE - BitDistance;
580
581     for (int I = NumWords - 1; I > 0; --I) {
582       Bits[I] <<= BitDistance;
583       Bits[I] |= (Bits[I - 1] & Mask) >> RSH;
584     }
585     Bits[0] <<= BitDistance;
586     clear_unused_bits();
587
588     return *this;
589   }
590
591   // Assignment operator.
592   const BitVector &operator=(const BitVector &RHS) {
593     if (this == &RHS) return *this;
594
595     Size = RHS.size();
596     unsigned RHSWords = NumBitWords(Size);
597     if (Size <= getBitCapacity()) {
598       if (Size)
599         std::memcpy(Bits.data(), RHS.Bits.data(), RHSWords * sizeof(BitWord));
600       clear_unused_bits();
601       return *this;
602     }
603
604     // Grow the bitvector to have enough elements.
605     unsigned NewCapacity = RHSWords;
606     assert(NewCapacity > 0 && "negative capacity?");
607     auto NewBits = allocate(NewCapacity);
608     std::memcpy(NewBits.data(), RHS.Bits.data(), NewCapacity * sizeof(BitWord));
609
610     // Destroy the old bits.
611     std::free(Bits.data());
612     Bits = NewBits;
613
614     return *this;
615   }
616
617   const BitVector &operator=(BitVector &&RHS) {
618     if (this == &RHS) return *this;
619
620     std::free(Bits.data());
621     Bits = RHS.Bits;
622     Size = RHS.Size;
623
624     RHS.Bits = MutableArrayRef<BitWord>();
625     RHS.Size = 0;
626
627     return *this;
628   }
629
630   void swap(BitVector &RHS) {
631     std::swap(Bits, RHS.Bits);
632     std::swap(Size, RHS.Size);
633   }
634
635   //===--------------------------------------------------------------------===//
636   // Portable bit mask operations.
637   //===--------------------------------------------------------------------===//
638   //
639   // These methods all operate on arrays of uint32_t, each holding 32 bits. The
640   // fixed word size makes it easier to work with literal bit vector constants
641   // in portable code.
642   //
643   // The LSB in each word is the lowest numbered bit.  The size of a portable
644   // bit mask is always a whole multiple of 32 bits.  If no bit mask size is
645   // given, the bit mask is assumed to cover the entire BitVector.
646
647   /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
648   /// This computes "*this |= Mask".
649   void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
650     applyMask<true, false>(Mask, MaskWords);
651   }
652
653   /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
654   /// Don't resize. This computes "*this &= ~Mask".
655   void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
656     applyMask<false, false>(Mask, MaskWords);
657   }
658
659   /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
660   /// Don't resize.  This computes "*this |= ~Mask".
661   void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
662     applyMask<true, true>(Mask, MaskWords);
663   }
664
665   /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
666   /// Don't resize.  This computes "*this &= Mask".
667   void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
668     applyMask<false, true>(Mask, MaskWords);
669   }
670
671 private:
672   /// \brief Perform a logical left shift of \p Count words by moving everything
673   /// \p Count words to the right in memory.
674   ///
675   /// While confusing, words are stored from least significant at Bits[0] to
676   /// most significant at Bits[NumWords-1].  A logical shift left, however,
677   /// moves the current least significant bit to a higher logical index, and
678   /// fills the previous least significant bits with 0.  Thus, we actually
679   /// need to move the bytes of the memory to the right, not to the left.
680   /// Example:
681   ///   Words = [0xBBBBAAAA, 0xDDDDFFFF, 0x00000000, 0xDDDD0000]
682   /// represents a BitVector where 0xBBBBAAAA contain the least significant
683   /// bits.  So if we want to shift the BitVector left by 2 words, we need to
684   /// turn this into 0x00000000 0x00000000 0xBBBBAAAA 0xDDDDFFFF by using a
685   /// memmove which moves right, not left.
686   void wordShl(uint32_t Count) {
687     if (Count == 0)
688       return;
689
690     uint32_t NumWords = NumBitWords(Size);
691
692     auto Src = Bits.take_front(NumWords).drop_back(Count);
693     auto Dest = Bits.take_front(NumWords).drop_front(Count);
694
695     // Since we always move Word-sized chunks of data with src and dest both
696     // aligned to a word-boundary, we don't need to worry about endianness
697     // here.
698     std::memmove(Dest.begin(), Src.begin(), Dest.size() * sizeof(BitWord));
699     std::memset(Bits.data(), 0, Count * sizeof(BitWord));
700     clear_unused_bits();
701   }
702
703   /// \brief Perform a logical right shift of \p Count words by moving those
704   /// words to the left in memory.  See wordShl for more information.
705   ///
706   void wordShr(uint32_t Count) {
707     if (Count == 0)
708       return;
709
710     uint32_t NumWords = NumBitWords(Size);
711
712     auto Src = Bits.take_front(NumWords).drop_front(Count);
713     auto Dest = Bits.take_front(NumWords).drop_back(Count);
714     assert(Dest.size() == Src.size());
715
716     std::memmove(Dest.begin(), Src.begin(), Dest.size() * sizeof(BitWord));
717     std::memset(Dest.end(), 0, Count * sizeof(BitWord));
718   }
719
720   MutableArrayRef<BitWord> allocate(size_t NumWords) {
721     BitWord *RawBits = (BitWord *)std::malloc(NumWords * sizeof(BitWord));
722     return MutableArrayRef<BitWord>(RawBits, NumWords);
723   }
724
725   int next_unset_in_word(int WordIndex, BitWord Word) const {
726     unsigned Result = WordIndex * BITWORD_SIZE + countTrailingOnes(Word);
727     return Result < size() ? Result : -1;
728   }
729
730   unsigned NumBitWords(unsigned S) const {
731     return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
732   }
733
734   // Set the unused bits in the high words.
735   void set_unused_bits(bool t = true) {
736     //  Set high words first.
737     unsigned UsedWords = NumBitWords(Size);
738     if (Bits.size() > UsedWords)
739       init_words(Bits.drop_front(UsedWords), t);
740
741     //  Then set any stray high bits of the last used word.
742     unsigned ExtraBits = Size % BITWORD_SIZE;
743     if (ExtraBits) {
744       BitWord ExtraBitMask = ~0UL << ExtraBits;
745       if (t)
746         Bits[UsedWords-1] |= ExtraBitMask;
747       else
748         Bits[UsedWords-1] &= ~ExtraBitMask;
749     }
750   }
751
752   // Clear the unused bits in the high words.
753   void clear_unused_bits() {
754     set_unused_bits(false);
755   }
756
757   void grow(unsigned NewSize) {
758     size_t NewCapacity = std::max<size_t>(NumBitWords(NewSize), Bits.size() * 2);
759     assert(NewCapacity > 0 && "realloc-ing zero space");
760     BitWord *NewBits =
761         (BitWord *)std::realloc(Bits.data(), NewCapacity * sizeof(BitWord));
762     Bits = MutableArrayRef<BitWord>(NewBits, NewCapacity);
763     clear_unused_bits();
764   }
765
766   void init_words(MutableArrayRef<BitWord> B, bool t) {
767     if (B.size() > 0)
768       memset(B.data(), 0 - (int)t, B.size() * sizeof(BitWord));
769   }
770
771   template<bool AddBits, bool InvertMask>
772   void applyMask(const uint32_t *Mask, unsigned MaskWords) {
773     static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
774     MaskWords = std::min(MaskWords, (size() + 31) / 32);
775     const unsigned Scale = BITWORD_SIZE / 32;
776     unsigned i;
777     for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
778       BitWord BW = Bits[i];
779       // This inner loop should unroll completely when BITWORD_SIZE > 32.
780       for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
781         uint32_t M = *Mask++;
782         if (InvertMask) M = ~M;
783         if (AddBits) BW |=   BitWord(M) << b;
784         else         BW &= ~(BitWord(M) << b);
785       }
786       Bits[i] = BW;
787     }
788     for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
789       uint32_t M = *Mask++;
790       if (InvertMask) M = ~M;
791       if (AddBits) Bits[i] |=   BitWord(M) << b;
792       else         Bits[i] &= ~(BitWord(M) << b);
793     }
794     if (AddBits)
795       clear_unused_bits();
796   }
797
798 public:
799   /// Return the size (in bytes) of the bit vector.
800   size_t getMemorySize() const { return Bits.size() * sizeof(BitWord); }
801   size_t getBitCapacity() const { return Bits.size() * BITWORD_SIZE; }
802 };
803
804 static inline size_t capacity_in_bytes(const BitVector &X) {
805   return X.getMemorySize();
806 }
807
808 } // end namespace llvm
809
810 namespace std {
811   /// Implement std::swap in terms of BitVector swap.
812   inline void
813   swap(llvm::BitVector &LHS, llvm::BitVector &RHS) {
814     LHS.swap(RHS);
815   }
816 } // end namespace std
817
818 #endif // LLVM_ADT_BITVECTOR_H