LLVM 24.0.0git
BitVector.h
Go to the documentation of this file.
1//===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
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"
22#include <algorithm>
23#include <cassert>
24#include <climits>
25#include <cstdint>
26#include <cstdlib>
27#include <cstring>
28#include <iterator>
29#include <utility>
30
31namespace llvm {
32
33/// ForwardIterator for the bits that are set.
34/// Iterators get invalidated when resize / reserve is called.
35template <typename BitVectorT> class const_set_bits_iterator_impl {
36 const BitVectorT &Parent;
37 int Current = 0;
38
39 void advance() {
40 assert(Current != -1 && "Trying to advance past end.");
41 Current = Parent.find_next(Current);
42 }
43
44 void retreat() {
45 if (Current == -1) {
46 Current = Parent.find_last();
47 } else {
48 Current = Parent.find_prev(Current);
49 }
50 }
51
52public:
53 using iterator_category = std::bidirectional_iterator_tag;
54 using difference_type = std::ptrdiff_t;
56 using pointer = const value_type *;
58
59 const_set_bits_iterator_impl(const BitVectorT &Parent, int Current)
60 : Parent(Parent), Current(Current) {}
61 explicit const_set_bits_iterator_impl(const BitVectorT &Parent)
62 : const_set_bits_iterator_impl(Parent, Parent.find_first()) {}
64
66 auto Prev = *this;
67 advance();
68 return Prev;
69 }
70
72 advance();
73 return *this;
74 }
75
77 auto Prev = *this;
78 retreat();
79 return Prev;
80 }
81
83 retreat();
84 return *this;
85 }
86
87 unsigned operator*() const { return Current; }
88
90 assert(&Parent == &Other.Parent &&
91 "Comparing iterators from different BitVectors");
92 return Current == Other.Current;
93 }
94
96 assert(&Parent == &Other.Parent &&
97 "Comparing iterators from different BitVectors");
98 return Current != Other.Current;
99 }
100};
101
103 using BitWord = uintptr_t;
104
105 enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
106
107 static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
108 "Unsupported word size");
109
110 using Storage = SmallVector<BitWord>;
111
112 Storage Bits; // Actual bits.
113 unsigned Size = 0; // Size of bitvector in bits.
114
115public:
117
118 // Encapsulation of a single bit.
119 class reference {
120
121 BitWord *WordRef;
122 unsigned BitPos;
123
124 public:
125 reference(BitVector &b, unsigned Idx) {
126 WordRef = &b.Bits[Idx / BITWORD_SIZE];
127 BitPos = Idx % BITWORD_SIZE;
128 }
129
130 reference() = delete;
131 reference(const reference&) = default;
132
134 *this = bool(t);
135 return *this;
136 }
137
139 if (t)
140 *WordRef |= BitWord(1) << BitPos;
141 else
142 *WordRef &= ~(BitWord(1) << BitPos);
143 return *this;
144 }
145
146 operator bool() const {
147 return ((*WordRef) & (BitWord(1) << BitPos)) != 0;
148 }
149 };
150
153
158 return const_set_bits_iterator(*this, -1);
159 }
163
164 /// BitVector default ctor - Creates an empty bitvector.
165 BitVector() = default;
166
167 /// BitVector ctor - Creates a bitvector of specified number of bits. All
168 /// bits are initialized to the specified value.
169 explicit BitVector(unsigned s, bool t = false)
170 : Bits(NumBitWords(s), 0 - (BitWord)t), Size(s) {
171 if (t)
172 clear_unused_bits();
173 }
174
175 /// Returns whether there are no bits in this bitvector.
176 bool empty() const { return Size == 0; }
177
178 /// Returns the number of bits in this bitvector.
179 size_type size() const { return Size; }
180
181 /// Returns the number of bits which are set.
182 size_type count() const {
183 unsigned NumBits = 0;
184 for (auto Bit : Bits)
185 NumBits += llvm::popcount(Bit);
186 return NumBits;
187 }
188
189 /// Returns true if any bit is set.
190 bool any() const {
191 return any_of(Bits, [](BitWord Bit) { return Bit != 0; });
192 }
193
194 /// Returns true if all bits are set.
195 bool all() const {
196 for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
197 if (Bits[i] != ~BitWord(0))
198 return false;
199
200 // If bits remain check that they are ones. The unused bits are always zero.
201 if (unsigned Remainder = Size % BITWORD_SIZE)
202 return Bits[Size / BITWORD_SIZE] == (BitWord(1) << Remainder) - 1;
203
204 return true;
205 }
206
207 /// Returns true if none of the bits are set.
208 bool none() const {
209 return !any();
210 }
211
212 /// Returns the index of the first set/unset bit, depending on \p Set, in
213 /// the range [Begin, End). Returns -1 if all bits in the range are unset/set.
214 int find_first_in(unsigned Begin, unsigned End, bool Set = true) const {
215 assert(Begin <= End && End <= Size);
216 if (Begin == End)
217 return -1;
218
219 unsigned FirstWord = Begin / BITWORD_SIZE;
220 unsigned LastWord = (End - 1) / BITWORD_SIZE;
221
222 // Check subsequent words.
223 // The code below is based on search for the first _set_ bit. If
224 // we're searching for the first _unset_, we just take the
225 // complement of each word before we use it and apply
226 // the same method.
227 for (unsigned i = FirstWord; i <= LastWord; ++i) {
228 BitWord Copy = Bits[i];
229 if (!Set)
230 Copy = ~Copy;
231
232 if (i == FirstWord) {
233 unsigned FirstBit = Begin % BITWORD_SIZE;
234 Copy &= maskTrailingZeros<BitWord>(FirstBit);
235 }
236
237 if (i == LastWord) {
238 unsigned LastBit = (End - 1) % BITWORD_SIZE;
239 Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
240 }
241 if (Copy != 0)
242 return i * BITWORD_SIZE + llvm::countr_zero(Copy);
243 }
244 return -1;
245 }
246
247 /// Returns the index of the last set bit in the range [Begin, End).
248 /// Returns -1 if all bits in the range are unset.
249 int find_last_in(unsigned Begin, unsigned End) const {
250 assert(Begin <= End && End <= Size);
251 if (Begin == End)
252 return -1;
253
254 unsigned LastWord = (End - 1) / BITWORD_SIZE;
255 unsigned FirstWord = Begin / BITWORD_SIZE;
256
257 for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
258 unsigned CurrentWord = i - 1;
259
260 BitWord Copy = Bits[CurrentWord];
261 if (CurrentWord == LastWord) {
262 unsigned LastBit = (End - 1) % BITWORD_SIZE;
263 Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
264 }
265
266 if (CurrentWord == FirstWord) {
267 unsigned FirstBit = Begin % BITWORD_SIZE;
268 Copy &= maskTrailingZeros<BitWord>(FirstBit);
269 }
270
271 if (Copy != 0)
272 return (CurrentWord + 1) * BITWORD_SIZE - llvm::countl_zero(Copy) - 1;
273 }
274
275 return -1;
276 }
277
278 /// Returns the index of the first unset bit in the range [Begin, End).
279 /// Returns -1 if all bits in the range are set.
280 int find_first_unset_in(unsigned Begin, unsigned End) const {
281 return find_first_in(Begin, End, /* Set = */ false);
282 }
283
284 /// Returns the index of the last unset bit in the range [Begin, End).
285 /// Returns -1 if all bits in the range are set.
286 int find_last_unset_in(unsigned Begin, unsigned End) const {
287 assert(Begin <= End && End <= Size);
288 if (Begin == End)
289 return -1;
290
291 unsigned LastWord = (End - 1) / BITWORD_SIZE;
292 unsigned FirstWord = Begin / BITWORD_SIZE;
293
294 for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
295 unsigned CurrentWord = i - 1;
296
297 BitWord Copy = Bits[CurrentWord];
298 if (CurrentWord == LastWord) {
299 unsigned LastBit = (End - 1) % BITWORD_SIZE;
300 Copy |= maskTrailingZeros<BitWord>(LastBit + 1);
301 }
302
303 if (CurrentWord == FirstWord) {
304 unsigned FirstBit = Begin % BITWORD_SIZE;
305 Copy |= maskTrailingOnes<BitWord>(FirstBit);
306 }
307
308 if (Copy != ~BitWord(0)) {
309 unsigned Result =
310 (CurrentWord + 1) * BITWORD_SIZE - llvm::countl_one(Copy) - 1;
311 return Result < Size ? Result : -1;
312 }
313 }
314 return -1;
315 }
316
317 /// Returns the index of the first set bit, -1 if none of the bits are set.
318 int find_first() const { return find_first_in(0, Size); }
319
320 /// Returns the index of the last set bit, -1 if none of the bits are set.
321 int find_last() const { return find_last_in(0, Size); }
322
323 /// Returns the index of the next set bit following the "Prev" bit.
324 /// Returns -1 if the next set bit is not found.
325 int find_next(unsigned Prev) const { return find_first_in(Prev + 1, Size); }
326
327 /// Returns the index of the first set bit that precedes the bit at
328 /// \p PriorTo. Returns -1 if all previous bits are unset.
329 int find_prev(unsigned PriorTo) const { return find_last_in(0, PriorTo); }
330
331 /// Returns the index of the first unset bit, -1 if all of the bits are set.
332 int find_first_unset() const { return find_first_unset_in(0, Size); }
333
334 /// Returns the index of the next unset bit following the \p Prev bit.
335 /// Returns -1 if all remaining bits are set.
336 int find_next_unset(unsigned Prev) const {
337 return find_first_unset_in(Prev + 1, Size);
338 }
339
340 /// Returns the index of the last unset bit, -1 if all of the bits are set.
341 int find_last_unset() const { return find_last_unset_in(0, Size); }
342
343 /// Returns the index of the first unset bit that precedes the bit at
344 /// \p PriorTo. Returns -1 if all previous bits are set.
345 int find_prev_unset(unsigned PriorTo) const {
346 return find_last_unset_in(0, PriorTo);
347 }
348
349 /// Removes all bits from the bitvector.
350 void clear() {
351 Size = 0;
352 Bits.clear();
353 }
354
355 /// Grow or shrink the bitvector.
356 void resize(unsigned N, bool t = false) {
357 set_unused_bits(t);
358 Size = N;
359 Bits.resize(NumBitWords(N), 0 - BitWord(t));
360 clear_unused_bits();
361 }
362
363 /// Reserve space for atleast \p N bits in the bitvector.
364 void reserve(unsigned N) { Bits.reserve(NumBitWords(N)); }
365
366 /// Set all bits in the bitvector.
368 init_words(true);
369 clear_unused_bits();
370 return *this;
371 }
372
373 // Set bit \p Idx in the bitvector.
374 BitVector &set(unsigned Idx) {
375 assert(Idx < Size && "access in bound");
376 Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
377 return *this;
378 }
379
380 /// Efficiently set a range of bits in [I, E)
381 BitVector &set(unsigned I, unsigned E) {
382 assert(I <= E && "Attempted to set backwards range!");
383 assert(E <= size() && "Attempted to set out-of-bounds range!");
384
385 if (I == E) return *this;
386
387 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
388 BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
389 BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
390 BitWord Mask = EMask - IMask;
391 Bits[I / BITWORD_SIZE] |= Mask;
392 return *this;
393 }
394
395 BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
396 Bits[I / BITWORD_SIZE] |= PrefixMask;
397 I = alignTo(I, BITWORD_SIZE);
398
399 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
400 Bits[I / BITWORD_SIZE] = ~BitWord(0);
401
402 BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
403 if (I < E)
404 Bits[I / BITWORD_SIZE] |= PostfixMask;
405
406 return *this;
407 }
408
409 /// Reset all bits in the bitvector.
411 init_words(false);
412 return *this;
413 }
414
415 /// Reset bit \p Idx in the bitvector.
416 BitVector &reset(unsigned Idx) {
417 Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
418 return *this;
419 }
420
421 /// Efficiently reset a range of bits in [I, E)
422 BitVector &reset(unsigned I, unsigned E) {
423 assert(I <= E && "Attempted to reset backwards range!");
424 assert(E <= size() && "Attempted to reset out-of-bounds range!");
425
426 if (I == E) return *this;
427
428 if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
429 BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
430 BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
431 BitWord Mask = EMask - IMask;
432 Bits[I / BITWORD_SIZE] &= ~Mask;
433 return *this;
434 }
435
436 BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
437 Bits[I / BITWORD_SIZE] &= ~PrefixMask;
438 I = alignTo(I, BITWORD_SIZE);
439
440 for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
441 Bits[I / BITWORD_SIZE] = BitWord(0);
442
443 BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
444 if (I < E)
445 Bits[I / BITWORD_SIZE] &= ~PostfixMask;
446
447 return *this;
448 }
449
450 /// Flip all bits in the bitvector.
452 for (auto &Bit : Bits)
453 Bit = ~Bit;
454 clear_unused_bits();
455 return *this;
456 }
457
458 /// Flip bit \p Idx in the bitvector.
459 BitVector &flip(unsigned Idx) {
460 Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
461 return *this;
462 }
463
464 // Indexing.
465 reference operator[](unsigned Idx) {
466 assert (Idx < Size && "Out-of-bounds Bit access.");
467 return reference(*this, Idx);
468 }
469
470 bool operator[](unsigned Idx) const {
471 assert (Idx < Size && "Out-of-bounds Bit access.");
472 BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
473 return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
474 }
475
476 /// Return the last element in the bitvector.
477 bool back() const {
478 assert(!empty() && "Getting last element of empty vector.");
479 return (*this)[size() - 1];
480 }
481
482 /// Returns true if bit \p Idx is set.
483 bool test(unsigned Idx) const {
484 return (*this)[Idx];
485 }
486
487 /// Returns true if all bits in the range [Begin, End) are set.
488 bool test_all(unsigned Begin, unsigned End) const {
489 for (unsigned i = Begin; i < End; ++i) {
490 if (!test(i))
491 return false;
492 }
493 return true;
494 }
495
496 /// Returns true if any of the bits in the range [Begin, End) are set.
497 bool test_any(unsigned Begin, unsigned End) const {
498 for (unsigned i = Begin; i < End; ++i) {
499 if (test(i))
500 return true;
501 }
502 return false;
503 }
504
505 // Push single bit to end of bitvector.
506 void push_back(bool Val) {
507 unsigned OldSize = Size;
508 unsigned NewSize = Size + 1;
509
510 // Resize, which will insert zeros.
511 // If we already fit then the unused bits will be already zero.
512 if (NewSize > getBitCapacity())
513 resize(NewSize, false);
514 else
515 Size = NewSize;
516
517 // If true, set single bit.
518 if (Val)
519 set(OldSize);
520 }
521
522 /// Pop one bit from the end of the vector.
523 void pop_back() {
524 assert(!empty() && "Empty vector has no element to pop.");
525 resize(size() - 1);
526 }
527
528 /// Test if any common bits are set.
529 bool anyCommon(const BitVector &RHS) const {
530 unsigned ThisWords = Bits.size();
531 unsigned RHSWords = RHS.Bits.size();
532 for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
533 if (Bits[i] & RHS.Bits[i])
534 return true;
535 return false;
536 }
537
538 // Comparison operators.
539 bool operator==(const BitVector &RHS) const {
540 if (size() != RHS.size())
541 return false;
542 unsigned NumWords = Bits.size();
543 return std::equal(Bits.begin(), Bits.begin() + NumWords, RHS.Bits.begin());
544 }
545
546 bool operator!=(const BitVector &RHS) const { return !(*this == RHS); }
547
548 /// Intersection of this bitvector with \p RHS.
550 unsigned ThisWords = Bits.size();
551 unsigned RHSWords = RHS.Bits.size();
552 unsigned i;
553 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
554 Bits[i] &= RHS.Bits[i];
555
556 // Any bits that are just in this bitvector become zero, because they aren't
557 // in the RHS bit vector. Any words only in RHS are ignored because they
558 // are already zero in the LHS.
559 for (; i != ThisWords; ++i)
560 Bits[i] = 0;
561
562 return *this;
563 }
564
565 /// Reset bits that are set in RHS. Same as *this &= ~RHS.
567 unsigned ThisWords = Bits.size();
568 unsigned RHSWords = RHS.Bits.size();
569 for (unsigned i = 0; i != std::min(ThisWords, RHSWords); ++i)
570 Bits[i] &= ~RHS.Bits[i];
571 return *this;
572 }
573
574 /// Check if (This - RHS) is non-zero.
575 /// This is the same as reset(RHS) and any().
576 bool test(const BitVector &RHS) const {
577 unsigned ThisWords = Bits.size();
578 unsigned RHSWords = RHS.Bits.size();
579 unsigned i;
580 for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
581 if ((Bits[i] & ~RHS.Bits[i]) != 0)
582 return true;
583
584 for (; i != ThisWords ; ++i)
585 if (Bits[i] != 0)
586 return true;
587
588 return false;
589 }
590
591 /// Check if This is a subset of RHS.
592 bool subsetOf(const BitVector &RHS) const { return !test(RHS); }
593
594 template <class F, class... ArgTys>
595 static BitVector &apply(F &&f, BitVector &Out, BitVector const &Arg,
596 ArgTys const &...Args) {
597 assert(((Arg.size() == Args.size()) && ...) && "consistent sizes");
598 Out.resize(Arg.size());
599 for (size_type I = 0, E = Arg.Bits.size(); I != E; ++I)
600 Out.Bits[I] = f(Arg.Bits[I], Args.Bits[I]...);
601 Out.clear_unused_bits();
602 return Out;
603 }
604
605 /// Union of this bitvector with \p RHS.
607 if (size() < RHS.size())
608 resize(RHS.size());
609 for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
610 Bits[I] |= RHS.Bits[I];
611 return *this;
612 }
613
614 /// Disjoint union of this bitvector with \p RHS.
616 if (size() < RHS.size())
617 resize(RHS.size());
618 for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
619 Bits[I] ^= RHS.Bits[I];
620 return *this;
621 }
622
624 assert(N <= Size);
625 if (LLVM_UNLIKELY(empty() || N == 0))
626 return *this;
627
628 unsigned NumWords = Bits.size();
629 assert(NumWords >= 1);
630
631 wordShr(N / BITWORD_SIZE);
632
633 unsigned BitDistance = N % BITWORD_SIZE;
634 if (BitDistance == 0)
635 return *this;
636
637 // When the shift size is not a multiple of the word size, then we have
638 // a tricky situation where each word in succession needs to extract some
639 // of the bits from the next word and or them into this word while
640 // shifting this word to make room for the new bits. This has to be done
641 // for every word in the array.
642
643 // Since we're shifting each word right, some bits will fall off the end
644 // of each word to the right, and empty space will be created on the left.
645 // The final word in the array will lose bits permanently, so starting at
646 // the beginning, work forwards shifting each word to the right, and
647 // OR'ing in the bits from the end of the next word to the beginning of
648 // the current word.
649
650 // Example:
651 // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting right
652 // by 4 bits.
653 // Step 1: Word[0] >>= 4 ; 0x0ABBCCDD
654 // Step 2: Word[0] |= 0x10000000 ; 0x1ABBCCDD
655 // Step 3: Word[1] >>= 4 ; 0x0EEFF001
656 // Step 4: Word[1] |= 0x50000000 ; 0x5EEFF001
657 // Step 5: Word[2] >>= 4 ; 0x02334455
658 // Result: { 0x1ABBCCDD, 0x5EEFF001, 0x02334455 }
659 const BitWord Mask = maskTrailingOnes<BitWord>(BitDistance);
660 const unsigned LSH = BITWORD_SIZE - BitDistance;
661
662 for (unsigned I = 0; I < NumWords - 1; ++I) {
663 Bits[I] >>= BitDistance;
664 Bits[I] |= (Bits[I + 1] & Mask) << LSH;
665 }
666
667 Bits[NumWords - 1] >>= BitDistance;
668
669 return *this;
670 }
671
673 assert(N <= Size);
674 if (LLVM_UNLIKELY(empty() || N == 0))
675 return *this;
676
677 unsigned NumWords = Bits.size();
678 assert(NumWords >= 1);
679
680 wordShl(N / BITWORD_SIZE);
681
682 unsigned BitDistance = N % BITWORD_SIZE;
683 if (BitDistance == 0)
684 return *this;
685
686 // When the shift size is not a multiple of the word size, then we have
687 // a tricky situation where each word in succession needs to extract some
688 // of the bits from the previous word and or them into this word while
689 // shifting this word to make room for the new bits. This has to be done
690 // for every word in the array. This is similar to the algorithm outlined
691 // in operator>>=, but backwards.
692
693 // Since we're shifting each word left, some bits will fall off the end
694 // of each word to the left, and empty space will be created on the right.
695 // The first word in the array will lose bits permanently, so starting at
696 // the end, work backwards shifting each word to the left, and OR'ing
697 // in the bits from the end of the next word to the beginning of the
698 // current word.
699
700 // Example:
701 // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting left
702 // by 4 bits.
703 // Step 1: Word[2] <<= 4 ; 0x23344550
704 // Step 2: Word[2] |= 0x0000000E ; 0x2334455E
705 // Step 3: Word[1] <<= 4 ; 0xEFF00110
706 // Step 4: Word[1] |= 0x0000000A ; 0xEFF0011A
707 // Step 5: Word[0] <<= 4 ; 0xABBCCDD0
708 // Result: { 0xABBCCDD0, 0xEFF0011A, 0x2334455E }
709 const BitWord Mask = maskLeadingOnes<BitWord>(BitDistance);
710 const unsigned RSH = BITWORD_SIZE - BitDistance;
711
712 for (int I = NumWords - 1; I > 0; --I) {
713 Bits[I] <<= BitDistance;
714 Bits[I] |= (Bits[I - 1] & Mask) >> RSH;
715 }
716 Bits[0] <<= BitDistance;
717 clear_unused_bits();
718
719 return *this;
720 }
721
723 std::swap(Bits, RHS.Bits);
724 std::swap(Size, RHS.Size);
725 }
726
727 ArrayRef<BitWord> getData() const { return {Bits.data(), Bits.size()}; }
728
729 //===--------------------------------------------------------------------===//
730 // Portable bit mask operations.
731 //===--------------------------------------------------------------------===//
732 //
733 // These methods all operate on arrays of uint32_t, each holding 32 bits. The
734 // fixed word size makes it easier to work with literal bit vector constants
735 // in portable code.
736 //
737 // The LSB in each word is the lowest numbered bit. The size of a portable
738 // bit mask is always a whole multiple of 32 bits. If no bit mask size is
739 // given, the bit mask is assumed to cover the entire BitVector.
740
741 /// Add '1' bits from Mask to this vector. Don't resize.
742 /// This computes "*this |= Mask".
743 void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
744 applyMask<true, false>(Mask, MaskWords);
745 }
746
747 /// Clear any bits in this vector that are set in Mask.
748 /// Don't resize. This computes "*this &= ~Mask".
749 void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
750 applyMask<false, false>(Mask, MaskWords);
751 }
752
753 /// Add a bit to this vector for every '0' bit in Mask.
754 /// Don't resize. This computes "*this |= ~Mask".
755 void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
756 applyMask<true, true>(Mask, MaskWords);
757 }
758
759 /// Clear a bit in this vector for every '0' bit in Mask.
760 /// Don't resize. This computes "*this &= Mask".
761 void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
762 applyMask<false, true>(Mask, MaskWords);
763 }
764
765private:
766 /// Perform a logical left shift of \p Count words by moving everything
767 /// \p Count words to the right in memory.
768 ///
769 /// While confusing, words are stored from least significant at Bits[0] to
770 /// most significant at Bits[NumWords-1]. A logical shift left, however,
771 /// moves the current least significant bit to a higher logical index, and
772 /// fills the previous least significant bits with 0. Thus, we actually
773 /// need to move the bytes of the memory to the right, not to the left.
774 /// Example:
775 /// Words = [0xBBBBAAAA, 0xDDDDFFFF, 0x00000000, 0xDDDD0000]
776 /// represents a BitVector where 0xBBBBAAAA contain the least significant
777 /// bits. So if we want to shift the BitVector left by 2 words, we need
778 /// to turn this into 0x00000000 0x00000000 0xBBBBAAAA 0xDDDDFFFF by using a
779 /// memmove which moves right, not left.
780 void wordShl(uint32_t Count) {
781 if (Count == 0)
782 return;
783
784 uint32_t NumWords = Bits.size();
785
786 // Since we always move Word-sized chunks of data with src and dest both
787 // aligned to a word-boundary, we don't need to worry about endianness
788 // here.
789 std::copy(Bits.begin(), Bits.begin() + NumWords - Count,
790 Bits.begin() + Count);
791 std::fill(Bits.begin(), Bits.begin() + Count, 0);
792 clear_unused_bits();
793 }
794
795 /// Perform a logical right shift of \p Count words by moving those
796 /// words to the left in memory. See wordShl for more information.
797 ///
798 void wordShr(uint32_t Count) {
799 if (Count == 0)
800 return;
801
802 uint32_t NumWords = Bits.size();
803
804 std::copy(Bits.begin() + Count, Bits.begin() + NumWords, Bits.begin());
805 std::fill(Bits.begin() + NumWords - Count, Bits.begin() + NumWords, 0);
806 }
807
808 unsigned NumBitWords(unsigned S) const {
809 return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
810 }
811
812 // Set the unused bits in the high words.
813 void set_unused_bits(bool t = true) {
814 // Then set any stray high bits of the last used word.
815 if (unsigned ExtraBits = Size % BITWORD_SIZE) {
816 BitWord ExtraBitMask = ~BitWord(0) << ExtraBits;
817 if (t)
818 Bits.back() |= ExtraBitMask;
819 else
820 Bits.back() &= ~ExtraBitMask;
821 }
822 }
823
824 // Clear the unused bits in the high words.
825 void clear_unused_bits() {
826 set_unused_bits(false);
827 }
828
829 void init_words(bool t) { llvm::fill(Bits, 0 - (BitWord)t); }
830
831 template<bool AddBits, bool InvertMask>
832 void applyMask(const uint32_t *Mask, unsigned MaskWords) {
833 static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
834 MaskWords = std::min(MaskWords, (size() + 31) / 32);
835 const unsigned Scale = BITWORD_SIZE / 32;
836 unsigned i;
837 for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
838 BitWord BW = Bits[i];
839 // This inner loop should unroll completely when BITWORD_SIZE > 32.
840 for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
841 uint32_t M = *Mask++;
842 if (InvertMask) M = ~M;
843 if (AddBits) BW |= BitWord(M) << b;
844 else BW &= ~(BitWord(M) << b);
845 }
846 Bits[i] = BW;
847 }
848 for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
849 uint32_t M = *Mask++;
850 if (InvertMask) M = ~M;
851 if (AddBits) Bits[i] |= BitWord(M) << b;
852 else Bits[i] &= ~(BitWord(M) << b);
853 }
854 if (AddBits)
855 clear_unused_bits();
856 }
857
858public:
859 /// Return the size (in bytes) of the bit vector.
860 size_type getMemorySize() const { return Bits.size() * sizeof(BitWord); }
861 size_type getBitCapacity() const { return Bits.size() * BITWORD_SIZE; }
862};
863
865 return X.getMemorySize();
866}
867
868template <> struct DenseMapInfo<BitVector> {
869 static unsigned getHashValue(const BitVector &V) {
871 getHashValue(std::make_pair(V.size(), V.getData()));
872 }
873 static bool isEqual(const BitVector &LHS, const BitVector &RHS) {
874 return LHS == RHS;
875 }
876};
877} // end namespace llvm
878
879namespace std {
880 /// Implement std::swap in terms of BitVector swap.
882} // end namespace std
883
884#endif // LLVM_ADT_BITVECTOR_H
static int alignTo(int Num, int PowOf2)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:348
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:240
This file defines DenseMapInfo traits for DenseMap.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
modulo schedule test
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
reference & operator=(bool t)
Definition BitVector.h:138
reference(BitVector &b, unsigned Idx)
Definition BitVector.h:125
reference & operator=(reference t)
Definition BitVector.h:133
reference(const reference &)=default
BitVector & operator>>=(unsigned N)
Definition BitVector.h:623
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:483
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:410
void swap(BitVector &RHS)
Definition BitVector.h:722
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:318
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:356
bool anyCommon(const BitVector &RHS) const
Test if any common bits are set.
Definition BitVector.h:529
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:350
bool test(const BitVector &RHS) const
Check if (This - RHS) is non-zero.
Definition BitVector.h:576
BitVector()=default
BitVector default ctor - Creates an empty bitvector.
bool back() const
Return the last element in the bitvector.
Definition BitVector.h:477
bool operator!=(const BitVector &RHS) const
Definition BitVector.h:546
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear a bit in this vector for every '0' bit in Mask.
Definition BitVector.h:761
int find_last() const
Returns the index of the last set bit, -1 if none of the bits are set.
Definition BitVector.h:321
int find_first_unset_in(unsigned Begin, unsigned End) const
Returns the index of the first unset bit in the range [Begin, End).
Definition BitVector.h:280
size_type count() const
Returns the number of bits which are set.
Definition BitVector.h:182
BitVector & operator<<=(unsigned N)
Definition BitVector.h:672
ArrayRef< BitWord > getData() const
Definition BitVector.h:727
const_set_bits_iterator set_bits_end() const
Definition BitVector.h:157
BitVector & reset(unsigned Idx)
Reset bit Idx in the bitvector.
Definition BitVector.h:416
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:367
int find_last_unset() const
Returns the index of the last unset bit, -1 if all of the bits are set.
Definition BitVector.h:341
void reserve(unsigned N)
Reserve space for atleast N bits in the bitvector.
Definition BitVector.h:364
void setBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Add '1' bits from Mask to this vector.
Definition BitVector.h:743
const_set_bits_iterator set_iterator
Definition BitVector.h:152
bool any() const
Returns true if any bit is set.
Definition BitVector.h:190
bool all() const
Returns true if all bits are set.
Definition BitVector.h:195
void push_back(bool Val)
Definition BitVector.h:506
BitVector(unsigned s, bool t=false)
BitVector ctor - Creates a bitvector of specified number of bits.
Definition BitVector.h:169
BitVector & reset(const BitVector &RHS)
Reset bits that are set in RHS. Same as *this &= ~RHS.
Definition BitVector.h:566
BitVector & operator|=(const BitVector &RHS)
Union of this bitvector with RHS.
Definition BitVector.h:606
void pop_back()
Pop one bit from the end of the vector.
Definition BitVector.h:523
void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Clear any bits in this vector that are set in Mask.
Definition BitVector.h:749
int find_prev(unsigned PriorTo) const
Returns the index of the first set bit that precedes the bit at PriorTo.
Definition BitVector.h:329
const_set_bits_iterator_impl< BitVector > const_set_bits_iterator
Definition BitVector.h:151
int find_last_in(unsigned Begin, unsigned End) const
Returns the index of the last set bit in the range [Begin, End).
Definition BitVector.h:249
void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
Add a bit to this vector for every '0' bit in Mask.
Definition BitVector.h:755
BitVector & flip()
Flip all bits in the bitvector.
Definition BitVector.h:451
BitVector & reset(unsigned I, unsigned E)
Efficiently reset a range of bits in [I, E)
Definition BitVector.h:422
bool operator==(const BitVector &RHS) const
Definition BitVector.h:539
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:325
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:208
const_set_bits_iterator set_bits_begin() const
Definition BitVector.h:154
iterator_range< const_set_bits_iterator > set_bits() const
Definition BitVector.h:160
BitVector & set(unsigned I, unsigned E)
Efficiently set a range of bits in [I, E)
Definition BitVector.h:381
bool test_any(unsigned Begin, unsigned End) const
Returns true if any of the bits in the range [Begin, End) are set.
Definition BitVector.h:497
size_type getBitCapacity() const
Definition BitVector.h:861
int find_first_in(unsigned Begin, unsigned End, bool Set=true) const
Returns the index of the first set/unset bit, depending on Set, in the range [Begin,...
Definition BitVector.h:214
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:179
BitVector & operator^=(const BitVector &RHS)
Disjoint union of this bitvector with RHS.
Definition BitVector.h:615
BitVector & flip(unsigned Idx)
Flip bit Idx in the bitvector.
Definition BitVector.h:459
bool test_all(unsigned Begin, unsigned End) const
Returns true if all bits in the range [Begin, End) are set.
Definition BitVector.h:488
size_type getMemorySize() const
Return the size (in bytes) of the bit vector.
Definition BitVector.h:860
static BitVector & apply(F &&f, BitVector &Out, BitVector const &Arg, ArgTys const &...Args)
Definition BitVector.h:595
unsigned size_type
Definition BitVector.h:116
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:176
int find_next_unset(unsigned Prev) const
Returns the index of the next unset bit following the Prev bit.
Definition BitVector.h:336
BitVector & set(unsigned Idx)
Definition BitVector.h:374
int find_prev_unset(unsigned PriorTo) const
Returns the index of the first unset bit that precedes the bit at PriorTo.
Definition BitVector.h:345
BitVector & operator&=(const BitVector &RHS)
Intersection of this bitvector with RHS.
Definition BitVector.h:549
int find_first_unset() const
Returns the index of the first unset bit, -1 if all of the bits are set.
Definition BitVector.h:332
bool subsetOf(const BitVector &RHS) const
Check if This is a subset of RHS.
Definition BitVector.h:592
int find_last_unset_in(unsigned Begin, unsigned End) const
Returns the index of the last unset bit in the range [Begin, End).
Definition BitVector.h:286
bool operator[](unsigned Idx) const
Definition BitVector.h:470
reference operator[](unsigned Idx)
Definition BitVector.h:465
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
ForwardIterator for the bits that are set.
Definition BitVector.h:35
const_set_bits_iterator_impl operator--(int)
Definition BitVector.h:76
const_set_bits_iterator_impl(const BitVectorT &Parent)
Definition BitVector.h:61
std::bidirectional_iterator_tag iterator_category
Definition BitVector.h:53
bool operator==(const const_set_bits_iterator_impl &Other) const
Definition BitVector.h:89
const_set_bits_iterator_impl(const const_set_bits_iterator_impl &)=default
const_set_bits_iterator_impl & operator++()
Definition BitVector.h:71
const_set_bits_iterator_impl & operator--()
Definition BitVector.h:82
const_set_bits_iterator_impl operator++(int)
Definition BitVector.h:65
const_set_bits_iterator_impl(const BitVectorT &Parent, int Current)
Definition BitVector.h:59
bool operator!=(const const_set_bits_iterator_impl &Other) const
Definition BitVector.h:95
A range adaptor for a pair of iterators.
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
This is an optimization pass for GlobalISel generic memory operations.
void fill(R &&Range, T &&Value)
Provide wrappers to std::fill which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1775
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1685
BitVector::size_type capacity_in_bytes(const BitVector &X)
Definition BitVector.h:864
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
constexpr T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:89
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
int countl_one(T Value)
Count the number of ones from the most significant bit to the first zero bit.
Definition bit.h:302
@ Other
Any other memory.
Definition ModRef.h:68
constexpr T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition MathExtras.h:95
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
constexpr T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition MathExtras.h:78
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
static bool isEqual(const BitVector &LHS, const BitVector &RHS)
Definition BitVector.h:873
static unsigned getHashValue(const BitVector &V)
Definition BitVector.h:869
An information struct used to provide DenseMap with the various necessary components for a given valu...