ImmutableSet.h 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. //===--- ImmutableSet.h - Immutable (functional) set interface --*- 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 ImutAVLTree and ImmutableSet classes.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_ADT_IMMUTABLESET_H
  14. #define LLVM_ADT_IMMUTABLESET_H
  15. #include "llvm/ADT/DenseMap.h"
  16. #include "llvm/ADT/FoldingSet.h"
  17. #include "llvm/Support/Allocator.h"
  18. #include "llvm/Support/DataTypes.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include <cassert>
  21. #include <functional>
  22. #include <vector>
  23. namespace llvm {
  24. //===----------------------------------------------------------------------===//
  25. // Immutable AVL-Tree Definition.
  26. //===----------------------------------------------------------------------===//
  27. template <typename ImutInfo> class ImutAVLFactory;
  28. template <typename ImutInfo> class ImutIntervalAVLFactory;
  29. template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
  30. template <typename ImutInfo> class ImutAVLTreeGenericIterator;
  31. template <typename ImutInfo >
  32. class ImutAVLTree {
  33. public:
  34. typedef typename ImutInfo::key_type_ref key_type_ref;
  35. typedef typename ImutInfo::value_type value_type;
  36. typedef typename ImutInfo::value_type_ref value_type_ref;
  37. typedef ImutAVLFactory<ImutInfo> Factory;
  38. friend class ImutAVLFactory<ImutInfo>;
  39. friend class ImutIntervalAVLFactory<ImutInfo>;
  40. friend class ImutAVLTreeGenericIterator<ImutInfo>;
  41. typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
  42. //===----------------------------------------------------===//
  43. // Public Interface.
  44. //===----------------------------------------------------===//
  45. /// Return a pointer to the left subtree. This value
  46. /// is NULL if there is no left subtree.
  47. ImutAVLTree *getLeft() const { return left; }
  48. /// Return a pointer to the right subtree. This value is
  49. /// NULL if there is no right subtree.
  50. ImutAVLTree *getRight() const { return right; }
  51. /// getHeight - Returns the height of the tree. A tree with no subtrees
  52. /// has a height of 1.
  53. unsigned getHeight() const { return height; }
  54. /// getValue - Returns the data value associated with the tree node.
  55. const value_type& getValue() const { return value; }
  56. /// find - Finds the subtree associated with the specified key value.
  57. /// This method returns NULL if no matching subtree is found.
  58. ImutAVLTree* find(key_type_ref K) {
  59. ImutAVLTree *T = this;
  60. while (T) {
  61. key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
  62. if (ImutInfo::isEqual(K,CurrentKey))
  63. return T;
  64. else if (ImutInfo::isLess(K,CurrentKey))
  65. T = T->getLeft();
  66. else
  67. T = T->getRight();
  68. }
  69. return nullptr;
  70. }
  71. /// getMaxElement - Find the subtree associated with the highest ranged
  72. /// key value.
  73. ImutAVLTree* getMaxElement() {
  74. ImutAVLTree *T = this;
  75. ImutAVLTree *Right = T->getRight();
  76. while (Right) { T = Right; Right = T->getRight(); }
  77. return T;
  78. }
  79. /// size - Returns the number of nodes in the tree, which includes
  80. /// both leaves and non-leaf nodes.
  81. unsigned size() const {
  82. unsigned n = 1;
  83. if (const ImutAVLTree* L = getLeft())
  84. n += L->size();
  85. if (const ImutAVLTree* R = getRight())
  86. n += R->size();
  87. return n;
  88. }
  89. /// begin - Returns an iterator that iterates over the nodes of the tree
  90. /// in an inorder traversal. The returned iterator thus refers to the
  91. /// the tree node with the minimum data element.
  92. iterator begin() const { return iterator(this); }
  93. /// end - Returns an iterator for the tree that denotes the end of an
  94. /// inorder traversal.
  95. iterator end() const { return iterator(); }
  96. bool isElementEqual(value_type_ref V) const {
  97. // Compare the keys.
  98. if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
  99. ImutInfo::KeyOfValue(V)))
  100. return false;
  101. // Also compare the data values.
  102. if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
  103. ImutInfo::DataOfValue(V)))
  104. return false;
  105. return true;
  106. }
  107. bool isElementEqual(const ImutAVLTree* RHS) const {
  108. return isElementEqual(RHS->getValue());
  109. }
  110. /// isEqual - Compares two trees for structural equality and returns true
  111. /// if they are equal. This worst case performance of this operation is
  112. // linear in the sizes of the trees.
  113. bool isEqual(const ImutAVLTree& RHS) const {
  114. if (&RHS == this)
  115. return true;
  116. iterator LItr = begin(), LEnd = end();
  117. iterator RItr = RHS.begin(), REnd = RHS.end();
  118. while (LItr != LEnd && RItr != REnd) {
  119. if (&*LItr == &*RItr) {
  120. LItr.skipSubTree();
  121. RItr.skipSubTree();
  122. continue;
  123. }
  124. if (!LItr->isElementEqual(&*RItr))
  125. return false;
  126. ++LItr;
  127. ++RItr;
  128. }
  129. return LItr == LEnd && RItr == REnd;
  130. }
  131. /// isNotEqual - Compares two trees for structural inequality. Performance
  132. /// is the same is isEqual.
  133. bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
  134. /// contains - Returns true if this tree contains a subtree (node) that
  135. /// has an data element that matches the specified key. Complexity
  136. /// is logarithmic in the size of the tree.
  137. bool contains(key_type_ref K) { return (bool) find(K); }
  138. /// foreach - A member template the accepts invokes operator() on a functor
  139. /// object (specifed by Callback) for every node/subtree in the tree.
  140. /// Nodes are visited using an inorder traversal.
  141. template <typename Callback>
  142. void foreach(Callback& C) {
  143. if (ImutAVLTree* L = getLeft())
  144. L->foreach(C);
  145. C(value);
  146. if (ImutAVLTree* R = getRight())
  147. R->foreach(C);
  148. }
  149. /// validateTree - A utility method that checks that the balancing and
  150. /// ordering invariants of the tree are satisifed. It is a recursive
  151. /// method that returns the height of the tree, which is then consumed
  152. /// by the enclosing validateTree call. External callers should ignore the
  153. /// return value. An invalid tree will cause an assertion to fire in
  154. /// a debug build.
  155. unsigned validateTree() const {
  156. unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
  157. unsigned HR = getRight() ? getRight()->validateTree() : 0;
  158. (void) HL;
  159. (void) HR;
  160. assert(getHeight() == ( HL > HR ? HL : HR ) + 1
  161. && "Height calculation wrong");
  162. assert((HL > HR ? HL-HR : HR-HL) <= 2
  163. && "Balancing invariant violated");
  164. assert((!getLeft() ||
  165. ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
  166. ImutInfo::KeyOfValue(getValue()))) &&
  167. "Value in left child is not less that current value");
  168. assert(!(getRight() ||
  169. ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
  170. ImutInfo::KeyOfValue(getRight()->getValue()))) &&
  171. "Current value is not less that value of right child");
  172. return getHeight();
  173. }
  174. //===----------------------------------------------------===//
  175. // Internal values.
  176. //===----------------------------------------------------===//
  177. private:
  178. Factory *factory;
  179. ImutAVLTree *left;
  180. ImutAVLTree *right;
  181. ImutAVLTree *prev;
  182. ImutAVLTree *next;
  183. unsigned height : 28;
  184. unsigned IsMutable : 1;
  185. unsigned IsDigestCached : 1;
  186. unsigned IsCanonicalized : 1;
  187. value_type value;
  188. uint32_t digest;
  189. uint32_t refCount;
  190. //===----------------------------------------------------===//
  191. // Internal methods (node manipulation; used by Factory).
  192. //===----------------------------------------------------===//
  193. private:
  194. /// ImutAVLTree - Internal constructor that is only called by
  195. /// ImutAVLFactory.
  196. ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
  197. unsigned height)
  198. : factory(f), left(l), right(r), prev(nullptr), next(nullptr),
  199. height(height), IsMutable(true), IsDigestCached(false),
  200. IsCanonicalized(0), value(v), digest(0), refCount(0)
  201. {
  202. if (left) left->retain();
  203. if (right) right->retain();
  204. }
  205. /// isMutable - Returns true if the left and right subtree references
  206. /// (as well as height) can be changed. If this method returns false,
  207. /// the tree is truly immutable. Trees returned from an ImutAVLFactory
  208. /// object should always have this method return true. Further, if this
  209. /// method returns false for an instance of ImutAVLTree, all subtrees
  210. /// will also have this method return false. The converse is not true.
  211. bool isMutable() const { return IsMutable; }
  212. /// hasCachedDigest - Returns true if the digest for this tree is cached.
  213. /// This can only be true if the tree is immutable.
  214. bool hasCachedDigest() const { return IsDigestCached; }
  215. //===----------------------------------------------------===//
  216. // Mutating operations. A tree root can be manipulated as
  217. // long as its reference has not "escaped" from internal
  218. // methods of a factory object (see below). When a tree
  219. // pointer is externally viewable by client code, the
  220. // internal "mutable bit" is cleared to mark the tree
  221. // immutable. Note that a tree that still has its mutable
  222. // bit set may have children (subtrees) that are themselves
  223. // immutable.
  224. //===----------------------------------------------------===//
  225. /// markImmutable - Clears the mutable flag for a tree. After this happens,
  226. /// it is an error to call setLeft(), setRight(), and setHeight().
  227. void markImmutable() {
  228. assert(isMutable() && "Mutable flag already removed.");
  229. IsMutable = false;
  230. }
  231. /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
  232. void markedCachedDigest() {
  233. assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
  234. IsDigestCached = true;
  235. }
  236. /// setHeight - Changes the height of the tree. Used internally by
  237. /// ImutAVLFactory.
  238. void setHeight(unsigned h) {
  239. assert(isMutable() && "Only a mutable tree can have its height changed.");
  240. height = h;
  241. }
  242. static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
  243. value_type_ref V) {
  244. uint32_t digest = 0;
  245. if (L)
  246. digest += L->computeDigest();
  247. // Compute digest of stored data.
  248. FoldingSetNodeID ID;
  249. ImutInfo::Profile(ID,V);
  250. digest += ID.ComputeHash();
  251. if (R)
  252. digest += R->computeDigest();
  253. return digest;
  254. }
  255. uint32_t computeDigest() {
  256. // Check the lowest bit to determine if digest has actually been
  257. // pre-computed.
  258. if (hasCachedDigest())
  259. return digest;
  260. uint32_t X = computeDigest(getLeft(), getRight(), getValue());
  261. digest = X;
  262. markedCachedDigest();
  263. return X;
  264. }
  265. //===----------------------------------------------------===//
  266. // Reference count operations.
  267. //===----------------------------------------------------===//
  268. public:
  269. void retain() { ++refCount; }
  270. void release() {
  271. assert(refCount > 0);
  272. if (--refCount == 0)
  273. destroy();
  274. }
  275. void destroy() {
  276. if (left)
  277. left->release();
  278. if (right)
  279. right->release();
  280. if (IsCanonicalized) {
  281. if (next)
  282. next->prev = prev;
  283. if (prev)
  284. prev->next = next;
  285. else
  286. factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
  287. }
  288. // We need to clear the mutability bit in case we are
  289. // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
  290. IsMutable = false;
  291. factory->freeNodes.push_back(this);
  292. }
  293. };
  294. //===----------------------------------------------------------------------===//
  295. // Immutable AVL-Tree Factory class.
  296. //===----------------------------------------------------------------------===//
  297. template <typename ImutInfo >
  298. class ImutAVLFactory {
  299. friend class ImutAVLTree<ImutInfo>;
  300. typedef ImutAVLTree<ImutInfo> TreeTy;
  301. typedef typename TreeTy::value_type_ref value_type_ref;
  302. typedef typename TreeTy::key_type_ref key_type_ref;
  303. typedef DenseMap<unsigned, TreeTy*> CacheTy;
  304. CacheTy Cache;
  305. uintptr_t Allocator;
  306. std::vector<TreeTy*> createdNodes;
  307. std::vector<TreeTy*> freeNodes;
  308. bool ownsAllocator() const {
  309. return Allocator & 0x1 ? false : true;
  310. }
  311. BumpPtrAllocator& getAllocator() const {
  312. return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
  313. }
  314. //===--------------------------------------------------===//
  315. // Public interface.
  316. //===--------------------------------------------------===//
  317. public:
  318. ImutAVLFactory()
  319. : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
  320. ImutAVLFactory(BumpPtrAllocator& Alloc)
  321. : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
  322. ~ImutAVLFactory() {
  323. if (ownsAllocator()) delete &getAllocator();
  324. }
  325. TreeTy* add(TreeTy* T, value_type_ref V) {
  326. T = add_internal(V,T);
  327. markImmutable(T);
  328. recoverNodes();
  329. return T;
  330. }
  331. TreeTy* remove(TreeTy* T, key_type_ref V) {
  332. T = remove_internal(V,T);
  333. markImmutable(T);
  334. recoverNodes();
  335. return T;
  336. }
  337. TreeTy* getEmptyTree() const { return nullptr; }
  338. protected:
  339. //===--------------------------------------------------===//
  340. // A bunch of quick helper functions used for reasoning
  341. // about the properties of trees and their children.
  342. // These have succinct names so that the balancing code
  343. // is as terse (and readable) as possible.
  344. //===--------------------------------------------------===//
  345. bool isEmpty(TreeTy* T) const { return !T; }
  346. unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
  347. TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
  348. TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
  349. value_type_ref getValue(TreeTy* T) const { return T->value; }
  350. // Make sure the index is not the Tombstone or Entry key of the DenseMap.
  351. static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
  352. unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
  353. unsigned hl = getHeight(L);
  354. unsigned hr = getHeight(R);
  355. return (hl > hr ? hl : hr) + 1;
  356. }
  357. static bool compareTreeWithSection(TreeTy* T,
  358. typename TreeTy::iterator& TI,
  359. typename TreeTy::iterator& TE) {
  360. typename TreeTy::iterator I = T->begin(), E = T->end();
  361. for ( ; I!=E ; ++I, ++TI) {
  362. if (TI == TE || !I->isElementEqual(&*TI))
  363. return false;
  364. }
  365. return true;
  366. }
  367. //===--------------------------------------------------===//
  368. // "createNode" is used to generate new tree roots that link
  369. // to other trees. The functon may also simply move links
  370. // in an existing root if that root is still marked mutable.
  371. // This is necessary because otherwise our balancing code
  372. // would leak memory as it would create nodes that are
  373. // then discarded later before the finished tree is
  374. // returned to the caller.
  375. //===--------------------------------------------------===//
  376. TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
  377. BumpPtrAllocator& A = getAllocator();
  378. TreeTy* T;
  379. if (!freeNodes.empty()) {
  380. T = freeNodes.back();
  381. freeNodes.pop_back();
  382. assert(T != L);
  383. assert(T != R);
  384. } else {
  385. T = (TreeTy*) A.Allocate<TreeTy>();
  386. }
  387. new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
  388. createdNodes.push_back(T);
  389. return T;
  390. }
  391. TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
  392. return createNode(newLeft, getValue(oldTree), newRight);
  393. }
  394. void recoverNodes() {
  395. for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
  396. TreeTy *N = createdNodes[i];
  397. if (N->isMutable() && N->refCount == 0)
  398. N->destroy();
  399. }
  400. createdNodes.clear();
  401. }
  402. /// balanceTree - Used by add_internal and remove_internal to
  403. /// balance a newly created tree.
  404. TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
  405. unsigned hl = getHeight(L);
  406. unsigned hr = getHeight(R);
  407. if (hl > hr + 2) {
  408. assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
  409. TreeTy *LL = getLeft(L);
  410. TreeTy *LR = getRight(L);
  411. if (getHeight(LL) >= getHeight(LR))
  412. return createNode(LL, L, createNode(LR,V,R));
  413. assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
  414. TreeTy *LRL = getLeft(LR);
  415. TreeTy *LRR = getRight(LR);
  416. return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
  417. }
  418. if (hr > hl + 2) {
  419. assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
  420. TreeTy *RL = getLeft(R);
  421. TreeTy *RR = getRight(R);
  422. if (getHeight(RR) >= getHeight(RL))
  423. return createNode(createNode(L,V,RL), R, RR);
  424. assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
  425. TreeTy *RLL = getLeft(RL);
  426. TreeTy *RLR = getRight(RL);
  427. return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
  428. }
  429. return createNode(L,V,R);
  430. }
  431. /// add_internal - Creates a new tree that includes the specified
  432. /// data and the data from the original tree. If the original tree
  433. /// already contained the data item, the original tree is returned.
  434. TreeTy* add_internal(value_type_ref V, TreeTy* T) {
  435. if (isEmpty(T))
  436. return createNode(T, V, T);
  437. assert(!T->isMutable());
  438. key_type_ref K = ImutInfo::KeyOfValue(V);
  439. key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
  440. if (ImutInfo::isEqual(K,KCurrent))
  441. return createNode(getLeft(T), V, getRight(T));
  442. else if (ImutInfo::isLess(K,KCurrent))
  443. return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
  444. else
  445. return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
  446. }
  447. /// remove_internal - Creates a new tree that includes all the data
  448. /// from the original tree except the specified data. If the
  449. /// specified data did not exist in the original tree, the original
  450. /// tree is returned.
  451. TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
  452. if (isEmpty(T))
  453. return T;
  454. assert(!T->isMutable());
  455. key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
  456. if (ImutInfo::isEqual(K,KCurrent)) {
  457. return combineTrees(getLeft(T), getRight(T));
  458. } else if (ImutInfo::isLess(K,KCurrent)) {
  459. return balanceTree(remove_internal(K, getLeft(T)),
  460. getValue(T), getRight(T));
  461. } else {
  462. return balanceTree(getLeft(T), getValue(T),
  463. remove_internal(K, getRight(T)));
  464. }
  465. }
  466. TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
  467. if (isEmpty(L))
  468. return R;
  469. if (isEmpty(R))
  470. return L;
  471. TreeTy* OldNode;
  472. TreeTy* newRight = removeMinBinding(R,OldNode);
  473. return balanceTree(L, getValue(OldNode), newRight);
  474. }
  475. TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
  476. assert(!isEmpty(T));
  477. if (isEmpty(getLeft(T))) {
  478. Noderemoved = T;
  479. return getRight(T);
  480. }
  481. return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
  482. getValue(T), getRight(T));
  483. }
  484. /// markImmutable - Clears the mutable bits of a root and all of its
  485. /// descendants.
  486. void markImmutable(TreeTy* T) {
  487. if (!T || !T->isMutable())
  488. return;
  489. T->markImmutable();
  490. markImmutable(getLeft(T));
  491. markImmutable(getRight(T));
  492. }
  493. public:
  494. TreeTy *getCanonicalTree(TreeTy *TNew) {
  495. if (!TNew)
  496. return nullptr;
  497. if (TNew->IsCanonicalized)
  498. return TNew;
  499. // Search the hashtable for another tree with the same digest, and
  500. // if find a collision compare those trees by their contents.
  501. unsigned digest = TNew->computeDigest();
  502. TreeTy *&entry = Cache[maskCacheIndex(digest)];
  503. do {
  504. if (!entry)
  505. break;
  506. for (TreeTy *T = entry ; T != nullptr; T = T->next) {
  507. // Compare the Contents('T') with Contents('TNew')
  508. typename TreeTy::iterator TI = T->begin(), TE = T->end();
  509. if (!compareTreeWithSection(TNew, TI, TE))
  510. continue;
  511. if (TI != TE)
  512. continue; // T has more contents than TNew.
  513. // Trees did match! Return 'T'.
  514. if (TNew->refCount == 0)
  515. TNew->destroy();
  516. return T;
  517. }
  518. entry->prev = TNew;
  519. TNew->next = entry;
  520. }
  521. while (false);
  522. entry = TNew;
  523. TNew->IsCanonicalized = true;
  524. return TNew;
  525. }
  526. };
  527. //===----------------------------------------------------------------------===//
  528. // Immutable AVL-Tree Iterators.
  529. //===----------------------------------------------------------------------===//
  530. template <typename ImutInfo>
  531. class ImutAVLTreeGenericIterator
  532. : public std::iterator<std::bidirectional_iterator_tag,
  533. ImutAVLTree<ImutInfo>> {
  534. SmallVector<uintptr_t,20> stack;
  535. public:
  536. enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
  537. Flags=0x3 };
  538. typedef ImutAVLTree<ImutInfo> TreeTy;
  539. ImutAVLTreeGenericIterator() {}
  540. ImutAVLTreeGenericIterator(const TreeTy *Root) {
  541. if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
  542. }
  543. TreeTy &operator*() const {
  544. assert(!stack.empty());
  545. return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
  546. }
  547. TreeTy *operator->() const { return &*this; }
  548. uintptr_t getVisitState() const {
  549. assert(!stack.empty());
  550. return stack.back() & Flags;
  551. }
  552. bool atEnd() const { return stack.empty(); }
  553. bool atBeginning() const {
  554. return stack.size() == 1 && getVisitState() == VisitedNone;
  555. }
  556. void skipToParent() {
  557. assert(!stack.empty());
  558. stack.pop_back();
  559. if (stack.empty())
  560. return;
  561. switch (getVisitState()) {
  562. case VisitedNone:
  563. stack.back() |= VisitedLeft;
  564. break;
  565. case VisitedLeft:
  566. stack.back() |= VisitedRight;
  567. break;
  568. default:
  569. llvm_unreachable("Unreachable.");
  570. }
  571. }
  572. bool operator==(const ImutAVLTreeGenericIterator &x) const {
  573. return stack == x.stack;
  574. }
  575. bool operator!=(const ImutAVLTreeGenericIterator &x) const {
  576. return !(*this == x);
  577. }
  578. ImutAVLTreeGenericIterator &operator++() {
  579. assert(!stack.empty());
  580. TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
  581. assert(Current);
  582. switch (getVisitState()) {
  583. case VisitedNone:
  584. if (TreeTy* L = Current->getLeft())
  585. stack.push_back(reinterpret_cast<uintptr_t>(L));
  586. else
  587. stack.back() |= VisitedLeft;
  588. break;
  589. case VisitedLeft:
  590. if (TreeTy* R = Current->getRight())
  591. stack.push_back(reinterpret_cast<uintptr_t>(R));
  592. else
  593. stack.back() |= VisitedRight;
  594. break;
  595. case VisitedRight:
  596. skipToParent();
  597. break;
  598. default:
  599. llvm_unreachable("Unreachable.");
  600. }
  601. return *this;
  602. }
  603. ImutAVLTreeGenericIterator &operator--() {
  604. assert(!stack.empty());
  605. TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
  606. assert(Current);
  607. switch (getVisitState()) {
  608. case VisitedNone:
  609. stack.pop_back();
  610. break;
  611. case VisitedLeft:
  612. stack.back() &= ~Flags; // Set state to "VisitedNone."
  613. if (TreeTy* L = Current->getLeft())
  614. stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
  615. break;
  616. case VisitedRight:
  617. stack.back() &= ~Flags;
  618. stack.back() |= VisitedLeft;
  619. if (TreeTy* R = Current->getRight())
  620. stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
  621. break;
  622. default:
  623. llvm_unreachable("Unreachable.");
  624. }
  625. return *this;
  626. }
  627. };
  628. template <typename ImutInfo>
  629. class ImutAVLTreeInOrderIterator
  630. : public std::iterator<std::bidirectional_iterator_tag,
  631. ImutAVLTree<ImutInfo>> {
  632. typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
  633. InternalIteratorTy InternalItr;
  634. public:
  635. typedef ImutAVLTree<ImutInfo> TreeTy;
  636. ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
  637. if (Root)
  638. ++*this; // Advance to first element.
  639. }
  640. ImutAVLTreeInOrderIterator() : InternalItr() {}
  641. bool operator==(const ImutAVLTreeInOrderIterator &x) const {
  642. return InternalItr == x.InternalItr;
  643. }
  644. bool operator!=(const ImutAVLTreeInOrderIterator &x) const {
  645. return !(*this == x);
  646. }
  647. TreeTy &operator*() const { return *InternalItr; }
  648. TreeTy *operator->() const { return &*InternalItr; }
  649. ImutAVLTreeInOrderIterator &operator++() {
  650. do ++InternalItr;
  651. while (!InternalItr.atEnd() &&
  652. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
  653. return *this;
  654. }
  655. ImutAVLTreeInOrderIterator &operator--() {
  656. do --InternalItr;
  657. while (!InternalItr.atBeginning() &&
  658. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
  659. return *this;
  660. }
  661. void skipSubTree() {
  662. InternalItr.skipToParent();
  663. while (!InternalItr.atEnd() &&
  664. InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
  665. ++InternalItr;
  666. }
  667. };
  668. /// Generic iterator that wraps a T::TreeTy::iterator and exposes
  669. /// iterator::getValue() on dereference.
  670. template <typename T>
  671. struct ImutAVLValueIterator
  672. : iterator_adaptor_base<
  673. ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
  674. typename std::iterator_traits<
  675. typename T::TreeTy::iterator>::iterator_category,
  676. const typename T::value_type> {
  677. ImutAVLValueIterator() = default;
  678. explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
  679. : ImutAVLValueIterator::iterator_adaptor_base(Tree) {}
  680. typename ImutAVLValueIterator::reference operator*() const {
  681. return this->I->getValue();
  682. }
  683. };
  684. //===----------------------------------------------------------------------===//
  685. // Trait classes for Profile information.
  686. //===----------------------------------------------------------------------===//
  687. /// Generic profile template. The default behavior is to invoke the
  688. /// profile method of an object. Specializations for primitive integers
  689. /// and generic handling of pointers is done below.
  690. template <typename T>
  691. struct ImutProfileInfo {
  692. typedef const T value_type;
  693. typedef const T& value_type_ref;
  694. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  695. FoldingSetTrait<T>::Profile(X,ID);
  696. }
  697. };
  698. /// Profile traits for integers.
  699. template <typename T>
  700. struct ImutProfileInteger {
  701. typedef const T value_type;
  702. typedef const T& value_type_ref;
  703. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  704. ID.AddInteger(X);
  705. }
  706. };
  707. #define PROFILE_INTEGER_INFO(X)\
  708. template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
  709. PROFILE_INTEGER_INFO(char)
  710. PROFILE_INTEGER_INFO(unsigned char)
  711. PROFILE_INTEGER_INFO(short)
  712. PROFILE_INTEGER_INFO(unsigned short)
  713. PROFILE_INTEGER_INFO(unsigned)
  714. PROFILE_INTEGER_INFO(signed)
  715. PROFILE_INTEGER_INFO(long)
  716. PROFILE_INTEGER_INFO(unsigned long)
  717. PROFILE_INTEGER_INFO(long long)
  718. PROFILE_INTEGER_INFO(unsigned long long)
  719. #undef PROFILE_INTEGER_INFO
  720. /// Profile traits for booleans.
  721. template <>
  722. struct ImutProfileInfo<bool> {
  723. typedef const bool value_type;
  724. typedef const bool& value_type_ref;
  725. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  726. ID.AddBoolean(X);
  727. }
  728. };
  729. /// Generic profile trait for pointer types. We treat pointers as
  730. /// references to unique objects.
  731. template <typename T>
  732. struct ImutProfileInfo<T*> {
  733. typedef const T* value_type;
  734. typedef value_type value_type_ref;
  735. static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
  736. ID.AddPointer(X);
  737. }
  738. };
  739. //===----------------------------------------------------------------------===//
  740. // Trait classes that contain element comparison operators and type
  741. // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
  742. // inherit from the profile traits (ImutProfileInfo) to include operations
  743. // for element profiling.
  744. //===----------------------------------------------------------------------===//
  745. /// ImutContainerInfo - Generic definition of comparison operations for
  746. /// elements of immutable containers that defaults to using
  747. /// std::equal_to<> and std::less<> to perform comparison of elements.
  748. template <typename T>
  749. struct ImutContainerInfo : public ImutProfileInfo<T> {
  750. typedef typename ImutProfileInfo<T>::value_type value_type;
  751. typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
  752. typedef value_type key_type;
  753. typedef value_type_ref key_type_ref;
  754. typedef bool data_type;
  755. typedef bool data_type_ref;
  756. static key_type_ref KeyOfValue(value_type_ref D) { return D; }
  757. static data_type_ref DataOfValue(value_type_ref) { return true; }
  758. static bool isEqual(key_type_ref LHS, key_type_ref RHS) {
  759. return std::equal_to<key_type>()(LHS,RHS);
  760. }
  761. static bool isLess(key_type_ref LHS, key_type_ref RHS) {
  762. return std::less<key_type>()(LHS,RHS);
  763. }
  764. static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
  765. };
  766. /// ImutContainerInfo - Specialization for pointer values to treat pointers
  767. /// as references to unique objects. Pointers are thus compared by
  768. /// their addresses.
  769. template <typename T>
  770. struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
  771. typedef typename ImutProfileInfo<T*>::value_type value_type;
  772. typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
  773. typedef value_type key_type;
  774. typedef value_type_ref key_type_ref;
  775. typedef bool data_type;
  776. typedef bool data_type_ref;
  777. static key_type_ref KeyOfValue(value_type_ref D) { return D; }
  778. static data_type_ref DataOfValue(value_type_ref) { return true; }
  779. static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
  780. static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
  781. static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
  782. };
  783. //===----------------------------------------------------------------------===//
  784. // Immutable Set
  785. // //
  786. ///////////////////////////////////////////////////////////////////////////////
  787. template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
  788. class ImmutableSet {
  789. public:
  790. typedef typename ValInfo::value_type value_type;
  791. typedef typename ValInfo::value_type_ref value_type_ref;
  792. typedef ImutAVLTree<ValInfo> TreeTy;
  793. private:
  794. TreeTy *Root;
  795. public:
  796. /// Constructs a set from a pointer to a tree root. In general one
  797. /// should use a Factory object to create sets instead of directly
  798. /// invoking the constructor, but there are cases where make this
  799. /// constructor public is useful.
  800. explicit ImmutableSet(TreeTy* R) : Root(R) {
  801. if (Root) { Root->retain(); }
  802. }
  803. ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
  804. if (Root) { Root->retain(); }
  805. }
  806. ImmutableSet &operator=(const ImmutableSet &X) {
  807. if (Root != X.Root) {
  808. if (X.Root) { X.Root->retain(); }
  809. if (Root) { Root->release(); }
  810. Root = X.Root;
  811. }
  812. return *this;
  813. }
  814. ~ImmutableSet() {
  815. if (Root) { Root->release(); }
  816. }
  817. class Factory {
  818. typename TreeTy::Factory F;
  819. const bool Canonicalize;
  820. public:
  821. Factory(bool canonicalize = true)
  822. : Canonicalize(canonicalize) {}
  823. Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
  824. : F(Alloc), Canonicalize(canonicalize) {}
  825. /// getEmptySet - Returns an immutable set that contains no elements.
  826. ImmutableSet getEmptySet() {
  827. return ImmutableSet(F.getEmptyTree());
  828. }
  829. /// add - Creates a new immutable set that contains all of the values
  830. /// of the original set with the addition of the specified value. If
  831. /// the original set already included the value, then the original set is
  832. /// returned and no memory is allocated. The time and space complexity
  833. /// of this operation is logarithmic in the size of the original set.
  834. /// The memory allocated to represent the set is released when the
  835. /// factory object that created the set is destroyed.
  836. ImmutableSet add(ImmutableSet Old, value_type_ref V) {
  837. TreeTy *NewT = F.add(Old.Root, V);
  838. return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
  839. }
  840. /// remove - Creates a new immutable set that contains all of the values
  841. /// of the original set with the exception of the specified value. If
  842. /// the original set did not contain the value, the original set is
  843. /// returned and no memory is allocated. The time and space complexity
  844. /// of this operation is logarithmic in the size of the original set.
  845. /// The memory allocated to represent the set is released when the
  846. /// factory object that created the set is destroyed.
  847. ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
  848. TreeTy *NewT = F.remove(Old.Root, V);
  849. return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
  850. }
  851. BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
  852. typename TreeTy::Factory *getTreeFactory() const {
  853. return const_cast<typename TreeTy::Factory *>(&F);
  854. }
  855. private:
  856. Factory(const Factory& RHS) = delete;
  857. void operator=(const Factory& RHS) = delete;
  858. };
  859. friend class Factory;
  860. /// Returns true if the set contains the specified value.
  861. bool contains(value_type_ref V) const {
  862. return Root ? Root->contains(V) : false;
  863. }
  864. bool operator==(const ImmutableSet &RHS) const {
  865. return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
  866. }
  867. bool operator!=(const ImmutableSet &RHS) const {
  868. return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
  869. }
  870. TreeTy *getRoot() {
  871. if (Root) { Root->retain(); }
  872. return Root;
  873. }
  874. TreeTy *getRootWithoutRetain() const {
  875. return Root;
  876. }
  877. /// isEmpty - Return true if the set contains no elements.
  878. bool isEmpty() const { return !Root; }
  879. /// isSingleton - Return true if the set contains exactly one element.
  880. /// This method runs in constant time.
  881. bool isSingleton() const { return getHeight() == 1; }
  882. template <typename Callback>
  883. void foreach(Callback& C) { if (Root) Root->foreach(C); }
  884. template <typename Callback>
  885. void foreach() { if (Root) { Callback C; Root->foreach(C); } }
  886. //===--------------------------------------------------===//
  887. // Iterators.
  888. //===--------------------------------------------------===//
  889. typedef ImutAVLValueIterator<ImmutableSet> iterator;
  890. iterator begin() const { return iterator(Root); }
  891. iterator end() const { return iterator(); }
  892. //===--------------------------------------------------===//
  893. // Utility methods.
  894. //===--------------------------------------------------===//
  895. unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
  896. static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
  897. ID.AddPointer(S.Root);
  898. }
  899. void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
  900. //===--------------------------------------------------===//
  901. // For testing.
  902. //===--------------------------------------------------===//
  903. void validateTree() const { if (Root) Root->validateTree(); }
  904. };
  905. // NOTE: This may some day replace the current ImmutableSet.
  906. template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
  907. class ImmutableSetRef {
  908. public:
  909. typedef typename ValInfo::value_type value_type;
  910. typedef typename ValInfo::value_type_ref value_type_ref;
  911. typedef ImutAVLTree<ValInfo> TreeTy;
  912. typedef typename TreeTy::Factory FactoryTy;
  913. private:
  914. TreeTy *Root;
  915. FactoryTy *Factory;
  916. public:
  917. /// Constructs a set from a pointer to a tree root. In general one
  918. /// should use a Factory object to create sets instead of directly
  919. /// invoking the constructor, but there are cases where make this
  920. /// constructor public is useful.
  921. explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
  922. : Root(R),
  923. Factory(F) {
  924. if (Root) { Root->retain(); }
  925. }
  926. ImmutableSetRef(const ImmutableSetRef &X)
  927. : Root(X.Root),
  928. Factory(X.Factory) {
  929. if (Root) { Root->retain(); }
  930. }
  931. ImmutableSetRef &operator=(const ImmutableSetRef &X) {
  932. if (Root != X.Root) {
  933. if (X.Root) { X.Root->retain(); }
  934. if (Root) { Root->release(); }
  935. Root = X.Root;
  936. Factory = X.Factory;
  937. }
  938. return *this;
  939. }
  940. ~ImmutableSetRef() {
  941. if (Root) { Root->release(); }
  942. }
  943. static ImmutableSetRef getEmptySet(FactoryTy *F) {
  944. return ImmutableSetRef(0, F);
  945. }
  946. ImmutableSetRef add(value_type_ref V) {
  947. return ImmutableSetRef(Factory->add(Root, V), Factory);
  948. }
  949. ImmutableSetRef remove(value_type_ref V) {
  950. return ImmutableSetRef(Factory->remove(Root, V), Factory);
  951. }
  952. /// Returns true if the set contains the specified value.
  953. bool contains(value_type_ref V) const {
  954. return Root ? Root->contains(V) : false;
  955. }
  956. ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
  957. return ImmutableSet<ValT>(canonicalize ?
  958. Factory->getCanonicalTree(Root) : Root);
  959. }
  960. TreeTy *getRootWithoutRetain() const {
  961. return Root;
  962. }
  963. bool operator==(const ImmutableSetRef &RHS) const {
  964. return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
  965. }
  966. bool operator!=(const ImmutableSetRef &RHS) const {
  967. return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
  968. }
  969. /// isEmpty - Return true if the set contains no elements.
  970. bool isEmpty() const { return !Root; }
  971. /// isSingleton - Return true if the set contains exactly one element.
  972. /// This method runs in constant time.
  973. bool isSingleton() const { return getHeight() == 1; }
  974. //===--------------------------------------------------===//
  975. // Iterators.
  976. //===--------------------------------------------------===//
  977. typedef ImutAVLValueIterator<ImmutableSetRef> iterator;
  978. iterator begin() const { return iterator(Root); }
  979. iterator end() const { return iterator(); }
  980. //===--------------------------------------------------===//
  981. // Utility methods.
  982. //===--------------------------------------------------===//
  983. unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
  984. static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
  985. ID.AddPointer(S.Root);
  986. }
  987. void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
  988. //===--------------------------------------------------===//
  989. // For testing.
  990. //===--------------------------------------------------===//
  991. void validateTree() const { if (Root) Root->validateTree(); }
  992. };
  993. } // end namespace llvm
  994. #endif