BitVector.h 30 KB

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