1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Ted Kremenek and is distributed under
6 // the University of Illinois Open Source 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;
29 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
31 template <typename ImutInfo >
32 class ImutAVLTree : public FoldingSetNode {
33 struct ComputeIsEqual;
35 typedef typename ImutInfo::key_type_ref key_type_ref;
36 typedef typename ImutInfo::value_type value_type;
37 typedef typename ImutInfo::value_type_ref value_type_ref;
39 typedef ImutAVLFactory<ImutInfo> Factory;
40 friend class ImutAVLFactory<ImutInfo>;
42 typedef ImutAVLTreeInOrderIterator<ImutInfo> iterator;
44 //===----------------------------------------------------===//
46 //===----------------------------------------------------===//
48 /// getLeft - Returns a pointer to the left subtree. This value
49 /// is NULL if there is no left subtree.
50 ImutAVLTree* getLeft() const {
51 assert (!isMutable() && "Node is incorrectly marked mutable.");
53 return reinterpret_cast<ImutAVLTree*>(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; }
61 /// getHeight - Returns the height of the tree. A tree with no subtrees
62 /// has a height of 1.
63 unsigned getHeight() const { return Height; }
65 /// getValue - Returns the data value associated with the tree node.
66 const value_type& getValue() const { return Value; }
68 /// find - Finds the subtree associated with the specified key value.
69 /// This method returns NULL if no matching subtree is found.
70 ImutAVLTree* find(key_type_ref K) {
71 ImutAVLTree *T = this;
74 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
76 if (ImutInfo::isEqual(K,CurrentKey))
78 else if (ImutInfo::isLess(K,CurrentKey))
87 /// size - Returns the number of nodes in the tree, which includes
88 /// both leaves and non-leaf nodes.
89 unsigned size() const {
92 if (const ImutAVLTree* L = getLeft()) n += L->size();
93 if (const ImutAVLTree* R = getRight()) n += R->size();
98 /// begin - Returns an iterator that iterates over the nodes of the tree
99 /// in an inorder traversal. The returned iterator thus refers to the
100 /// the tree node with the minimum data element.
101 iterator begin() const { return iterator(this); }
103 /// end - Returns an iterator for the tree that denotes the end of an
104 /// inorder traversal.
105 iterator end() const { return iterator(); }
107 /// isEqual - Compares two trees for structural equality and returns true
108 /// if they are equal. This worst case performance of this operation is
109 // linear in the sizes of the trees.
110 bool isEqual(const ImutAVLTree& RHS) const {
114 iterator LItr = begin(), LEnd = end();
115 iterator RItr = RHS.begin(), REnd = RHS.end();
117 while (LItr != LEnd && RItr != REnd) {
118 if (*LItr == *RItr) {
124 // FIXME: need to compare data values, not key values, but our
125 // traits don't support this yet.
126 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(LItr->getValue()),
127 ImutInfo::KeyOfValue(RItr->getValue())))
134 return LItr == LEnd && RItr == REnd;
137 /// isNotEqual - Compares two trees for structural inequality. Performance
138 /// is the same is isEqual.
139 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
141 /// contains - Returns true if this tree contains a subtree (node) that
142 /// has an data element that matches the specified key. Complexity
143 /// is logarithmic in the size of the tree.
144 bool contains(const key_type_ref K) { return (bool) find(K); }
146 /// foreach - A member template the accepts invokes operator() on a functor
147 /// object (specifed by Callback) for every node/subtree in the tree.
148 /// Nodes are visited using an inorder traversal.
149 template <typename Callback>
150 void foreach(Callback& C) {
151 if (ImutAVLTree* L = getLeft()) L->foreach(C);
155 if (ImutAVLTree* R = getRight()) R->foreach(C);
158 /// verify - A utility method that checks that the balancing and
159 /// ordering invariants of the tree are satisifed. It is a recursive
160 /// method that returns the height of the tree, which is then consumed
161 /// by the enclosing verify call. External callers should ignore the
162 /// return value. An invalid tree will cause an assertion to fire in
164 unsigned verify() const {
165 unsigned HL = getLeft() ? getLeft()->verify() : 0;
166 unsigned HR = getRight() ? getRight()->verify() : 0;
168 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
169 && "Height calculation wrong.");
171 assert ((HL > HR ? HL-HR : HR-HL) <= 2
172 && "Balancing invariant violated.");
176 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
177 ImutInfo::KeyOfValue(getValue()))
178 && "Value in left child is not less that current value.");
182 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
183 ImutInfo::KeyOfValue(getRight()->getValue()))
184 && "Current value is not less that value of right child.");
189 //===----------------------------------------------------===//
191 //===----------------------------------------------------===//
199 //===----------------------------------------------------===//
200 // Profiling or FoldingSet.
201 //===----------------------------------------------------===//
204 void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
205 unsigned H, value_type_ref V) {
209 ImutInfo::Profile(ID,V);
214 void Profile(FoldingSetNodeID& ID) {
215 Profile(ID,getSafeLeft(),getRight(),getHeight(),getValue());
218 //===----------------------------------------------------===//
219 // Internal methods (node manipulation; used by Factory).
220 //===----------------------------------------------------===//
224 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
225 : Left(reinterpret_cast<uintptr_t>(l) | 0x1),
226 Right(r), Height(height), Value(v) {}
228 bool isMutable() const { return Left & 0x1; }
230 ImutAVLTree* getSafeLeft() const {
231 return reinterpret_cast<ImutAVLTree*>(Left & ~0x1);
234 // Mutating operations. A tree root can be manipulated as long as
235 // its reference has not "escaped" from internal methods of a
236 // factory object (see below). When a tree pointer is externally
237 // viewable by client code, the internal "mutable bit" is cleared
238 // to mark the tree immutable. Note that a tree that still has
239 // its mutable bit set may have children (subtrees) that are themselves
242 void RemoveMutableFlag() {
243 assert (Left & 0x1 && "Mutable flag already removed.");
247 void setLeft(ImutAVLTree* NewLeft) {
248 assert (isMutable());
249 Left = reinterpret_cast<uintptr_t>(NewLeft) | 0x1;
252 void setRight(ImutAVLTree* NewRight) {
253 assert (isMutable());
257 void setHeight(unsigned h) {
258 assert (isMutable());
263 //===----------------------------------------------------------------------===//
264 // Immutable AVL-Tree Factory class.
265 //===----------------------------------------------------------------------===//
267 template <typename ImutInfo >
268 class ImutAVLFactory {
269 typedef ImutAVLTree<ImutInfo> TreeTy;
270 typedef typename TreeTy::value_type_ref value_type_ref;
271 typedef typename TreeTy::key_type_ref key_type_ref;
273 typedef FoldingSet<TreeTy> CacheTy;
276 BumpPtrAllocator Allocator;
278 //===--------------------------------------------------===//
280 //===--------------------------------------------------===//
285 TreeTy* Add(TreeTy* T, value_type_ref V) {
286 T = Add_internal(V,T);
291 TreeTy* Remove(TreeTy* T, key_type_ref V) {
292 T = Remove_internal(V,T);
297 TreeTy* GetEmptyTree() const { return NULL; }
299 //===--------------------------------------------------===//
300 // A bunch of quick helper functions used for reasoning
301 // about the properties of trees and their children.
302 // These have succinct names so that the balancing code
303 // is as terse (and readable) as possible.
304 //===--------------------------------------------------===//
307 bool isEmpty(TreeTy* T) const {
311 unsigned Height(TreeTy* T) const {
312 return T ? T->getHeight() : 0;
315 TreeTy* Left(TreeTy* T) const {
317 return T->getSafeLeft();
320 TreeTy* Right(TreeTy* T) const {
322 return T->getRight();
325 value_type_ref Value(TreeTy* T) const {
330 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
331 unsigned hl = Height(L);
332 unsigned hr = Height(R);
333 return ( hl > hr ? hl : hr ) + 1;
336 //===--------------------------------------------------===//
337 // "CreateNode" is used to generate new tree roots that link
338 // to other trees. The functon may also simply move links
339 // in an existing root if that root is still marked mutable.
340 // This is necessary because otherwise our balancing code
341 // would leak memory as it would create nodes that are
342 // then discarded later before the finished tree is
343 // returned to the caller.
344 //===--------------------------------------------------===//
346 TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
348 unsigned height = IncrementHeight(L,R);
350 TreeTy::Profile(ID,L,R,height,V);
353 if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
356 assert (InsertPos != NULL);
358 // FIXME: more intelligent calculation of alignment.
359 TreeTy* T = (TreeTy*) Allocator.Allocate(sizeof(*T),16);
360 new (T) TreeTy(L,R,V,height);
362 Cache.InsertNode(T,InsertPos);
366 TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
367 assert (!isEmpty(OldTree));
369 if (OldTree->isMutable()) {
371 OldTree->setRight(R);
372 OldTree->setHeight(IncrementHeight(L,R));
375 else return CreateNode(L, Value(OldTree), R);
378 /// Balance - Used by Add_internal and Remove_internal to
379 /// balance a newly created tree.
380 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
382 unsigned hl = Height(L);
383 unsigned hr = Height(R);
386 assert (!isEmpty(L) &&
387 "Left tree cannot be empty to have a height >= 2.");
389 TreeTy* LL = Left(L);
390 TreeTy* LR = Right(L);
392 if (Height(LL) >= Height(LR))
393 return CreateNode(LL, L, CreateNode(LR,V,R));
395 assert (!isEmpty(LR) &&
396 "LR cannot be empty because it has a height >= 1.");
398 TreeTy* LRL = Left(LR);
399 TreeTy* LRR = Right(LR);
401 return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
403 else if (hr > hl + 2) {
404 assert (!isEmpty(R) &&
405 "Right tree cannot be empty to have a height >= 2.");
407 TreeTy* RL = Left(R);
408 TreeTy* RR = Right(R);
410 if (Height(RR) >= Height(RL))
411 return CreateNode(CreateNode(L,V,RL), R, RR);
413 assert (!isEmpty(RL) &&
414 "RL cannot be empty because it has a height >= 1.");
416 TreeTy* RLL = Left(RL);
417 TreeTy* RLR = Right(RL);
419 return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
422 return CreateNode(L,V,R);
425 /// Add_internal - Creates a new tree that includes the specified
426 /// data and the data from the original tree. If the original tree
427 /// already contained the data item, the original tree is returned.
428 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
430 return CreateNode(T, V, T);
432 assert (!T->isMutable());
434 key_type_ref K = ImutInfo::KeyOfValue(V);
435 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
437 if (ImutInfo::isEqual(K,KCurrent))
438 return CreateNode(Left(T), V, Right(T));
439 else if (ImutInfo::isLess(K,KCurrent))
440 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
442 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
445 /// Remove_interal - Creates a new tree that includes all the data
446 /// from the original tree except the specified data. If the
447 /// specified data did not exist in the original tree, the original
448 /// tree is returned.
449 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
453 assert (!T->isMutable());
455 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
457 if (ImutInfo::isEqual(K,KCurrent))
458 return CombineLeftRightTrees(Left(T),Right(T));
459 else if (ImutInfo::isLess(K,KCurrent))
460 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
462 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
465 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
466 if (isEmpty(L)) return R;
467 if (isEmpty(R)) return L;
470 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
471 return Balance(L,Value(OldNode),NewRight);
474 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
475 assert (!isEmpty(T));
477 if (isEmpty(Left(T))) {
482 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
485 /// MarkImmutable - Clears the mutable bits of a root and all of its
487 void MarkImmutable(TreeTy* T) {
488 if (!T || !T->isMutable())
491 T->RemoveMutableFlag();
492 MarkImmutable(Left(T));
493 MarkImmutable(Right(T));
498 //===----------------------------------------------------------------------===//
499 // Immutable AVL-Tree Iterators.
500 //===----------------------------------------------------------------------===//
502 template <typename ImutInfo>
503 class ImutAVLTreeGenericIterator {
504 SmallVector<uintptr_t,20> stack;
506 enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
509 typedef ImutAVLTree<ImutInfo> TreeTy;
510 typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
512 inline ImutAVLTreeGenericIterator() {}
513 inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
514 if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
517 TreeTy* operator*() const {
518 assert (!stack.empty());
519 return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
522 uintptr_t getVisitState() {
523 assert (!stack.empty());
524 return stack.back() & Flags;
528 bool AtEnd() const { return stack.empty(); }
530 bool AtBeginning() const {
531 return stack.size() == 1 && getVisitState() == VisitedNone;
534 void SkipToParent() {
535 assert (!stack.empty());
541 switch (getVisitState()) {
543 stack.back() |= VisitedLeft;
546 stack.back() |= VisitedRight;
549 assert (false && "Unreachable.");
553 inline bool operator==(const _Self& x) const {
554 if (stack.size() != x.stack.size())
557 for (unsigned i = 0 ; i < stack.size(); i++)
558 if (stack[i] != x.stack[i])
564 inline bool operator!=(const _Self& x) const { return !operator==(x); }
566 _Self& operator++() {
567 assert (!stack.empty());
569 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
572 switch (getVisitState()) {
574 if (TreeTy* L = Current->getLeft())
575 stack.push_back(reinterpret_cast<uintptr_t>(L));
577 stack.back() |= VisitedLeft;
582 if (TreeTy* R = Current->getRight())
583 stack.push_back(reinterpret_cast<uintptr_t>(R));
585 stack.back() |= VisitedRight;
594 assert (false && "Unreachable.");
600 _Self& operator--() {
601 assert (!stack.empty());
603 TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
606 switch (getVisitState()) {
612 stack.back() &= ~Flags; // Set state to "VisitedNone."
614 if (TreeTy* L = Current->getLeft())
615 stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
620 stack.back() &= ~Flags;
621 stack.back() |= VisitedLeft;
623 if (TreeTy* R = Current->getRight())
624 stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
629 assert (false && "Unreachable.");
636 template <typename ImutInfo>
637 class ImutAVLTreeInOrderIterator {
638 typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
639 InternalIteratorTy InternalItr;
642 typedef ImutAVLTree<ImutInfo> TreeTy;
643 typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
645 ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
646 if (Root) operator++(); // Advance to first element.
649 ImutAVLTreeInOrderIterator() : InternalItr() {}
651 inline bool operator==(const _Self& x) const {
652 return InternalItr == x.InternalItr;
655 inline bool operator!=(const _Self& x) const { return !operator==(x); }
657 inline TreeTy* operator*() { return *InternalItr; }
658 inline TreeTy* operator->() { return *InternalItr; }
660 inline _Self& operator++() {
662 while (!InternalItr.AtEnd() &&
663 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
668 inline _Self& operator--() {
670 while (!InternalItr.AtBeginning() &&
671 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
676 inline void SkipSubTree() {
677 InternalItr.SkipToParent();
679 while (!InternalItr.AtEnd() &&
680 InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
685 //===----------------------------------------------------------------------===//
686 // Trait classes for Profile information.
687 //===----------------------------------------------------------------------===//
689 /// Generic profile template. The default behavior is to invoke the
690 /// profile method of an object. Specializations for primitive integers
691 /// and generic handling of pointers is done below.
692 template <typename T>
693 struct ImutProfileInfo {
694 typedef const T value_type;
695 typedef const T& value_type_ref;
697 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
702 /// Profile traits for integers.
703 template <typename T>
704 struct ImutProfileInteger {
705 typedef const T value_type;
706 typedef const T& value_type_ref;
708 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
713 #define PROFILE_INTEGER_INFO(X)\
714 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
716 PROFILE_INTEGER_INFO(char)
717 PROFILE_INTEGER_INFO(unsigned char)
718 PROFILE_INTEGER_INFO(short)
719 PROFILE_INTEGER_INFO(unsigned short)
720 PROFILE_INTEGER_INFO(unsigned)
721 PROFILE_INTEGER_INFO(signed)
722 PROFILE_INTEGER_INFO(long)
723 PROFILE_INTEGER_INFO(unsigned long)
724 PROFILE_INTEGER_INFO(long long)
725 PROFILE_INTEGER_INFO(unsigned long long)
727 #undef PROFILE_INTEGER_INFO
729 /// Generic profile trait for pointer types. We treat pointers as
730 /// references to unique objects.
731 template <typename T>
732 struct ImutProfileInfo<T*> {
733 typedef const T* value_type;
734 typedef value_type value_type_ref;
736 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
741 //===----------------------------------------------------------------------===//
742 // Trait classes that contain element comparison operators and type
743 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
744 // inherit from the profile traits (ImutProfileInfo) to include operations
745 // for element profiling.
746 //===----------------------------------------------------------------------===//
749 /// ImutContainerInfo - Generic definition of comparison operations for
750 /// elements of immutable containers that defaults to using
751 /// std::equal_to<> and std::less<> to perform comparison of elements.
752 template <typename T>
753 struct ImutContainerInfo : public ImutProfileInfo<T> {
754 typedef typename ImutProfileInfo<T>::value_type value_type;
755 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
756 typedef value_type key_type;
757 typedef value_type_ref key_type_ref;
759 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
761 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
762 return std::equal_to<key_type>()(LHS,RHS);
765 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
766 return std::less<key_type>()(LHS,RHS);
770 /// ImutContainerInfo - Specialization for pointer values to treat pointers
771 /// as references to unique objects. Pointers are thus compared by
773 template <typename T>
774 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
775 typedef typename ImutProfileInfo<T*>::value_type value_type;
776 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
777 typedef value_type key_type;
778 typedef value_type_ref key_type_ref;
780 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
782 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
786 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
791 //===----------------------------------------------------------------------===//
793 //===----------------------------------------------------------------------===//
795 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
798 typedef typename ValInfo::value_type value_type;
799 typedef typename ValInfo::value_type_ref value_type_ref;
802 typedef ImutAVLTree<ValInfo> TreeTy;
805 ImmutableSet(TreeTy* R) : Root(R) {}
810 typename TreeTy::Factory F;
815 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
817 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
818 return ImmutableSet(F.Add(Old.Root,V));
821 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
822 return ImmutableSet(F.Remove(Old.Root,V));
826 Factory(const Factory& RHS) {};
827 void operator=(const Factory& RHS) {};
830 friend class Factory;
832 bool contains(const value_type_ref V) const {
833 return Root ? Root->contains(V) : false;
836 bool operator==(ImmutableSet RHS) const {
837 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
840 bool operator!=(ImmutableSet RHS) const {
841 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
844 bool isEmpty() const { return !Root; }
846 template <typename Callback>
847 void foreach(Callback& C) { if (Root) Root->foreach(C); }
849 template <typename Callback>
850 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
852 //===--------------------------------------------------===//
854 //===--------------------------------------------------===//
856 void verify() const { if (Root) Root->verify(); }
857 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
860 } // end namespace llvm