1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ImutAVLTree and ImmutableSet classes.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_IMMUTABLESET_H
15 #define LLVM_ADT_IMMUTABLESET_H
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/Support/Allocator.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
28 //===----------------------------------------------------------------------===//
29 // Immutable AVL-Tree Definition.
30 //===----------------------------------------------------------------------===//
32 template <typename ImutInfo> class ImutAVLFactory;
33 template <typename ImutInfo> class ImutIntervalAVLFactory;
34 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
35 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
37 template <typename ImutInfo >
40 typedef typename ImutInfo::key_type_ref key_type_ref;
41 typedef typename ImutInfo::value_type value_type;
42 typedef typename ImutInfo::value_type_ref value_type_ref;
44 typedef ImutAVLFactory<ImutInfo> Factory;
45 friend class ImutAVLFactory<ImutInfo>;
46 friend class ImutIntervalAVLFactory<ImutInfo>;
48 friend class ImutAVLTreeGenericIterator<ImutInfo>;
50 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
52 //===----------------------------------------------------===//
54 //===----------------------------------------------------===//
56 /// Return a pointer to the left subtree. This value
57 /// is NULL if there is no left subtree.
58 ImutAVLTree *getLeft() const { return left; }
60 /// Return a pointer to the right subtree. This value is
61 /// NULL if there is no right subtree.
62 ImutAVLTree *getRight() const { return right; }
64 /// getHeight - Returns the height of the tree. A tree with no subtrees
65 /// has a height of 1.
66 unsigned getHeight() const { return height; }
68 /// getValue - Returns the data value associated with the tree node.
69 const value_type& getValue() const { return value; }
71 /// find - Finds the subtree associated with the specified key value.
72 /// This method returns NULL if no matching subtree is found.
73 ImutAVLTree* find(key_type_ref K) {
74 ImutAVLTree *T = this;
76 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
77 if (ImutInfo::isEqual(K,CurrentKey))
79 else if (ImutInfo::isLess(K,CurrentKey))
87 /// getMaxElement - Find the subtree associated with the highest ranged
89 ImutAVLTree* getMaxElement() {
90 ImutAVLTree *T = this;
91 ImutAVLTree *Right = T->getRight();
92 while (Right) { T = Right; Right = T->getRight(); }
96 /// size - Returns the number of nodes in the tree, which includes
97 /// both leaves and non-leaf nodes.
98 unsigned size() const {
100 if (const ImutAVLTree* L = getLeft())
102 if (const ImutAVLTree* R = getRight())
107 /// begin - Returns an iterator that iterates over the nodes of the tree
108 /// in an inorder traversal. The returned iterator thus refers to the
109 /// the tree node with the minimum data element.
110 iterator begin() const { return iterator(this); }
112 /// end - Returns an iterator for the tree that denotes the end of an
113 /// inorder traversal.
114 iterator end() const { return iterator(); }
116 bool isElementEqual(value_type_ref V) const {
118 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
119 ImutInfo::KeyOfValue(V)))
122 // Also compare the data values.
123 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
124 ImutInfo::DataOfValue(V)))
130 bool isElementEqual(const ImutAVLTree* RHS) const {
131 return isElementEqual(RHS->getValue());
134 /// isEqual - Compares two trees for structural equality and returns true
135 /// if they are equal. This worst case performance of this operation is
136 // linear in the sizes of the trees.
137 bool isEqual(const ImutAVLTree& RHS) const {
141 iterator LItr = begin(), LEnd = end();
142 iterator RItr = RHS.begin(), REnd = RHS.end();
144 while (LItr != LEnd && RItr != REnd) {
145 if (&*LItr == &*RItr) {
151 if (!LItr->isElementEqual(&*RItr))
158 return LItr == LEnd && RItr == REnd;
161 /// isNotEqual - Compares two trees for structural inequality. Performance
162 /// is the same is isEqual.
163 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
165 /// contains - Returns true if this tree contains a subtree (node) that
166 /// has an data element that matches the specified key. Complexity
167 /// is logarithmic in the size of the tree.
168 bool contains(key_type_ref K) { return (bool) find(K); }
170 /// foreach - A member template the accepts invokes operator() on a functor
171 /// object (specifed by Callback) for every node/subtree in the tree.
172 /// Nodes are visited using an inorder traversal.
173 template <typename Callback>
174 void foreach(Callback& C) {
175 if (ImutAVLTree* L = getLeft())
180 if (ImutAVLTree* R = getRight())
184 /// validateTree - A utility method that checks that the balancing and
185 /// ordering invariants of the tree are satisifed. It is a recursive
186 /// method that returns the height of the tree, which is then consumed
187 /// by the enclosing validateTree call. External callers should ignore the
188 /// return value. An invalid tree will cause an assertion to fire in
190 unsigned validateTree() const {
191 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
192 unsigned HR = getRight() ? getRight()->validateTree() : 0;
196 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
197 && "Height calculation wrong");
199 assert((HL > HR ? HL-HR : HR-HL) <= 2
200 && "Balancing invariant violated");
202 assert((!getLeft() ||
203 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
204 ImutInfo::KeyOfValue(getValue()))) &&
205 "Value in left child is not less that current value");
208 assert(!(getRight() ||
209 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
210 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
211 "Current value is not less that value of right child");
216 //===----------------------------------------------------===//
218 //===----------------------------------------------------===//
227 unsigned height : 28;
228 unsigned IsMutable : 1;
229 unsigned IsDigestCached : 1;
230 unsigned IsCanonicalized : 1;
236 //===----------------------------------------------------===//
237 // Internal methods (node manipulation; used by Factory).
238 //===----------------------------------------------------===//
241 /// ImutAVLTree - Internal constructor that is only called by
243 ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
245 : factory(f), left(l), right(r), prev(nullptr), next(nullptr),
246 height(height), IsMutable(true), IsDigestCached(false),
247 IsCanonicalized(0), value(v), digest(0), refCount(0)
249 if (left) left->retain();
250 if (right) right->retain();
253 /// isMutable - Returns true if the left and right subtree references
254 /// (as well as height) can be changed. If this method returns false,
255 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
256 /// object should always have this method return true. Further, if this
257 /// method returns false for an instance of ImutAVLTree, all subtrees
258 /// will also have this method return false. The converse is not true.
259 bool isMutable() const { return IsMutable; }
261 /// hasCachedDigest - Returns true if the digest for this tree is cached.
262 /// This can only be true if the tree is immutable.
263 bool hasCachedDigest() const { return IsDigestCached; }
265 //===----------------------------------------------------===//
266 // Mutating operations. A tree root can be manipulated as
267 // long as its reference has not "escaped" from internal
268 // methods of a factory object (see below). When a tree
269 // pointer is externally viewable by client code, the
270 // internal "mutable bit" is cleared to mark the tree
271 // immutable. Note that a tree that still has its mutable
272 // bit set may have children (subtrees) that are themselves
274 //===----------------------------------------------------===//
276 /// markImmutable - Clears the mutable flag for a tree. After this happens,
277 /// it is an error to call setLeft(), setRight(), and setHeight().
278 void markImmutable() {
279 assert(isMutable() && "Mutable flag already removed.");
283 /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
284 void markedCachedDigest() {
285 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
286 IsDigestCached = true;
289 /// setHeight - Changes the height of the tree. Used internally by
291 void setHeight(unsigned h) {
292 assert(isMutable() && "Only a mutable tree can have its height changed.");
296 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
301 digest += L->computeDigest();
303 // Compute digest of stored data.
305 ImutInfo::Profile(ID,V);
306 digest += ID.ComputeHash();
309 digest += R->computeDigest();
314 uint32_t computeDigest() {
315 // Check the lowest bit to determine if digest has actually been
317 if (hasCachedDigest())
320 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
322 markedCachedDigest();
326 //===----------------------------------------------------===//
327 // Reference count operations.
328 //===----------------------------------------------------===//
331 void retain() { ++refCount; }
333 assert(refCount > 0);
342 if (IsCanonicalized) {
349 factory->Cache[factory->maskCacheIndex(computeDigest())] = next;
352 // We need to clear the mutability bit in case we are
353 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
355 factory->freeNodes.push_back(this);
359 //===----------------------------------------------------------------------===//
360 // Immutable AVL-Tree Factory class.
361 //===----------------------------------------------------------------------===//
363 template <typename ImutInfo >
364 class ImutAVLFactory {
365 friend class ImutAVLTree<ImutInfo>;
366 typedef ImutAVLTree<ImutInfo> TreeTy;
367 typedef typename TreeTy::value_type_ref value_type_ref;
368 typedef typename TreeTy::key_type_ref key_type_ref;
370 typedef DenseMap<unsigned, TreeTy*> CacheTy;
374 std::vector<TreeTy*> createdNodes;
375 std::vector<TreeTy*> freeNodes;
377 bool ownsAllocator() const {
378 return Allocator & 0x1 ? false : true;
381 BumpPtrAllocator& getAllocator() const {
382 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
385 //===--------------------------------------------------===//
387 //===--------------------------------------------------===//
391 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
393 ImutAVLFactory(BumpPtrAllocator& Alloc)
394 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
397 if (ownsAllocator()) delete &getAllocator();
400 TreeTy* add(TreeTy* T, value_type_ref V) {
401 T = add_internal(V,T);
407 TreeTy* remove(TreeTy* T, key_type_ref V) {
408 T = remove_internal(V,T);
414 TreeTy* getEmptyTree() const { return nullptr; }
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 //===--------------------------------------------------===//
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; }
431 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
432 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
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;
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))
451 //===--------------------------------------------------===//
452 // "createNode" is used to generate new tree roots that link
453 // to other trees. The functon 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 //===--------------------------------------------------===//
461 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
462 BumpPtrAllocator& A = getAllocator();
464 if (!freeNodes.empty()) {
465 T = freeNodes.back();
466 freeNodes.pop_back();
470 T = (TreeTy*) A.Allocate<TreeTy>();
472 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
473 createdNodes.push_back(T);
477 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
478 return createNode(newLeft, getValue(oldTree), newRight);
481 void recoverNodes() {
482 for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
483 TreeTy *N = createdNodes[i];
484 if (N->isMutable() && N->refCount == 0)
487 createdNodes.clear();
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);
497 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
499 TreeTy *LL = getLeft(L);
500 TreeTy *LR = getRight(L);
502 if (getHeight(LL) >= getHeight(LR))
503 return createNode(LL, L, createNode(LR,V,R));
505 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
507 TreeTy *LRL = getLeft(LR);
508 TreeTy *LRR = getRight(LR);
510 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
514 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
516 TreeTy *RL = getLeft(R);
517 TreeTy *RR = getRight(R);
519 if (getHeight(RR) >= getHeight(RL))
520 return createNode(createNode(L,V,RL), R, RR);
522 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
524 TreeTy *RLL = getLeft(RL);
525 TreeTy *RLR = getRight(RL);
527 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
530 return createNode(L,V,R);
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) {
538 return createNode(T, V, T);
539 assert(!T->isMutable());
541 key_type_ref K = ImutInfo::KeyOfValue(V);
542 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
544 if (ImutInfo::isEqual(K,KCurrent))
545 return createNode(getLeft(T), V, getRight(T));
546 else if (ImutInfo::isLess(K,KCurrent))
547 return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
549 return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
552 /// remove_internal - Creates a new tree that includes all the data
553 /// from the original tree except the specified data. If the
554 /// specified data did not exist in the original tree, the original
555 /// tree is returned.
556 TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
560 assert(!T->isMutable());
562 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
564 if (ImutInfo::isEqual(K,KCurrent)) {
565 return combineTrees(getLeft(T), getRight(T));
566 } else if (ImutInfo::isLess(K,KCurrent)) {
567 return balanceTree(remove_internal(K, getLeft(T)),
568 getValue(T), getRight(T));
570 return balanceTree(getLeft(T), getValue(T),
571 remove_internal(K, getRight(T)));
575 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
581 TreeTy* newRight = removeMinBinding(R,OldNode);
582 return balanceTree(L, getValue(OldNode), newRight);
585 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
587 if (isEmpty(getLeft(T))) {
591 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
592 getValue(T), getRight(T));
595 /// markImmutable - Clears the mutable bits of a root and all of its
597 void markImmutable(TreeTy* T) {
598 if (!T || !T->isMutable())
601 markImmutable(getLeft(T));
602 markImmutable(getRight(T));
606 TreeTy *getCanonicalTree(TreeTy *TNew) {
610 if (TNew->IsCanonicalized)
613 // Search the hashtable for another tree with the same digest, and
614 // if find a collision compare those trees by their contents.
615 unsigned digest = TNew->computeDigest();
616 TreeTy *&entry = Cache[maskCacheIndex(digest)];
620 for (TreeTy *T = entry ; T != nullptr; T = T->next) {
621 // Compare the Contents('T') with Contents('TNew')
622 typename TreeTy::iterator TI = T->begin(), TE = T->end();
623 if (!compareTreeWithSection(TNew, TI, TE))
626 continue; // T has more contents than TNew.
627 // Trees did match! Return 'T'.
628 if (TNew->refCount == 0)
638 TNew->IsCanonicalized = true;
643 //===----------------------------------------------------------------------===//
644 // Immutable AVL-Tree Iterators.
645 //===----------------------------------------------------------------------===//
647 template <typename ImutInfo>
648 class ImutAVLTreeGenericIterator
649 : public std::iterator<std::bidirectional_iterator_tag,
650 ImutAVLTree<ImutInfo>> {
651 SmallVector<uintptr_t,20> stack;
653 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
656 typedef ImutAVLTree<ImutInfo> TreeTy;
658 ImutAVLTreeGenericIterator() {}
659 ImutAVLTreeGenericIterator(const TreeTy *Root) {
660 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
663 TreeTy &operator*() const {
664 assert(!stack.empty());
665 return *reinterpret_cast<TreeTy *>(stack.back() & ~Flags);
667 TreeTy *operator->() const { return &*this; }
669 uintptr_t getVisitState() const {
670 assert(!stack.empty());
671 return stack.back() & Flags;
675 bool atEnd() const { return stack.empty(); }
677 bool atBeginning() const {
678 return stack.size() == 1 && getVisitState() == VisitedNone;
681 void skipToParent() {
682 assert(!stack.empty());
686 switch (getVisitState()) {
688 stack.back() |= VisitedLeft;
691 stack.back() |= VisitedRight;
694 llvm_unreachable("Unreachable.");
698 bool operator==(const ImutAVLTreeGenericIterator &x) const {
699 return stack == x.stack;
702 bool operator!=(const ImutAVLTreeGenericIterator &x) const {
703 return !(*this == x);
706 ImutAVLTreeGenericIterator &operator++() {
707 assert(!stack.empty());
708 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
710 switch (getVisitState()) {
712 if (TreeTy* L = Current->getLeft())
713 stack.push_back(reinterpret_cast<uintptr_t>(L));
715 stack.back() |= VisitedLeft;
718 if (TreeTy* R = Current->getRight())
719 stack.push_back(reinterpret_cast<uintptr_t>(R));
721 stack.back() |= VisitedRight;
727 llvm_unreachable("Unreachable.");
732 ImutAVLTreeGenericIterator &operator--() {
733 assert(!stack.empty());
734 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
736 switch (getVisitState()) {
741 stack.back() &= ~Flags; // Set state to "VisitedNone."
742 if (TreeTy* L = Current->getLeft())
743 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
746 stack.back() &= ~Flags;
747 stack.back() |= VisitedLeft;
748 if (TreeTy* R = Current->getRight())
749 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
752 llvm_unreachable("Unreachable.");
758 template <typename ImutInfo>
759 class ImutAVLTreeInOrderIterator
760 : public std::iterator<std::bidirectional_iterator_tag,
761 ImutAVLTree<ImutInfo>> {
762 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
763 InternalIteratorTy InternalItr;
766 typedef ImutAVLTree<ImutInfo> TreeTy;
768 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
770 ++*this; // Advance to first element.
773 ImutAVLTreeInOrderIterator() : InternalItr() {}
775 bool operator==(const ImutAVLTreeInOrderIterator &x) const {
776 return InternalItr == x.InternalItr;
779 bool operator!=(const ImutAVLTreeInOrderIterator &x) const {
780 return !(*this == x);
783 TreeTy &operator*() const { return *InternalItr; }
784 TreeTy *operator->() const { return &*InternalItr; }
786 ImutAVLTreeInOrderIterator &operator++() {
788 while (!InternalItr.atEnd() &&
789 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
794 ImutAVLTreeInOrderIterator &operator--() {
796 while (!InternalItr.atBeginning() &&
797 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
803 InternalItr.skipToParent();
805 while (!InternalItr.atEnd() &&
806 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
811 /// Generic iterator that wraps a T::TreeTy::iterator and exposes
812 /// iterator::getValue() on dereference.
813 template <typename T>
814 struct ImutAVLValueIterator
815 : iterator_adaptor_base<
816 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
817 typename std::iterator_traits<
818 typename T::TreeTy::iterator>::iterator_category,
819 const typename T::value_type> {
820 ImutAVLValueIterator() = default;
821 explicit ImutAVLValueIterator(typename T::TreeTy *Tree)
822 : ImutAVLValueIterator::iterator_adaptor_base(Tree) {}
824 typename ImutAVLValueIterator::reference operator*() const {
825 return this->I->getValue();
829 //===----------------------------------------------------------------------===//
830 // Trait classes for Profile information.
831 //===----------------------------------------------------------------------===//
833 /// Generic profile template. The default behavior is to invoke the
834 /// profile method of an object. Specializations for primitive integers
835 /// and generic handling of pointers is done below.
836 template <typename T>
837 struct ImutProfileInfo {
838 typedef const T value_type;
839 typedef const T& value_type_ref;
841 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
842 FoldingSetTrait<T>::Profile(X,ID);
846 /// Profile traits for integers.
847 template <typename T>
848 struct ImutProfileInteger {
849 typedef const T value_type;
850 typedef const T& value_type_ref;
852 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
857 #define PROFILE_INTEGER_INFO(X)\
858 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
860 PROFILE_INTEGER_INFO(char)
861 PROFILE_INTEGER_INFO(unsigned char)
862 PROFILE_INTEGER_INFO(short)
863 PROFILE_INTEGER_INFO(unsigned short)
864 PROFILE_INTEGER_INFO(unsigned)
865 PROFILE_INTEGER_INFO(signed)
866 PROFILE_INTEGER_INFO(long)
867 PROFILE_INTEGER_INFO(unsigned long)
868 PROFILE_INTEGER_INFO(long long)
869 PROFILE_INTEGER_INFO(unsigned long long)
871 #undef PROFILE_INTEGER_INFO
873 /// Profile traits for booleans.
875 struct ImutProfileInfo<bool> {
876 typedef const bool value_type;
877 typedef const bool& value_type_ref;
879 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
885 /// Generic profile trait for pointer types. We treat pointers as
886 /// references to unique objects.
887 template <typename T>
888 struct ImutProfileInfo<T*> {
889 typedef const T* value_type;
890 typedef value_type value_type_ref;
892 static void Profile(FoldingSetNodeID &ID, value_type_ref X) {
897 //===----------------------------------------------------------------------===//
898 // Trait classes that contain element comparison operators and type
899 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
900 // inherit from the profile traits (ImutProfileInfo) to include operations
901 // for element profiling.
902 //===----------------------------------------------------------------------===//
905 /// ImutContainerInfo - Generic definition of comparison operations for
906 /// elements of immutable containers that defaults to using
907 /// std::equal_to<> and std::less<> to perform comparison of elements.
908 template <typename T>
909 struct ImutContainerInfo : public ImutProfileInfo<T> {
910 typedef typename ImutProfileInfo<T>::value_type value_type;
911 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
912 typedef value_type key_type;
913 typedef value_type_ref key_type_ref;
914 typedef bool data_type;
915 typedef bool data_type_ref;
917 static key_type_ref KeyOfValue(value_type_ref D) { return D; }
918 static data_type_ref DataOfValue(value_type_ref) { return true; }
920 static bool isEqual(key_type_ref LHS, key_type_ref RHS) {
921 return std::equal_to<key_type>()(LHS,RHS);
924 static bool isLess(key_type_ref LHS, key_type_ref RHS) {
925 return std::less<key_type>()(LHS,RHS);
928 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
931 /// ImutContainerInfo - Specialization for pointer values to treat pointers
932 /// as references to unique objects. Pointers are thus compared by
934 template <typename T>
935 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
936 typedef typename ImutProfileInfo<T*>::value_type value_type;
937 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
938 typedef value_type key_type;
939 typedef value_type_ref key_type_ref;
940 typedef bool data_type;
941 typedef bool data_type_ref;
943 static key_type_ref KeyOfValue(value_type_ref D) { return D; }
944 static data_type_ref DataOfValue(value_type_ref) { return true; }
946 static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
948 static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
950 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
953 //===----------------------------------------------------------------------===//
955 //===----------------------------------------------------------------------===//
957 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
960 typedef typename ValInfo::value_type value_type;
961 typedef typename ValInfo::value_type_ref value_type_ref;
962 typedef ImutAVLTree<ValInfo> TreeTy;
968 /// Constructs a set from a pointer to a tree root. In general one
969 /// should use a Factory object to create sets instead of directly
970 /// invoking the constructor, but there are cases where make this
971 /// constructor public is useful.
972 explicit ImmutableSet(TreeTy* R) : Root(R) {
973 if (Root) { Root->retain(); }
975 ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
976 if (Root) { Root->retain(); }
978 ImmutableSet &operator=(const ImmutableSet &X) {
979 if (Root != X.Root) {
980 if (X.Root) { X.Root->retain(); }
981 if (Root) { Root->release(); }
987 if (Root) { Root->release(); }
991 typename TreeTy::Factory F;
992 const bool Canonicalize;
995 Factory(bool canonicalize = true)
996 : Canonicalize(canonicalize) {}
998 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
999 : F(Alloc), Canonicalize(canonicalize) {}
1001 /// getEmptySet - Returns an immutable set that contains no elements.
1002 ImmutableSet getEmptySet() {
1003 return ImmutableSet(F.getEmptyTree());
1006 /// add - Creates a new immutable set that contains all of the values
1007 /// of the original set with the addition of the specified value. If
1008 /// the original set already included the value, then the original set is
1009 /// returned and no memory is allocated. The time and space complexity
1010 /// of this operation is logarithmic in the size of the original set.
1011 /// The memory allocated to represent the set is released when the
1012 /// factory object that created the set is destroyed.
1013 ImmutableSet add(ImmutableSet Old, value_type_ref V) {
1014 TreeTy *NewT = F.add(Old.Root, V);
1015 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1018 /// remove - Creates a new immutable set that contains all of the values
1019 /// of the original set with the exception of the specified value. If
1020 /// the original set did not contain the value, the original set is
1021 /// returned and no memory is allocated. The time and space complexity
1022 /// of this operation is logarithmic in the size of the original set.
1023 /// The memory allocated to represent the set is released when the
1024 /// factory object that created the set is destroyed.
1025 ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
1026 TreeTy *NewT = F.remove(Old.Root, V);
1027 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1030 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1032 typename TreeTy::Factory *getTreeFactory() const {
1033 return const_cast<typename TreeTy::Factory *>(&F);
1037 Factory(const Factory& RHS) = delete;
1038 void operator=(const Factory& RHS) = delete;
1041 friend class Factory;
1043 /// Returns true if the set contains the specified value.
1044 bool contains(value_type_ref V) const {
1045 return Root ? Root->contains(V) : false;
1048 bool operator==(const ImmutableSet &RHS) const {
1049 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1052 bool operator!=(const ImmutableSet &RHS) const {
1053 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1057 if (Root) { Root->retain(); }
1061 TreeTy *getRootWithoutRetain() const {
1065 /// isEmpty - Return true if the set contains no elements.
1066 bool isEmpty() const { return !Root; }
1068 /// isSingleton - Return true if the set contains exactly one element.
1069 /// This method runs in constant time.
1070 bool isSingleton() const { return getHeight() == 1; }
1072 template <typename Callback>
1073 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1075 template <typename Callback>
1076 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1078 //===--------------------------------------------------===//
1080 //===--------------------------------------------------===//
1082 typedef ImutAVLValueIterator<ImmutableSet> iterator;
1084 iterator begin() const { return iterator(Root); }
1085 iterator end() const { return iterator(); }
1087 //===--------------------------------------------------===//
1089 //===--------------------------------------------------===//
1091 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1093 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1094 ID.AddPointer(S.Root);
1097 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1099 //===--------------------------------------------------===//
1101 //===--------------------------------------------------===//
1103 void validateTree() const { if (Root) Root->validateTree(); }
1106 // NOTE: This may some day replace the current ImmutableSet.
1107 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
1108 class ImmutableSetRef {
1110 typedef typename ValInfo::value_type value_type;
1111 typedef typename ValInfo::value_type_ref value_type_ref;
1112 typedef ImutAVLTree<ValInfo> TreeTy;
1113 typedef typename TreeTy::Factory FactoryTy;
1120 /// Constructs a set from a pointer to a tree root. In general one
1121 /// should use a Factory object to create sets instead of directly
1122 /// invoking the constructor, but there are cases where make this
1123 /// constructor public is useful.
1124 explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
1127 if (Root) { Root->retain(); }
1129 ImmutableSetRef(const ImmutableSetRef &X)
1131 Factory(X.Factory) {
1132 if (Root) { Root->retain(); }
1134 ImmutableSetRef &operator=(const ImmutableSetRef &X) {
1135 if (Root != X.Root) {
1136 if (X.Root) { X.Root->retain(); }
1137 if (Root) { Root->release(); }
1139 Factory = X.Factory;
1143 ~ImmutableSetRef() {
1144 if (Root) { Root->release(); }
1147 static ImmutableSetRef getEmptySet(FactoryTy *F) {
1148 return ImmutableSetRef(0, F);
1151 ImmutableSetRef add(value_type_ref V) {
1152 return ImmutableSetRef(Factory->add(Root, V), Factory);
1155 ImmutableSetRef remove(value_type_ref V) {
1156 return ImmutableSetRef(Factory->remove(Root, V), Factory);
1159 /// Returns true if the set contains the specified value.
1160 bool contains(value_type_ref V) const {
1161 return Root ? Root->contains(V) : false;
1164 ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1165 return ImmutableSet<ValT>(canonicalize ?
1166 Factory->getCanonicalTree(Root) : Root);
1169 TreeTy *getRootWithoutRetain() const {
1173 bool operator==(const ImmutableSetRef &RHS) const {
1174 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1177 bool operator!=(const ImmutableSetRef &RHS) const {
1178 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1181 /// isEmpty - Return true if the set contains no elements.
1182 bool isEmpty() const { return !Root; }
1184 /// isSingleton - Return true if the set contains exactly one element.
1185 /// This method runs in constant time.
1186 bool isSingleton() const { return getHeight() == 1; }
1188 //===--------------------------------------------------===//
1190 //===--------------------------------------------------===//
1192 typedef ImutAVLValueIterator<ImmutableSetRef> iterator;
1194 iterator begin() const { return iterator(Root); }
1195 iterator end() const { return iterator(); }
1197 //===--------------------------------------------------===//
1199 //===--------------------------------------------------===//
1201 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1203 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1204 ID.AddPointer(S.Root);
1207 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1209 //===--------------------------------------------------===//
1211 //===--------------------------------------------------===//
1213 void validateTree() const { if (Root) Root->validateTree(); }
1216 } // end namespace llvm