BitVector.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. ///
  14. /// \file
  15. /// This file implements the BitVector class.
  16. ///
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_ADT_BITVECTOR_H
  19. #define LLVM_ADT_BITVECTOR_H
  20. #include "llvm/ADT/ArrayRef.h"
  21. #include "llvm/ADT/DenseMapInfo.h"
  22. #include "llvm/ADT/iterator_range.h"
  23. #include "llvm/Support/MathExtras.h"
  24. #include <algorithm>
  25. #include <cassert>
  26. #include <climits>
  27. #include <cstdint>
  28. #include <cstdlib>
  29. #include <cstring>
  30. #include <utility>
  31. namespace llvm {
  32. /// ForwardIterator for the bits that are set.
  33. /// Iterators get invalidated when resize / reserve is called.
  34. template <typename BitVectorT> class const_set_bits_iterator_impl {
  35. const BitVectorT &Parent;
  36. int Current = 0;
  37. void advance() {
  38. assert(Current != -1 && "Trying to advance past end.");
  39. Current = Parent.find_next(Current);
  40. }
  41. public:
  42. const_set_bits_iterator_impl(const BitVectorT &Parent, int Current)
  43. : Parent(Parent), Current(Current) {}
  44. explicit const_set_bits_iterator_impl(const BitVectorT &Parent)
  45. : const_set_bits_iterator_impl(Parent, Parent.find_first()) {}
  46. const_set_bits_iterator_impl(const const_set_bits_iterator_impl &) = default;
  47. const_set_bits_iterator_impl operator++(int) {
  48. auto Prev = *this;
  49. advance();
  50. return Prev;
  51. }
  52. const_set_bits_iterator_impl &operator++() {
  53. advance();
  54. return *this;
  55. }
  56. unsigned operator*() const { return Current; }
  57. bool operator==(const const_set_bits_iterator_impl &Other) const {
  58. assert(&Parent == &Other.Parent &&
  59. "Comparing iterators from different BitVectors");
  60. return Current == Other.Current;
  61. }
  62. bool operator!=(const const_set_bits_iterator_impl &Other) const {
  63. assert(&Parent == &Other.Parent &&
  64. "Comparing iterators from different BitVectors");
  65. return Current != Other.Current;
  66. }
  67. };
  68. class BitVector {
  69. typedef uintptr_t BitWord;
  70. enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT };
  71. static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32,
  72. "Unsupported word size");
  73. using Storage = SmallVector<BitWord>;
  74. Storage Bits; // Actual bits.
  75. unsigned Size = 0; // Size of bitvector in bits.
  76. public:
  77. using size_type = unsigned;
  78. // Encapsulation of a single bit.
  79. class reference {
  80. BitWord *WordRef;
  81. unsigned BitPos;
  82. public:
  83. reference(BitVector &b, unsigned Idx) {
  84. WordRef = &b.Bits[Idx / BITWORD_SIZE];
  85. BitPos = Idx % BITWORD_SIZE;
  86. }
  87. reference() = delete;
  88. reference(const reference&) = default;
  89. reference &operator=(reference t) {
  90. *this = bool(t);
  91. return *this;
  92. }
  93. reference& operator=(bool t) {
  94. if (t)
  95. *WordRef |= BitWord(1) << BitPos;
  96. else
  97. *WordRef &= ~(BitWord(1) << BitPos);
  98. return *this;
  99. }
  100. operator bool() const {
  101. return ((*WordRef) & (BitWord(1) << BitPos)) != 0;
  102. }
  103. };
  104. typedef const_set_bits_iterator_impl<BitVector> const_set_bits_iterator;
  105. typedef const_set_bits_iterator set_iterator;
  106. const_set_bits_iterator set_bits_begin() const {
  107. return const_set_bits_iterator(*this);
  108. }
  109. const_set_bits_iterator set_bits_end() const {
  110. return const_set_bits_iterator(*this, -1);
  111. }
  112. iterator_range<const_set_bits_iterator> set_bits() const {
  113. return make_range(set_bits_begin(), set_bits_end());
  114. }
  115. /// BitVector default ctor - Creates an empty bitvector.
  116. BitVector() = default;
  117. /// BitVector ctor - Creates a bitvector of specified number of bits. All
  118. /// bits are initialized to the specified value.
  119. explicit BitVector(unsigned s, bool t = false)
  120. : Bits(NumBitWords(s), 0 - (BitWord)t), Size(s) {
  121. if (t)
  122. clear_unused_bits();
  123. }
  124. /// empty - Tests whether there are no bits in this bitvector.
  125. bool empty() const { return Size == 0; }
  126. /// size - Returns the number of bits in this bitvector.
  127. size_type size() const { return Size; }
  128. /// count - Returns the number of bits which are set.
  129. size_type count() const {
  130. unsigned NumBits = 0;
  131. for (auto Bit : Bits)
  132. NumBits += llvm::popcount(Bit);
  133. return NumBits;
  134. }
  135. /// any - Returns true if any bit is set.
  136. bool any() const {
  137. return any_of(Bits, [](BitWord Bit) { return Bit != 0; });
  138. }
  139. /// all - Returns true if all bits are set.
  140. bool all() const {
  141. for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i)
  142. if (Bits[i] != ~BitWord(0))
  143. return false;
  144. // If bits remain check that they are ones. The unused bits are always zero.
  145. if (unsigned Remainder = Size % BITWORD_SIZE)
  146. return Bits[Size / BITWORD_SIZE] == (BitWord(1) << Remainder) - 1;
  147. return true;
  148. }
  149. /// none - Returns true if none of the bits are set.
  150. bool none() const {
  151. return !any();
  152. }
  153. /// find_first_in - Returns the index of the first set / unset bit,
  154. /// depending on \p Set, in the range [Begin, End).
  155. /// Returns -1 if all bits in the range are unset / set.
  156. int find_first_in(unsigned Begin, unsigned End, bool Set = true) const {
  157. assert(Begin <= End && End <= Size);
  158. if (Begin == End)
  159. return -1;
  160. unsigned FirstWord = Begin / BITWORD_SIZE;
  161. unsigned LastWord = (End - 1) / BITWORD_SIZE;
  162. // Check subsequent words.
  163. // The code below is based on search for the first _set_ bit. If
  164. // we're searching for the first _unset_, we just take the
  165. // complement of each word before we use it and apply
  166. // the same method.
  167. for (unsigned i = FirstWord; i <= LastWord; ++i) {
  168. BitWord Copy = Bits[i];
  169. if (!Set)
  170. Copy = ~Copy;
  171. if (i == FirstWord) {
  172. unsigned FirstBit = Begin % BITWORD_SIZE;
  173. Copy &= maskTrailingZeros<BitWord>(FirstBit);
  174. }
  175. if (i == LastWord) {
  176. unsigned LastBit = (End - 1) % BITWORD_SIZE;
  177. Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
  178. }
  179. if (Copy != 0)
  180. return i * BITWORD_SIZE + countTrailingZeros(Copy);
  181. }
  182. return -1;
  183. }
  184. /// find_last_in - Returns the index of the last set bit in the range
  185. /// [Begin, End). Returns -1 if all bits in the range are unset.
  186. int find_last_in(unsigned Begin, unsigned End) const {
  187. assert(Begin <= End && End <= Size);
  188. if (Begin == End)
  189. return -1;
  190. unsigned LastWord = (End - 1) / BITWORD_SIZE;
  191. unsigned FirstWord = Begin / BITWORD_SIZE;
  192. for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
  193. unsigned CurrentWord = i - 1;
  194. BitWord Copy = Bits[CurrentWord];
  195. if (CurrentWord == LastWord) {
  196. unsigned LastBit = (End - 1) % BITWORD_SIZE;
  197. Copy &= maskTrailingOnes<BitWord>(LastBit + 1);
  198. }
  199. if (CurrentWord == FirstWord) {
  200. unsigned FirstBit = Begin % BITWORD_SIZE;
  201. Copy &= maskTrailingZeros<BitWord>(FirstBit);
  202. }
  203. if (Copy != 0)
  204. return (CurrentWord + 1) * BITWORD_SIZE - countLeadingZeros(Copy) - 1;
  205. }
  206. return -1;
  207. }
  208. /// find_first_unset_in - Returns the index of the first unset bit in the
  209. /// range [Begin, End). Returns -1 if all bits in the range are set.
  210. int find_first_unset_in(unsigned Begin, unsigned End) const {
  211. return find_first_in(Begin, End, /* Set = */ false);
  212. }
  213. /// find_last_unset_in - Returns the index of the last unset bit in the
  214. /// range [Begin, End). Returns -1 if all bits in the range are set.
  215. int find_last_unset_in(unsigned Begin, unsigned End) const {
  216. assert(Begin <= End && End <= Size);
  217. if (Begin == End)
  218. return -1;
  219. unsigned LastWord = (End - 1) / BITWORD_SIZE;
  220. unsigned FirstWord = Begin / BITWORD_SIZE;
  221. for (unsigned i = LastWord + 1; i >= FirstWord + 1; --i) {
  222. unsigned CurrentWord = i - 1;
  223. BitWord Copy = Bits[CurrentWord];
  224. if (CurrentWord == LastWord) {
  225. unsigned LastBit = (End - 1) % BITWORD_SIZE;
  226. Copy |= maskTrailingZeros<BitWord>(LastBit + 1);
  227. }
  228. if (CurrentWord == FirstWord) {
  229. unsigned FirstBit = Begin % BITWORD_SIZE;
  230. Copy |= maskTrailingOnes<BitWord>(FirstBit);
  231. }
  232. if (Copy != ~BitWord(0)) {
  233. unsigned Result =
  234. (CurrentWord + 1) * BITWORD_SIZE - countLeadingOnes(Copy) - 1;
  235. return Result < Size ? Result : -1;
  236. }
  237. }
  238. return -1;
  239. }
  240. /// find_first - Returns the index of the first set bit, -1 if none
  241. /// of the bits are set.
  242. int find_first() const { return find_first_in(0, Size); }
  243. /// find_last - Returns the index of the last set bit, -1 if none of the bits
  244. /// are set.
  245. int find_last() const { return find_last_in(0, Size); }
  246. /// find_next - Returns the index of the next set bit following the
  247. /// "Prev" bit. Returns -1 if the next set bit is not found.
  248. int find_next(unsigned Prev) const { return find_first_in(Prev + 1, Size); }
  249. /// find_prev - Returns the index of the first set bit that precedes the
  250. /// the bit at \p PriorTo. Returns -1 if all previous bits are unset.
  251. int find_prev(unsigned PriorTo) const { return find_last_in(0, PriorTo); }
  252. /// find_first_unset - Returns the index of the first unset bit, -1 if all
  253. /// of the bits are set.
  254. int find_first_unset() const { return find_first_unset_in(0, Size); }
  255. /// find_next_unset - Returns the index of the next unset bit following the
  256. /// "Prev" bit. Returns -1 if all remaining bits are set.
  257. int find_next_unset(unsigned Prev) const {
  258. return find_first_unset_in(Prev + 1, Size);
  259. }
  260. /// find_last_unset - Returns the index of the last unset bit, -1 if all of
  261. /// the bits are set.
  262. int find_last_unset() const { return find_last_unset_in(0, Size); }
  263. /// find_prev_unset - Returns the index of the first unset bit that precedes
  264. /// the bit at \p PriorTo. Returns -1 if all previous bits are set.
  265. int find_prev_unset(unsigned PriorTo) {
  266. return find_last_unset_in(0, PriorTo);
  267. }
  268. /// clear - Removes all bits from the bitvector.
  269. void clear() {
  270. Size = 0;
  271. Bits.clear();
  272. }
  273. /// resize - Grow or shrink the bitvector.
  274. void resize(unsigned N, bool t = false) {
  275. set_unused_bits(t);
  276. Size = N;
  277. Bits.resize(NumBitWords(N), 0 - BitWord(t));
  278. clear_unused_bits();
  279. }
  280. void reserve(unsigned N) { Bits.reserve(NumBitWords(N)); }
  281. // Set, reset, flip
  282. BitVector &set() {
  283. init_words(true);
  284. clear_unused_bits();
  285. return *this;
  286. }
  287. BitVector &set(unsigned Idx) {
  288. assert(Idx < Size && "access in bound");
  289. Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE);
  290. return *this;
  291. }
  292. /// set - Efficiently set a range of bits in [I, E)
  293. BitVector &set(unsigned I, unsigned E) {
  294. assert(I <= E && "Attempted to set backwards range!");
  295. assert(E <= size() && "Attempted to set out-of-bounds range!");
  296. if (I == E) return *this;
  297. if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
  298. BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
  299. BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
  300. BitWord Mask = EMask - IMask;
  301. Bits[I / BITWORD_SIZE] |= Mask;
  302. return *this;
  303. }
  304. BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
  305. Bits[I / BITWORD_SIZE] |= PrefixMask;
  306. I = alignTo(I, BITWORD_SIZE);
  307. for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
  308. Bits[I / BITWORD_SIZE] = ~BitWord(0);
  309. BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
  310. if (I < E)
  311. Bits[I / BITWORD_SIZE] |= PostfixMask;
  312. return *this;
  313. }
  314. BitVector &reset() {
  315. init_words(false);
  316. return *this;
  317. }
  318. BitVector &reset(unsigned Idx) {
  319. Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE));
  320. return *this;
  321. }
  322. /// reset - Efficiently reset a range of bits in [I, E)
  323. BitVector &reset(unsigned I, unsigned E) {
  324. assert(I <= E && "Attempted to reset backwards range!");
  325. assert(E <= size() && "Attempted to reset out-of-bounds range!");
  326. if (I == E) return *this;
  327. if (I / BITWORD_SIZE == E / BITWORD_SIZE) {
  328. BitWord EMask = BitWord(1) << (E % BITWORD_SIZE);
  329. BitWord IMask = BitWord(1) << (I % BITWORD_SIZE);
  330. BitWord Mask = EMask - IMask;
  331. Bits[I / BITWORD_SIZE] &= ~Mask;
  332. return *this;
  333. }
  334. BitWord PrefixMask = ~BitWord(0) << (I % BITWORD_SIZE);
  335. Bits[I / BITWORD_SIZE] &= ~PrefixMask;
  336. I = alignTo(I, BITWORD_SIZE);
  337. for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE)
  338. Bits[I / BITWORD_SIZE] = BitWord(0);
  339. BitWord PostfixMask = (BitWord(1) << (E % BITWORD_SIZE)) - 1;
  340. if (I < E)
  341. Bits[I / BITWORD_SIZE] &= ~PostfixMask;
  342. return *this;
  343. }
  344. BitVector &flip() {
  345. for (auto &Bit : Bits)
  346. Bit = ~Bit;
  347. clear_unused_bits();
  348. return *this;
  349. }
  350. BitVector &flip(unsigned Idx) {
  351. Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE);
  352. return *this;
  353. }
  354. // Indexing.
  355. reference operator[](unsigned Idx) {
  356. assert (Idx < Size && "Out-of-bounds Bit access.");
  357. return reference(*this, Idx);
  358. }
  359. bool operator[](unsigned Idx) const {
  360. assert (Idx < Size && "Out-of-bounds Bit access.");
  361. BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE);
  362. return (Bits[Idx / BITWORD_SIZE] & Mask) != 0;
  363. }
  364. /// Return the last element in the vector.
  365. bool back() const {
  366. assert(!empty() && "Getting last element of empty vector.");
  367. return (*this)[size() - 1];
  368. }
  369. bool test(unsigned Idx) const {
  370. return (*this)[Idx];
  371. }
  372. // Push single bit to end of vector.
  373. void push_back(bool Val) {
  374. unsigned OldSize = Size;
  375. unsigned NewSize = Size + 1;
  376. // Resize, which will insert zeros.
  377. // If we already fit then the unused bits will be already zero.
  378. if (NewSize > getBitCapacity())
  379. resize(NewSize, false);
  380. else
  381. Size = NewSize;
  382. // If true, set single bit.
  383. if (Val)
  384. set(OldSize);
  385. }
  386. /// Pop one bit from the end of the vector.
  387. void pop_back() {
  388. assert(!empty() && "Empty vector has no element to pop.");
  389. resize(size() - 1);
  390. }
  391. /// Test if any common bits are set.
  392. bool anyCommon(const BitVector &RHS) const {
  393. unsigned ThisWords = Bits.size();
  394. unsigned RHSWords = RHS.Bits.size();
  395. for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i)
  396. if (Bits[i] & RHS.Bits[i])
  397. return true;
  398. return false;
  399. }
  400. // Comparison operators.
  401. bool operator==(const BitVector &RHS) const {
  402. if (size() != RHS.size())
  403. return false;
  404. unsigned NumWords = Bits.size();
  405. return std::equal(Bits.begin(), Bits.begin() + NumWords, RHS.Bits.begin());
  406. }
  407. bool operator!=(const BitVector &RHS) const { return !(*this == RHS); }
  408. /// Intersection, union, disjoint union.
  409. BitVector &operator&=(const BitVector &RHS) {
  410. unsigned ThisWords = Bits.size();
  411. unsigned RHSWords = RHS.Bits.size();
  412. unsigned i;
  413. for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
  414. Bits[i] &= RHS.Bits[i];
  415. // Any bits that are just in this bitvector become zero, because they aren't
  416. // in the RHS bit vector. Any words only in RHS are ignored because they
  417. // are already zero in the LHS.
  418. for (; i != ThisWords; ++i)
  419. Bits[i] = 0;
  420. return *this;
  421. }
  422. /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS.
  423. BitVector &reset(const BitVector &RHS) {
  424. unsigned ThisWords = Bits.size();
  425. unsigned RHSWords = RHS.Bits.size();
  426. for (unsigned i = 0; i != std::min(ThisWords, RHSWords); ++i)
  427. Bits[i] &= ~RHS.Bits[i];
  428. return *this;
  429. }
  430. /// test - Check if (This - RHS) is zero.
  431. /// This is the same as reset(RHS) and any().
  432. bool test(const BitVector &RHS) const {
  433. unsigned ThisWords = Bits.size();
  434. unsigned RHSWords = RHS.Bits.size();
  435. unsigned i;
  436. for (i = 0; i != std::min(ThisWords, RHSWords); ++i)
  437. if ((Bits[i] & ~RHS.Bits[i]) != 0)
  438. return true;
  439. for (; i != ThisWords ; ++i)
  440. if (Bits[i] != 0)
  441. return true;
  442. return false;
  443. }
  444. template <class F, class... ArgTys>
  445. static BitVector &apply(F &&f, BitVector &Out, BitVector const &Arg,
  446. ArgTys const &...Args) {
  447. assert(llvm::all_of(
  448. std::initializer_list<unsigned>{Args.size()...},
  449. [&Arg](auto const &BV) { return Arg.size() == BV; }) &&
  450. "consistent sizes");
  451. Out.resize(Arg.size());
  452. for (size_type I = 0, E = Arg.Bits.size(); I != E; ++I)
  453. Out.Bits[I] = f(Arg.Bits[I], Args.Bits[I]...);
  454. Out.clear_unused_bits();
  455. return Out;
  456. }
  457. BitVector &operator|=(const BitVector &RHS) {
  458. if (size() < RHS.size())
  459. resize(RHS.size());
  460. for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
  461. Bits[I] |= RHS.Bits[I];
  462. return *this;
  463. }
  464. BitVector &operator^=(const BitVector &RHS) {
  465. if (size() < RHS.size())
  466. resize(RHS.size());
  467. for (size_type I = 0, E = RHS.Bits.size(); I != E; ++I)
  468. Bits[I] ^= RHS.Bits[I];
  469. return *this;
  470. }
  471. BitVector &operator>>=(unsigned N) {
  472. assert(N <= Size);
  473. if (LLVM_UNLIKELY(empty() || N == 0))
  474. return *this;
  475. unsigned NumWords = Bits.size();
  476. assert(NumWords >= 1);
  477. wordShr(N / BITWORD_SIZE);
  478. unsigned BitDistance = N % BITWORD_SIZE;
  479. if (BitDistance == 0)
  480. return *this;
  481. // When the shift size is not a multiple of the word size, then we have
  482. // a tricky situation where each word in succession needs to extract some
  483. // of the bits from the next word and or them into this word while
  484. // shifting this word to make room for the new bits. This has to be done
  485. // for every word in the array.
  486. // Since we're shifting each word right, some bits will fall off the end
  487. // of each word to the right, and empty space will be created on the left.
  488. // The final word in the array will lose bits permanently, so starting at
  489. // the beginning, work forwards shifting each word to the right, and
  490. // OR'ing in the bits from the end of the next word to the beginning of
  491. // the current word.
  492. // Example:
  493. // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting right
  494. // by 4 bits.
  495. // Step 1: Word[0] >>= 4 ; 0x0ABBCCDD
  496. // Step 2: Word[0] |= 0x10000000 ; 0x1ABBCCDD
  497. // Step 3: Word[1] >>= 4 ; 0x0EEFF001
  498. // Step 4: Word[1] |= 0x50000000 ; 0x5EEFF001
  499. // Step 5: Word[2] >>= 4 ; 0x02334455
  500. // Result: { 0x1ABBCCDD, 0x5EEFF001, 0x02334455 }
  501. const BitWord Mask = maskTrailingOnes<BitWord>(BitDistance);
  502. const unsigned LSH = BITWORD_SIZE - BitDistance;
  503. for (unsigned I = 0; I < NumWords - 1; ++I) {
  504. Bits[I] >>= BitDistance;
  505. Bits[I] |= (Bits[I + 1] & Mask) << LSH;
  506. }
  507. Bits[NumWords - 1] >>= BitDistance;
  508. return *this;
  509. }
  510. BitVector &operator<<=(unsigned N) {
  511. assert(N <= Size);
  512. if (LLVM_UNLIKELY(empty() || N == 0))
  513. return *this;
  514. unsigned NumWords = Bits.size();
  515. assert(NumWords >= 1);
  516. wordShl(N / BITWORD_SIZE);
  517. unsigned BitDistance = N % BITWORD_SIZE;
  518. if (BitDistance == 0)
  519. return *this;
  520. // When the shift size is not a multiple of the word size, then we have
  521. // a tricky situation where each word in succession needs to extract some
  522. // of the bits from the previous word and or them into this word while
  523. // shifting this word to make room for the new bits. This has to be done
  524. // for every word in the array. This is similar to the algorithm outlined
  525. // in operator>>=, but backwards.
  526. // Since we're shifting each word left, some bits will fall off the end
  527. // of each word to the left, and empty space will be created on the right.
  528. // The first word in the array will lose bits permanently, so starting at
  529. // the end, work backwards shifting each word to the left, and OR'ing
  530. // in the bits from the end of the next word to the beginning of the
  531. // current word.
  532. // Example:
  533. // Starting with {0xAABBCCDD, 0xEEFF0011, 0x22334455} and shifting left
  534. // by 4 bits.
  535. // Step 1: Word[2] <<= 4 ; 0x23344550
  536. // Step 2: Word[2] |= 0x0000000E ; 0x2334455E
  537. // Step 3: Word[1] <<= 4 ; 0xEFF00110
  538. // Step 4: Word[1] |= 0x0000000A ; 0xEFF0011A
  539. // Step 5: Word[0] <<= 4 ; 0xABBCCDD0
  540. // Result: { 0xABBCCDD0, 0xEFF0011A, 0x2334455E }
  541. const BitWord Mask = maskLeadingOnes<BitWord>(BitDistance);
  542. const unsigned RSH = BITWORD_SIZE - BitDistance;
  543. for (int I = NumWords - 1; I > 0; --I) {
  544. Bits[I] <<= BitDistance;
  545. Bits[I] |= (Bits[I - 1] & Mask) >> RSH;
  546. }
  547. Bits[0] <<= BitDistance;
  548. clear_unused_bits();
  549. return *this;
  550. }
  551. void swap(BitVector &RHS) {
  552. std::swap(Bits, RHS.Bits);
  553. std::swap(Size, RHS.Size);
  554. }
  555. void invalid() {
  556. assert(!Size && Bits.empty());
  557. Size = (unsigned)-1;
  558. }
  559. bool isInvalid() const { return Size == (unsigned)-1; }
  560. ArrayRef<BitWord> getData() const { return {&Bits[0], Bits.size()}; }
  561. //===--------------------------------------------------------------------===//
  562. // Portable bit mask operations.
  563. //===--------------------------------------------------------------------===//
  564. //
  565. // These methods all operate on arrays of uint32_t, each holding 32 bits. The
  566. // fixed word size makes it easier to work with literal bit vector constants
  567. // in portable code.
  568. //
  569. // The LSB in each word is the lowest numbered bit. The size of a portable
  570. // bit mask is always a whole multiple of 32 bits. If no bit mask size is
  571. // given, the bit mask is assumed to cover the entire BitVector.
  572. /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize.
  573. /// This computes "*this |= Mask".
  574. void setBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
  575. applyMask<true, false>(Mask, MaskWords);
  576. }
  577. /// clearBitsInMask - Clear any bits in this vector that are set in Mask.
  578. /// Don't resize. This computes "*this &= ~Mask".
  579. void clearBitsInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
  580. applyMask<false, false>(Mask, MaskWords);
  581. }
  582. /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask.
  583. /// Don't resize. This computes "*this |= ~Mask".
  584. void setBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
  585. applyMask<true, true>(Mask, MaskWords);
  586. }
  587. /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask.
  588. /// Don't resize. This computes "*this &= Mask".
  589. void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords = ~0u) {
  590. applyMask<false, true>(Mask, MaskWords);
  591. }
  592. private:
  593. /// Perform a logical left shift of \p Count words by moving everything
  594. /// \p Count words to the right in memory.
  595. ///
  596. /// While confusing, words are stored from least significant at Bits[0] to
  597. /// most significant at Bits[NumWords-1]. A logical shift left, however,
  598. /// moves the current least significant bit to a higher logical index, and
  599. /// fills the previous least significant bits with 0. Thus, we actually
  600. /// need to move the bytes of the memory to the right, not to the left.
  601. /// Example:
  602. /// Words = [0xBBBBAAAA, 0xDDDDFFFF, 0x00000000, 0xDDDD0000]
  603. /// represents a BitVector where 0xBBBBAAAA contain the least significant
  604. /// bits. So if we want to shift the BitVector left by 2 words, we need
  605. /// to turn this into 0x00000000 0x00000000 0xBBBBAAAA 0xDDDDFFFF by using a
  606. /// memmove which moves right, not left.
  607. void wordShl(uint32_t Count) {
  608. if (Count == 0)
  609. return;
  610. uint32_t NumWords = Bits.size();
  611. // Since we always move Word-sized chunks of data with src and dest both
  612. // aligned to a word-boundary, we don't need to worry about endianness
  613. // here.
  614. std::copy(Bits.begin(), Bits.begin() + NumWords - Count,
  615. Bits.begin() + Count);
  616. std::fill(Bits.begin(), Bits.begin() + Count, 0);
  617. clear_unused_bits();
  618. }
  619. /// Perform a logical right shift of \p Count words by moving those
  620. /// words to the left in memory. See wordShl for more information.
  621. ///
  622. void wordShr(uint32_t Count) {
  623. if (Count == 0)
  624. return;
  625. uint32_t NumWords = Bits.size();
  626. std::copy(Bits.begin() + Count, Bits.begin() + NumWords, Bits.begin());
  627. std::fill(Bits.begin() + NumWords - Count, Bits.begin() + NumWords, 0);
  628. }
  629. int next_unset_in_word(int WordIndex, BitWord Word) const {
  630. unsigned Result = WordIndex * BITWORD_SIZE + countTrailingOnes(Word);
  631. return Result < size() ? Result : -1;
  632. }
  633. unsigned NumBitWords(unsigned S) const {
  634. return (S + BITWORD_SIZE-1) / BITWORD_SIZE;
  635. }
  636. // Set the unused bits in the high words.
  637. void set_unused_bits(bool t = true) {
  638. // Then set any stray high bits of the last used word.
  639. if (unsigned ExtraBits = Size % BITWORD_SIZE) {
  640. BitWord ExtraBitMask = ~BitWord(0) << ExtraBits;
  641. if (t)
  642. Bits.back() |= ExtraBitMask;
  643. else
  644. Bits.back() &= ~ExtraBitMask;
  645. }
  646. }
  647. // Clear the unused bits in the high words.
  648. void clear_unused_bits() {
  649. set_unused_bits(false);
  650. }
  651. void init_words(bool t) {
  652. std::fill(Bits.begin(), Bits.end(), 0 - (BitWord)t);
  653. }
  654. template<bool AddBits, bool InvertMask>
  655. void applyMask(const uint32_t *Mask, unsigned MaskWords) {
  656. static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size.");
  657. MaskWords = std::min(MaskWords, (size() + 31) / 32);
  658. const unsigned Scale = BITWORD_SIZE / 32;
  659. unsigned i;
  660. for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) {
  661. BitWord BW = Bits[i];
  662. // This inner loop should unroll completely when BITWORD_SIZE > 32.
  663. for (unsigned b = 0; b != BITWORD_SIZE; b += 32) {
  664. uint32_t M = *Mask++;
  665. if (InvertMask) M = ~M;
  666. if (AddBits) BW |= BitWord(M) << b;
  667. else BW &= ~(BitWord(M) << b);
  668. }
  669. Bits[i] = BW;
  670. }
  671. for (unsigned b = 0; MaskWords; b += 32, --MaskWords) {
  672. uint32_t M = *Mask++;
  673. if (InvertMask) M = ~M;
  674. if (AddBits) Bits[i] |= BitWord(M) << b;
  675. else Bits[i] &= ~(BitWord(M) << b);
  676. }
  677. if (AddBits)
  678. clear_unused_bits();
  679. }
  680. public:
  681. /// Return the size (in bytes) of the bit vector.
  682. size_type getMemorySize() const { return Bits.size() * sizeof(BitWord); }
  683. size_type getBitCapacity() const { return Bits.size() * BITWORD_SIZE; }
  684. };
  685. inline BitVector::size_type capacity_in_bytes(const BitVector &X) {
  686. return X.getMemorySize();
  687. }
  688. template <> struct DenseMapInfo<BitVector> {
  689. static inline BitVector getEmptyKey() { return {}; }
  690. static inline BitVector getTombstoneKey() {
  691. BitVector V;
  692. V.invalid();
  693. return V;
  694. }
  695. static unsigned getHashValue(const BitVector &V) {
  696. return DenseMapInfo<std::pair<BitVector::size_type, ArrayRef<uintptr_t>>>::
  697. getHashValue(std::make_pair(V.size(), V.getData()));
  698. }
  699. static bool isEqual(const BitVector &LHS, const BitVector &RHS) {
  700. if (LHS.isInvalid() || RHS.isInvalid())
  701. return LHS.isInvalid() == RHS.isInvalid();
  702. return LHS == RHS;
  703. }
  704. };
  705. } // end namespace llvm
  706. namespace std {
  707. /// Implement std::swap in terms of BitVector swap.
  708. inline void swap(llvm::BitVector &LHS, llvm::BitVector &RHS) { LHS.swap(RHS); }
  709. } // end namespace std
  710. #endif // LLVM_ADT_BITVECTOR_H
  711. #ifdef __GNUC__
  712. #pragma GCC diagnostic pop
  713. #endif