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/Support/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 {
55 assert (!isMutable() && "Node is incorrectly marked mutable.");
57 return reinterpret_cast<ImutAVLTree*>(Left);
60 /// getRight - Returns a pointer to the right subtree. This value is
61 /// NULL if there is no right subtree.
62 ImutAVLTree* getRight() const { return Right; }
64 /// getHeight - Returns the height of the tree. A tree with no subtrees
65 /// has a height of 1.
66 unsigned getHeight() const { return Height; }
68 /// getValue - Returns the data value associated with the tree node.
69 const value_type& getValue() const { return Value; }
71 /// find - Finds the subtree associated with the specified key value.
72 /// This method returns NULL if no matching subtree is found.
73 ImutAVLTree* find(key_type_ref K) {
74 ImutAVLTree *T = this;
77 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
79 if (ImutInfo::isEqual(K,CurrentKey))
81 else if (ImutInfo::isLess(K,CurrentKey))
90 /// size - Returns the number of nodes in the tree, which includes
91 /// both leaves and non-leaf nodes.
92 unsigned size() const {
95 if (const ImutAVLTree* L = getLeft()) n += L->size();
96 if (const ImutAVLTree* R = getRight()) n += R->size();
101 /// begin - Returns an iterator that iterates over the nodes of the tree
102 /// in an inorder traversal. The returned iterator thus refers to the
103 /// the tree node with the minimum data element.
104 iterator begin() const { return iterator(this); }
106 /// end - Returns an iterator for the tree that denotes the end of an
107 /// inorder traversal.
108 iterator end() const { return iterator(); }
110 bool ElementEqual(value_type_ref V) const {
112 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
113 ImutInfo::KeyOfValue(V)))
116 // Also compare the data values.
117 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
118 ImutInfo::DataOfValue(V)))
124 bool ElementEqual(const ImutAVLTree* RHS) const {
125 return ElementEqual(RHS->getValue());
128 /// isEqual - Compares two trees for structural equality and returns true
129 /// if they are equal. This worst case performance of this operation is
130 // linear in the sizes of the trees.
131 bool isEqual(const ImutAVLTree& RHS) const {
135 iterator LItr = begin(), LEnd = end();
136 iterator RItr = RHS.begin(), REnd = RHS.end();
138 while (LItr != LEnd && RItr != REnd) {
139 if (*LItr == *RItr) {
145 if (!LItr->ElementEqual(*RItr))
152 return LItr == LEnd && RItr == REnd;
155 /// isNotEqual - Compares two trees for structural inequality. Performance
156 /// is the same is isEqual.
157 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
159 /// contains - Returns true if this tree contains a subtree (node) that
160 /// has an data element that matches the specified key. Complexity
161 /// is logarithmic in the size of the tree.
162 bool contains(const key_type_ref K) { return (bool) find(K); }
164 /// foreach - A member template the accepts invokes operator() on a functor
165 /// object (specifed by Callback) for every node/subtree in the tree.
166 /// Nodes are visited using an inorder traversal.
167 template <typename Callback>
168 void foreach(Callback& C) {
169 if (ImutAVLTree* L = getLeft()) L->foreach(C);
173 if (ImutAVLTree* R = getRight()) R->foreach(C);
176 /// verify - A utility method that checks that the balancing and
177 /// ordering invariants of the tree are satisifed. It is a recursive
178 /// method that returns the height of the tree, which is then consumed
179 /// by the enclosing verify call. External callers should ignore the
180 /// return value. An invalid tree will cause an assertion to fire in
182 unsigned verify() const {
183 unsigned HL = getLeft() ? getLeft()->verify() : 0;
184 unsigned HR = getRight() ? getRight()->verify() : 0;
186 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
187 && "Height calculation wrong.");
189 assert ((HL > HR ? HL-HR : HR-HL) <= 2
190 && "Balancing invariant violated.");
194 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
195 ImutInfo::KeyOfValue(getValue()))
196 && "Value in left child is not less that current value.");
200 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
201 ImutInfo::KeyOfValue(getRight()->getValue()))
202 && "Current value is not less that value of right child.");
207 /// Profile - Profiling for ImutAVLTree.
208 void Profile(llvm::FoldingSetNodeID& ID) {
209 ID.AddInteger(ComputeDigest());
212 //===----------------------------------------------------===//
214 //===----------------------------------------------------===//
223 //===----------------------------------------------------===//
224 // Internal methods (node manipulation; used by Factory).
225 //===----------------------------------------------------===//
229 enum { Mutable = 0x1 };
231 /// ImutAVLTree - Internal constructor that is only called by
233 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
234 : Left(reinterpret_cast<uintptr_t>(l) | Mutable),
235 Right(r), Height(height), Value(v), Digest(0) {}
238 /// isMutable - Returns true if the left and right subtree references
239 /// (as well as height) can be changed. If this method returns false,
240 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
241 /// object should always have this method return true. Further, if this
242 /// method returns false for an instance of ImutAVLTree, all subtrees
243 /// will also have this method return false. The converse is not true.
244 bool isMutable() const { return Left & Mutable; }
246 /// getSafeLeft - Returns the pointer to the left tree by always masking
247 /// out the mutable bit. This is used internally by ImutAVLFactory,
248 /// as no trees returned to the client should have the mutable flag set.
249 ImutAVLTree* getSafeLeft() const {
250 return reinterpret_cast<ImutAVLTree*>(Left & ~Mutable);
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 //===----------------------------------------------------===//
265 /// MarkImmutable - Clears the mutable flag for a tree. After this happens,
266 /// it is an error to call setLeft(), setRight(), and setHeight(). It
267 /// is also then safe to call getLeft() instead of getSafeLeft().
268 void MarkImmutable() {
269 assert (isMutable() && "Mutable flag already removed.");
273 /// setLeft - Changes the reference of the left subtree. Used internally
274 /// by ImutAVLFactory.
275 void setLeft(ImutAVLTree* NewLeft) {
276 assert (isMutable() &&
277 "Only a mutable tree can have its left subtree changed.");
279 Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
282 /// setRight - Changes the reference of the right subtree. Used internally
283 /// by ImutAVLFactory.
284 void setRight(ImutAVLTree* NewRight) {
285 assert (isMutable() &&
286 "Only a mutable tree can have its right subtree changed.");
291 /// setHeight - Changes the height of the tree. Used internally by
293 void setHeight(unsigned h) {
294 assert (isMutable() && "Only a mutable tree can have its height changed.");
300 unsigned ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
303 if (L) digest += L->ComputeDigest();
305 { // Compute digest of stored data.
307 ImutInfo::Profile(ID,V);
308 digest += ID.ComputeHash();
311 if (R) digest += R->ComputeDigest();
316 inline unsigned ComputeDigest() {
317 if (Digest) return Digest;
319 unsigned X = ComputeDigest(getSafeLeft(), getRight(), getValue());
320 if (!isMutable()) Digest = X;
326 //===----------------------------------------------------------------------===//
327 // Immutable AVL-Tree Factory class.
328 //===----------------------------------------------------------------------===//
330 template <typename ImutInfo >
331 class ImutAVLFactory {
332 typedef ImutAVLTree<ImutInfo> TreeTy;
333 typedef typename TreeTy::value_type_ref value_type_ref;
334 typedef typename TreeTy::key_type_ref key_type_ref;
336 typedef FoldingSet<TreeTy> CacheTy;
341 bool ownsAllocator() const {
342 return Allocator & 0x1 ? false : true;
345 BumpPtrAllocator& getAllocator() const {
346 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
349 //===--------------------------------------------------===//
351 //===--------------------------------------------------===//
355 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
357 ImutAVLFactory(BumpPtrAllocator& Alloc)
358 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
361 if (ownsAllocator()) delete &getAllocator();
364 TreeTy* Add(TreeTy* T, value_type_ref V) {
365 T = Add_internal(V,T);
370 TreeTy* Remove(TreeTy* T, key_type_ref V) {
371 T = Remove_internal(V,T);
376 TreeTy* GetEmptyTree() const { return NULL; }
378 //===--------------------------------------------------===//
379 // A bunch of quick helper functions used for reasoning
380 // about the properties of trees and their children.
381 // These have succinct names so that the balancing code
382 // is as terse (and readable) as possible.
383 //===--------------------------------------------------===//
386 bool isEmpty(TreeTy* T) const { return !T; }
387 unsigned Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
388 TreeTy* Left(TreeTy* T) const { return T->getSafeLeft(); }
389 TreeTy* Right(TreeTy* T) const { return T->getRight(); }
390 value_type_ref Value(TreeTy* T) const { return T->Value; }
392 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
393 unsigned hl = Height(L);
394 unsigned hr = Height(R);
395 return ( hl > hr ? hl : hr ) + 1;
399 static bool CompareTreeWithSection(TreeTy* T,
400 typename TreeTy::iterator& TI,
401 typename TreeTy::iterator& TE) {
403 typename TreeTy::iterator I = T->begin(), E = T->end();
405 for ( ; I!=E ; ++I, ++TI)
406 if (TI == TE || !I->ElementEqual(*TI))
412 //===--------------------------------------------------===//
413 // "CreateNode" is used to generate new tree roots that link
414 // to other trees. The functon may also simply move links
415 // in an existing root if that root is still marked mutable.
416 // This is necessary because otherwise our balancing code
417 // would leak memory as it would create nodes that are
418 // then discarded later before the finished tree is
419 // returned to the caller.
420 //===--------------------------------------------------===//
422 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
423 // Search the FoldingSet bucket for a Tree with the same digest.
425 unsigned digest = TreeTy::ComputeDigest(L, R, V);
426 ID.AddInteger(digest);
427 unsigned hash = ID.ComputeHash();
429 typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
430 typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
432 for (; I != E; ++I) {
435 if (T->ComputeDigest() != digest)
438 // We found a collision. Perform a comparison of Contents('T')
439 // with Contents('L')+'V'+Contents('R').
441 typename TreeTy::iterator TI = T->begin(), TE = T->end();
443 // First compare Contents('L') with the (initial) contents of T.
444 if (!CompareTreeWithSection(L, TI, TE))
447 // Now compare the new data element.
448 if (TI == TE || !TI->ElementEqual(V))
453 // Now compare the remainder of 'T' with 'R'.
454 if (!CompareTreeWithSection(R, TI, TE))
457 if (TI != TE) // Contents('R') did not match suffix of 'T'.
460 // Trees did match! Return 'T'.
464 // No tree with the contents: Contents('L')+'V'+Contents('R').
467 // Allocate the new tree node and insert it into the cache.
468 BumpPtrAllocator& A = getAllocator();
469 TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
470 new (T) TreeTy(L,R,V,IncrementHeight(L,R));
472 // We do not insert 'T' into the FoldingSet here. This is because
473 // this tree is still mutable and things may get rebalanced.
474 // Because our digest is associative and based on the contents of
475 // the set, this should hopefully not cause any strange bugs.
476 // 'T' is inserted by 'MarkImmutable'.
481 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
482 assert (!isEmpty(OldTree));
484 if (OldTree->isMutable()) {
486 OldTree->setRight(R);
487 OldTree->setHeight(IncrementHeight(L,R));
490 else return CreateNode(L, Value(OldTree), R);
493 /// Balance - Used by Add_internal and Remove_internal to
494 /// balance a newly created tree.
495 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
497 unsigned hl = Height(L);
498 unsigned hr = Height(R);
501 assert (!isEmpty(L) &&
502 "Left tree cannot be empty to have a height >= 2.");
504 TreeTy* LL = Left(L);
505 TreeTy* LR = Right(L);
507 if (Height(LL) >= Height(LR))
508 return CreateNode(LL, L, CreateNode(LR,V,R));
510 assert (!isEmpty(LR) &&
511 "LR cannot be empty because it has a height >= 1.");
513 TreeTy* LRL = Left(LR);
514 TreeTy* LRR = Right(LR);
516 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
518 else if (hr > hl + 2) {
519 assert (!isEmpty(R) &&
520 "Right tree cannot be empty to have a height >= 2.");
522 TreeTy* RL = Left(R);
523 TreeTy* RR = Right(R);
525 if (Height(RR) >= Height(RL))
526 return CreateNode(CreateNode(L,V,RL), R, RR);
528 assert (!isEmpty(RL) &&
529 "RL cannot be empty because it has a height >= 1.");
531 TreeTy* RLL = Left(RL);
532 TreeTy* RLR = Right(RL);
534 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
537 return CreateNode(L,V,R);
540 /// Add_internal - Creates a new tree that includes the specified
541 /// data and the data from the original tree. If the original tree
542 /// already contained the data item, the original tree is returned.
543 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
545 return CreateNode(T, V, T);
547 assert (!T->isMutable());
549 key_type_ref K = ImutInfo::KeyOfValue(V);
550 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
552 if (ImutInfo::isEqual(K,KCurrent))
553 return CreateNode(Left(T), V, Right(T));
554 else if (ImutInfo::isLess(K,KCurrent))
555 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
557 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
560 /// Remove_internal - Creates a new tree that includes all the data
561 /// from the original tree except the specified data. If the
562 /// specified data did not exist in the original tree, the original
563 /// tree is returned.
564 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
568 assert (!T->isMutable());
570 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
572 if (ImutInfo::isEqual(K,KCurrent))
573 return CombineLeftRightTrees(Left(T),Right(T));
574 else if (ImutInfo::isLess(K,KCurrent))
575 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
577 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
580 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
581 if (isEmpty(L)) return R;
582 if (isEmpty(R)) return L;
585 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
586 return Balance(L,Value(OldNode),NewRight);
589 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
590 assert (!isEmpty(T));
592 if (isEmpty(Left(T))) {
597 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
600 /// MarkImmutable - Clears the mutable bits of a root and all of its
602 void MarkImmutable(TreeTy* T) {
603 if (!T || !T->isMutable())
607 MarkImmutable(Left(T));
608 MarkImmutable(Right(T));
610 // Now that the node is immutable it can safely be inserted
611 // into the node cache.
612 llvm::FoldingSetNodeID ID;
613 ID.AddInteger(T->ComputeDigest());
614 Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
619 //===----------------------------------------------------------------------===//
620 // Immutable AVL-Tree Iterators.
621 //===----------------------------------------------------------------------===//
623 template <typename ImutInfo>
624 class ImutAVLTreeGenericIterator {
625 SmallVector<uintptr_t,20> stack;
627 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
630 typedef ImutAVLTree<ImutInfo> TreeTy;
631 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
633 inline ImutAVLTreeGenericIterator() {}
634 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
635 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
638 TreeTy* operator*() const {
639 assert (!stack.empty());
640 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
643 uintptr_t getVisitState() {
644 assert (!stack.empty());
645 return stack.back() & Flags;
649 bool AtEnd() const { return stack.empty(); }
651 bool AtBeginning() const {
652 return stack.size() == 1 && getVisitState() == VisitedNone;
655 void SkipToParent() {
656 assert (!stack.empty());
662 switch (getVisitState()) {
664 stack.back() |= VisitedLeft;
667 stack.back() |= VisitedRight;
670 assert (false && "Unreachable.");
674 inline bool operator==(const _Self& x) const {
675 if (stack.size() != x.stack.size())
678 for (unsigned i = 0 ; i < stack.size(); i++)
679 if (stack[i] != x.stack[i])
685 inline bool operator!=(const _Self& x) const { return !operator==(x); }
687 _Self& operator++() {
688 assert (!stack.empty());
690 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
693 switch (getVisitState()) {
695 if (TreeTy* L = Current->getSafeLeft())
696 stack.push_back(reinterpret_cast<uintptr_t>(L));
698 stack.back() |= VisitedLeft;
703 if (TreeTy* R = Current->getRight())
704 stack.push_back(reinterpret_cast<uintptr_t>(R));
706 stack.back() |= VisitedRight;
715 assert (false && "Unreachable.");
721 _Self& operator--() {
722 assert (!stack.empty());
724 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
727 switch (getVisitState()) {
733 stack.back() &= ~Flags; // Set state to "VisitedNone."
735 if (TreeTy* L = Current->getLeft())
736 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
741 stack.back() &= ~Flags;
742 stack.back() |= VisitedLeft;
744 if (TreeTy* R = Current->getRight())
745 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
750 assert (false && "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) {}
944 typename TreeTy::Factory F;
949 Factory(BumpPtrAllocator& Alloc)
952 /// GetEmptySet - Returns an immutable set that contains no elements.
953 ImmutableSet GetEmptySet() { 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 return ImmutableSet(F.Add(Old.Root,V));
966 /// Remove - Creates a new immutable set that contains all of the values
967 /// of the original set with the exception of the specified value. If
968 /// the original set did not contain the value, the original set is
969 /// returned and no memory is allocated. The time and space complexity
970 /// of this operation is logarithmic in the size of the original set.
971 /// The memory allocated to represent the set is released when the
972 /// factory object that created the set is destroyed.
973 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
974 return ImmutableSet(F.Remove(Old.Root,V));
977 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
980 Factory(const Factory& RHS) {};
981 void operator=(const Factory& RHS) {};
984 friend class Factory;
986 /// contains - Returns true if the set contains the specified value.
987 bool contains(const value_type_ref V) const {
988 return Root ? Root->contains(V) : false;
991 bool operator==(ImmutableSet RHS) const {
992 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
995 bool operator!=(ImmutableSet RHS) const {
996 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
999 TreeTy* getRoot() const { return Root; }
1001 /// isEmpty - Return true if the set contains no elements.
1002 bool isEmpty() const { return !Root; }
1004 /// isSingleton - Return true if the set contains exactly one element.
1005 /// This method runs in constant time.
1006 bool isSingleton() const { return getHeight() == 1; }
1008 template <typename Callback>
1009 void foreach(Callback& C) { if (Root) Root->foreach(C); }
1011 template <typename Callback>
1012 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1014 //===--------------------------------------------------===//
1016 //===--------------------------------------------------===//
1019 typename TreeTy::iterator itr;
1022 iterator(TreeTy* t) : itr(t) {}
1023 friend class ImmutableSet<ValT,ValInfo>;
1025 inline value_type_ref operator*() const { return itr->getValue(); }
1026 inline iterator& operator++() { ++itr; return *this; }
1027 inline iterator operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1028 inline iterator& operator--() { --itr; return *this; }
1029 inline iterator operator--(int) { iterator tmp(*this); --itr; return tmp; }
1030 inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1031 inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1032 inline value_type *operator->() const { return &(operator*()); }
1035 iterator begin() const { return iterator(Root); }
1036 iterator end() const { return iterator(); }
1038 //===--------------------------------------------------===//
1040 //===--------------------------------------------------===//
1042 inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1044 static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1045 ID.AddPointer(S.Root);
1048 inline void Profile(FoldingSetNodeID& ID) const {
1049 return Profile(ID,*this);
1052 //===--------------------------------------------------===//
1054 //===--------------------------------------------------===//
1056 void verify() const { if (Root) Root->verify(); }
1059 } // end namespace llvm