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/FoldingSet.h"
19 #include "llvm/System/DataTypes.h"
25 //===----------------------------------------------------------------------===//
26 // Immutable AVL-Tree Definition.
27 //===----------------------------------------------------------------------===//
29 template <typename ImutInfo> class ImutAVLFactory;
30 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
31 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
33 template <typename ImutInfo >
34 class ImutAVLTree : public FoldingSetNode {
36 typedef typename ImutInfo::key_type_ref key_type_ref;
37 typedef typename ImutInfo::value_type value_type;
38 typedef typename ImutInfo::value_type_ref value_type_ref;
40 typedef ImutAVLFactory<ImutInfo> Factory;
41 friend class ImutAVLFactory<ImutInfo>;
43 friend class ImutAVLTreeGenericIterator<ImutInfo>;
44 friend class FoldingSet<ImutAVLTree>;
46 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
48 //===----------------------------------------------------===//
50 //===----------------------------------------------------===//
52 /// getLeft - Returns a pointer to the left subtree. This value
53 /// is NULL if there is no left subtree.
54 ImutAVLTree *getLeft() const { return Left; }
56 /// getRight - Returns a pointer to the right subtree. This value is
57 /// NULL if there is no right subtree.
58 ImutAVLTree *getRight() const { return Right; }
60 /// getHeight - Returns the height of the tree. A tree with no subtrees
61 /// has a height of 1.
62 unsigned getHeight() const { return Height; }
64 /// getValue - Returns the data value associated with the tree node.
65 const value_type& getValue() const { return Value; }
67 /// find - Finds the subtree associated with the specified key value.
68 /// This method returns NULL if no matching subtree is found.
69 ImutAVLTree* find(key_type_ref K) {
70 ImutAVLTree *T = this;
73 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
75 if (ImutInfo::isEqual(K,CurrentKey))
77 else if (ImutInfo::isLess(K,CurrentKey))
86 /// getMaxElement - Find the subtree associated with the highest ranged
88 ImutAVLTree* getMaxElement() {
89 ImutAVLTree *T = this;
90 ImutAVLTree *Right = T->getRight();
91 while (Right) { T = Right; Right = T->getRight(); }
95 /// size - Returns the number of nodes in the tree, which includes
96 /// both leaves and non-leaf nodes.
97 unsigned size() const {
100 if (const ImutAVLTree* L = getLeft()) n += L->size();
101 if (const ImutAVLTree* R = getRight()) n += R->size();
106 /// begin - Returns an iterator that iterates over the nodes of the tree
107 /// in an inorder traversal. The returned iterator thus refers to the
108 /// the tree node with the minimum data element.
109 iterator begin() const { return iterator(this); }
111 /// end - Returns an iterator for the tree that denotes the end of an
112 /// inorder traversal.
113 iterator end() const { return iterator(); }
115 bool ElementEqual(value_type_ref V) const {
117 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
118 ImutInfo::KeyOfValue(V)))
121 // Also compare the data values.
122 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
123 ImutInfo::DataOfValue(V)))
129 bool ElementEqual(const ImutAVLTree* RHS) const {
130 return ElementEqual(RHS->getValue());
133 /// isEqual - Compares two trees for structural equality and returns true
134 /// if they are equal. This worst case performance of this operation is
135 // linear in the sizes of the trees.
136 bool isEqual(const ImutAVLTree& RHS) const {
140 iterator LItr = begin(), LEnd = end();
141 iterator RItr = RHS.begin(), REnd = RHS.end();
143 while (LItr != LEnd && RItr != REnd) {
144 if (*LItr == *RItr) {
150 if (!LItr->ElementEqual(*RItr))
157 return LItr == LEnd && RItr == REnd;
160 /// isNotEqual - Compares two trees for structural inequality. Performance
161 /// is the same is isEqual.
162 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
164 /// contains - Returns true if this tree contains a subtree (node) that
165 /// has an data element that matches the specified key. Complexity
166 /// is logarithmic in the size of the tree.
167 bool contains(key_type_ref K) { return (bool) find(K); }
169 /// foreach - A member template the accepts invokes operator() on a functor
170 /// object (specifed by Callback) for every node/subtree in the tree.
171 /// Nodes are visited using an inorder traversal.
172 template <typename Callback>
173 void foreach(Callback& C) {
174 if (ImutAVLTree* L = getLeft()) L->foreach(C);
178 if (ImutAVLTree* R = getRight()) R->foreach(C);
181 /// verify - A utility method that checks that the balancing and
182 /// ordering invariants of the tree are satisifed. It is a recursive
183 /// method that returns the height of the tree, which is then consumed
184 /// by the enclosing verify call. External callers should ignore the
185 /// return value. An invalid tree will cause an assertion to fire in
187 unsigned verify() const {
188 unsigned HL = getLeft() ? getLeft()->verify() : 0;
189 unsigned HR = getRight() ? getRight()->verify() : 0;
191 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
192 && "Height calculation wrong");
194 assert((HL > HR ? HL-HR : HR-HL) <= 2
195 && "Balancing invariant violated");
198 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
199 ImutInfo::KeyOfValue(getValue()))
200 && "Value in left child is not less that current value");
204 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
205 ImutInfo::KeyOfValue(getRight()->getValue()))
206 && "Current value is not less that value of right child");
211 /// Profile - Profiling for ImutAVLTree.
212 void Profile(llvm::FoldingSetNodeID& ID) {
213 ID.AddInteger(ComputeDigest());
216 //===----------------------------------------------------===//
218 //===----------------------------------------------------===//
223 unsigned Height : 28;
224 unsigned Mutable : 1;
225 unsigned CachedDigest : 1;
229 //===----------------------------------------------------===//
230 // Internal methods (node manipulation; used by Factory).
231 //===----------------------------------------------------===//
234 /// ImutAVLTree - Internal constructor that is only called by
236 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v,
238 : Left(l), Right(r), Height(height), Mutable(true), CachedDigest(false),
239 Value(v), Digest(0) {}
241 /// isMutable - Returns true if the left and right subtree references
242 /// (as well as height) can be changed. If this method returns false,
243 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
244 /// object should always have this method return true. Further, if this
245 /// method returns false for an instance of ImutAVLTree, all subtrees
246 /// will also have this method return false. The converse is not true.
247 bool isMutable() const { return Mutable; }
249 /// hasCachedDigest - Returns true if the digest for this tree is cached.
250 /// This can only be true if the tree is immutable.
251 bool hasCachedDigest() const { return CachedDigest; }
253 //===----------------------------------------------------===//
254 // Mutating operations. A tree root can be manipulated as
255 // long as its reference has not "escaped" from internal
256 // methods of a factory object (see below). When a tree
257 // pointer is externally viewable by client code, the
258 // internal "mutable bit" is cleared to mark the tree
259 // immutable. Note that a tree that still has its mutable
260 // bit set may have children (subtrees) that are themselves
262 //===----------------------------------------------------===//
264 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
265 /// it is an error to call setLeft(), setRight(), and setHeight().
266 void MarkImmutable() {
267 assert(isMutable() && "Mutable flag already removed.");
271 /// MarkedCachedDigest - Clears the NoCachedDigest flag for a tree.
272 void MarkedCachedDigest() {
273 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
277 /// setLeft - Changes the reference of the left subtree. Used internally
278 /// by ImutAVLFactory.
279 void setLeft(ImutAVLTree* NewLeft) {
280 assert(isMutable() &&
281 "Only a mutable tree can have its left subtree changed.");
283 CachedDigest = false;
286 /// setRight - Changes the reference of the right subtree. Used internally
287 /// by ImutAVLFactory.
288 void setRight(ImutAVLTree* NewRight) {
289 assert(isMutable() &&
290 "Only a mutable tree can have its right subtree changed.");
293 CachedDigest = false;
296 /// setHeight - Changes the height of the tree. Used internally by
298 void setHeight(unsigned h) {
299 assert(isMutable() && "Only a mutable tree can have its height changed.");
304 uint32_t ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
308 digest += L->ComputeDigest();
310 // Compute digest of stored data.
312 ImutInfo::Profile(ID,V);
313 digest += ID.ComputeHash();
316 digest += R->ComputeDigest();
321 inline uint32_t ComputeDigest() {
322 // Check the lowest bit to determine if digest has actually been
324 if (hasCachedDigest())
327 uint32_t X = ComputeDigest(getLeft(), getRight(), getValue());
329 MarkedCachedDigest();
334 //===----------------------------------------------------------------------===//
335 // Immutable AVL-Tree Factory class.
336 //===----------------------------------------------------------------------===//
338 template <typename ImutInfo >
339 class ImutAVLFactory {
340 typedef ImutAVLTree<ImutInfo> TreeTy;
341 typedef typename TreeTy::value_type_ref value_type_ref;
342 typedef typename TreeTy::key_type_ref key_type_ref;
344 typedef FoldingSet<TreeTy> CacheTy;
349 bool ownsAllocator() const {
350 return Allocator & 0x1 ? false : true;
353 BumpPtrAllocator& getAllocator() const {
354 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
357 //===--------------------------------------------------===//
359 //===--------------------------------------------------===//
363 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
365 ImutAVLFactory(BumpPtrAllocator& Alloc)
366 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
369 if (ownsAllocator()) delete &getAllocator();
372 TreeTy* Add(TreeTy* T, value_type_ref V) {
373 T = Add_internal(V,T);
378 TreeTy* Remove(TreeTy* T, key_type_ref V) {
379 T = Remove_internal(V,T);
384 TreeTy* GetEmptyTree() const { return NULL; }
386 //===--------------------------------------------------===//
387 // A bunch of quick helper functions used for reasoning
388 // about the properties of trees and their children.
389 // These have succinct names so that the balancing code
390 // is as terse (and readable) as possible.
391 //===--------------------------------------------------===//
394 bool isEmpty(TreeTy* T) const { return !T; }
395 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
396 TreeTy* Left(TreeTy* T) const { return T->getLeft(); }
397 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
398 value_type_ref Value(TreeTy* T) const { return T->Value; }
400 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
401 unsigned hl = Height(L);
402 unsigned hr = Height(R);
403 return (hl > hr ? hl : hr) + 1;
406 static bool CompareTreeWithSection(TreeTy* T,
407 typename TreeTy::iterator& TI,
408 typename TreeTy::iterator& TE) {
410 typename TreeTy::iterator I = T->begin(), E = T->end();
412 for ( ; I!=E ; ++I, ++TI)
413 if (TI == TE || !I->ElementEqual(*TI))
419 //===--------------------------------------------------===//
420 // "CreateNode" is used to generate new tree roots that link
421 // to other trees. The functon may also simply move links
422 // in an existing root if that root is still marked mutable.
423 // This is necessary because otherwise our balancing code
424 // would leak memory as it would create nodes that are
425 // then discarded later before the finished tree is
426 // returned to the caller.
427 //===--------------------------------------------------===//
429 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
430 BumpPtrAllocator& A = getAllocator();
431 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
432 new (T) TreeTy(L, R, V, IncrementHeight(L,R));
436 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
437 assert(!isEmpty(OldTree));
439 if (OldTree->isMutable()) {
441 OldTree->setRight(R);
442 OldTree->setHeight(IncrementHeight(L, R));
446 return CreateNode(L, Value(OldTree), R);
449 /// Balance - Used by Add_internal and Remove_internal to
450 /// balance a newly created tree.
451 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
453 unsigned hl = Height(L);
454 unsigned hr = Height(R);
457 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
459 TreeTy* LL = Left(L);
460 TreeTy* LR = Right(L);
462 if (Height(LL) >= Height(LR))
463 return CreateNode(LL, L, CreateNode(LR,V,R));
465 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
467 TreeTy* LRL = Left(LR);
468 TreeTy* LRR = Right(LR);
470 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
472 else if (hr > hl + 2) {
473 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
475 TreeTy* RL = Left(R);
476 TreeTy* RR = Right(R);
478 if (Height(RR) >= Height(RL))
479 return CreateNode(CreateNode(L,V,RL), R, RR);
481 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
483 TreeTy* RLL = Left(RL);
484 TreeTy* RLR = Right(RL);
486 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
489 return CreateNode(L,V,R);
492 /// Add_internal - Creates a new tree that includes the specified
493 /// data and the data from the original tree. If the original tree
494 /// already contained the data item, the original tree is returned.
495 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
497 return CreateNode(T, V, T);
499 assert(!T->isMutable());
501 key_type_ref K = ImutInfo::KeyOfValue(V);
502 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
504 if (ImutInfo::isEqual(K,KCurrent))
505 return CreateNode(Left(T), V, Right(T));
506 else if (ImutInfo::isLess(K,KCurrent))
507 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
509 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
512 /// Remove_internal - Creates a new tree that includes all the data
513 /// from the original tree except the specified data. If the
514 /// specified data did not exist in the original tree, the original
515 /// tree is returned.
516 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
520 assert(!T->isMutable());
522 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
524 if (ImutInfo::isEqual(K,KCurrent))
525 return CombineLeftRightTrees(Left(T),Right(T));
526 else if (ImutInfo::isLess(K,KCurrent))
527 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
529 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
532 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
533 if (isEmpty(L)) return R;
534 if (isEmpty(R)) return L;
537 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
538 return Balance(L,Value(OldNode),NewRight);
541 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
544 if (isEmpty(Left(T))) {
549 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
552 /// MarkImmutable - Clears the mutable bits of a root and all of its
554 void MarkImmutable(TreeTy* T) {
555 if (!T || !T->isMutable())
559 MarkImmutable(Left(T));
560 MarkImmutable(Right(T));
564 TreeTy *GetCanonicalTree(TreeTy *TNew) {
568 // Search the FoldingSet bucket for a Tree with the same digest.
570 unsigned digest = TNew->ComputeDigest();
571 ID.AddInteger(digest);
572 unsigned hash = ID.ComputeHash();
574 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
575 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
577 for (; I != E; ++I) {
580 if (T->ComputeDigest() != digest)
583 // We found a collision. Perform a comparison of Contents('T')
584 // with Contents('L')+'V'+Contents('R').
585 typename TreeTy::iterator TI = T->begin(), TE = T->end();
587 // First compare Contents('L') with the (initial) contents of T.
588 if (!CompareTreeWithSection(TNew->getLeft(), TI, TE))
591 // Now compare the new data element.
592 if (TI == TE || !TI->ElementEqual(TNew->getValue()))
597 // Now compare the remainder of 'T' with 'R'.
598 if (!CompareTreeWithSection(TNew->getRight(), TI, TE))
602 continue; // Contents('R') did not match suffix of 'T'.
604 // Trees did match! Return 'T'.
608 // 'TNew' is the only tree of its kind. Return it.
609 Cache.InsertNode(TNew, (void*) &*Cache.bucket_end(hash));
615 //===----------------------------------------------------------------------===//
616 // Immutable AVL-Tree Iterators.
617 //===----------------------------------------------------------------------===//
619 template <typename ImutInfo>
620 class ImutAVLTreeGenericIterator {
621 SmallVector<uintptr_t,20> stack;
623 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
626 typedef ImutAVLTree<ImutInfo> TreeTy;
627 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
629 inline ImutAVLTreeGenericIterator() {}
630 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
631 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
634 TreeTy* operator*() const {
635 assert(!stack.empty());
636 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
639 uintptr_t getVisitState() {
640 assert(!stack.empty());
641 return stack.back() & Flags;
645 bool AtEnd() const { return stack.empty(); }
647 bool AtBeginning() const {
648 return stack.size() == 1 && getVisitState() == VisitedNone;
651 void SkipToParent() {
652 assert(!stack.empty());
658 switch (getVisitState()) {
660 stack.back() |= VisitedLeft;
663 stack.back() |= VisitedRight;
666 assert(false && "Unreachable.");
670 inline bool operator==(const _Self& x) const {
671 if (stack.size() != x.stack.size())
674 for (unsigned i = 0 ; i < stack.size(); i++)
675 if (stack[i] != x.stack[i])
681 inline bool operator!=(const _Self& x) const { return !operator==(x); }
683 _Self& operator++() {
684 assert(!stack.empty());
686 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
689 switch (getVisitState()) {
691 if (TreeTy* L = Current->getLeft())
692 stack.push_back(reinterpret_cast<uintptr_t>(L));
694 stack.back() |= VisitedLeft;
699 if (TreeTy* R = Current->getRight())
700 stack.push_back(reinterpret_cast<uintptr_t>(R));
702 stack.back() |= VisitedRight;
711 assert(false && "Unreachable.");
717 _Self& operator--() {
718 assert(!stack.empty());
720 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
723 switch (getVisitState()) {
729 stack.back() &= ~Flags; // Set state to "VisitedNone."
731 if (TreeTy* L = Current->getLeft())
732 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
737 stack.back() &= ~Flags;
738 stack.back() |= VisitedLeft;
740 if (TreeTy* R = Current->getRight())
741 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
746 assert(false && "Unreachable.");
753 template <typename ImutInfo>
754 class ImutAVLTreeInOrderIterator {
755 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
756 InternalIteratorTy InternalItr;
759 typedef ImutAVLTree<ImutInfo> TreeTy;
760 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
762 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
763 if (Root) operator++(); // Advance to first element.
766 ImutAVLTreeInOrderIterator() : InternalItr() {}
768 inline bool operator==(const _Self& x) const {
769 return InternalItr == x.InternalItr;
772 inline bool operator!=(const _Self& x) const { return !operator==(x); }
774 inline TreeTy* operator*() const { return *InternalItr; }
775 inline TreeTy* operator->() const { return *InternalItr; }
777 inline _Self& operator++() {
779 while (!InternalItr.AtEnd() &&
780 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
785 inline _Self& operator--() {
787 while (!InternalItr.AtBeginning() &&
788 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
793 inline void SkipSubTree() {
794 InternalItr.SkipToParent();
796 while (!InternalItr.AtEnd() &&
797 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
802 //===----------------------------------------------------------------------===//
803 // Trait classes for Profile information.
804 //===----------------------------------------------------------------------===//
806 /// Generic profile template. The default behavior is to invoke the
807 /// profile method of an object. Specializations for primitive integers
808 /// and generic handling of pointers is done below.
809 template <typename T>
810 struct ImutProfileInfo {
811 typedef const T value_type;
812 typedef const T& value_type_ref;
814 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
815 FoldingSetTrait<T>::Profile(X,ID);
819 /// Profile traits for integers.
820 template <typename T>
821 struct ImutProfileInteger {
822 typedef const T value_type;
823 typedef const T& value_type_ref;
825 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
830 #define PROFILE_INTEGER_INFO(X)\
831 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
833 PROFILE_INTEGER_INFO(char)
834 PROFILE_INTEGER_INFO(unsigned char)
835 PROFILE_INTEGER_INFO(short)
836 PROFILE_INTEGER_INFO(unsigned short)
837 PROFILE_INTEGER_INFO(unsigned)
838 PROFILE_INTEGER_INFO(signed)
839 PROFILE_INTEGER_INFO(long)
840 PROFILE_INTEGER_INFO(unsigned long)
841 PROFILE_INTEGER_INFO(long long)
842 PROFILE_INTEGER_INFO(unsigned long long)
844 #undef PROFILE_INTEGER_INFO
846 /// Generic profile trait for pointer types. We treat pointers as
847 /// references to unique objects.
848 template <typename T>
849 struct ImutProfileInfo<T*> {
850 typedef const T* value_type;
851 typedef value_type value_type_ref;
853 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
858 //===----------------------------------------------------------------------===//
859 // Trait classes that contain element comparison operators and type
860 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
861 // inherit from the profile traits (ImutProfileInfo) to include operations
862 // for element profiling.
863 //===----------------------------------------------------------------------===//
866 /// ImutContainerInfo - Generic definition of comparison operations for
867 /// elements of immutable containers that defaults to using
868 /// std::equal_to<> and std::less<> to perform comparison of elements.
869 template <typename T>
870 struct ImutContainerInfo : public ImutProfileInfo<T> {
871 typedef typename ImutProfileInfo<T>::value_type value_type;
872 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
873 typedef value_type key_type;
874 typedef value_type_ref key_type_ref;
875 typedef bool data_type;
876 typedef bool data_type_ref;
878 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
879 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
881 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
882 return std::equal_to<key_type>()(LHS,RHS);
885 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
886 return std::less<key_type>()(LHS,RHS);
889 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
892 /// ImutContainerInfo - Specialization for pointer values to treat pointers
893 /// as references to unique objects. Pointers are thus compared by
895 template <typename T>
896 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
897 typedef typename ImutProfileInfo<T*>::value_type value_type;
898 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
899 typedef value_type key_type;
900 typedef value_type_ref key_type_ref;
901 typedef bool data_type;
902 typedef bool data_type_ref;
904 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
905 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
907 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
911 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
915 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
918 //===----------------------------------------------------------------------===//
920 //===----------------------------------------------------------------------===//
922 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
925 typedef typename ValInfo::value_type value_type;
926 typedef typename ValInfo::value_type_ref value_type_ref;
927 typedef ImutAVLTree<ValInfo> TreeTy;
933 /// Constructs a set from a pointer to a tree root. In general one
934 /// should use a Factory object to create sets instead of directly
935 /// invoking the constructor, but there are cases where make this
936 /// constructor public is useful.
937 explicit ImmutableSet(TreeTy* R) : Root(R) {}
940 typename TreeTy::Factory F;
941 const bool Canonicalize;
944 Factory(bool canonicalize = true)
945 : Canonicalize(canonicalize) {}
947 Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
948 : F(Alloc), Canonicalize(canonicalize) {}
950 /// GetEmptySet - Returns an immutable set that contains no elements.
951 ImmutableSet GetEmptySet() {
952 return ImmutableSet(F.GetEmptyTree());
955 /// Add - Creates a new immutable set that contains all of the values
956 /// of the original set with the addition of the specified value. If
957 /// the original set already included the value, then the original set is
958 /// returned and no memory is allocated. The time and space complexity
959 /// of this operation is logarithmic in the size of the original set.
960 /// The memory allocated to represent the set is released when the
961 /// factory object that created the set is destroyed.
962 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
963 TreeTy *NewT = F.Add(Old.Root, V);
964 return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
967 /// Remove - Creates a new immutable set that contains all of the values
968 /// of the original set with the exception of the specified value. If
969 /// the original set did not contain the value, the original set is
970 /// returned and no memory is allocated. The time and space complexity
971 /// of this operation is logarithmic in the size of the original set.
972 /// The memory allocated to represent the set is released when the
973 /// factory object that created the set is destroyed.
974 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
975 TreeTy *NewT = F.Remove(Old.Root, V);
976 return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
979 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
982 Factory(const Factory& RHS); // DO NOT IMPLEMENT
983 void operator=(const Factory& RHS); // DO NOT IMPLEMENT
986 friend class Factory;
988 /// contains - Returns true if the set contains the specified value.
989 bool contains(value_type_ref V) const {
990 return Root ? Root->contains(V) : false;
993 bool operator==(ImmutableSet RHS) const {
994 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
997 bool operator!=(ImmutableSet RHS) const {
998 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1005 /// isEmpty - Return true if the set contains no elements.
1006 bool isEmpty() const { return !Root; }
1008 /// isSingleton - Return true if the set contains exactly one element.
1009 /// This method runs in constant time.
1010 bool isSingleton() const { return getHeight() == 1; }
1012 template <typename Callback>
1013 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1015 template <typename Callback>
1016 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1018 //===--------------------------------------------------===//
1020 //===--------------------------------------------------===//
1023 typename TreeTy::iterator itr;
1024 iterator(TreeTy* t) : itr(t) {}
1025 friend class ImmutableSet<ValT,ValInfo>;
1028 inline value_type_ref operator*() const { return itr->getValue(); }
1029 inline iterator& operator++() { ++itr; return *this; }
1030 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1031 inline iterator& operator--() { --itr; return *this; }
1032 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1033 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1034 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1035 inline value_type *operator->() const { return &(operator*()); }
1038 iterator begin() const { return iterator(Root); }
1039 iterator end() const { return iterator(); }
1041 //===--------------------------------------------------===//
1043 //===--------------------------------------------------===//
1045 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1047 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1048 ID.AddPointer(S.Root);
1051 inline void Profile(FoldingSetNodeID& ID) const {
1052 return Profile(ID,*this);
1055 //===--------------------------------------------------===//
1057 //===--------------------------------------------------===//
1059 void verify() const { if (Root) Root->verify(); }
1062 } // end namespace llvm