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_IMSET_H
15 #define LLVM_ADT_IMSET_H
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/Support/DataTypes.h"
21 #include "llvm/Support/ErrorHandling.h"
29 //===----------------------------------------------------------------------===//
30 // Immutable AVL-Tree Definition.
31 //===----------------------------------------------------------------------===//
33 template <typename ImutInfo> class ImutAVLFactory;
34 template <typename ImutInfo> class ImutIntervalAVLFactory;
35 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
36 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
38 template <typename ImutInfo >
41 typedef typename ImutInfo::key_type_ref key_type_ref;
42 typedef typename ImutInfo::value_type value_type;
43 typedef typename ImutInfo::value_type_ref value_type_ref;
45 typedef ImutAVLFactory<ImutInfo> Factory;
46 friend class ImutAVLFactory<ImutInfo>;
47 friend class ImutIntervalAVLFactory<ImutInfo>;
49 friend class ImutAVLTreeGenericIterator<ImutInfo>;
51 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
53 //===----------------------------------------------------===//
55 //===----------------------------------------------------===//
57 /// Return a pointer to the left subtree. This value
58 /// is NULL if there is no left subtree.
59 ImutAVLTree *getLeft() const { return left; }
61 /// Return a pointer to the right subtree. This value is
62 /// NULL if there is no right subtree.
63 ImutAVLTree *getRight() const { return right; }
65 /// getHeight - Returns the height of the tree. A tree with no subtrees
66 /// has a height of 1.
67 unsigned getHeight() const { return height; }
69 /// getValue - Returns the data value associated with the tree node.
70 const value_type& getValue() const { return value; }
72 /// find - Finds the subtree associated with the specified key value.
73 /// This method returns NULL if no matching subtree is found.
74 ImutAVLTree* find(key_type_ref K) {
75 ImutAVLTree *T = this;
77 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
78 if (ImutInfo::isEqual(K,CurrentKey))
80 else if (ImutInfo::isLess(K,CurrentKey))
88 /// getMaxElement - Find the subtree associated with the highest ranged
90 ImutAVLTree* getMaxElement() {
91 ImutAVLTree *T = this;
92 ImutAVLTree *Right = T->getRight();
93 while (Right) { T = right; right = T->getRight(); }
97 /// size - Returns the number of nodes in the tree, which includes
98 /// both leaves and non-leaf nodes.
99 unsigned size() const {
101 if (const ImutAVLTree* L = getLeft())
103 if (const ImutAVLTree* R = getRight())
108 /// begin - Returns an iterator that iterates over the nodes of the tree
109 /// in an inorder traversal. The returned iterator thus refers to the
110 /// the tree node with the minimum data element.
111 iterator begin() const { return iterator(this); }
113 /// end - Returns an iterator for the tree that denotes the end of an
114 /// inorder traversal.
115 iterator end() const { return iterator(); }
117 bool isElementEqual(value_type_ref V) const {
119 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
120 ImutInfo::KeyOfValue(V)))
123 // Also compare the data values.
124 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
125 ImutInfo::DataOfValue(V)))
131 bool isElementEqual(const ImutAVLTree* RHS) const {
132 return isElementEqual(RHS->getValue());
135 /// isEqual - Compares two trees for structural equality and returns true
136 /// if they are equal. This worst case performance of this operation is
137 // linear in the sizes of the trees.
138 bool isEqual(const ImutAVLTree& RHS) const {
142 iterator LItr = begin(), LEnd = end();
143 iterator RItr = RHS.begin(), REnd = RHS.end();
145 while (LItr != LEnd && RItr != REnd) {
146 if (*LItr == *RItr) {
152 if (!LItr->isElementEqual(*RItr))
159 return LItr == LEnd && RItr == REnd;
162 /// isNotEqual - Compares two trees for structural inequality. Performance
163 /// is the same is isEqual.
164 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
166 /// contains - Returns true if this tree contains a subtree (node) that
167 /// has an data element that matches the specified key. Complexity
168 /// is logarithmic in the size of the tree.
169 bool contains(key_type_ref K) { return (bool) find(K); }
171 /// foreach - A member template the accepts invokes operator() on a functor
172 /// object (specifed by Callback) for every node/subtree in the tree.
173 /// Nodes are visited using an inorder traversal.
174 template <typename Callback>
175 void foreach(Callback& C) {
176 if (ImutAVLTree* L = getLeft())
181 if (ImutAVLTree* R = getRight())
185 /// validateTree - A utility method that checks that the balancing and
186 /// ordering invariants of the tree are satisifed. It is a recursive
187 /// method that returns the height of the tree, which is then consumed
188 /// by the enclosing validateTree call. External callers should ignore the
189 /// return value. An invalid tree will cause an assertion to fire in
191 unsigned validateTree() const {
192 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
193 unsigned HR = getRight() ? getRight()->validateTree() : 0;
197 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
198 && "Height calculation wrong");
200 assert((HL > HR ? HL-HR : HR-HL) <= 2
201 && "Balancing invariant violated");
203 assert((!getLeft() ||
204 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
205 ImutInfo::KeyOfValue(getValue()))) &&
206 "Value in left child is not less that current value");
209 assert(!(getRight() ||
210 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
211 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
212 "Current value is not less that value of right child");
217 //===----------------------------------------------------===//
219 //===----------------------------------------------------===//
228 unsigned height : 28;
229 unsigned IsMutable : 1;
230 unsigned IsDigestCached : 1;
231 unsigned IsCanonicalized : 1;
237 //===----------------------------------------------------===//
238 // Internal methods (node manipulation; used by Factory).
239 //===----------------------------------------------------===//
242 /// ImutAVLTree - Internal constructor that is only called by
244 ImutAVLTree(Factory *f, ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
246 : factory(f), left(l), right(r), prev(0), next(0), height(height),
247 IsMutable(true), IsDigestCached(false), IsCanonicalized(0),
248 value(v), digest(0), refCount(0)
250 if (left) left->retain();
251 if (right) right->retain();
254 /// isMutable - Returns true if the left and right subtree references
255 /// (as well as height) can be changed. If this method returns false,
256 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
257 /// object should always have this method return true. Further, if this
258 /// method returns false for an instance of ImutAVLTree, all subtrees
259 /// will also have this method return false. The converse is not true.
260 bool isMutable() const { return IsMutable; }
262 /// hasCachedDigest - Returns true if the digest for this tree is cached.
263 /// This can only be true if the tree is immutable.
264 bool hasCachedDigest() const { return IsDigestCached; }
266 //===----------------------------------------------------===//
267 // Mutating operations. A tree root can be manipulated as
268 // long as its reference has not "escaped" from internal
269 // methods of a factory object (see below). When a tree
270 // pointer is externally viewable by client code, the
271 // internal "mutable bit" is cleared to mark the tree
272 // immutable. Note that a tree that still has its mutable
273 // bit set may have children (subtrees) that are themselves
275 //===----------------------------------------------------===//
277 /// markImmutable - Clears the mutable flag for a tree. After this happens,
278 /// it is an error to call setLeft(), setRight(), and setHeight().
279 void markImmutable() {
280 assert(isMutable() && "Mutable flag already removed.");
284 /// markedCachedDigest - Clears the NoCachedDigest flag for a tree.
285 void markedCachedDigest() {
286 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
287 IsDigestCached = true;
290 /// setHeight - Changes the height of the tree. Used internally by
292 void setHeight(unsigned h) {
293 assert(isMutable() && "Only a mutable tree can have its height changed.");
298 uint32_t computeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
302 digest += L->computeDigest();
304 // Compute digest of stored data.
306 ImutInfo::Profile(ID,V);
307 digest += ID.ComputeHash();
310 digest += R->computeDigest();
315 inline uint32_t computeDigest() {
316 // Check the lowest bit to determine if digest has actually been
318 if (hasCachedDigest())
321 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
323 markedCachedDigest();
327 //===----------------------------------------------------===//
328 // Reference count operations.
329 //===----------------------------------------------------===//
332 void retain() { ++refCount; }
334 assert(refCount > 0);
343 if (IsCanonicalized) {
350 factory->Cache[computeDigest()] = next;
353 // We need to clear the mutability bit in case we are
354 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
356 factory->freeNodes.push_back(this);
360 //===----------------------------------------------------------------------===//
361 // Immutable AVL-Tree Factory class.
362 //===----------------------------------------------------------------------===//
364 template <typename ImutInfo >
365 class ImutAVLFactory {
366 friend class ImutAVLTree<ImutInfo>;
367 typedef ImutAVLTree<ImutInfo> TreeTy;
368 typedef typename TreeTy::value_type_ref value_type_ref;
369 typedef typename TreeTy::key_type_ref key_type_ref;
371 typedef DenseMap<unsigned, TreeTy*> CacheTy;
375 std::vector<TreeTy*> createdNodes;
376 std::vector<TreeTy*> freeNodes;
378 bool ownsAllocator() const {
379 return Allocator & 0x1 ? false : true;
382 BumpPtrAllocator& getAllocator() const {
383 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
386 //===--------------------------------------------------===//
388 //===--------------------------------------------------===//
392 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
394 ImutAVLFactory(BumpPtrAllocator& Alloc)
395 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
398 if (ownsAllocator()) delete &getAllocator();
401 TreeTy* add(TreeTy* T, value_type_ref V) {
402 T = add_internal(V,T);
408 TreeTy* remove(TreeTy* T, key_type_ref V) {
409 T = remove_internal(V,T);
415 TreeTy* getEmptyTree() const { return NULL; }
419 //===--------------------------------------------------===//
420 // A bunch of quick helper functions used for reasoning
421 // about the properties of trees and their children.
422 // These have succinct names so that the balancing code
423 // is as terse (and readable) as possible.
424 //===--------------------------------------------------===//
426 bool isEmpty(TreeTy* T) const { return !T; }
427 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
428 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
429 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
430 value_type_ref getValue(TreeTy* T) const { return T->value; }
432 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
433 unsigned hl = getHeight(L);
434 unsigned hr = getHeight(R);
435 return (hl > hr ? hl : hr) + 1;
438 static bool compareTreeWithSection(TreeTy* T,
439 typename TreeTy::iterator& TI,
440 typename TreeTy::iterator& TE) {
441 typename TreeTy::iterator I = T->begin(), E = T->end();
442 for ( ; I!=E ; ++I, ++TI) {
443 if (TI == TE || !I->isElementEqual(*TI))
449 //===--------------------------------------------------===//
450 // "createNode" is used to generate new tree roots that link
451 // to other trees. The functon may also simply move links
452 // in an existing root if that root is still marked mutable.
453 // This is necessary because otherwise our balancing code
454 // would leak memory as it would create nodes that are
455 // then discarded later before the finished tree is
456 // returned to the caller.
457 //===--------------------------------------------------===//
459 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
460 BumpPtrAllocator& A = getAllocator();
462 if (!freeNodes.empty()) {
463 T = freeNodes.back();
464 freeNodes.pop_back();
469 T = (TreeTy*) A.Allocate<TreeTy>();
471 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
472 createdNodes.push_back(T);
476 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
477 return createNode(newLeft, getValue(oldTree), newRight);
480 void recoverNodes() {
481 for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
482 TreeTy *N = createdNodes[i];
483 if (N->isMutable() && N->refCount == 0)
486 createdNodes.clear();
489 /// balanceTree - Used by add_internal and remove_internal to
490 /// balance a newly created tree.
491 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
492 unsigned hl = getHeight(L);
493 unsigned hr = getHeight(R);
496 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
498 TreeTy *LL = getLeft(L);
499 TreeTy *LR = getRight(L);
501 if (getHeight(LL) >= getHeight(LR))
502 return createNode(LL, L, createNode(LR,V,R));
504 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
506 TreeTy *LRL = getLeft(LR);
507 TreeTy *LRR = getRight(LR);
509 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
511 else if (hr > hl + 2) {
512 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
514 TreeTy *RL = getLeft(R);
515 TreeTy *RR = getRight(R);
517 if (getHeight(RR) >= getHeight(RL))
518 return createNode(createNode(L,V,RL), R, RR);
520 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
522 TreeTy *RLL = getLeft(RL);
523 TreeTy *RLR = getRight(RL);
525 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
528 return createNode(L,V,R);
531 /// add_internal - Creates a new tree that includes the specified
532 /// data and the data from the original tree. If the original tree
533 /// already contained the data item, the original tree is returned.
534 TreeTy* add_internal(value_type_ref V, TreeTy* T) {
536 return createNode(T, V, T);
537 assert(!T->isMutable());
539 key_type_ref K = ImutInfo::KeyOfValue(V);
540 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
542 if (ImutInfo::isEqual(K,KCurrent))
543 return createNode(getLeft(T), V, getRight(T));
544 else if (ImutInfo::isLess(K,KCurrent))
545 return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
547 return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
550 /// remove_internal - Creates a new tree that includes all the data
551 /// from the original tree except the specified data. If the
552 /// specified data did not exist in the original tree, the original
553 /// tree is returned.
554 TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
558 assert(!T->isMutable());
560 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
562 if (ImutInfo::isEqual(K,KCurrent)) {
563 return combineTrees(getLeft(T), getRight(T));
564 } else if (ImutInfo::isLess(K,KCurrent)) {
565 return balanceTree(remove_internal(K, getLeft(T)),
566 getValue(T), getRight(T));
568 return balanceTree(getLeft(T), getValue(T),
569 remove_internal(K, getRight(T)));
573 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
579 TreeTy* newRight = removeMinBinding(R,OldNode);
580 return balanceTree(L, getValue(OldNode), newRight);
583 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
585 if (isEmpty(getLeft(T))) {
589 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
590 getValue(T), getRight(T));
593 /// markImmutable - Clears the mutable bits of a root and all of its
595 void markImmutable(TreeTy* T) {
596 if (!T || !T->isMutable())
599 markImmutable(getLeft(T));
600 markImmutable(getRight(T));
604 TreeTy *getCanonicalTree(TreeTy *TNew) {
608 if (TNew->IsCanonicalized)
611 // Search the hashtable for another tree with the same digest, and
612 // if find a collision compare those trees by their contents.
613 unsigned digest = TNew->computeDigest();
614 TreeTy *&entry = Cache[digest];
618 for (TreeTy *T = entry ; T != 0; T = T->next) {
619 // Compare the Contents('T') with Contents('TNew')
620 typename TreeTy::iterator TI = T->begin(), TE = T->end();
621 if (!compareTreeWithSection(TNew, TI, TE))
624 continue; // T has more contents than TNew.
625 // Trees did match! Return 'T'.
626 if (TNew->refCount == 0)
636 TNew->IsCanonicalized = true;
641 //===----------------------------------------------------------------------===//
642 // Immutable AVL-Tree Iterators.
643 //===----------------------------------------------------------------------===//
645 template <typename ImutInfo>
646 class ImutAVLTreeGenericIterator {
647 SmallVector<uintptr_t,20> stack;
649 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
652 typedef ImutAVLTree<ImutInfo> TreeTy;
653 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
655 inline ImutAVLTreeGenericIterator() {}
656 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
657 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
660 TreeTy* operator*() const {
661 assert(!stack.empty());
662 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
665 uintptr_t getVisitState() {
666 assert(!stack.empty());
667 return stack.back() & Flags;
671 bool atEnd() const { return stack.empty(); }
673 bool atBeginning() const {
674 return stack.size() == 1 && getVisitState() == VisitedNone;
677 void skipToParent() {
678 assert(!stack.empty());
682 switch (getVisitState()) {
684 stack.back() |= VisitedLeft;
687 stack.back() |= VisitedRight;
690 llvm_unreachable("Unreachable.");
694 inline bool operator==(const _Self& x) const {
695 if (stack.size() != x.stack.size())
697 for (unsigned i = 0 ; i < stack.size(); i++)
698 if (stack[i] != x.stack[i])
703 inline bool operator!=(const _Self& x) const { return !operator==(x); }
705 _Self& operator++() {
706 assert(!stack.empty());
707 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
709 switch (getVisitState()) {
711 if (TreeTy* L = Current->getLeft())
712 stack.push_back(reinterpret_cast<uintptr_t>(L));
714 stack.back() |= VisitedLeft;
717 if (TreeTy* R = Current->getRight())
718 stack.push_back(reinterpret_cast<uintptr_t>(R));
720 stack.back() |= VisitedRight;
726 llvm_unreachable("Unreachable.");
731 _Self& operator--() {
732 assert(!stack.empty());
733 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
735 switch (getVisitState()) {
740 stack.back() &= ~Flags; // Set state to "VisitedNone."
741 if (TreeTy* L = Current->getLeft())
742 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
745 stack.back() &= ~Flags;
746 stack.back() |= VisitedLeft;
747 if (TreeTy* R = Current->getRight())
748 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
751 llvm_unreachable("Unreachable.");
757 template <typename ImutInfo>
758 class ImutAVLTreeInOrderIterator {
759 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
760 InternalIteratorTy InternalItr;
763 typedef ImutAVLTree<ImutInfo> TreeTy;
764 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
766 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
767 if (Root) operator++(); // Advance to first element.
770 ImutAVLTreeInOrderIterator() : InternalItr() {}
772 inline bool operator==(const _Self& x) const {
773 return InternalItr == x.InternalItr;
776 inline bool operator!=(const _Self& x) const { return !operator==(x); }
778 inline TreeTy* operator*() const { return *InternalItr; }
779 inline TreeTy* operator->() const { return *InternalItr; }
781 inline _Self& operator++() {
783 while (!InternalItr.atEnd() &&
784 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
789 inline _Self& operator--() {
791 while (!InternalItr.atBeginning() &&
792 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
797 inline void skipSubTree() {
798 InternalItr.skipToParent();
800 while (!InternalItr.atEnd() &&
801 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
806 //===----------------------------------------------------------------------===//
807 // Trait classes for Profile information.
808 //===----------------------------------------------------------------------===//
810 /// Generic profile template. The default behavior is to invoke the
811 /// profile method of an object. Specializations for primitive integers
812 /// and generic handling of pointers is done below.
813 template <typename T>
814 struct ImutProfileInfo {
815 typedef const T value_type;
816 typedef const T& value_type_ref;
818 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
819 FoldingSetTrait<T>::Profile(X,ID);
823 /// Profile traits for integers.
824 template <typename T>
825 struct ImutProfileInteger {
826 typedef const T value_type;
827 typedef const T& value_type_ref;
829 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
834 #define PROFILE_INTEGER_INFO(X)\
835 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
837 PROFILE_INTEGER_INFO(char)
838 PROFILE_INTEGER_INFO(unsigned char)
839 PROFILE_INTEGER_INFO(short)
840 PROFILE_INTEGER_INFO(unsigned short)
841 PROFILE_INTEGER_INFO(unsigned)
842 PROFILE_INTEGER_INFO(signed)
843 PROFILE_INTEGER_INFO(long)
844 PROFILE_INTEGER_INFO(unsigned long)
845 PROFILE_INTEGER_INFO(long long)
846 PROFILE_INTEGER_INFO(unsigned long long)
848 #undef PROFILE_INTEGER_INFO
850 /// Generic profile trait for pointer types. We treat pointers as
851 /// references to unique objects.
852 template <typename T>
853 struct ImutProfileInfo<T*> {
854 typedef const T* value_type;
855 typedef value_type value_type_ref;
857 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
862 //===----------------------------------------------------------------------===//
863 // Trait classes that contain element comparison operators and type
864 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
865 // inherit from the profile traits (ImutProfileInfo) to include operations
866 // for element profiling.
867 //===----------------------------------------------------------------------===//
870 /// ImutContainerInfo - Generic definition of comparison operations for
871 /// elements of immutable containers that defaults to using
872 /// std::equal_to<> and std::less<> to perform comparison of elements.
873 template <typename T>
874 struct ImutContainerInfo : public ImutProfileInfo<T> {
875 typedef typename ImutProfileInfo<T>::value_type value_type;
876 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
877 typedef value_type key_type;
878 typedef value_type_ref key_type_ref;
879 typedef bool data_type;
880 typedef bool data_type_ref;
882 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
883 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
885 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
886 return std::equal_to<key_type>()(LHS,RHS);
889 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
890 return std::less<key_type>()(LHS,RHS);
893 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
896 /// ImutContainerInfo - Specialization for pointer values to treat pointers
897 /// as references to unique objects. Pointers are thus compared by
899 template <typename T>
900 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
901 typedef typename ImutProfileInfo<T*>::value_type value_type;
902 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
903 typedef value_type key_type;
904 typedef value_type_ref key_type_ref;
905 typedef bool data_type;
906 typedef bool data_type_ref;
908 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
909 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
911 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
915 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
919 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
922 //===----------------------------------------------------------------------===//
924 //===----------------------------------------------------------------------===//
926 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
929 typedef typename ValInfo::value_type value_type;
930 typedef typename ValInfo::value_type_ref value_type_ref;
931 typedef ImutAVLTree<ValInfo> TreeTy;
937 /// Constructs a set from a pointer to a tree root. In general one
938 /// should use a Factory object to create sets instead of directly
939 /// invoking the constructor, but there are cases where make this
940 /// constructor public is useful.
941 explicit ImmutableSet(TreeTy* R) : Root(R) {
942 if (Root) { Root->retain(); }
944 ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
945 if (Root) { Root->retain(); }
947 ImmutableSet &operator=(const ImmutableSet &X) {
948 if (Root != X.Root) {
949 if (X.Root) { X.Root->retain(); }
950 if (Root) { Root->release(); }
956 if (Root) { Root->release(); }
960 typename TreeTy::Factory F;
961 const bool Canonicalize;
964 Factory(bool canonicalize = true)
965 : Canonicalize(canonicalize) {}
967 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
968 : F(Alloc), Canonicalize(canonicalize) {}
970 /// getEmptySet - Returns an immutable set that contains no elements.
971 ImmutableSet getEmptySet() {
972 return ImmutableSet(F.getEmptyTree());
975 /// add - Creates a new immutable set that contains all of the values
976 /// of the original set with the addition of the specified value. If
977 /// the original set already included the value, then the original set is
978 /// returned and no memory is allocated. The time and space complexity
979 /// of this operation is logarithmic in the size of the original set.
980 /// The memory allocated to represent the set is released when the
981 /// factory object that created the set is destroyed.
982 ImmutableSet add(ImmutableSet Old, value_type_ref V) {
983 TreeTy *NewT = F.add(Old.Root, V);
984 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
987 /// remove - Creates a new immutable set that contains all of the values
988 /// of the original set with the exception of the specified value. If
989 /// the original set did not contain the value, the original set is
990 /// returned and no memory is allocated. The time and space complexity
991 /// of this operation is logarithmic in the size of the original set.
992 /// The memory allocated to represent the set is released when the
993 /// factory object that created the set is destroyed.
994 ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
995 TreeTy *NewT = F.remove(Old.Root, V);
996 return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
999 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1001 typename TreeTy::Factory *getTreeFactory() const {
1002 return const_cast<typename TreeTy::Factory *>(&F);
1006 Factory(const Factory& RHS); // DO NOT IMPLEMENT
1007 void operator=(const Factory& RHS); // DO NOT IMPLEMENT
1010 friend class Factory;
1012 /// Returns true if the set contains the specified value.
1013 bool contains(value_type_ref V) const {
1014 return Root ? Root->contains(V) : false;
1017 bool operator==(const ImmutableSet &RHS) const {
1018 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1021 bool operator!=(const ImmutableSet &RHS) const {
1022 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1026 if (Root) { Root->retain(); }
1030 TreeTy *getRootWithoutRetain() const {
1034 /// isEmpty - Return true if the set contains no elements.
1035 bool isEmpty() const { return !Root; }
1037 /// isSingleton - Return true if the set contains exactly one element.
1038 /// This method runs in constant time.
1039 bool isSingleton() const { return getHeight() == 1; }
1041 template <typename Callback>
1042 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1044 template <typename Callback>
1045 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1047 //===--------------------------------------------------===//
1049 //===--------------------------------------------------===//
1052 typename TreeTy::iterator itr;
1053 iterator(TreeTy* t) : itr(t) {}
1054 friend class ImmutableSet<ValT,ValInfo>;
1057 inline value_type_ref operator*() const { return itr->getValue(); }
1058 inline iterator& operator++() { ++itr; return *this; }
1059 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1060 inline iterator& operator--() { --itr; return *this; }
1061 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1062 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1063 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1064 inline value_type *operator->() const { return &(operator*()); }
1067 iterator begin() const { return iterator(Root); }
1068 iterator end() const { return iterator(); }
1070 //===--------------------------------------------------===//
1072 //===--------------------------------------------------===//
1074 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1076 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1077 ID.AddPointer(S.Root);
1080 inline void Profile(FoldingSetNodeID& ID) const {
1081 return Profile(ID,*this);
1084 //===--------------------------------------------------===//
1086 //===--------------------------------------------------===//
1088 void validateTree() const { if (Root) Root->validateTree(); }
1091 // NOTE: This may some day replace the current ImmutableSet.
1092 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
1093 class ImmutableSetRef {
1095 typedef typename ValInfo::value_type value_type;
1096 typedef typename ValInfo::value_type_ref value_type_ref;
1097 typedef ImutAVLTree<ValInfo> TreeTy;
1098 typedef typename TreeTy::Factory FactoryTy;
1105 /// Constructs a set from a pointer to a tree root. In general one
1106 /// should use a Factory object to create sets instead of directly
1107 /// invoking the constructor, but there are cases where make this
1108 /// constructor public is useful.
1109 explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
1112 if (Root) { Root->retain(); }
1114 ImmutableSetRef(const ImmutableSetRef &X)
1116 Factory(X.Factory) {
1117 if (Root) { Root->retain(); }
1119 ImmutableSetRef &operator=(const ImmutableSetRef &X) {
1120 if (Root != X.Root) {
1121 if (X.Root) { X.Root->retain(); }
1122 if (Root) { Root->release(); }
1124 Factory = X.Factory;
1128 ~ImmutableSetRef() {
1129 if (Root) { Root->release(); }
1132 static inline ImmutableSetRef getEmptySet(FactoryTy *F) {
1133 return ImmutableSetRef(0, F);
1136 ImmutableSetRef add(value_type_ref V) {
1137 return ImmutableSetRef(Factory->add(Root, V), Factory);
1140 ImmutableSetRef remove(value_type_ref V) {
1141 return ImmutableSetRef(Factory->remove(Root, V), Factory);
1144 /// Returns true if the set contains the specified value.
1145 bool contains(value_type_ref V) const {
1146 return Root ? Root->contains(V) : false;
1149 ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1150 return ImmutableSet<ValT>(canonicalize ?
1151 Factory->getCanonicalTree(Root) : Root);
1154 TreeTy *getRootWithoutRetain() const {
1158 bool operator==(const ImmutableSetRef &RHS) const {
1159 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1162 bool operator!=(const ImmutableSetRef &RHS) const {
1163 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1166 /// isEmpty - Return true if the set contains no elements.
1167 bool isEmpty() const { return !Root; }
1169 /// isSingleton - Return true if the set contains exactly one element.
1170 /// This method runs in constant time.
1171 bool isSingleton() const { return getHeight() == 1; }
1173 //===--------------------------------------------------===//
1175 //===--------------------------------------------------===//
1178 typename TreeTy::iterator itr;
1179 iterator(TreeTy* t) : itr(t) {}
1180 friend class ImmutableSetRef<ValT,ValInfo>;
1183 inline value_type_ref operator*() const { return itr->getValue(); }
1184 inline iterator& operator++() { ++itr; return *this; }
1185 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1186 inline iterator& operator--() { --itr; return *this; }
1187 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1188 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1189 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1190 inline value_type *operator->() const { return &(operator*()); }
1193 iterator begin() const { return iterator(Root); }
1194 iterator end() const { return iterator(); }
1196 //===--------------------------------------------------===//
1198 //===--------------------------------------------------===//
1200 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1202 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSetRef& S) {
1203 ID.AddPointer(S.Root);
1206 inline void Profile(FoldingSetNodeID& ID) const {
1207 return Profile(ID,*this);
1210 //===--------------------------------------------------===//
1212 //===--------------------------------------------------===//
1214 void validateTree() const { if (Root) Root->validateTree(); }
1217 } // end namespace llvm