llvm-DenseMap.h 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. //===- llvm/ADT/DenseMap.h - Dense probed hash table ------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the DenseMap class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. // Taken from clang-1100.247.11.10.9
  14. #ifndef LLVM_ADT_DENSEMAP_H
  15. #define LLVM_ADT_DENSEMAP_H
  16. #include "llvm-type_traits.h"
  17. #include "llvm-MathExtras.h"
  18. #include "llvm-AlignOf.h"
  19. #include "llvm-DenseMapInfo.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <cstddef>
  23. #include <cstring>
  24. #include <iterator>
  25. #include <new>
  26. #include <type_traits>
  27. #include <utility>
  28. #include <TargetConditionals.h>
  29. #include "objc-private.h"
  30. #define MIN_BUCKETS 4
  31. #define MIN_COMPACT 1024
  32. #define LLVM_UNLIKELY slowpath
  33. #define LLVM_LIKELY fastpath
  34. namespace objc {
  35. namespace detail {
  36. // We extend a pair to allow users to override the bucket type with their own
  37. // implementation without requiring two members.
  38. template <typename KeyT, typename ValueT>
  39. struct DenseMapPair : public std::pair<KeyT, ValueT> {
  40. // FIXME: Switch to inheriting constructors when we drop support for older
  41. // clang versions.
  42. // NOTE: This default constructor is declared with '{}' rather than
  43. // '= default' to work around a separate bug in clang-3.8. This can
  44. // also go when we switch to inheriting constructors.
  45. DenseMapPair() {}
  46. DenseMapPair(const KeyT &Key, const ValueT &Value)
  47. : std::pair<KeyT, ValueT>(Key, Value) {}
  48. DenseMapPair(KeyT &&Key, ValueT &&Value)
  49. : std::pair<KeyT, ValueT>(std::move(Key), std::move(Value)) {}
  50. template <typename AltKeyT, typename AltValueT>
  51. DenseMapPair(AltKeyT &&AltKey, AltValueT &&AltValue,
  52. typename std::enable_if<
  53. std::is_convertible<AltKeyT, KeyT>::value &&
  54. std::is_convertible<AltValueT, ValueT>::value>::type * = 0)
  55. : std::pair<KeyT, ValueT>(std::forward<AltKeyT>(AltKey),
  56. std::forward<AltValueT>(AltValue)) {}
  57. template <typename AltPairT>
  58. DenseMapPair(AltPairT &&AltPair,
  59. typename std::enable_if<std::is_convertible<
  60. AltPairT, std::pair<KeyT, ValueT>>::value>::type * = 0)
  61. : std::pair<KeyT, ValueT>(std::forward<AltPairT>(AltPair)) {}
  62. KeyT &getFirst() { return std::pair<KeyT, ValueT>::first; }
  63. const KeyT &getFirst() const { return std::pair<KeyT, ValueT>::first; }
  64. ValueT &getSecond() { return std::pair<KeyT, ValueT>::second; }
  65. const ValueT &getSecond() const { return std::pair<KeyT, ValueT>::second; }
  66. };
  67. } // end namespace detail
  68. template <
  69. typename KeyT, typename ValueT,
  70. typename ValueInfoT = DenseMapValueInfo<ValueT>,
  71. typename KeyInfoT = DenseMapInfo<KeyT>,
  72. typename Bucket = detail::DenseMapPair<KeyT, ValueT>,
  73. bool IsConst = false>
  74. class DenseMapIterator;
  75. // ValueInfoT is used by the refcount table.
  76. // A key/value pair with value==0 is not required to be stored
  77. // in the refcount table; it could correctly be erased instead.
  78. // For performance, we do keep zero values in the table when the
  79. // true refcount decreases to 1: this makes any future retain faster.
  80. // For memory size, we allow rehashes and table insertions to
  81. // remove a zero value as if it were a tombstone.
  82. template <typename DerivedT, typename KeyT, typename ValueT,
  83. typename ValueInfoT, typename KeyInfoT, typename BucketT>
  84. class DenseMapBase {
  85. template <typename T>
  86. using const_arg_type_t = typename const_pointer_or_const_ref<T>::type;
  87. public:
  88. using size_type = unsigned;
  89. using key_type = KeyT;
  90. using mapped_type = ValueT;
  91. using value_type = BucketT;
  92. using iterator = DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>;
  93. using const_iterator =
  94. DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT, true>;
  95. inline iterator begin() {
  96. // When the map is empty, avoid the overhead of advancing/retreating past
  97. // empty buckets.
  98. if (empty())
  99. return end();
  100. return makeIterator(getBuckets(), getBucketsEnd());
  101. }
  102. inline iterator end() {
  103. return makeIterator(getBucketsEnd(), getBucketsEnd(), true);
  104. }
  105. inline const_iterator begin() const {
  106. if (empty())
  107. return end();
  108. return makeConstIterator(getBuckets(), getBucketsEnd());
  109. }
  110. inline const_iterator end() const {
  111. return makeConstIterator(getBucketsEnd(), getBucketsEnd(), true);
  112. }
  113. bool empty() const {
  114. return getNumEntries() == 0;
  115. }
  116. unsigned size() const { return getNumEntries(); }
  117. /// Grow the densemap so that it can contain at least \p NumEntries items
  118. /// before resizing again.
  119. void reserve(size_type NumEntries) {
  120. auto NumBuckets = getMinBucketToReserveForEntries(NumEntries);
  121. if (NumBuckets > getNumBuckets())
  122. grow(NumBuckets);
  123. }
  124. void clear() {
  125. if (getNumEntries() == 0 && getNumTombstones() == 0) return;
  126. // If the capacity of the array is huge, and the # elements used is small,
  127. // shrink the array.
  128. if (getNumEntries() * 4 < getNumBuckets() && getNumBuckets() > MIN_BUCKETS) {
  129. shrink_and_clear();
  130. return;
  131. }
  132. const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
  133. if (is_trivially_copyable<KeyT>::value &&
  134. is_trivially_copyable<ValueT>::value) {
  135. // Use a simpler loop when these are trivial types.
  136. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P)
  137. P->getFirst() = EmptyKey;
  138. } else {
  139. unsigned NumEntries = getNumEntries();
  140. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
  141. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey)) {
  142. if (!KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  143. P->getSecond().~ValueT();
  144. --NumEntries;
  145. }
  146. P->getFirst() = EmptyKey;
  147. }
  148. }
  149. ASSERT(NumEntries == 0 && "Node count imbalance!");
  150. }
  151. setNumEntries(0);
  152. setNumTombstones(0);
  153. }
  154. /// Return 1 if the specified key is in the map, 0 otherwise.
  155. size_type count(const_arg_type_t<KeyT> Val) const {
  156. const BucketT *TheBucket;
  157. return LookupBucketFor(Val, TheBucket) ? 1 : 0;
  158. }
  159. iterator find(const_arg_type_t<KeyT> Val) {
  160. BucketT *TheBucket;
  161. if (LookupBucketFor(Val, TheBucket))
  162. return makeIterator(TheBucket, getBucketsEnd(), true);
  163. return end();
  164. }
  165. const_iterator find(const_arg_type_t<KeyT> Val) const {
  166. const BucketT *TheBucket;
  167. if (LookupBucketFor(Val, TheBucket))
  168. return makeConstIterator(TheBucket, getBucketsEnd(), true);
  169. return end();
  170. }
  171. /// Alternate version of find() which allows a different, and possibly
  172. /// less expensive, key type.
  173. /// The DenseMapInfo is responsible for supplying methods
  174. /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
  175. /// type used.
  176. template<class LookupKeyT>
  177. iterator find_as(const LookupKeyT &Val) {
  178. BucketT *TheBucket;
  179. if (LookupBucketFor(Val, TheBucket))
  180. return makeIterator(TheBucket, getBucketsEnd(), true);
  181. return end();
  182. }
  183. template<class LookupKeyT>
  184. const_iterator find_as(const LookupKeyT &Val) const {
  185. const BucketT *TheBucket;
  186. if (LookupBucketFor(Val, TheBucket))
  187. return makeConstIterator(TheBucket, getBucketsEnd(), true);
  188. return end();
  189. }
  190. /// lookup - Return the entry for the specified key, or a default
  191. /// constructed value if no such entry exists.
  192. ValueT lookup(const_arg_type_t<KeyT> Val) const {
  193. const BucketT *TheBucket;
  194. if (LookupBucketFor(Val, TheBucket))
  195. return TheBucket->getSecond();
  196. return ValueT();
  197. }
  198. // Inserts key,value pair into the map if the key isn't already in the map.
  199. // If the key is already in the map, it returns false and doesn't update the
  200. // value.
  201. std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
  202. return try_emplace(KV.first, KV.second);
  203. }
  204. // Inserts key,value pair into the map if the key isn't already in the map.
  205. // If the key is already in the map, it returns false and doesn't update the
  206. // value.
  207. std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
  208. return try_emplace(std::move(KV.first), std::move(KV.second));
  209. }
  210. // Inserts key,value pair into the map if the key isn't already in the map.
  211. // The value is constructed in-place if the key is not in the map, otherwise
  212. // it is not moved.
  213. template <typename... Ts>
  214. std::pair<iterator, bool> try_emplace(KeyT &&Key, Ts &&... Args) {
  215. BucketT *TheBucket;
  216. if (LookupBucketFor(Key, TheBucket))
  217. return std::make_pair(
  218. makeIterator(TheBucket, getBucketsEnd(), true),
  219. false); // Already in map.
  220. // Otherwise, insert the new element.
  221. TheBucket =
  222. InsertIntoBucket(TheBucket, std::move(Key), std::forward<Ts>(Args)...);
  223. return std::make_pair(
  224. makeIterator(TheBucket, getBucketsEnd(), true),
  225. true);
  226. }
  227. // Inserts key,value pair into the map if the key isn't already in the map.
  228. // The value is constructed in-place if the key is not in the map, otherwise
  229. // it is not moved.
  230. template <typename... Ts>
  231. std::pair<iterator, bool> try_emplace(const KeyT &Key, Ts &&... Args) {
  232. BucketT *TheBucket;
  233. if (LookupBucketFor(Key, TheBucket))
  234. return std::make_pair(
  235. makeIterator(TheBucket, getBucketsEnd(), true),
  236. false); // Already in map.
  237. // Otherwise, insert the new element.
  238. TheBucket = InsertIntoBucket(TheBucket, Key, std::forward<Ts>(Args)...);
  239. return std::make_pair(
  240. makeIterator(TheBucket, getBucketsEnd(), true),
  241. true);
  242. }
  243. /// Alternate version of insert() which allows a different, and possibly
  244. /// less expensive, key type.
  245. /// The DenseMapInfo is responsible for supplying methods
  246. /// getHashValue(LookupKeyT) and isEqual(LookupKeyT, KeyT) for each key
  247. /// type used.
  248. template <typename LookupKeyT>
  249. std::pair<iterator, bool> insert_as(std::pair<KeyT, ValueT> &&KV,
  250. const LookupKeyT &Val) {
  251. BucketT *TheBucket;
  252. if (LookupBucketFor(Val, TheBucket))
  253. return std::make_pair(
  254. makeIterator(TheBucket, getBucketsEnd(), *this, true),
  255. false); // Already in map.
  256. // Otherwise, insert the new element.
  257. TheBucket = InsertIntoBucketWithLookup(TheBucket, std::move(KV.first),
  258. std::move(KV.second), Val);
  259. return std::make_pair(
  260. makeIterator(TheBucket, getBucketsEnd(), *this, true),
  261. true);
  262. }
  263. /// insert - Range insertion of pairs.
  264. template<typename InputIt>
  265. void insert(InputIt I, InputIt E) {
  266. for (; I != E; ++I)
  267. insert(*I);
  268. }
  269. // Clear if empty.
  270. // Shrink if at least 15/16 empty and larger than MIN_COMPACT.
  271. void compact() {
  272. if (getNumEntries() == 0) {
  273. shrink_and_clear();
  274. }
  275. else if (getNumBuckets() / 16 > getNumEntries() &&
  276. getNumBuckets() > MIN_COMPACT)
  277. {
  278. grow(getNumEntries() * 2);
  279. }
  280. }
  281. bool erase(const KeyT &Val) {
  282. BucketT *TheBucket;
  283. if (!LookupBucketFor(Val, TheBucket))
  284. return false; // not in map.
  285. TheBucket->getSecond().~ValueT();
  286. TheBucket->getFirst() = getTombstoneKey();
  287. decrementNumEntries();
  288. incrementNumTombstones();
  289. compact();
  290. return true;
  291. }
  292. void erase(iterator I) {
  293. BucketT *TheBucket = &*I;
  294. TheBucket->getSecond().~ValueT();
  295. TheBucket->getFirst() = getTombstoneKey();
  296. decrementNumEntries();
  297. incrementNumTombstones();
  298. compact();
  299. }
  300. value_type& FindAndConstruct(const KeyT &Key) {
  301. BucketT *TheBucket;
  302. if (LookupBucketFor(Key, TheBucket))
  303. return *TheBucket;
  304. return *InsertIntoBucket(TheBucket, Key);
  305. }
  306. ValueT &operator[](const KeyT &Key) {
  307. return FindAndConstruct(Key).second;
  308. }
  309. value_type& FindAndConstruct(KeyT &&Key) {
  310. BucketT *TheBucket;
  311. if (LookupBucketFor(Key, TheBucket))
  312. return *TheBucket;
  313. return *InsertIntoBucket(TheBucket, std::move(Key));
  314. }
  315. ValueT &operator[](KeyT &&Key) {
  316. return FindAndConstruct(std::move(Key)).second;
  317. }
  318. /// isPointerIntoBucketsArray - Return true if the specified pointer points
  319. /// somewhere into the DenseMap's array of buckets (i.e. either to a key or
  320. /// value in the DenseMap).
  321. bool isPointerIntoBucketsArray(const void *Ptr) const {
  322. return Ptr >= getBuckets() && Ptr < getBucketsEnd();
  323. }
  324. /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
  325. /// array. In conjunction with the previous method, this can be used to
  326. /// determine whether an insertion caused the DenseMap to reallocate.
  327. const void *getPointerIntoBucketsArray() const { return getBuckets(); }
  328. protected:
  329. DenseMapBase() = default;
  330. void destroyAll() {
  331. if (getNumBuckets() == 0) // Nothing to do.
  332. return;
  333. const KeyT EmptyKey = getEmptyKey(), TombstoneKey = getTombstoneKey();
  334. for (BucketT *P = getBuckets(), *E = getBucketsEnd(); P != E; ++P) {
  335. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
  336. !KeyInfoT::isEqual(P->getFirst(), TombstoneKey))
  337. P->getSecond().~ValueT();
  338. P->getFirst().~KeyT();
  339. }
  340. }
  341. void initEmpty() {
  342. setNumEntries(0);
  343. setNumTombstones(0);
  344. ASSERT((getNumBuckets() & (getNumBuckets()-1)) == 0 &&
  345. "# initial buckets must be a power of two!");
  346. const KeyT EmptyKey = getEmptyKey();
  347. for (BucketT *B = getBuckets(), *E = getBucketsEnd(); B != E; ++B)
  348. ::new (&B->getFirst()) KeyT(EmptyKey);
  349. }
  350. /// Returns the number of buckets to allocate to ensure that the DenseMap can
  351. /// accommodate \p NumEntries without need to grow().
  352. unsigned getMinBucketToReserveForEntries(unsigned NumEntries) {
  353. // Ensure that "NumEntries * 4 < NumBuckets * 3"
  354. if (NumEntries == 0)
  355. return 0;
  356. // +1 is required because of the strict equality.
  357. // For example if NumEntries is 48, we need to return 401.
  358. return NextPowerOf2(NumEntries * 4 / 3 + 1);
  359. }
  360. void moveFromOldBuckets(BucketT *OldBucketsBegin, BucketT *OldBucketsEnd) {
  361. initEmpty();
  362. // Insert all the old elements.
  363. const KeyT EmptyKey = getEmptyKey();
  364. const KeyT TombstoneKey = getTombstoneKey();
  365. for (BucketT *B = OldBucketsBegin, *E = OldBucketsEnd; B != E; ++B) {
  366. if (ValueInfoT::isPurgeable(B->getSecond())) {
  367. // Free the value.
  368. B->getSecond().~ValueT();
  369. } else if (!KeyInfoT::isEqual(B->getFirst(), EmptyKey) &&
  370. !KeyInfoT::isEqual(B->getFirst(), TombstoneKey)) {
  371. // Insert the key/value into the new table.
  372. BucketT *DestBucket;
  373. bool FoundVal = LookupBucketFor(B->getFirst(), DestBucket);
  374. (void)FoundVal; // silence warning.
  375. ASSERT(!FoundVal && "Key already in new map?");
  376. DestBucket->getFirst() = std::move(B->getFirst());
  377. ::new (&DestBucket->getSecond()) ValueT(std::move(B->getSecond()));
  378. incrementNumEntries();
  379. // Free the value.
  380. B->getSecond().~ValueT();
  381. }
  382. B->getFirst().~KeyT();
  383. }
  384. }
  385. template <typename OtherBaseT>
  386. void copyFrom(
  387. const DenseMapBase<OtherBaseT, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> &other) {
  388. ASSERT(&other != this);
  389. ASSERT(getNumBuckets() == other.getNumBuckets());
  390. setNumEntries(other.getNumEntries());
  391. setNumTombstones(other.getNumTombstones());
  392. if (is_trivially_copyable<KeyT>::value &&
  393. is_trivially_copyable<ValueT>::value)
  394. memcpy(reinterpret_cast<void *>(getBuckets()), other.getBuckets(),
  395. getNumBuckets() * sizeof(BucketT));
  396. else
  397. for (size_t i = 0; i < getNumBuckets(); ++i) {
  398. ::new (&getBuckets()[i].getFirst())
  399. KeyT(other.getBuckets()[i].getFirst());
  400. if (!KeyInfoT::isEqual(getBuckets()[i].getFirst(), getEmptyKey()) &&
  401. !KeyInfoT::isEqual(getBuckets()[i].getFirst(), getTombstoneKey()))
  402. ::new (&getBuckets()[i].getSecond())
  403. ValueT(other.getBuckets()[i].getSecond());
  404. }
  405. }
  406. static unsigned getHashValue(const KeyT &Val) {
  407. return KeyInfoT::getHashValue(Val);
  408. }
  409. template<typename LookupKeyT>
  410. static unsigned getHashValue(const LookupKeyT &Val) {
  411. return KeyInfoT::getHashValue(Val);
  412. }
  413. static const KeyT getEmptyKey() {
  414. static_assert(std::is_base_of<DenseMapBase, DerivedT>::value,
  415. "Must pass the derived type to this template!");
  416. return KeyInfoT::getEmptyKey();
  417. }
  418. static const KeyT getTombstoneKey() {
  419. return KeyInfoT::getTombstoneKey();
  420. }
  421. private:
  422. iterator makeIterator(BucketT *P, BucketT *E,
  423. bool NoAdvance=false) {
  424. return iterator(P, E, NoAdvance);
  425. }
  426. const_iterator makeConstIterator(const BucketT *P, const BucketT *E,
  427. const bool NoAdvance=false) const {
  428. return const_iterator(P, E, NoAdvance);
  429. }
  430. unsigned getNumEntries() const {
  431. return static_cast<const DerivedT *>(this)->getNumEntries();
  432. }
  433. void setNumEntries(unsigned Num) {
  434. static_cast<DerivedT *>(this)->setNumEntries(Num);
  435. }
  436. void incrementNumEntries() {
  437. setNumEntries(getNumEntries() + 1);
  438. }
  439. void decrementNumEntries() {
  440. setNumEntries(getNumEntries() - 1);
  441. }
  442. unsigned getNumTombstones() const {
  443. return static_cast<const DerivedT *>(this)->getNumTombstones();
  444. }
  445. void setNumTombstones(unsigned Num) {
  446. static_cast<DerivedT *>(this)->setNumTombstones(Num);
  447. }
  448. void incrementNumTombstones() {
  449. setNumTombstones(getNumTombstones() + 1);
  450. }
  451. void decrementNumTombstones() {
  452. setNumTombstones(getNumTombstones() - 1);
  453. }
  454. const BucketT *getBuckets() const {
  455. return static_cast<const DerivedT *>(this)->getBuckets();
  456. }
  457. BucketT *getBuckets() {
  458. return static_cast<DerivedT *>(this)->getBuckets();
  459. }
  460. unsigned getNumBuckets() const {
  461. return static_cast<const DerivedT *>(this)->getNumBuckets();
  462. }
  463. BucketT *getBucketsEnd() {
  464. return getBuckets() + getNumBuckets();
  465. }
  466. const BucketT *getBucketsEnd() const {
  467. return getBuckets() + getNumBuckets();
  468. }
  469. void grow(unsigned AtLeast) {
  470. static_cast<DerivedT *>(this)->grow(AtLeast);
  471. }
  472. void shrink_and_clear() {
  473. static_cast<DerivedT *>(this)->shrink_and_clear();
  474. }
  475. template <typename KeyArg, typename... ValueArgs>
  476. BucketT *InsertIntoBucket(BucketT *TheBucket, KeyArg &&Key,
  477. ValueArgs &&... Values) {
  478. TheBucket = InsertIntoBucketImpl(Key, Key, TheBucket);
  479. TheBucket->getFirst() = std::forward<KeyArg>(Key);
  480. ::new (&TheBucket->getSecond()) ValueT(std::forward<ValueArgs>(Values)...);
  481. return TheBucket;
  482. }
  483. template <typename LookupKeyT>
  484. BucketT *InsertIntoBucketWithLookup(BucketT *TheBucket, KeyT &&Key,
  485. ValueT &&Value, LookupKeyT &Lookup) {
  486. TheBucket = InsertIntoBucketImpl(Key, Lookup, TheBucket);
  487. TheBucket->getFirst() = std::move(Key);
  488. ::new (&TheBucket->getSecond()) ValueT(std::move(Value));
  489. return TheBucket;
  490. }
  491. template <typename LookupKeyT>
  492. BucketT *InsertIntoBucketImpl(const KeyT &Key, const LookupKeyT &Lookup,
  493. BucketT *TheBucket) {
  494. // If the load of the hash table is more than 3/4, or if fewer than 1/8 of
  495. // the buckets are empty (meaning that many are filled with tombstones),
  496. // grow the table.
  497. //
  498. // The later case is tricky. For example, if we had one empty bucket with
  499. // tons of tombstones, failing lookups (e.g. for insertion) would have to
  500. // probe almost the entire table until it found the empty bucket. If the
  501. // table completely filled with tombstones, no lookup would ever succeed,
  502. // causing infinite loops in lookup.
  503. unsigned NewNumEntries = getNumEntries() + 1;
  504. unsigned NumBuckets = getNumBuckets();
  505. if (LLVM_UNLIKELY(NewNumEntries * 4 >= NumBuckets * 3)) {
  506. this->grow(NumBuckets * 2);
  507. LookupBucketFor(Lookup, TheBucket);
  508. NumBuckets = getNumBuckets();
  509. } else if (LLVM_UNLIKELY(NumBuckets-(NewNumEntries+getNumTombstones()) <=
  510. NumBuckets/8)) {
  511. this->grow(NumBuckets);
  512. LookupBucketFor(Lookup, TheBucket);
  513. }
  514. ASSERT(TheBucket);
  515. // Only update the state after we've grown our bucket space appropriately
  516. // so that when growing buckets we have self-consistent entry count.
  517. // If we are writing over a tombstone or zero value, remember this.
  518. if (KeyInfoT::isEqual(TheBucket->getFirst(), getEmptyKey())) {
  519. // Replacing an empty bucket.
  520. incrementNumEntries();
  521. } else if (KeyInfoT::isEqual(TheBucket->getFirst(), getTombstoneKey())) {
  522. // Replacing a tombstone.
  523. incrementNumEntries();
  524. decrementNumTombstones();
  525. } else {
  526. // we should be purging a zero. No accounting changes.
  527. ASSERT(ValueInfoT::isPurgeable(TheBucket->getSecond()));
  528. TheBucket->getSecond().~ValueT();
  529. }
  530. return TheBucket;
  531. }
  532. __attribute__((noinline, noreturn, cold))
  533. void FatalCorruptHashTables(const BucketT *BucketsPtr, unsigned NumBuckets) const
  534. {
  535. _objc_fatal("Hash table corrupted. This is probably a memory error "
  536. "somewhere. (table at %p, buckets at %p (%zu bytes), "
  537. "%u buckets, %u entries, %u tombstones, "
  538. "data %p %p %p %p)",
  539. this, BucketsPtr, malloc_size(BucketsPtr),
  540. NumBuckets, getNumEntries(), getNumTombstones(),
  541. ((void**)BucketsPtr)[0], ((void**)BucketsPtr)[1],
  542. ((void**)BucketsPtr)[2], ((void**)BucketsPtr)[3]);
  543. }
  544. /// LookupBucketFor - Lookup the appropriate bucket for Val, returning it in
  545. /// FoundBucket. If the bucket contains the key and a value, this returns
  546. /// true, otherwise it returns a bucket with an empty marker or tombstone and
  547. /// returns false.
  548. template<typename LookupKeyT>
  549. bool LookupBucketFor(const LookupKeyT &Val,
  550. const BucketT *&FoundBucket) const {
  551. const BucketT *BucketsPtr = getBuckets();
  552. const unsigned NumBuckets = getNumBuckets();
  553. if (NumBuckets == 0) {
  554. FoundBucket = nullptr;
  555. return false;
  556. }
  557. // FoundTombstone - Keep track of whether we find a tombstone while probing.
  558. const BucketT *FoundTombstone = nullptr;
  559. const KeyT EmptyKey = getEmptyKey();
  560. const KeyT TombstoneKey = getTombstoneKey();
  561. assert(!KeyInfoT::isEqual(Val, EmptyKey) &&
  562. !KeyInfoT::isEqual(Val, TombstoneKey) &&
  563. "Empty/Tombstone value shouldn't be inserted into map!");
  564. unsigned BucketNo = getHashValue(Val) & (NumBuckets-1);
  565. unsigned ProbeAmt = 1;
  566. while (true) {
  567. const BucketT *ThisBucket = BucketsPtr + BucketNo;
  568. // Found Val's bucket? If so, return it.
  569. if (LLVM_LIKELY(KeyInfoT::isEqual(Val, ThisBucket->getFirst()))) {
  570. FoundBucket = ThisBucket;
  571. return true;
  572. }
  573. // If we found an empty bucket, the key doesn't exist in the set.
  574. // Insert it and return the default value.
  575. if (LLVM_LIKELY(KeyInfoT::isEqual(ThisBucket->getFirst(), EmptyKey))) {
  576. // If we've already seen a tombstone while probing, fill it in instead
  577. // of the empty bucket we eventually probed to.
  578. FoundBucket = FoundTombstone ? FoundTombstone : ThisBucket;
  579. return false;
  580. }
  581. // If this is a tombstone, remember it. If Val ends up not in the map, we
  582. // prefer to return it than something that would require more probing.
  583. // Ditto for zero values.
  584. if (KeyInfoT::isEqual(ThisBucket->getFirst(), TombstoneKey) &&
  585. !FoundTombstone)
  586. FoundTombstone = ThisBucket; // Remember the first tombstone found.
  587. if (ValueInfoT::isPurgeable(ThisBucket->getSecond()) && !FoundTombstone)
  588. FoundTombstone = ThisBucket;
  589. // Otherwise, it's a hash collision or a tombstone, continue quadratic
  590. // probing.
  591. if (ProbeAmt > NumBuckets) {
  592. FatalCorruptHashTables(BucketsPtr, NumBuckets);
  593. }
  594. BucketNo += ProbeAmt++;
  595. BucketNo &= (NumBuckets-1);
  596. }
  597. }
  598. template <typename LookupKeyT>
  599. bool LookupBucketFor(const LookupKeyT &Val, BucketT *&FoundBucket) {
  600. const BucketT *ConstFoundBucket;
  601. bool Result = const_cast<const DenseMapBase *>(this)
  602. ->LookupBucketFor(Val, ConstFoundBucket);
  603. FoundBucket = const_cast<BucketT *>(ConstFoundBucket);
  604. return Result;
  605. }
  606. public:
  607. /// Return the approximate size (in bytes) of the actual map.
  608. /// This is just the raw memory used by DenseMap.
  609. /// If entries are pointers to objects, the size of the referenced objects
  610. /// are not included.
  611. size_t getMemorySize() const {
  612. return getNumBuckets() * sizeof(BucketT);
  613. }
  614. };
  615. /// Equality comparison for DenseMap.
  616. ///
  617. /// Iterates over elements of LHS confirming that each (key, value) pair in LHS
  618. /// is also in RHS, and that no additional pairs are in RHS.
  619. /// Equivalent to N calls to RHS.find and N value comparisons. Amortized
  620. /// complexity is linear, worst case is O(N^2) (if every hash collides).
  621. template <typename DerivedT, typename KeyT, typename ValueT,
  622. typename ValueInfoT, typename KeyInfoT, typename BucketT>
  623. bool operator==(
  624. const DenseMapBase<DerivedT, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> &LHS,
  625. const DenseMapBase<DerivedT, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> &RHS) {
  626. if (LHS.size() != RHS.size())
  627. return false;
  628. for (auto &KV : LHS) {
  629. auto I = RHS.find(KV.first);
  630. if (I == RHS.end() || I->second != KV.second)
  631. return false;
  632. }
  633. return true;
  634. }
  635. /// Inequality comparison for DenseMap.
  636. ///
  637. /// Equivalent to !(LHS == RHS). See operator== for performance notes.
  638. template <typename DerivedT, typename KeyT, typename ValueT,
  639. typename ValueInfoT, typename KeyInfoT, typename BucketT>
  640. bool operator!=(
  641. const DenseMapBase<DerivedT, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> &LHS,
  642. const DenseMapBase<DerivedT, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> &RHS) {
  643. return !(LHS == RHS);
  644. }
  645. template <typename KeyT, typename ValueT,
  646. typename ValueInfoT = DenseMapValueInfo<ValueT>,
  647. typename KeyInfoT = DenseMapInfo<KeyT>,
  648. typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
  649. class DenseMap : public DenseMapBase<DenseMap<KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>,
  650. KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT> {
  651. friend class DenseMapBase<DenseMap, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>;
  652. // Lift some types from the dependent base class into this class for
  653. // simplicity of referring to them.
  654. using BaseT = DenseMapBase<DenseMap, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>;
  655. BucketT *Buckets;
  656. unsigned NumEntries;
  657. unsigned NumTombstones;
  658. unsigned NumBuckets;
  659. public:
  660. /// Create a DenseMap wth an optional \p InitialReserve that guarantee that
  661. /// this number of elements can be inserted in the map without grow()
  662. explicit DenseMap(unsigned InitialReserve = 0) { init(InitialReserve); }
  663. DenseMap(const DenseMap &other) : BaseT() {
  664. init(0);
  665. copyFrom(other);
  666. }
  667. DenseMap(DenseMap &&other) : BaseT() {
  668. init(0);
  669. swap(other);
  670. }
  671. template<typename InputIt>
  672. DenseMap(const InputIt &I, const InputIt &E) {
  673. init(std::distance(I, E));
  674. this->insert(I, E);
  675. }
  676. DenseMap(std::initializer_list<typename BaseT::value_type> Vals) {
  677. init(Vals.size());
  678. this->insert(Vals.begin(), Vals.end());
  679. }
  680. ~DenseMap() {
  681. this->destroyAll();
  682. operator delete(Buckets);
  683. }
  684. void swap(DenseMap& RHS) {
  685. std::swap(Buckets, RHS.Buckets);
  686. std::swap(NumEntries, RHS.NumEntries);
  687. std::swap(NumTombstones, RHS.NumTombstones);
  688. std::swap(NumBuckets, RHS.NumBuckets);
  689. }
  690. DenseMap& operator=(const DenseMap& other) {
  691. if (&other != this)
  692. copyFrom(other);
  693. return *this;
  694. }
  695. DenseMap& operator=(DenseMap &&other) {
  696. this->destroyAll();
  697. operator delete(Buckets);
  698. init(0);
  699. swap(other);
  700. return *this;
  701. }
  702. void copyFrom(const DenseMap& other) {
  703. this->destroyAll();
  704. operator delete(Buckets);
  705. if (allocateBuckets(other.NumBuckets)) {
  706. this->BaseT::copyFrom(other);
  707. } else {
  708. NumEntries = 0;
  709. NumTombstones = 0;
  710. }
  711. }
  712. void init(unsigned InitNumEntries) {
  713. auto InitBuckets = BaseT::getMinBucketToReserveForEntries(InitNumEntries);
  714. if (allocateBuckets(InitBuckets)) {
  715. this->BaseT::initEmpty();
  716. } else {
  717. NumEntries = 0;
  718. NumTombstones = 0;
  719. }
  720. }
  721. void grow(unsigned AtLeast) {
  722. unsigned OldNumBuckets = NumBuckets;
  723. BucketT *OldBuckets = Buckets;
  724. allocateBuckets(std::max<unsigned>(MIN_BUCKETS, static_cast<unsigned>(NextPowerOf2(AtLeast-1))));
  725. ASSERT(Buckets);
  726. if (!OldBuckets) {
  727. this->BaseT::initEmpty();
  728. return;
  729. }
  730. this->moveFromOldBuckets(OldBuckets, OldBuckets+OldNumBuckets);
  731. // Free the old table.
  732. operator delete(OldBuckets);
  733. }
  734. void shrink_and_clear() {
  735. unsigned OldNumEntries = NumEntries;
  736. this->destroyAll();
  737. // Reduce the number of buckets.
  738. unsigned NewNumBuckets = 0;
  739. if (OldNumEntries)
  740. NewNumBuckets = std::max(MIN_BUCKETS, 1 << (Log2_32_Ceil(OldNumEntries) + 1));
  741. if (NewNumBuckets == NumBuckets) {
  742. this->BaseT::initEmpty();
  743. return;
  744. }
  745. operator delete(Buckets);
  746. init(NewNumBuckets);
  747. }
  748. private:
  749. unsigned getNumEntries() const {
  750. return NumEntries;
  751. }
  752. void setNumEntries(unsigned Num) {
  753. NumEntries = Num;
  754. }
  755. unsigned getNumTombstones() const {
  756. return NumTombstones;
  757. }
  758. void setNumTombstones(unsigned Num) {
  759. NumTombstones = Num;
  760. }
  761. BucketT *getBuckets() const {
  762. return Buckets;
  763. }
  764. unsigned getNumBuckets() const {
  765. return NumBuckets;
  766. }
  767. bool allocateBuckets(unsigned Num) {
  768. NumBuckets = Num;
  769. if (NumBuckets == 0) {
  770. Buckets = nullptr;
  771. return false;
  772. }
  773. Buckets = static_cast<BucketT*>(operator new(sizeof(BucketT) * NumBuckets));
  774. return true;
  775. }
  776. };
  777. template <typename KeyT, typename ValueT, unsigned InlineBuckets = 4,
  778. typename ValueInfoT = DenseMapValueInfo<ValueT>,
  779. typename KeyInfoT = DenseMapInfo<KeyT>,
  780. typename BucketT = detail::DenseMapPair<KeyT, ValueT>>
  781. class SmallDenseMap
  782. : public DenseMapBase<
  783. SmallDenseMap<KeyT, ValueT, InlineBuckets, ValueInfoT, KeyInfoT, BucketT>, KeyT,
  784. ValueT, ValueInfoT, KeyInfoT, BucketT> {
  785. friend class DenseMapBase<SmallDenseMap, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>;
  786. // Lift some types from the dependent base class into this class for
  787. // simplicity of referring to them.
  788. using BaseT = DenseMapBase<SmallDenseMap, KeyT, ValueT, ValueInfoT, KeyInfoT, BucketT>;
  789. static_assert(powerof2(InlineBuckets),
  790. "InlineBuckets must be a power of 2.");
  791. unsigned Small : 1;
  792. unsigned NumEntries : 31;
  793. unsigned NumTombstones;
  794. struct LargeRep {
  795. BucketT *Buckets;
  796. unsigned NumBuckets;
  797. };
  798. /// A "union" of an inline bucket array and the struct representing
  799. /// a large bucket. This union will be discriminated by the 'Small' bit.
  800. AlignedCharArrayUnion<BucketT[InlineBuckets], LargeRep> storage;
  801. public:
  802. explicit SmallDenseMap(unsigned NumInitBuckets = 0) {
  803. init(NumInitBuckets);
  804. }
  805. SmallDenseMap(const SmallDenseMap &other) : BaseT() {
  806. init(0);
  807. copyFrom(other);
  808. }
  809. SmallDenseMap(SmallDenseMap &&other) : BaseT() {
  810. init(0);
  811. swap(other);
  812. }
  813. template<typename InputIt>
  814. SmallDenseMap(const InputIt &I, const InputIt &E) {
  815. init(NextPowerOf2(std::distance(I, E)));
  816. this->insert(I, E);
  817. }
  818. ~SmallDenseMap() {
  819. this->destroyAll();
  820. deallocateBuckets();
  821. }
  822. void swap(SmallDenseMap& RHS) {
  823. unsigned TmpNumEntries = RHS.NumEntries;
  824. RHS.NumEntries = NumEntries;
  825. NumEntries = TmpNumEntries;
  826. std::swap(NumTombstones, RHS.NumTombstones);
  827. const KeyT EmptyKey = this->getEmptyKey();
  828. const KeyT TombstoneKey = this->getTombstoneKey();
  829. if (Small && RHS.Small) {
  830. // If we're swapping inline bucket arrays, we have to cope with some of
  831. // the tricky bits of DenseMap's storage system: the buckets are not
  832. // fully initialized. Thus we swap every key, but we may have
  833. // a one-directional move of the value.
  834. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  835. BucketT *LHSB = &getInlineBuckets()[i],
  836. *RHSB = &RHS.getInlineBuckets()[i];
  837. bool hasLHSValue = (!KeyInfoT::isEqual(LHSB->getFirst(), EmptyKey) &&
  838. !KeyInfoT::isEqual(LHSB->getFirst(), TombstoneKey));
  839. bool hasRHSValue = (!KeyInfoT::isEqual(RHSB->getFirst(), EmptyKey) &&
  840. !KeyInfoT::isEqual(RHSB->getFirst(), TombstoneKey));
  841. if (hasLHSValue && hasRHSValue) {
  842. // Swap together if we can...
  843. std::swap(*LHSB, *RHSB);
  844. continue;
  845. }
  846. // Swap separately and handle any assymetry.
  847. std::swap(LHSB->getFirst(), RHSB->getFirst());
  848. if (hasLHSValue) {
  849. ::new (&RHSB->getSecond()) ValueT(std::move(LHSB->getSecond()));
  850. LHSB->getSecond().~ValueT();
  851. } else if (hasRHSValue) {
  852. ::new (&LHSB->getSecond()) ValueT(std::move(RHSB->getSecond()));
  853. RHSB->getSecond().~ValueT();
  854. }
  855. }
  856. return;
  857. }
  858. if (!Small && !RHS.Small) {
  859. std::swap(getLargeRep()->Buckets, RHS.getLargeRep()->Buckets);
  860. std::swap(getLargeRep()->NumBuckets, RHS.getLargeRep()->NumBuckets);
  861. return;
  862. }
  863. SmallDenseMap &SmallSide = Small ? *this : RHS;
  864. SmallDenseMap &LargeSide = Small ? RHS : *this;
  865. // First stash the large side's rep and move the small side across.
  866. LargeRep TmpRep = std::move(*LargeSide.getLargeRep());
  867. LargeSide.getLargeRep()->~LargeRep();
  868. LargeSide.Small = true;
  869. // This is similar to the standard move-from-old-buckets, but the bucket
  870. // count hasn't actually rotated in this case. So we have to carefully
  871. // move construct the keys and values into their new locations, but there
  872. // is no need to re-hash things.
  873. for (unsigned i = 0, e = InlineBuckets; i != e; ++i) {
  874. BucketT *NewB = &LargeSide.getInlineBuckets()[i],
  875. *OldB = &SmallSide.getInlineBuckets()[i];
  876. ::new (&NewB->getFirst()) KeyT(std::move(OldB->getFirst()));
  877. OldB->getFirst().~KeyT();
  878. if (!KeyInfoT::isEqual(NewB->getFirst(), EmptyKey) &&
  879. !KeyInfoT::isEqual(NewB->getFirst(), TombstoneKey)) {
  880. ::new (&NewB->getSecond()) ValueT(std::move(OldB->getSecond()));
  881. OldB->getSecond().~ValueT();
  882. }
  883. }
  884. // The hard part of moving the small buckets across is done, just move
  885. // the TmpRep into its new home.
  886. SmallSide.Small = false;
  887. new (SmallSide.getLargeRep()) LargeRep(std::move(TmpRep));
  888. }
  889. SmallDenseMap& operator=(const SmallDenseMap& other) {
  890. if (&other != this)
  891. copyFrom(other);
  892. return *this;
  893. }
  894. SmallDenseMap& operator=(SmallDenseMap &&other) {
  895. this->destroyAll();
  896. deallocateBuckets();
  897. init(0);
  898. swap(other);
  899. return *this;
  900. }
  901. void copyFrom(const SmallDenseMap& other) {
  902. this->destroyAll();
  903. deallocateBuckets();
  904. Small = true;
  905. if (other.getNumBuckets() > InlineBuckets) {
  906. Small = false;
  907. new (getLargeRep()) LargeRep(allocateBuckets(other.getNumBuckets()));
  908. }
  909. this->BaseT::copyFrom(other);
  910. }
  911. void init(unsigned InitBuckets) {
  912. Small = true;
  913. if (InitBuckets > InlineBuckets) {
  914. Small = false;
  915. new (getLargeRep()) LargeRep(allocateBuckets(InitBuckets));
  916. }
  917. this->BaseT::initEmpty();
  918. }
  919. void grow(unsigned AtLeast) {
  920. if (AtLeast >= InlineBuckets)
  921. AtLeast = std::max<unsigned>(MIN_BUCKETS, NextPowerOf2(AtLeast));
  922. if (Small) {
  923. if (AtLeast < InlineBuckets)
  924. return; // Nothing to do.
  925. // First move the inline buckets into a temporary storage.
  926. AlignedCharArrayUnion<BucketT[InlineBuckets]> TmpStorage;
  927. BucketT *TmpBegin = reinterpret_cast<BucketT *>(TmpStorage.buffer);
  928. BucketT *TmpEnd = TmpBegin;
  929. // Loop over the buckets, moving non-empty, non-tombstones into the
  930. // temporary storage. Have the loop move the TmpEnd forward as it goes.
  931. const KeyT EmptyKey = this->getEmptyKey();
  932. const KeyT TombstoneKey = this->getTombstoneKey();
  933. for (BucketT *P = getBuckets(), *E = P + InlineBuckets; P != E; ++P) {
  934. if (!KeyInfoT::isEqual(P->getFirst(), EmptyKey) &&
  935. !KeyInfoT::isEqual(P->getFirst(), TombstoneKey)) {
  936. assert(size_t(TmpEnd - TmpBegin) < InlineBuckets &&
  937. "Too many inline buckets!");
  938. ::new (&TmpEnd->getFirst()) KeyT(std::move(P->getFirst()));
  939. ::new (&TmpEnd->getSecond()) ValueT(std::move(P->getSecond()));
  940. ++TmpEnd;
  941. P->getSecond().~ValueT();
  942. }
  943. P->getFirst().~KeyT();
  944. }
  945. // Now make this map use the large rep, and move all the entries back
  946. // into it.
  947. Small = false;
  948. new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
  949. this->moveFromOldBuckets(TmpBegin, TmpEnd);
  950. return;
  951. }
  952. LargeRep OldRep = std::move(*getLargeRep());
  953. getLargeRep()->~LargeRep();
  954. if (AtLeast <= InlineBuckets) {
  955. Small = true;
  956. } else {
  957. new (getLargeRep()) LargeRep(allocateBuckets(AtLeast));
  958. }
  959. this->moveFromOldBuckets(OldRep.Buckets, OldRep.Buckets+OldRep.NumBuckets);
  960. // Free the old table.
  961. operator delete(OldRep.Buckets);
  962. }
  963. void shrink_and_clear() {
  964. unsigned OldSize = this->size();
  965. this->destroyAll();
  966. // Reduce the number of buckets.
  967. unsigned NewNumBuckets = 0;
  968. if (OldSize) {
  969. NewNumBuckets = 1 << (Log2_32_Ceil(OldSize) + 1);
  970. if (NewNumBuckets > InlineBuckets && NewNumBuckets < MIN_BUCKETS)
  971. NewNumBuckets = MIN_BUCKETS;
  972. }
  973. if ((Small && NewNumBuckets <= InlineBuckets) ||
  974. (!Small && NewNumBuckets == getLargeRep()->NumBuckets)) {
  975. this->BaseT::initEmpty();
  976. return;
  977. }
  978. deallocateBuckets();
  979. init(NewNumBuckets);
  980. }
  981. private:
  982. unsigned getNumEntries() const {
  983. return NumEntries;
  984. }
  985. void setNumEntries(unsigned Num) {
  986. // NumEntries is hardcoded to be 31 bits wide.
  987. ASSERT(Num < (1U << 31) && "Cannot support more than 1<<31 entries");
  988. NumEntries = Num;
  989. }
  990. unsigned getNumTombstones() const {
  991. return NumTombstones;
  992. }
  993. void setNumTombstones(unsigned Num) {
  994. NumTombstones = Num;
  995. }
  996. const BucketT *getInlineBuckets() const {
  997. ASSERT(Small);
  998. // Note that this cast does not violate aliasing rules as we assert that
  999. // the memory's dynamic type is the small, inline bucket buffer, and the
  1000. // 'storage.buffer' static type is 'char *'.
  1001. return reinterpret_cast<const BucketT *>(storage.buffer);
  1002. }
  1003. BucketT *getInlineBuckets() {
  1004. return const_cast<BucketT *>(
  1005. const_cast<const SmallDenseMap *>(this)->getInlineBuckets());
  1006. }
  1007. const LargeRep *getLargeRep() const {
  1008. ASSERT(!Small);
  1009. // Note, same rule about aliasing as with getInlineBuckets.
  1010. return reinterpret_cast<const LargeRep *>(storage.buffer);
  1011. }
  1012. LargeRep *getLargeRep() {
  1013. return const_cast<LargeRep *>(
  1014. const_cast<const SmallDenseMap *>(this)->getLargeRep());
  1015. }
  1016. const BucketT *getBuckets() const {
  1017. return Small ? getInlineBuckets() : getLargeRep()->Buckets;
  1018. }
  1019. BucketT *getBuckets() {
  1020. return const_cast<BucketT *>(
  1021. const_cast<const SmallDenseMap *>(this)->getBuckets());
  1022. }
  1023. unsigned getNumBuckets() const {
  1024. return Small ? InlineBuckets : getLargeRep()->NumBuckets;
  1025. }
  1026. void deallocateBuckets() {
  1027. if (Small)
  1028. return;
  1029. operator delete(getLargeRep()->Buckets);
  1030. getLargeRep()->~LargeRep();
  1031. }
  1032. LargeRep allocateBuckets(unsigned Num) {
  1033. ASSERT(Num > InlineBuckets && "Must allocate more buckets than are inline");
  1034. LargeRep Rep = {
  1035. static_cast<BucketT*>(operator new(sizeof(BucketT) * Num)), Num
  1036. };
  1037. return Rep;
  1038. }
  1039. };
  1040. template <typename KeyT, typename ValueT, typename ValueInfoT,
  1041. typename KeyInfoT, typename Bucket, bool IsConst>
  1042. class DenseMapIterator {
  1043. friend class DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, Bucket, true>;
  1044. friend class DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, Bucket, false>;
  1045. using ConstIterator = DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, Bucket, true>;
  1046. public:
  1047. using difference_type = ptrdiff_t;
  1048. using value_type =
  1049. typename std::conditional<IsConst, const Bucket, Bucket>::type;
  1050. using pointer = value_type *;
  1051. using reference = value_type &;
  1052. using iterator_category = std::forward_iterator_tag;
  1053. private:
  1054. pointer Ptr = nullptr;
  1055. pointer End = nullptr;
  1056. public:
  1057. DenseMapIterator() = default;
  1058. DenseMapIterator(pointer Pos, pointer E,
  1059. bool NoAdvance = false)
  1060. : Ptr(Pos), End(E) {
  1061. if (NoAdvance) return;
  1062. AdvancePastEmptyBuckets();
  1063. }
  1064. // Converting ctor from non-const iterators to const iterators. SFINAE'd out
  1065. // for const iterator destinations so it doesn't end up as a user defined copy
  1066. // constructor.
  1067. template <bool IsConstSrc,
  1068. typename = typename std::enable_if<!IsConstSrc && IsConst>::type>
  1069. DenseMapIterator(
  1070. const DenseMapIterator<KeyT, ValueT, ValueInfoT, KeyInfoT, Bucket, IsConstSrc> &I)
  1071. : Ptr(I.Ptr), End(I.End) {}
  1072. reference operator*() const {
  1073. return *Ptr;
  1074. }
  1075. pointer operator->() const {
  1076. return Ptr;
  1077. }
  1078. bool operator==(const ConstIterator &RHS) const {
  1079. return Ptr == RHS.Ptr;
  1080. }
  1081. bool operator!=(const ConstIterator &RHS) const {
  1082. return Ptr != RHS.Ptr;
  1083. }
  1084. inline DenseMapIterator& operator++() { // Preincrement
  1085. ++Ptr;
  1086. AdvancePastEmptyBuckets();
  1087. return *this;
  1088. }
  1089. DenseMapIterator operator++(int) { // Postincrement
  1090. DenseMapIterator tmp = *this; ++*this; return tmp;
  1091. }
  1092. private:
  1093. void AdvancePastEmptyBuckets() {
  1094. ASSERT(Ptr <= End);
  1095. const KeyT Empty = KeyInfoT::getEmptyKey();
  1096. const KeyT Tombstone = KeyInfoT::getTombstoneKey();
  1097. while (Ptr != End && (KeyInfoT::isEqual(Ptr->getFirst(), Empty) ||
  1098. KeyInfoT::isEqual(Ptr->getFirst(), Tombstone)))
  1099. ++Ptr;
  1100. }
  1101. void RetreatPastEmptyBuckets() {
  1102. ASSERT(Ptr >= End);
  1103. const KeyT Empty = KeyInfoT::getEmptyKey();
  1104. const KeyT Tombstone = KeyInfoT::getTombstoneKey();
  1105. while (Ptr != End && (KeyInfoT::isEqual(Ptr[-1].getFirst(), Empty) ||
  1106. KeyInfoT::isEqual(Ptr[-1].getFirst(), Tombstone)))
  1107. --Ptr;
  1108. }
  1109. };
  1110. template <typename KeyT, typename ValueT, typename KeyInfoT>
  1111. inline size_t capacity_in_bytes(const DenseMap<KeyT, ValueT, KeyInfoT> &X) {
  1112. return X.getMemorySize();
  1113. }
  1114. } // end namespace objc
  1115. #endif // LLVM_ADT_DENSEMAP_H