LLVM 22.0.0git
ImmutableSet.h
Go to the documentation of this file.
1//===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the ImutAVLTree and ImmutableSet classes.
11///
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_IMMUTABLESET_H
15#define LLVM_ADT_IMMUTABLESET_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
21#include "llvm/ADT/iterator.h"
24#include "llvm/Support/Debug.h"
27#include <cassert>
28#include <cstdint>
29#include <functional>
30#include <iterator>
31#include <new>
32#include <vector>
33
34namespace llvm {
35
36//===----------------------------------------------------------------------===//
37// Immutable AVL-Tree Definition.
38//===----------------------------------------------------------------------===//
39
40template <typename ImutInfo> class ImutAVLFactory;
41template <typename ImutInfo> class ImutIntervalAVLFactory;
42template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
43template <typename ImutInfo> class ImutAVLTreeGenericIterator;
44
45template <typename ImutInfo >
46class ImutAVLTree {
47public:
48 using key_type_ref = typename ImutInfo::key_type_ref;
49 using value_type = typename ImutInfo::value_type;
50 using value_type_ref = typename ImutInfo::value_type_ref;
53
54 friend class ImutAVLFactory<ImutInfo>;
55 friend class ImutIntervalAVLFactory<ImutInfo>;
56 friend class ImutAVLTreeGenericIterator<ImutInfo>;
57
58 //===----------------------------------------------------===//
59 // Public Interface.
60 //===----------------------------------------------------===//
61
62 /// Return a pointer to the left subtree. This value
63 /// is NULL if there is no left subtree.
64 ImutAVLTree *getLeft() const { return left; }
65
66 /// Return a pointer to the right subtree. This value is
67 /// NULL if there is no right subtree.
68 ImutAVLTree *getRight() const { return right; }
69
70 /// getHeight - Returns the height of the tree. A tree with no subtrees
71 /// has a height of 1.
72 unsigned getHeight() const { return height; }
73
74 /// getValue - Returns the data value associated with the tree node.
75 const value_type& getValue() const { return value; }
76
77 /// find - Finds the subtree associated with the specified key value.
78 /// This method returns NULL if no matching subtree is found.
79 ImutAVLTree* find(key_type_ref K) {
80 ImutAVLTree *T = this;
81 while (T) {
82 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
83 if (ImutInfo::isEqual(K,CurrentKey))
84 return T;
85 else if (ImutInfo::isLess(K,CurrentKey))
86 T = T->getLeft();
87 else
88 T = T->getRight();
89 }
90 return nullptr;
91 }
92
93 /// getMaxElement - Find the subtree associated with the highest ranged
94 /// key value.
95 ImutAVLTree* getMaxElement() {
96 ImutAVLTree *T = this;
97 ImutAVLTree *Right = T->getRight();
98 while (Right) { T = Right; Right = T->getRight(); }
99 return T;
100 }
101
102 /// size - Returns the number of nodes in the tree, which includes
103 /// both leaves and non-leaf nodes.
104 unsigned size() const {
105 unsigned n = 1;
106 if (const ImutAVLTree* L = getLeft())
107 n += L->size();
108 if (const ImutAVLTree* R = getRight())
109 n += R->size();
110 return n;
111 }
112
113 /// begin - Returns an iterator that iterates over the nodes of the tree
114 /// in an inorder traversal. The returned iterator thus refers to the
115 /// the tree node with the minimum data element.
116 iterator begin() const { return iterator(this); }
117
118 /// end - Returns an iterator for the tree that denotes the end of an
119 /// inorder traversal.
120 iterator end() const { return iterator(); }
121
123 // Compare the keys.
124 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
125 ImutInfo::KeyOfValue(V)))
126 return false;
127
128 // Also compare the data values.
129 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
130 ImutInfo::DataOfValue(V)))
131 return false;
132
133 return true;
134 }
135
136 bool isElementEqual(const ImutAVLTree* RHS) const {
137 return isElementEqual(RHS->getValue());
138 }
139
140 /// isEqual - Compares two trees for structural equality and returns true
141 /// if they are equal. This worst case performance of this operation is
142 // linear in the sizes of the trees.
143 bool isEqual(const ImutAVLTree& RHS) const {
144 if (&RHS == this)
145 return true;
146
147 iterator LItr = begin(), LEnd = end();
148 iterator RItr = RHS.begin(), REnd = RHS.end();
149
150 while (LItr != LEnd && RItr != REnd) {
151 if (&*LItr == &*RItr) {
152 LItr.skipSubTree();
153 RItr.skipSubTree();
154 continue;
155 }
156
157 if (!LItr->isElementEqual(&*RItr))
158 return false;
159
160 ++LItr;
161 ++RItr;
162 }
163
164 return LItr == LEnd && RItr == REnd;
165 }
166
167 /// isNotEqual - Compares two trees for structural inequality. Performance
168 /// is the same is isEqual.
169 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
170
171 /// contains - Returns true if this tree contains a subtree (node) that
172 /// has an data element that matches the specified key. Complexity
173 /// is logarithmic in the size of the tree.
174 bool contains(key_type_ref K) { return (bool) find(K); }
175
176 /// validateTree - A utility method that checks that the balancing and
177 /// ordering invariants of the tree are satisfied. It is a recursive
178 /// method that returns the height of the tree, which is then consumed
179 /// by the enclosing validateTree call. External callers should ignore the
180 /// return value. An invalid tree will cause an assertion to fire in
181 /// a debug build.
182 unsigned validateTree() const {
183 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
184 unsigned HR = getRight() ? getRight()->validateTree() : 0;
185 (void) HL;
186 (void) HR;
187
188 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
189 && "Height calculation wrong");
190
191 assert((HL > HR ? HL-HR : HR-HL) <= 2
192 && "Balancing invariant violated");
193
194 assert((!getLeft() ||
195 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
196 ImutInfo::KeyOfValue(getValue()))) &&
197 "Value in left child is not less that current value");
198
199 assert((!getRight() ||
200 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
201 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
202 "Current value is not less that value of right child");
203
204 return getHeight();
205 }
206
207 //===----------------------------------------------------===//
208 // Internal values.
209 //===----------------------------------------------------===//
210
211private:
212 Factory *factory;
213 ImutAVLTree *left;
214 ImutAVLTree *right;
215 ImutAVLTree *prev = nullptr;
216 ImutAVLTree *next = nullptr;
217
218 unsigned height : 28;
220 unsigned IsMutable : 1;
222 unsigned IsDigestCached : 1;
224 unsigned IsCanonicalized : 1;
225
226 value_type value;
227 uint32_t digest = 0;
228 uint32_t refCount = 0;
229
230 //===----------------------------------------------------===//
231 // Internal methods (node manipulation; used by Factory).
232 //===----------------------------------------------------===//
233
234private:
235 /// ImutAVLTree - Internal constructor that is only called by
236 /// ImutAVLFactory.
238 unsigned height)
239 : factory(f), left(l), right(r), height(height), IsMutable(true),
240 IsDigestCached(false), IsCanonicalized(false), value(v)
241 {
242 if (left) left->retain();
243 if (right) right->retain();
244 }
245
246 /// isMutable - Returns true if the left and right subtree references
247 /// (as well as height) can be changed. If this method returns false,
248 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
249 /// object should always have this method return true. Further, if this
250 /// method returns false for an instance of ImutAVLTree, all subtrees
251 /// will also have this method return false. The converse is not true.
252 bool isMutable() const { return IsMutable; }
253
254 /// hasCachedDigest - Returns true if the digest for this tree is cached.
255 /// This can only be true if the tree is immutable.
256 bool hasCachedDigest() const { return IsDigestCached; }
257
258 //===----------------------------------------------------===//
259 // Mutating operations. A tree root can be manipulated as
260 // long as its reference has not "escaped" from internal
261 // methods of a factory object (see below). When a tree
262 // pointer is externally viewable by client code, the
263 // internal "mutable bit" is cleared to mark the tree
264 // immutable. Note that a tree that still has its mutable
265 // bit set may have children (subtrees) that are themselves
266 // immutable.
267 //===----------------------------------------------------===//
268
269 /// markImmutable - Clears the mutable flag for a tree. After this happens,
270 /// it is an error to call setLeft(), setRight(), and setHeight().
271 void markImmutable() {
272 assert(isMutable() && "Mutable flag already removed.");
273 IsMutable = false;
274 }
275
276 /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
277 void markedCachedDigest() {
278 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
279 IsDigestCached = true;
280 }
281
282 /// setHeight - Changes the height of the tree. Used internally by
283 /// ImutAVLFactory.
284 void setHeight(unsigned h) {
285 assert(isMutable() && "Only a mutable tree can have its height changed.");
286 height = h;
287 }
288
289 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
290 value_type_ref V) {
291 uint32_t digest = 0;
292
293 if (L)
294 digest += L->computeDigest();
295
296 // Compute digest of stored data.
297 FoldingSetNodeID ID;
298 ImutInfo::Profile(ID,V);
299 digest += ID.ComputeHash();
300
301 if (R)
302 digest += R->computeDigest();
303
304 return digest;
305 }
306
307 uint32_t computeDigest() {
308 // Check the lowest bit to determine if digest has actually been
309 // pre-computed.
310 if (hasCachedDigest())
311 return digest;
312
313 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
314 digest = X;
315 markedCachedDigest();
316 return X;
317 }
318
319 //===----------------------------------------------------===//
320 // Reference count operations.
321 //===----------------------------------------------------===//
322
323public:
324 void retain() { ++refCount; }
325
326 void release() {
327 assert(refCount > 0);
328 if (--refCount == 0)
329 destroy();
330 }
331
332 void destroy() {
333 if (left)
334 left->release();
335 if (right)
336 right->release();
337 if (IsCanonicalized) {
338 if (next)
339 next->prev = prev;
340
341 if (prev)
342 prev->next = next;
343 else
344 factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
345 }
346
347 // We need to clear the mutability bit in case we are
348 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
349 IsMutable = false;
350 factory->freeNodes.push_back(this);
351 }
352};
353
354template <typename ImutInfo>
356 static void retain(ImutAVLTree<ImutInfo> *Tree) { Tree->retain(); }
357 static void release(ImutAVLTree<ImutInfo> *Tree) { Tree->release(); }
358};
359
360//===----------------------------------------------------------------------===//
361// Immutable AVL-Tree Factory class.
362//===----------------------------------------------------------------------===//
363
364template <typename ImutInfo >
366 friend class ImutAVLTree<ImutInfo>;
367
368 using TreeTy = ImutAVLTree<ImutInfo>;
369 using value_type_ref = typename TreeTy::value_type_ref;
370 using key_type_ref = typename TreeTy::key_type_ref;
371 using CacheTy = DenseMap<unsigned, TreeTy*>;
372
373 CacheTy Cache;
374 uintptr_t Allocator;
375 std::vector<TreeTy*> createdNodes;
376 std::vector<TreeTy*> freeNodes;
377
378 bool ownsAllocator() const {
379 return (Allocator & 0x1) == 0;
380 }
381
382 BumpPtrAllocator& getAllocator() const {
383 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
384 }
385
386 //===--------------------------------------------------===//
387 // Public interface.
388 //===--------------------------------------------------===//
389
390public:
392 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
393
395 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
396
398 if (ownsAllocator()) delete &getAllocator();
399 }
400
401 TreeTy* add(TreeTy* T, value_type_ref V) {
402 T = add_internal(V,T);
404 recoverNodes();
405 return T;
406 }
407
408 TreeTy* remove(TreeTy* T, key_type_ref V) {
409 T = remove_internal(V,T);
411 recoverNodes();
412 return T;
413 }
414
415 TreeTy* getEmptyTree() const { return nullptr; }
416
417protected:
418 //===--------------------------------------------------===//
419 // A bunch of quick helper functions used for reasoning
420 // about the properties of trees and their children.
421 // These have succinct names so that the balancing code
422 // is as terse (and readable) as possible.
423 //===--------------------------------------------------===//
424
425 bool isEmpty(TreeTy* T) const { return !T; }
426 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
427 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
428 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
429 value_type_ref getValue(TreeTy* T) const { return T->value; }
430
431 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
432 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
433
434 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
435 unsigned hl = getHeight(L);
436 unsigned hr = getHeight(R);
437 return (hl > hr ? hl : hr) + 1;
438 }
439
440 static bool compareTreeWithSection(TreeTy* T,
441 typename TreeTy::iterator& TI,
442 typename TreeTy::iterator& TE) {
443 typename TreeTy::iterator I = T->begin(), E = T->end();
444 for ( ; I!=E ; ++I, ++TI) {
445 if (TI == TE || !I->isElementEqual(&*TI))
446 return false;
447 }
448 return true;
449 }
450
451 //===--------------------------------------------------===//
452 // "createNode" is used to generate new tree roots that link
453 // to other trees. The function may also simply move links
454 // in an existing root if that root is still marked mutable.
455 // This is necessary because otherwise our balancing code
456 // would leak memory as it would create nodes that are
457 // then discarded later before the finished tree is
458 // returned to the caller.
459 //===--------------------------------------------------===//
460
461 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
462 BumpPtrAllocator& A = getAllocator();
463 TreeTy* T;
464 if (!freeNodes.empty()) {
465 T = freeNodes.back();
466 freeNodes.pop_back();
467 assert(T != L);
468 assert(T != R);
469 } else {
470 T = (TreeTy*) A.Allocate<TreeTy>();
471 }
472 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
473 createdNodes.push_back(T);
474 return T;
475 }
476
477 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
478 return createNode(newLeft, getValue(oldTree), newRight);
479 }
480
482 for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
483 TreeTy *N = createdNodes[i];
484 if (N->isMutable() && N->refCount == 0)
485 N->destroy();
486 }
487 createdNodes.clear();
488 }
489
490 /// balanceTree - Used by add_internal and remove_internal to
491 /// balance a newly created tree.
492 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
493 unsigned hl = getHeight(L);
494 unsigned hr = getHeight(R);
495
496 if (hl > hr + 2) {
497 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
498
499 TreeTy *LL = getLeft(L);
500 TreeTy *LR = getRight(L);
501
502 if (getHeight(LL) >= getHeight(LR))
503 return createNode(LL, L, createNode(LR,V,R));
504
505 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
506
507 TreeTy *LRL = getLeft(LR);
508 TreeTy *LRR = getRight(LR);
509
510 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
511 }
512
513 if (hr > hl + 2) {
514 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
515
516 TreeTy *RL = getLeft(R);
517 TreeTy *RR = getRight(R);
518
519 if (getHeight(RR) >= getHeight(RL))
520 return createNode(createNode(L,V,RL), R, RR);
521
522 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
523
524 TreeTy *RLL = getLeft(RL);
525 TreeTy *RLR = getRight(RL);
526
527 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
528 }
529
530 return createNode(L,V,R);
531 }
532
533 /// add_internal - Creates a new tree that includes the specified
534 /// data and the data from the original tree. If the original tree
535 /// already contained the data item, the original tree is returned.
536 TreeTy *add_internal(value_type_ref V, TreeTy *T) {
537 if (isEmpty(T))
538 return createNode(T, V, T);
539 assert(!T->isMutable());
540
541 key_type_ref K = ImutInfo::KeyOfValue(V);
542 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
543
544 if (ImutInfo::isEqual(K, KCurrent)) {
545 // If both key and value are same, return the original tree.
546 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(V),
547 ImutInfo::DataOfValue(getValue(T))))
548 return T;
549 // Otherwise create a new node with the new value.
550 return createNode(getLeft(T), V, getRight(T));
551 }
552
553 TreeTy *NewL = getLeft(T);
554 TreeTy *NewR = getRight(T);
555 if (ImutInfo::isLess(K, KCurrent))
556 NewL = add_internal(V, NewL);
557 else
558 NewR = add_internal(V, NewR);
559
560 // If no changes were made, return the original tree. Otherwise, balance the
561 // tree and return the new root.
562 return NewL == getLeft(T) && NewR == getRight(T)
563 ? T
564 : balanceTree(NewL, getValue(T), NewR);
565 }
566
567 /// remove_internal - Creates a new tree that includes all the data
568 /// from the original tree except the specified data. If the
569 /// specified data did not exist in the original tree, the original
570 /// tree is returned.
571 TreeTy *remove_internal(key_type_ref K, TreeTy *T) {
572 if (isEmpty(T))
573 return T;
574
575 assert(!T->isMutable());
576
577 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
578
579 if (ImutInfo::isEqual(K, KCurrent))
580 return combineTrees(getLeft(T), getRight(T));
581
582 TreeTy *NewL = getLeft(T);
583 TreeTy *NewR = getRight(T);
584 if (ImutInfo::isLess(K, KCurrent))
585 NewL = remove_internal(K, NewL);
586 else
587 NewR = remove_internal(K, NewR);
588
589 // If no changes were made, return the original tree. Otherwise, balance the
590 // tree and return the new root.
591 return NewL == getLeft(T) && NewR == getRight(T)
592 ? T
593 : balanceTree(NewL, getValue(T), NewR);
594 }
595
596 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
597 if (isEmpty(L))
598 return R;
599 if (isEmpty(R))
600 return L;
601 TreeTy* OldNode;
602 TreeTy* newRight = removeMinBinding(R,OldNode);
603 return balanceTree(L, getValue(OldNode), newRight);
604 }
605
606 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
607 assert(!isEmpty(T));
608 if (isEmpty(getLeft(T))) {
609 Noderemoved = T;
610 return getRight(T);
611 }
612 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
613 getValue(T), getRight(T));
614 }
615
616 /// markImmutable - Clears the mutable bits of a root and all of its
617 /// descendants.
618 void markImmutable(TreeTy* T) {
619 if (!T || !T->isMutable())
620 return;
621 T->markImmutable();
624 }
625
626public:
627 TreeTy *getCanonicalTree(TreeTy *TNew) {
628 if (!TNew)
629 return nullptr;
630
631 if (TNew->IsCanonicalized)
632 return TNew;
633
634 // Search the hashtable for another tree with the same digest, and
635 // if find a collision compare those trees by their contents.
636 unsigned digest = TNew->computeDigest();
637 TreeTy *&entry = Cache[maskCacheIndex(digest)];
638 if (entry) {
639 for (TreeTy *T = entry ; T != nullptr; T = T->next) {
640 // Compare the Contents('T') with Contents('TNew')
641 typename TreeTy::iterator TI = T->begin(), TE = T->end();
642 if (!compareTreeWithSection(TNew, TI, TE))
643 continue;
644 if (TI != TE)
645 continue; // T has more contents than TNew.
646 // Trees did match! Return 'T'.
647 if (TNew->refCount == 0)
648 TNew->destroy();
649 return T;
650 }
651 entry->prev = TNew;
652 TNew->next = entry;
653 }
654
655 entry = TNew;
656 TNew->IsCanonicalized = true;
657 return TNew;
658 }
659};
660
661//===----------------------------------------------------------------------===//
662// Immutable AVL-Tree Iterators.
663//===----------------------------------------------------------------------===//
664
665template <typename ImutInfo> class ImutAVLTreeGenericIterator {
667
668public:
669 using iterator_category = std::bidirectional_iterator_tag;
671 using difference_type = std::ptrdiff_t;
674
676 Flags=0x3 };
677
679
682 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
683 }
684
685 TreeTy &operator*() const {
686 assert(!stack.empty());
687 return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
688 }
689 TreeTy *operator->() const { return &*this; }
690
691 uintptr_t getVisitState() const {
692 assert(!stack.empty());
693 return stack.back() & Flags;
694 }
695
696 bool atEnd() const { return stack.empty(); }
697
698 bool atBeginning() const {
699 return stack.size() == 1 && getVisitState() == VisitedNone;
700 }
701
703 assert(!stack.empty());
704 stack.pop_back();
705 if (stack.empty())
706 return;
707 switch (getVisitState()) {
708 case VisitedNone:
709 stack.back() |= VisitedLeft;
710 break;
711 case VisitedLeft:
712 stack.back() |= VisitedRight;
713 break;
714 default:
715 llvm_unreachable("Unreachable.");
716 }
717 }
718
720 return stack == x.stack;
721 }
722
724 return !(*this == x);
725 }
726
728 assert(!stack.empty());
729 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
730 assert(Current);
731 switch (getVisitState()) {
732 case VisitedNone:
733 if (TreeTy* L = Current->getLeft())
734 stack.push_back(reinterpret_cast<uintptr_t>(L));
735 else
736 stack.back() |= VisitedLeft;
737 break;
738 case VisitedLeft:
739 if (TreeTy* R = Current->getRight())
740 stack.push_back(reinterpret_cast<uintptr_t>(R));
741 else
742 stack.back() |= VisitedRight;
743 break;
744 case VisitedRight:
745 skipToParent();
746 break;
747 default:
748 llvm_unreachable("Unreachable.");
749 }
750 return *this;
751 }
752
754 assert(!stack.empty());
755 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
756 assert(Current);
757 switch (getVisitState()) {
758 case VisitedNone:
759 stack.pop_back();
760 break;
761 case VisitedLeft:
762 stack.back() &= ~Flags; // Set state to "VisitedNone."
763 if (TreeTy* L = Current->getLeft())
764 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
765 break;
766 case VisitedRight:
767 stack.back() &= ~Flags;
768 stack.back() |= VisitedLeft;
769 if (TreeTy* R = Current->getRight())
770 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
771 break;
772 default:
773 llvm_unreachable("Unreachable.");
774 }
775 return *this;
776 }
777};
778
779template <typename ImutInfo> class ImutAVLTreeInOrderIterator {
780 using InternalIteratorTy = ImutAVLTreeGenericIterator<ImutInfo>;
781
782 InternalIteratorTy InternalItr;
783
784public:
785 using iterator_category = std::bidirectional_iterator_tag;
787 using difference_type = std::ptrdiff_t;
790
792
793 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
794 if (Root)
795 ++*this; // Advance to first element.
796 }
797
798 ImutAVLTreeInOrderIterator() : InternalItr() {}
799
801 return InternalItr == x.InternalItr;
802 }
803
805 return !(*this == x);
806 }
807
808 TreeTy &operator*() const { return *InternalItr; }
809 TreeTy *operator->() const { return &*InternalItr; }
810
812 do ++InternalItr;
813 while (!InternalItr.atEnd() &&
814 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
815
816 return *this;
817 }
818
820 do --InternalItr;
821 while (!InternalItr.atBeginning() &&
822 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
823
824 return *this;
825 }
826
827 void skipSubTree() {
828 InternalItr.skipToParent();
829
830 while (!InternalItr.atEnd() &&
831 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
832 ++InternalItr;
833 }
834};
835
836/// Generic iterator that wraps a T::TreeTy::iterator and exposes
837/// iterator::getValue() on dereference.
838template <typename T>
841 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
842 typename std::iterator_traits<
843 typename T::TreeTy::iterator>::iterator_category,
844 const typename T::value_type> {
846 explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
848
850 return this->I->getValue();
851 }
852};
853
854//===----------------------------------------------------------------------===//
855// Trait classes for Profile information.
856//===----------------------------------------------------------------------===//
857
858/// Generic profile template. The default behavior is to invoke the
859/// profile method of an object. Specializations for primitive integers
860/// and generic handling of pointers is done below.
861template <typename T>
863 using value_type = const T;
864 using value_type_ref = const T&;
865
869};
870
871/// Profile traits for integers.
872template <typename T>
874 using value_type = const T;
875 using value_type_ref = const T&;
876
878 ID.AddInteger(X);
879 }
880};
881
882#define PROFILE_INTEGER_INFO(X)\
883template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
884
886PROFILE_INTEGER_INFO(unsigned char)
888PROFILE_INTEGER_INFO(unsigned short)
889PROFILE_INTEGER_INFO(unsigned)
892PROFILE_INTEGER_INFO(unsigned long)
893PROFILE_INTEGER_INFO(long long)
894PROFILE_INTEGER_INFO(unsigned long long)
895
896#undef PROFILE_INTEGER_INFO
897
898/// Profile traits for booleans.
899template <>
901 using value_type = const bool;
902 using value_type_ref = const bool&;
903
905 ID.AddBoolean(X);
906 }
907};
908
909/// Generic profile trait for pointer types. We treat pointers as
910/// references to unique objects.
911template <typename T>
913 using value_type = const T*;
915
917 ID.AddPointer(X);
918 }
919};
920
921//===----------------------------------------------------------------------===//
922// Trait classes that contain element comparison operators and type
923// definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
924// inherit from the profile traits (ImutProfileInfo) to include operations
925// for element profiling.
926//===----------------------------------------------------------------------===//
927
928/// ImutContainerInfo - Generic definition of comparison operations for
929/// elements of immutable containers that defaults to using
930/// std::equal_to<> and std::less<> to perform comparison of elements.
931template <typename T> struct ImutContainerInfo : ImutProfileInfo<T> {
938
940 static data_type_ref DataOfValue(value_type_ref) { return true; }
941
943 return std::equal_to<key_type>()(LHS,RHS);
944 }
945
947 return std::less<key_type>()(LHS,RHS);
948 }
949
950 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
951};
952
953/// ImutContainerInfo - Specialization for pointer values to treat pointers
954/// as references to unique objects. Pointers are thus compared by
955/// their addresses.
956template <typename T> struct ImutContainerInfo<T *> : ImutProfileInfo<T *> {
963
965 static data_type_ref DataOfValue(value_type_ref) { return true; }
966
967 static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
968
969 static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
970
971 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
972};
973
974//===----------------------------------------------------------------------===//
975// Immutable Set
976//===----------------------------------------------------------------------===//
977
978template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
980public:
981 using value_type = typename ValInfo::value_type;
982 using value_type_ref = typename ValInfo::value_type_ref;
984
985private:
987
988public:
989 /// Constructs a set from a pointer to a tree root. In general one
990 /// should use a Factory object to create sets instead of directly
991 /// invoking the constructor, but there are cases where make this
992 /// constructor public is useful.
993 explicit ImmutableSet(TreeTy *R) : Root(R) {}
994
995 class Factory {
996 typename TreeTy::Factory F;
997 const bool Canonicalize;
998
999 public:
1000 Factory(bool canonicalize = true)
1001 : Canonicalize(canonicalize) {}
1002
1003 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
1004 : F(Alloc), Canonicalize(canonicalize) {}
1005
1006 Factory(const Factory& RHS) = delete;
1007 void operator=(const Factory& RHS) = delete;
1008
1009 /// getEmptySet - Returns an immutable set that contains no elements.
1011 return ImmutableSet(F.getEmptyTree());
1012 }
1013
1014 /// add - Creates a new immutable set that contains all of the values
1015 /// of the original set with the addition of the specified value. If
1016 /// the original set already included the value, then the original set is
1017 /// returned and no memory is allocated. The time and space complexity
1018 /// of this operation is logarithmic in the size of the original set.
1019 /// The memory allocated to represent the set is released when the
1020 /// factory object that created the set is destroyed.
1022 TreeTy *NewT = F.add(Old.Root.get(), V);
1023 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1024 }
1025
1026 /// remove - Creates a new immutable set that contains all of the values
1027 /// of the original set with the exception of the specified value. If
1028 /// the original set did not contain the value, the original set is
1029 /// returned and no memory is allocated. The time and space complexity
1030 /// of this operation is logarithmic in the size of the original set.
1031 /// The memory allocated to represent the set is released when the
1032 /// factory object that created the set is destroyed.
1034 TreeTy *NewT = F.remove(Old.Root.get(), V);
1035 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1036 }
1037
1038 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1039
1041 return const_cast<typename TreeTy::Factory *>(&F);
1042 }
1043 };
1044
1045 friend class Factory;
1046
1047 /// Returns true if the set contains the specified value.
1048 bool contains(value_type_ref V) const {
1049 return Root ? Root->contains(V) : false;
1050 }
1051
1052 bool operator==(const ImmutableSet &RHS) const {
1053 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1054 }
1055
1056 bool operator!=(const ImmutableSet &RHS) const {
1057 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1058 : Root != RHS.Root;
1059 }
1060
1062 if (Root) { Root->retain(); }
1063 return Root.get();
1064 }
1065
1066 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1067
1068 /// isEmpty - Return true if the set contains no elements.
1069 bool isEmpty() const { return !Root; }
1070
1071 /// isSingleton - Return true if the set contains exactly one element.
1072 /// This method runs in constant time.
1073 bool isSingleton() const { return getHeight() == 1; }
1074
1075 //===--------------------------------------------------===//
1076 // Iterators.
1077 //===--------------------------------------------------===//
1078
1080
1081 iterator begin() const { return iterator(Root.get()); }
1082 iterator end() const { return iterator(); }
1083
1084 //===--------------------------------------------------===//
1085 // Utility methods.
1086 //===--------------------------------------------------===//
1087
1088 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1089
1090 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1091 ID.AddPointer(S.Root.get());
1092 }
1093
1094 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1095
1096 //===--------------------------------------------------===//
1097 // For testing.
1098 //===--------------------------------------------------===//
1099
1100 void validateTree() const { if (Root) Root->validateTree(); }
1101};
1102
1103// NOTE: This may some day replace the current ImmutableSet.
1104template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>>
1106public:
1107 using value_type = typename ValInfo::value_type;
1108 using value_type_ref = typename ValInfo::value_type_ref;
1110 using FactoryTy = typename TreeTy::Factory;
1111
1112private:
1114 FactoryTy *Factory;
1115
1116public:
1117 /// Constructs a set from a pointer to a tree root. In general one
1118 /// should use a Factory object to create sets instead of directly
1119 /// invoking the constructor, but there are cases where make this
1120 /// constructor public is useful.
1121 ImmutableSetRef(TreeTy *R, FactoryTy *F) : Root(R), Factory(F) {}
1122
1124 return ImmutableSetRef(0, F);
1125 }
1126
1128 return ImmutableSetRef(Factory->add(Root.get(), V), Factory);
1129 }
1130
1132 return ImmutableSetRef(Factory->remove(Root.get(), V), Factory);
1133 }
1134
1135 /// Returns true if the set contains the specified value.
1136 bool contains(value_type_ref V) const {
1137 return Root ? Root->contains(V) : false;
1138 }
1139
1140 ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1141 return ImmutableSet<ValT>(
1142 canonicalize ? Factory->getCanonicalTree(Root.get()) : Root.get());
1143 }
1144
1145 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1146
1147 bool operator==(const ImmutableSetRef &RHS) const {
1148 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1149 }
1150
1151 bool operator!=(const ImmutableSetRef &RHS) const {
1152 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1153 : Root != RHS.Root;
1154 }
1155
1156 /// isEmpty - Return true if the set contains no elements.
1157 bool isEmpty() const { return !Root; }
1158
1159 /// isSingleton - Return true if the set contains exactly one element.
1160 /// This method runs in constant time.
1161 bool isSingleton() const { return getHeight() == 1; }
1162
1163 //===--------------------------------------------------===//
1164 // Iterators.
1165 //===--------------------------------------------------===//
1166
1168
1169 iterator begin() const { return iterator(Root.get()); }
1170 iterator end() const { return iterator(); }
1171
1172 //===--------------------------------------------------===//
1173 // Utility methods.
1174 //===--------------------------------------------------===//
1175
1176 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1177
1178 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1179 ID.AddPointer(S.Root.get());
1180 }
1181
1182 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1183
1184 //===--------------------------------------------------===//
1185 // For testing.
1186 //===--------------------------------------------------===//
1187
1188 void validateTree() const { if (Root) Root->validateTree(); }
1189};
1190
1191} // end namespace llvm
1192
1193#endif // LLVM_ADT_IMMUTABLESET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:706
This file defines the DenseMap class.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define PROFILE_INTEGER_INFO(X)
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:55
#define I(x, y, z)
Definition MD5.cpp:58
#define T
if(PassOpts->AAPipeline)
This file defines the SmallVector class.
static TableGen::Emitter::OptClass< SkeletonEmitter > X("gen-skeleton-class", "Generate example skeleton class")
Value * RHS
Value * LHS
FoldingSetNodeID - This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:330
static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S)
void Profile(FoldingSetNodeID &ID) const
ImmutableSetRef add(value_type_ref V)
ImutAVLTree< ValInfo > TreeTy
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
bool operator!=(const ImmutableSetRef &RHS) const
ImmutableSetRef remove(value_type_ref V)
ImutAVLValueIterator< ImmutableSetRef > iterator
bool isSingleton() const
isSingleton - Return true if the set contains exactly one element.
iterator begin() const
bool isEmpty() const
isEmpty - Return true if the set contains no elements.
typename ValInfo::value_type value_type
ImmutableSetRef(TreeTy *R, FactoryTy *F)
Constructs a set from a pointer to a tree root.
typename ValInfo::value_type_ref value_type_ref
iterator end() const
unsigned getHeight() const
ImmutableSet< ValT > asImmutableSet(bool canonicalize=true) const
typename TreeTy::Factory FactoryTy
static ImmutableSetRef getEmptySet(FactoryTy *F)
void validateTree() const
bool operator==(const ImmutableSetRef &RHS) const
TreeTy * getRootWithoutRetain() const
Factory(const Factory &RHS)=delete
void operator=(const Factory &RHS)=delete
TreeTy::Factory * getTreeFactory() const
BumpPtrAllocator & getAllocator()
Factory(BumpPtrAllocator &Alloc, bool canonicalize=true)
ImmutableSet getEmptySet()
getEmptySet - Returns an immutable set that contains no elements.
Factory(bool canonicalize=true)
ImmutableSet remove(ImmutableSet Old, value_type_ref V)
remove - Creates a new immutable set that contains all of the values of the original set with the exc...
ImmutableSet add(ImmutableSet Old, value_type_ref V)
add - Creates a new immutable set that contains all of the values of the original set with the additi...
bool operator!=(const ImmutableSet &RHS) const
typename ValInfo::value_type value_type
bool operator==(const ImmutableSet &RHS) const
iterator end() const
bool isEmpty() const
isEmpty - Return true if the set contains no elements.
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool isSingleton() const
isSingleton - Return true if the set contains exactly one element.
TreeTy * getRootWithoutRetain() const
ImutAVLTree< ValInfo > TreeTy
void validateTree() const
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
void Profile(FoldingSetNodeID &ID) const
iterator begin() const
unsigned getHeight() const
static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S)
ImutAVLValueIterator< ImmutableSet > iterator
typename ValInfo::value_type_ref value_type_ref
static unsigned maskCacheIndex(unsigned I)
TreeTy * balanceTree(TreeTy *L, value_type_ref V, TreeTy *R)
balanceTree - Used by add_internal and remove_internal to balance a newly created tree.
unsigned getHeight(TreeTy *T) const
ImutAVLFactory(BumpPtrAllocator &Alloc)
TreeTy * add_internal(value_type_ref V, TreeTy *T)
add_internal - Creates a new tree that includes the specified data and the data from the original tre...
value_type_ref getValue(TreeTy *T) const
static bool compareTreeWithSection(TreeTy *T, typename TreeTy::iterator &TI, typename TreeTy::iterator &TE)
TreeTy * getLeft(TreeTy *T) const
TreeTy * getCanonicalTree(TreeTy *TNew)
TreeTy * add(TreeTy *T, value_type_ref V)
TreeTy * getRight(TreeTy *T) const
TreeTy * getEmptyTree() const
TreeTy * removeMinBinding(TreeTy *T, TreeTy *&Noderemoved)
TreeTy * createNode(TreeTy *newLeft, TreeTy *oldTree, TreeTy *newRight)
TreeTy * combineTrees(TreeTy *L, TreeTy *R)
TreeTy * remove_internal(key_type_ref K, TreeTy *T)
remove_internal - Creates a new tree that includes all the data from the original tree except the spe...
TreeTy * createNode(TreeTy *L, value_type_ref V, TreeTy *R)
unsigned incrementHeight(TreeTy *L, TreeTy *R) const
TreeTy * remove(TreeTy *T, key_type_ref V)
void markImmutable(TreeTy *T)
markImmutable - Clears the mutable bits of a root and all of its descendants.
bool isEmpty(TreeTy *T) const
ImutAVLTree< ImutInfo > value_type
bool operator==(const ImutAVLTreeGenericIterator &x) const
std::bidirectional_iterator_tag iterator_category
ImutAVLTreeGenericIterator(const TreeTy *Root)
ImutAVLTree< ImutInfo > TreeTy
ImutAVLTreeGenericIterator & operator--()
bool operator!=(const ImutAVLTreeGenericIterator &x) const
ImutAVLTreeGenericIterator & operator++()
bool operator!=(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTreeInOrderIterator & operator++()
ImutAVLTree< ImutInfo > TreeTy
ImutAVLTreeInOrderIterator & operator--()
std::bidirectional_iterator_tag iterator_category
ImutAVLTreeInOrderIterator(const TreeTy *Root)
bool operator==(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTree< ImutInfo > value_type
unsigned size() const
size - Returns the number of nodes in the tree, which includes both leaves and non-leaf nodes.
iterator end() const
end - Returns an iterator for the tree that denotes the end of an inorder traversal.
const value_type & getValue() const
getValue - Returns the data value associated with the tree node.
unsigned getHeight() const
getHeight - Returns the height of the tree.
typename ValInfo::key_type_ref key_type_ref
ImutAVLFactory< ValInfo > Factory
ImutAVLTree * find(key_type_ref K)
find - Finds the subtree associated with the specified key value.
typename ValInfo::value_type_ref value_type_ref
unsigned validateTree() const
validateTree - A utility method that checks that the balancing and ordering invariants of the tree ar...
bool isNotEqual(const ImutAVLTree &RHS) const
isNotEqual - Compares two trees for structural inequality.
bool isEqual(const ImutAVLTree &RHS) const
isEqual - Compares two trees for structural equality and returns true if they are equal.
ImutAVLTree * getLeft() const
Return a pointer to the left subtree.
ImutAVLTreeInOrderIterator< ValInfo > iterator
typename ValInfo::value_type value_type
ImutAVLTree * getRight() const
Return a pointer to the right subtree.
bool isElementEqual(const ImutAVLTree *RHS) const
bool contains(key_type_ref K)
contains - Returns true if this tree contains a subtree (node) that has an data element that matches ...
ImutAVLTree * getMaxElement()
getMaxElement - Find the subtree associated with the highest ranged key value.
iterator begin() const
begin - Returns an iterator that iterates over the nodes of the tree in an inorder traversal.
bool isElementEqual(value_type_ref V) const
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
This is an optimization pass for GlobalISel generic memory operations.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:383
#define N
static void Profile(const T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:237
Generic iterator that wraps a T::TreeTy::iterator and exposes iterator::getValue() on dereference.
ImutAVLValueIterator::reference operator*() const
ImutAVLValueIterator(typename T::TreeTy *Tree)
static bool isDataEqual(data_type_ref, data_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T * >::value_type_ref value_type_ref
typename ImutProfileInfo< T * >::value_type value_type
static data_type_ref DataOfValue(value_type_ref)
static bool isLess(key_type_ref LHS, key_type_ref RHS)
ImutContainerInfo - Generic definition of comparison operations for elements of immutable containers ...
static bool isLess(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T >::value_type value_type
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
static bool isDataEqual(data_type_ref, data_type_ref)
static data_type_ref DataOfValue(value_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
value_type_ref key_type_ref
typename ImutProfileInfo< T >::value_type_ref value_type_ref
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Generic profile template.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Profile traits for integers.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void retain(ImutAVLTree< ImutInfo > *Tree)
Class you can specialize to provide custom retain/release functionality for a type.