llvm-DenseMap.h 34 KB

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