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"
23 //===----------------------------------------------------------------------===//
24 // Immutable AVL-Tree Definition.
25 //===----------------------------------------------------------------------===//
27 template <typename ImutInfo> class ImutAVLFactory;
28 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
29 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
31 template <typename ImutInfo >
32 class ImutAVLTree : public FoldingSetNode {
34 typedef typename ImutInfo::key_type_ref key_type_ref;
35 typedef typename ImutInfo::value_type value_type;
36 typedef typename ImutInfo::value_type_ref value_type_ref;
38 typedef ImutAVLFactory<ImutInfo> Factory;
39 friend class ImutAVLFactory<ImutInfo>;
41 friend class ImutAVLTreeGenericIterator<ImutInfo>;
42 friend class FoldingSet<ImutAVLTree>;
44 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
46 //===----------------------------------------------------===//
48 //===----------------------------------------------------===//
50 /// getLeft - Returns a pointer to the left subtree. This value
51 /// is NULL if there is no left subtree.
52 ImutAVLTree* getLeft() const {
53 assert (!isMutable() && "Node is incorrectly marked mutable.");
55 return reinterpret_cast<ImutAVLTree*>(Left);
58 /// getRight - Returns a pointer to the right subtree. This value is
59 /// NULL if there is no right subtree.
60 ImutAVLTree* getRight() const { return Right; }
63 /// getHeight - Returns the height of the tree. A tree with no subtrees
64 /// has a height of 1.
65 unsigned getHeight() const { return Height; }
67 /// getValue - Returns the data value associated with the tree node.
68 const value_type& getValue() const { return Value; }
70 /// find - Finds the subtree associated with the specified key value.
71 /// This method returns NULL if no matching subtree is found.
72 ImutAVLTree* find(key_type_ref K) {
73 ImutAVLTree *T = this;
76 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
78 if (ImutInfo::isEqual(K,CurrentKey))
80 else if (ImutInfo::isLess(K,CurrentKey))
89 /// size - Returns the number of nodes in the tree, which includes
90 /// both leaves and non-leaf nodes.
91 unsigned size() const {
94 if (const ImutAVLTree* L = getLeft()) n += L->size();
95 if (const ImutAVLTree* R = getRight()) n += R->size();
100 /// begin - Returns an iterator that iterates over the nodes of the tree
101 /// in an inorder traversal. The returned iterator thus refers to the
102 /// the tree node with the minimum data element.
103 iterator begin() const { return iterator(this); }
105 /// end - Returns an iterator for the tree that denotes the end of an
106 /// inorder traversal.
107 iterator end() const { return iterator(); }
109 bool ElementEqual(value_type_ref V) const {
111 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
112 ImutInfo::KeyOfValue(V)))
115 // Also compare the data values.
116 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
117 ImutInfo::DataOfValue(V)))
123 bool ElementEqual(const ImutAVLTree* RHS) const {
124 return ElementEqual(RHS->getValue());
127 /// isEqual - Compares two trees for structural equality and returns true
128 /// if they are equal. This worst case performance of this operation is
129 // linear in the sizes of the trees.
130 bool isEqual(const ImutAVLTree& RHS) const {
134 iterator LItr = begin(), LEnd = end();
135 iterator RItr = RHS.begin(), REnd = RHS.end();
137 while (LItr != LEnd && RItr != REnd) {
138 if (*LItr == *RItr) {
144 if (!LItr->ElementEqual(*RItr))
151 return LItr == LEnd && RItr == REnd;
154 /// isNotEqual - Compares two trees for structural inequality. Performance
155 /// is the same is isEqual.
156 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
158 /// contains - Returns true if this tree contains a subtree (node) that
159 /// has an data element that matches the specified key. Complexity
160 /// is logarithmic in the size of the tree.
161 bool contains(const key_type_ref K) { return (bool) find(K); }
163 /// foreach - A member template the accepts invokes operator() on a functor
164 /// object (specifed by Callback) for every node/subtree in the tree.
165 /// Nodes are visited using an inorder traversal.
166 template <typename Callback>
167 void foreach(Callback& C) {
168 if (ImutAVLTree* L = getLeft()) L->foreach(C);
172 if (ImutAVLTree* R = getRight()) R->foreach(C);
175 /// verify - A utility method that checks that the balancing and
176 /// ordering invariants of the tree are satisifed. It is a recursive
177 /// method that returns the height of the tree, which is then consumed
178 /// by the enclosing verify call. External callers should ignore the
179 /// return value. An invalid tree will cause an assertion to fire in
181 unsigned verify() const {
182 unsigned HL = getLeft() ? getLeft()->verify() : 0;
183 unsigned HR = getRight() ? getRight()->verify() : 0;
185 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
186 && "Height calculation wrong.");
188 assert ((HL > HR ? HL-HR : HR-HL) <= 2
189 && "Balancing invariant violated.");
193 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
194 ImutInfo::KeyOfValue(getValue()))
195 && "Value in left child is not less that current value.");
199 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
200 ImutInfo::KeyOfValue(getRight()->getValue()))
201 && "Current value is not less that value of right child.");
206 /// Profile - Profiling for ImutAVLTree.
207 void Profile(llvm::FoldingSetNodeID& ID) {
208 ID.AddInteger(ComputeDigest());
211 //===----------------------------------------------------===//
213 //===----------------------------------------------------===//
222 //===----------------------------------------------------===//
223 // Internal methods (node manipulation; used by Factory).
224 //===----------------------------------------------------===//
228 enum { Mutable = 0x1 };
230 /// ImutAVLTree - Internal constructor that is only called by
232 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
233 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
234 Right(r), Height(height), Value(v), Digest(0) {}
237 /// isMutable - Returns true if the left and right subtree references
238 /// (as well as height) can be changed. If this method returns false,
239 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
240 /// object should always have this method return true. Further, if this
241 /// method returns false for an instance of ImutAVLTree, all subtrees
242 /// will also have this method return false. The converse is not true.
243 bool isMutable() const { return Left & Mutable; }
245 /// getSafeLeft - Returns the pointer to the left tree by always masking
246 /// out the mutable bit. This is used internally by ImutAVLFactory,
247 /// as no trees returned to the client should have the mutable flag set.
248 ImutAVLTree* getSafeLeft() const {
249 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
252 //===----------------------------------------------------===//
253 // Mutating operations. A tree root can be manipulated as
254 // long as its reference has not "escaped" from internal
255 // methods of a factory object (see below). When a tree
256 // pointer is externally viewable by client code, the
257 // internal "mutable bit" is cleared to mark the tree
258 // immutable. Note that a tree that still has its mutable
259 // bit set may have children (subtrees) that are themselves
261 //===----------------------------------------------------===//
264 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
265 /// it is an error to call setLeft(), setRight(), and setHeight(). It
266 /// is also then safe to call getLeft() instead of getSafeLeft().
267 void MarkImmutable() {
268 assert (isMutable() && "Mutable flag already removed.");
272 /// setLeft - Changes the reference of the left subtree. Used internally
273 /// by ImutAVLFactory.
274 void setLeft(ImutAVLTree* NewLeft) {
275 assert (isMutable() &&
276 "Only a mutable tree can have its left subtree changed.");
278 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
281 /// setRight - Changes the reference of the right subtree. Used internally
282 /// by ImutAVLFactory.
283 void setRight(ImutAVLTree* NewRight) {
284 assert (isMutable() &&
285 "Only a mutable tree can have its right subtree changed.");
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.");
299 unsigned ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
302 if (L) digest += L->ComputeDigest();
304 { // Compute digest of stored data.
306 ImutInfo::Profile(ID,V);
307 digest += ID.ComputeHash();
310 if (R) digest += R->ComputeDigest();
315 inline unsigned ComputeDigest() {
316 if (Digest) return Digest;
318 unsigned X = ComputeDigest(getSafeLeft(), getRight(), getValue());
319 if (!isMutable()) Digest = X;
325 //===----------------------------------------------------------------------===//
326 // Immutable AVL-Tree Factory class.
327 //===----------------------------------------------------------------------===//
329 template <typename ImutInfo >
330 class ImutAVLFactory {
331 typedef ImutAVLTree<ImutInfo> TreeTy;
332 typedef typename TreeTy::value_type_ref value_type_ref;
333 typedef typename TreeTy::key_type_ref key_type_ref;
335 typedef FoldingSet<TreeTy> CacheTy;
338 BumpPtrAllocator Allocator;
340 //===--------------------------------------------------===//
342 //===--------------------------------------------------===//
347 TreeTy* Add(TreeTy* T, value_type_ref V) {
348 T = Add_internal(V,T);
353 TreeTy* Remove(TreeTy* T, key_type_ref V) {
354 T = Remove_internal(V,T);
359 TreeTy* GetEmptyTree() const { return NULL; }
361 BumpPtrAllocator& getAllocator() { return Allocator; }
363 //===--------------------------------------------------===//
364 // A bunch of quick helper functions used for reasoning
365 // about the properties of trees and their children.
366 // These have succinct names so that the balancing code
367 // is as terse (and readable) as possible.
368 //===--------------------------------------------------===//
371 bool isEmpty(TreeTy* T) const { return !T; }
372 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
373 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
374 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
375 value_type_ref Value(TreeTy* T) const { return T->Value; }
377 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
378 unsigned hl = Height(L);
379 unsigned hr = Height(R);
380 return ( hl > hr ? hl : hr ) + 1;
384 static bool CompareTreeWithSection(TreeTy* T,
385 typename TreeTy::iterator& TI,
386 typename TreeTy::iterator& TE) {
388 typename TreeTy::iterator I = T->begin(), E = T->end();
390 for ( ; I!=E ; ++I, ++TI)
391 if (TI == TE || !I->ElementEqual(*TI))
397 //===--------------------------------------------------===//
398 // "CreateNode" is used to generate new tree roots that link
399 // to other trees. The functon may also simply move links
400 // in an existing root if that root is still marked mutable.
401 // This is necessary because otherwise our balancing code
402 // would leak memory as it would create nodes that are
403 // then discarded later before the finished tree is
404 // returned to the caller.
405 //===--------------------------------------------------===//
407 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
408 // Search the FoldingSet bucket for a Tree with the same digest.
410 unsigned digest = TreeTy::ComputeDigest(L, R, V);
411 ID.AddInteger(digest);
412 unsigned hash = ID.ComputeHash();
414 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
415 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
417 for (; I != E; ++I) {
420 if (T->ComputeDigest() != digest)
423 // We found a collision. Perform a comparison of Contents('T')
424 // with Contents('L')+'V'+Contents('R').
426 typename TreeTy::iterator TI = T->begin(), TE = T->end();
428 // First compare Contents('L') with the (initial) contents of T.
429 if (!CompareTreeWithSection(L, TI, TE))
432 // Now compare the new data element.
433 if (TI == TE || !TI->ElementEqual(V))
438 // Now compare the remainder of 'T' with 'R'.
439 if (!CompareTreeWithSection(R, TI, TE))
442 if (TI != TE) // Contents('R') did not match suffix of 'T'.
445 // Trees did match! Return 'T'.
449 // No tree with the contents: Contents('L')+'V'+Contents('R').
452 // Allocate the new tree node and insert it into the cache.
453 TreeTy* T = (TreeTy*) Allocator.Allocate<TreeTy>();
454 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
456 // We do not insert 'T' into the FoldingSet here. This is because
457 // this tree is still mutable and things may get rebalanced.
458 // Because our digest is associative and based on the contents of
459 // the set, this should hopefully not cause any strange bugs.
460 // 'T' is inserted by 'MarkImmutable'.
465 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
466 assert (!isEmpty(OldTree));
468 if (OldTree->isMutable()) {
470 OldTree->setRight(R);
471 OldTree->setHeight(IncrementHeight(L,R));
474 else return CreateNode(L, Value(OldTree), R);
477 /// Balance - Used by Add_internal and Remove_internal to
478 /// balance a newly created tree.
479 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
481 unsigned hl = Height(L);
482 unsigned hr = Height(R);
485 assert (!isEmpty(L) &&
486 "Left tree cannot be empty to have a height >= 2.");
488 TreeTy* LL = Left(L);
489 TreeTy* LR = Right(L);
491 if (Height(LL) >= Height(LR))
492 return CreateNode(LL, L, CreateNode(LR,V,R));
494 assert (!isEmpty(LR) &&
495 "LR cannot be empty because it has a height >= 1.");
497 TreeTy* LRL = Left(LR);
498 TreeTy* LRR = Right(LR);
500 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
502 else if (hr > hl + 2) {
503 assert (!isEmpty(R) &&
504 "Right tree cannot be empty to have a height >= 2.");
506 TreeTy* RL = Left(R);
507 TreeTy* RR = Right(R);
509 if (Height(RR) >= Height(RL))
510 return CreateNode(CreateNode(L,V,RL), R, RR);
512 assert (!isEmpty(RL) &&
513 "RL cannot be empty because it has a height >= 1.");
515 TreeTy* RLL = Left(RL);
516 TreeTy* RLR = Right(RL);
518 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
521 return CreateNode(L,V,R);
524 /// Add_internal - Creates a new tree that includes the specified
525 /// data and the data from the original tree. If the original tree
526 /// already contained the data item, the original tree is returned.
527 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
529 return CreateNode(T, V, T);
531 assert (!T->isMutable());
533 key_type_ref K = ImutInfo::KeyOfValue(V);
534 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
536 if (ImutInfo::isEqual(K,KCurrent))
537 return CreateNode(Left(T), V, Right(T));
538 else if (ImutInfo::isLess(K,KCurrent))
539 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
541 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
544 /// Remove_interal - Creates a new tree that includes all the data
545 /// from the original tree except the specified data. If the
546 /// specified data did not exist in the original tree, the original
547 /// tree is returned.
548 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
552 assert (!T->isMutable());
554 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
556 if (ImutInfo::isEqual(K,KCurrent))
557 return CombineLeftRightTrees(Left(T),Right(T));
558 else if (ImutInfo::isLess(K,KCurrent))
559 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
561 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
564 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
565 if (isEmpty(L)) return R;
566 if (isEmpty(R)) return L;
569 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
570 return Balance(L,Value(OldNode),NewRight);
573 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
574 assert (!isEmpty(T));
576 if (isEmpty(Left(T))) {
581 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
584 /// MarkImmutable - Clears the mutable bits of a root and all of its
586 void MarkImmutable(TreeTy* T) {
587 if (!T || !T->isMutable())
591 MarkImmutable(Left(T));
592 MarkImmutable(Right(T));
594 // Now that the node is immutable it can safely be inserted
595 // into the node cache.
596 llvm::FoldingSetNodeID ID;
597 ID.AddInteger(T->ComputeDigest());
598 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
603 //===----------------------------------------------------------------------===//
604 // Immutable AVL-Tree Iterators.
605 //===----------------------------------------------------------------------===//
607 template <typename ImutInfo>
608 class ImutAVLTreeGenericIterator {
609 SmallVector<uintptr_t,20> stack;
611 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
614 typedef ImutAVLTree<ImutInfo> TreeTy;
615 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
617 inline ImutAVLTreeGenericIterator() {}
618 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
619 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
622 TreeTy* operator*() const {
623 assert (!stack.empty());
624 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
627 uintptr_t getVisitState() {
628 assert (!stack.empty());
629 return stack.back() & Flags;
633 bool AtEnd() const { return stack.empty(); }
635 bool AtBeginning() const {
636 return stack.size() == 1 && getVisitState() == VisitedNone;
639 void SkipToParent() {
640 assert (!stack.empty());
646 switch (getVisitState()) {
648 stack.back() |= VisitedLeft;
651 stack.back() |= VisitedRight;
654 assert (false && "Unreachable.");
658 inline bool operator==(const _Self& x) const {
659 if (stack.size() != x.stack.size())
662 for (unsigned i = 0 ; i < stack.size(); i++)
663 if (stack[i] != x.stack[i])
669 inline bool operator!=(const _Self& x) const { return !operator==(x); }
671 _Self& operator++() {
672 assert (!stack.empty());
674 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
677 switch (getVisitState()) {
679 if (TreeTy* L = Current->getSafeLeft())
680 stack.push_back(reinterpret_cast<uintptr_t>(L));
682 stack.back() |= VisitedLeft;
687 if (TreeTy* R = Current->getRight())
688 stack.push_back(reinterpret_cast<uintptr_t>(R));
690 stack.back() |= VisitedRight;
699 assert (false && "Unreachable.");
705 _Self& operator--() {
706 assert (!stack.empty());
708 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
711 switch (getVisitState()) {
717 stack.back() &= ~Flags; // Set state to "VisitedNone."
719 if (TreeTy* L = Current->getLeft())
720 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
725 stack.back() &= ~Flags;
726 stack.back() |= VisitedLeft;
728 if (TreeTy* R = Current->getRight())
729 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
734 assert (false && "Unreachable.");
741 template <typename ImutInfo>
742 class ImutAVLTreeInOrderIterator {
743 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
744 InternalIteratorTy InternalItr;
747 typedef ImutAVLTree<ImutInfo> TreeTy;
748 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
750 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
751 if (Root) operator++(); // Advance to first element.
754 ImutAVLTreeInOrderIterator() : InternalItr() {}
756 inline bool operator==(const _Self& x) const {
757 return InternalItr == x.InternalItr;
760 inline bool operator!=(const _Self& x) const { return !operator==(x); }
762 inline TreeTy* operator*() const { return *InternalItr; }
763 inline TreeTy* operator->() const { return *InternalItr; }
765 inline _Self& operator++() {
767 while (!InternalItr.AtEnd() &&
768 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
773 inline _Self& operator--() {
775 while (!InternalItr.AtBeginning() &&
776 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
781 inline void SkipSubTree() {
782 InternalItr.SkipToParent();
784 while (!InternalItr.AtEnd() &&
785 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
790 //===----------------------------------------------------------------------===//
791 // Trait classes for Profile information.
792 //===----------------------------------------------------------------------===//
794 /// Generic profile template. The default behavior is to invoke the
795 /// profile method of an object. Specializations for primitive integers
796 /// and generic handling of pointers is done below.
797 template <typename T>
798 struct ImutProfileInfo {
799 typedef const T value_type;
800 typedef const T& value_type_ref;
802 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
803 FoldingSetTrait<T>::Profile(X,ID);
807 /// Profile traits for integers.
808 template <typename T>
809 struct ImutProfileInteger {
810 typedef const T value_type;
811 typedef const T& value_type_ref;
813 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
818 #define PROFILE_INTEGER_INFO(X)\
819 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
821 PROFILE_INTEGER_INFO(char)
822 PROFILE_INTEGER_INFO(unsigned char)
823 PROFILE_INTEGER_INFO(short)
824 PROFILE_INTEGER_INFO(unsigned short)
825 PROFILE_INTEGER_INFO(unsigned)
826 PROFILE_INTEGER_INFO(signed)
827 PROFILE_INTEGER_INFO(long)
828 PROFILE_INTEGER_INFO(unsigned long)
829 PROFILE_INTEGER_INFO(long long)
830 PROFILE_INTEGER_INFO(unsigned long long)
832 #undef PROFILE_INTEGER_INFO
834 /// Generic profile trait for pointer types. We treat pointers as
835 /// references to unique objects.
836 template <typename T>
837 struct ImutProfileInfo<T*> {
838 typedef const T* value_type;
839 typedef value_type value_type_ref;
841 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
846 //===----------------------------------------------------------------------===//
847 // Trait classes that contain element comparison operators and type
848 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
849 // inherit from the profile traits (ImutProfileInfo) to include operations
850 // for element profiling.
851 //===----------------------------------------------------------------------===//
854 /// ImutContainerInfo - Generic definition of comparison operations for
855 /// elements of immutable containers that defaults to using
856 /// std::equal_to<> and std::less<> to perform comparison of elements.
857 template <typename T>
858 struct ImutContainerInfo : public ImutProfileInfo<T> {
859 typedef typename ImutProfileInfo<T>::value_type value_type;
860 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
861 typedef value_type key_type;
862 typedef value_type_ref key_type_ref;
863 typedef bool data_type;
864 typedef bool data_type_ref;
866 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
867 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
869 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
870 return std::equal_to<key_type>()(LHS,RHS);
873 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
874 return std::less<key_type>()(LHS,RHS);
877 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
880 /// ImutContainerInfo - Specialization for pointer values to treat pointers
881 /// as references to unique objects. Pointers are thus compared by
883 template <typename T>
884 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
885 typedef typename ImutProfileInfo<T*>::value_type value_type;
886 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
887 typedef value_type key_type;
888 typedef value_type_ref key_type_ref;
889 typedef bool data_type;
890 typedef bool data_type_ref;
892 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
893 static inline data_type_ref DataOfValue(value_type_ref) { return true; }
895 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
899 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
903 static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
906 //===----------------------------------------------------------------------===//
908 //===----------------------------------------------------------------------===//
910 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
913 typedef typename ValInfo::value_type value_type;
914 typedef typename ValInfo::value_type_ref value_type_ref;
915 typedef ImutAVLTree<ValInfo> TreeTy;
921 /// Constructs a set from a pointer to a tree root. In general one
922 /// should use a Factory object to create sets instead of directly
923 /// invoking the constructor, but there are cases where make this
924 /// constructor public is useful.
925 explicit ImmutableSet(TreeTy* R) : Root(R) {}
928 typename TreeTy::Factory F;
933 /// GetEmptySet - Returns an immutable set that contains no elements.
934 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
936 /// Add - Creates a new immutable set that contains all of the values
937 /// of the original set with the addition of the specified value. If
938 /// the original set already included the value, then the original set is
939 /// returned and no memory is allocated. The time and space complexity
940 /// of this operation is logarithmic in the size of the original set.
941 /// The memory allocated to represent the set is released when the
942 /// factory object that created the set is destroyed.
943 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
944 return ImmutableSet(F.Add(Old.Root,V));
947 /// Remove - Creates a new immutable set that contains all of the values
948 /// of the original set with the exception of the specified value. If
949 /// the original set did not contain the value, the original set is
950 /// returned and no memory is allocated. The time and space complexity
951 /// of this operation is logarithmic in the size of the original set.
952 /// The memory allocated to represent the set is released when the
953 /// factory object that created the set is destroyed.
954 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
955 return ImmutableSet(F.Remove(Old.Root,V));
958 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
961 Factory(const Factory& RHS) {};
962 void operator=(const Factory& RHS) {};
965 friend class Factory;
967 /// contains - Returns true if the set contains the specified value.
968 bool contains(const value_type_ref V) const {
969 return Root ? Root->contains(V) : false;
972 bool operator==(ImmutableSet RHS) const {
973 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
976 bool operator!=(ImmutableSet RHS) const {
977 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
980 TreeTy* getRoot() const { return Root; }
982 /// isEmpty - Return true if the set contains no elements.
983 bool isEmpty() const { return !Root; }
985 template <typename Callback>
986 void foreach(Callback& C) { if (Root) Root->foreach(C); }
988 template <typename Callback>
989 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
991 //===--------------------------------------------------===//
993 //===--------------------------------------------------===//
996 typename TreeTy::iterator itr;
999 iterator(TreeTy* t) : itr(t) {}
1000 friend class ImmutableSet<ValT,ValInfo>;
1002 inline value_type_ref operator*() const { return itr->getValue(); }
1003 inline iterator& operator++() { ++itr; return *this; }
1004 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1005 inline iterator& operator--() { --itr; return *this; }
1006 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1007 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1008 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1011 iterator begin() const { return iterator(Root); }
1012 iterator end() const { return iterator(); }
1014 //===--------------------------------------------------===//
1016 //===--------------------------------------------------===//
1018 void verify() const { if (Root) Root->verify(); }
1019 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1022 } // end namespace llvm