Added iterators to ImmutableSet.
[oota-llvm.git] / include / llvm / ADT / ImmutableSet.h
1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the ImutAVLTree and ImmutableSet classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_ADT_IMSET_H
15 #define LLVM_ADT_IMSET_H
16
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include <cassert>
20
21 namespace llvm {
22   
23 //===----------------------------------------------------------------------===//    
24 // Immutable AVL-Tree Definition.
25 //===----------------------------------------------------------------------===//
26
27 template <typename ImutInfo> class ImutAVLFactory;
28
29 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
30   
31 template <typename ImutInfo >
32 class ImutAVLTree : public FoldingSetNode {
33 public:
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;
37
38   typedef ImutAVLFactory<ImutInfo>          Factory;
39   friend class ImutAVLFactory<ImutInfo>;
40   
41   typedef ImutAVLTreeInOrderIterator<ImutInfo>  iterator;
42   
43   //===----------------------------------------------------===//  
44   // Public Interface.
45   //===----------------------------------------------------===//  
46   
47   /// getLeft - Returns a pointer to the left subtree.  This value
48   ///  is NULL if there is no left subtree.
49   ImutAVLTree* getLeft() const { 
50     assert (!isMutable() && "Node is incorrectly marked mutable.");
51     
52     return reinterpret_cast<ImutAVLTree*>(Left);
53   }
54   
55   /// getRight - Returns a pointer to the right subtree.  This value is
56   ///  NULL if there is no right subtree.
57   ImutAVLTree* getRight() const { return Right; }  
58   
59   
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; }  
63   
64   /// getValue - Returns the data value associated with the tree node.
65   const value_type& getValue() const { return Value; }
66   
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;
71     
72     while (T) {
73       key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
74       
75       if (ImutInfo::isEqual(K,CurrentKey))
76         return T;
77       else if (ImutInfo::isLess(K,CurrentKey))
78         T = T->getLeft();
79       else
80         T = T->getRight();
81     }
82     
83     return NULL;
84   }
85   
86   /// size - Returns the number of nodes in the tree, which includes
87   ///  both leaves and non-leaf nodes.
88   unsigned size() const {
89     unsigned n = 1;
90     
91     if (const ImutAVLTree* L = getLeft())  n += L->size();
92     if (const ImutAVLTree* R = getRight()) n += R->size();
93     
94     return n;
95   }
96   
97   /// begin - Returns an iterator that iterates over the nodes of the tree
98   ///  in an inorder traversal.  The returned iterator thus refers to the
99   ///  the tree node with the minimum data element.
100   iterator begin() const { return iterator(this); }
101   
102   /// end - Returns an iterator for the tree that denotes the end of an
103   ///  inorder traversal.
104   iterator end() const { return iterator(); }
105   
106   /// isEqual - Compares two trees for structural equality and returns true
107   ///   if they are equal.  This worst case performance of this operation is
108   //    linear in the sizes of the trees.
109   bool isEqual(const ImutAVLTree& RHS) const {
110     if (&RHS == this)
111       return true;
112     
113     iterator LItr = begin(), LEnd = end();
114     iterator RItr = RHS.begin(), REnd = RHS.end();
115     
116     while (LItr != LEnd && RItr != REnd) {
117       if (*LItr == *RItr) {
118         LItr.SkipSubTree();
119         RItr.SkipSubTree();
120         continue;
121       }
122       
123       // FIXME: need to compare data values, not key values, but our
124       // traits don't support this yet.
125       if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(LItr->getValue()),
126                              ImutInfo::KeyOfValue(RItr->getValue())))
127         return false;
128       
129       ++LItr;
130       ++RItr;
131     }
132     
133     return LItr == LEnd && RItr == REnd;
134   }
135
136   /// isNotEqual - Compares two trees for structural inequality.  Performance
137   ///  is the same is isEqual.
138   bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
139   
140   /// contains - Returns true if this tree contains a subtree (node) that
141   ///  has an data element that matches the specified key.  Complexity
142   ///  is logarithmic in the size of the tree.
143   bool contains(const key_type_ref K) { return (bool) find(K); }
144   
145   /// foreach - A member template the accepts invokes operator() on a functor
146   ///  object (specifed by Callback) for every node/subtree in the tree.
147   ///  Nodes are visited using an inorder traversal.
148   template <typename Callback>
149   void foreach(Callback& C) {
150     if (ImutAVLTree* L = getLeft()) L->foreach(C);
151     
152     C(Value);    
153     
154     if (ImutAVLTree* R = getRight()) R->foreach(C);
155   }
156   
157   /// verify - A utility method that checks that the balancing and
158   ///  ordering invariants of the tree are satisifed.  It is a recursive
159   ///  method that returns the height of the tree, which is then consumed
160   ///  by the enclosing verify call.  External callers should ignore the
161   ///  return value.  An invalid tree will cause an assertion to fire in
162   ///  a debug build.
163   unsigned verify() const {
164     unsigned HL = getLeft() ? getLeft()->verify() : 0;
165     unsigned HR = getRight() ? getRight()->verify() : 0;
166     
167     assert (getHeight() == ( HL > HR ? HL : HR ) + 1 
168             && "Height calculation wrong.");
169     
170     assert ((HL > HR ? HL-HR : HR-HL) <= 2
171             && "Balancing invariant violated.");
172     
173     
174     assert (!getLeft()
175             || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
176                                 ImutInfo::KeyOfValue(getValue()))
177             && "Value in left child is not less that current value.");
178     
179     
180     assert (!getRight()
181             || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
182                                 ImutInfo::KeyOfValue(getRight()->getValue()))
183             && "Current value is not less that value of right child.");
184     
185     return getHeight();
186   }  
187   
188   //===----------------------------------------------------===//  
189   // Internal Values.
190   //===----------------------------------------------------===//
191   
192 private:
193   uintptr_t        Left;
194   ImutAVLTree*     Right;
195   unsigned         Height;
196   value_type       Value;
197   
198   //===----------------------------------------------------===//  
199   // Profiling or FoldingSet.
200   //===----------------------------------------------------===//
201   
202   static inline
203   void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
204                value_type_ref V) {    
205     ID.AddPointer(L);
206     ID.AddPointer(R);
207     ImutInfo::Profile(ID,V);
208   }
209   
210 public:
211   
212   void Profile(FoldingSetNodeID& ID) {
213     Profile(ID,getSafeLeft(),getRight(),getValue());    
214   }
215   
216   //===----------------------------------------------------===//    
217   // Internal methods (node manipulation; used by Factory).
218   //===----------------------------------------------------===//
219   
220 private:
221   
222   ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
223   : Left(reinterpret_cast<uintptr_t>(l) | 0x1),
224   Right(r), Height(height), Value(v) {}
225   
226   bool isMutable() const { return Left & 0x1; }
227   
228   ImutAVLTree* getSafeLeft() const { 
229     return reinterpret_cast<ImutAVLTree*>(Left & ~0x1);
230   }
231   
232   // Mutating operations.  A tree root can be manipulated as long as
233   // its reference has not "escaped" from internal methods of a
234   // factory object (see below).  When a tree pointer is externally
235   // viewable by client code, the internal "mutable bit" is cleared
236   // to mark the tree immutable.  Note that a tree that still has
237   // its mutable bit set may have children (subtrees) that are themselves
238   // immutable.
239   
240   void RemoveMutableFlag() {
241     assert (Left & 0x1 && "Mutable flag already removed.");
242     Left &= ~0x1;
243   }
244   
245   void setLeft(ImutAVLTree* NewLeft) {
246     assert (isMutable());
247     Left = reinterpret_cast<uintptr_t>(NewLeft) | 0x1;
248   }
249   
250   void setRight(ImutAVLTree* NewRight) {
251     assert (isMutable());
252     Right = NewRight;
253   }
254   
255   void setHeight(unsigned h) {
256     assert (isMutable());
257     Height = h;
258   }
259 };
260
261 //===----------------------------------------------------------------------===//    
262 // Immutable AVL-Tree Factory class.
263 //===----------------------------------------------------------------------===//
264
265 template <typename ImutInfo >  
266 class ImutAVLFactory {
267   typedef ImutAVLTree<ImutInfo> TreeTy;
268   typedef typename TreeTy::value_type_ref value_type_ref;
269   typedef typename TreeTy::key_type_ref   key_type_ref;
270   
271   typedef FoldingSet<TreeTy> CacheTy;
272   
273   CacheTy Cache;  
274   BumpPtrAllocator Allocator;    
275   
276   //===--------------------------------------------------===//    
277   // Public interface.
278   //===--------------------------------------------------===//
279   
280 public:
281   ImutAVLFactory() {}
282   
283   TreeTy* Add(TreeTy* T, value_type_ref V) {
284     T = Add_internal(V,T);
285     MarkImmutable(T);
286     return T;
287   }
288   
289   TreeTy* Remove(TreeTy* T, key_type_ref V) {
290     T = Remove_internal(V,T);
291     MarkImmutable(T);
292     return T;
293   }
294   
295   TreeTy* GetEmptyTree() const { return NULL; }
296   
297   //===--------------------------------------------------===//    
298   // A bunch of quick helper functions used for reasoning
299   // about the properties of trees and their children.
300   // These have succinct names so that the balancing code
301   // is as terse (and readable) as possible.
302   //===--------------------------------------------------===//
303 private:
304   
305   bool           isEmpty(TreeTy* T) const { return !T; }
306   unsigned        Height(TreeTy* T) const { return T ? T->getHeight() : 0; }  
307   TreeTy*           Left(TreeTy* T) const { return T->getSafeLeft(); }
308   TreeTy*          Right(TreeTy* T) const { return T->getRight(); }  
309   value_type_ref   Value(TreeTy* T) const { return T->Value; }
310   
311   unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
312     unsigned hl = Height(L);
313     unsigned hr = Height(R);
314     return ( hl > hr ? hl : hr ) + 1;
315   }
316   
317   //===--------------------------------------------------===//    
318   // "CreateNode" is used to generate new tree roots that link
319   // to other trees.  The functon may also simply move links
320   // in an existing root if that root is still marked mutable.
321   // This is necessary because otherwise our balancing code
322   // would leak memory as it would create nodes that are
323   // then discarded later before the finished tree is
324   // returned to the caller.
325   //===--------------------------------------------------===//
326   
327   TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
328     FoldingSetNodeID ID;      
329     TreeTy::Profile(ID,L,R,V);      
330     void* InsertPos;
331     
332     if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
333       return T;
334     
335     assert (InsertPos != NULL);
336     
337     // FIXME: more intelligent calculation of alignment.
338     TreeTy* T = (TreeTy*) Allocator.Allocate(sizeof(*T),16);
339     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
340     
341     Cache.InsertNode(T,InsertPos);
342     return T;      
343   }
344   
345   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {      
346     assert (!isEmpty(OldTree));
347     
348     if (OldTree->isMutable()) {
349       OldTree->setLeft(L);
350       OldTree->setRight(R);
351       OldTree->setHeight(IncrementHeight(L,R));
352       return OldTree;
353     }
354     else return CreateNode(L, Value(OldTree), R);
355   }
356   
357   /// Balance - Used by Add_internal and Remove_internal to
358   ///  balance a newly created tree.
359   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
360     
361     unsigned hl = Height(L);
362     unsigned hr = Height(R);
363     
364     if (hl > hr + 2) {
365       assert (!isEmpty(L) &&
366               "Left tree cannot be empty to have a height >= 2.");
367       
368       TreeTy* LL = Left(L);
369       TreeTy* LR = Right(L);
370       
371       if (Height(LL) >= Height(LR))
372         return CreateNode(LL, L, CreateNode(LR,V,R));
373       
374       assert (!isEmpty(LR) &&
375               "LR cannot be empty because it has a height >= 1.");
376       
377       TreeTy* LRL = Left(LR);
378       TreeTy* LRR = Right(LR);
379       
380       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));                              
381     }
382     else if (hr > hl + 2) {
383       assert (!isEmpty(R) &&
384               "Right tree cannot be empty to have a height >= 2.");
385       
386       TreeTy* RL = Left(R);
387       TreeTy* RR = Right(R);
388       
389       if (Height(RR) >= Height(RL))
390         return CreateNode(CreateNode(L,V,RL), R, RR);
391       
392       assert (!isEmpty(RL) &&
393               "RL cannot be empty because it has a height >= 1.");
394       
395       TreeTy* RLL = Left(RL);
396       TreeTy* RLR = Right(RL);
397       
398       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
399     }
400     else
401       return CreateNode(L,V,R);
402   }
403   
404   /// Add_internal - Creates a new tree that includes the specified
405   ///  data and the data from the original tree.  If the original tree
406   ///  already contained the data item, the original tree is returned.
407   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
408     if (isEmpty(T))
409       return CreateNode(T, V, T);
410     
411     assert (!T->isMutable());
412     
413     key_type_ref K = ImutInfo::KeyOfValue(V);
414     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
415     
416     if (ImutInfo::isEqual(K,KCurrent))
417       return CreateNode(Left(T), V, Right(T));
418     else if (ImutInfo::isLess(K,KCurrent))
419       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
420     else
421       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
422   }
423   
424   /// Remove_interal - Creates a new tree that includes all the data
425   ///  from the original tree except the specified data.  If the
426   ///  specified data did not exist in the original tree, the original
427   ///  tree is returned.
428   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
429     if (isEmpty(T))
430       return T;
431     
432     assert (!T->isMutable());
433     
434     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
435     
436     if (ImutInfo::isEqual(K,KCurrent))
437       return CombineLeftRightTrees(Left(T),Right(T));
438     else if (ImutInfo::isLess(K,KCurrent))
439       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
440     else
441       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
442   }
443   
444   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
445     if (isEmpty(L)) return R;      
446     if (isEmpty(R)) return L;
447     
448     TreeTy* OldNode;          
449     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
450     return Balance(L,Value(OldNode),NewRight);
451   }
452   
453   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
454     assert (!isEmpty(T));
455     
456     if (isEmpty(Left(T))) {
457       NodeRemoved = T;
458       return Right(T);
459     }
460     
461     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
462   }    
463   
464   /// MarkImmutable - Clears the mutable bits of a root and all of its
465   ///  descendants.
466   void MarkImmutable(TreeTy* T) {
467     if (!T || !T->isMutable())
468       return;
469     
470     T->RemoveMutableFlag();
471     MarkImmutable(Left(T));
472     MarkImmutable(Right(T));
473   }
474 };
475   
476   
477 //===----------------------------------------------------------------------===//    
478 // Immutable AVL-Tree Iterators.
479 //===----------------------------------------------------------------------===//  
480
481 template <typename ImutInfo>
482 class ImutAVLTreeGenericIterator {
483   SmallVector<uintptr_t,20> stack;
484 public:
485   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3, 
486                    Flags=0x3 };
487   
488   typedef ImutAVLTree<ImutInfo> TreeTy;      
489   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
490
491   inline ImutAVLTreeGenericIterator() {}
492   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
493     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
494   }  
495   
496   TreeTy* operator*() const {
497     assert (!stack.empty());    
498     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
499   }
500   
501   uintptr_t getVisitState() {
502     assert (!stack.empty());
503     return stack.back() & Flags;
504   }
505   
506   
507   bool AtEnd() const { return stack.empty(); }
508
509   bool AtBeginning() const { 
510     return stack.size() == 1 && getVisitState() == VisitedNone;
511   }
512   
513   void SkipToParent() {
514     assert (!stack.empty());
515     stack.pop_back();
516     
517     if (stack.empty())
518       return;
519     
520     switch (getVisitState()) {
521       case VisitedNone:
522         stack.back() |= VisitedLeft;
523         break;
524       case VisitedLeft:
525         stack.back() |= VisitedRight;
526         break;
527       default:
528         assert (false && "Unreachable.");            
529     }
530   }
531   
532   inline bool operator==(const _Self& x) const {
533     if (stack.size() != x.stack.size())
534       return false;
535     
536     for (unsigned i = 0 ; i < stack.size(); i++)
537       if (stack[i] != x.stack[i])
538         return false;
539     
540     return true;
541   }
542   
543   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
544   
545   _Self& operator++() {
546     assert (!stack.empty());
547     
548     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
549     assert (Current);
550     
551     switch (getVisitState()) {
552       case VisitedNone:
553         if (TreeTy* L = Current->getLeft())
554           stack.push_back(reinterpret_cast<uintptr_t>(L));
555         else
556           stack.back() |= VisitedLeft;
557         
558         break;
559         
560       case VisitedLeft:
561         if (TreeTy* R = Current->getRight())
562           stack.push_back(reinterpret_cast<uintptr_t>(R));
563         else
564           stack.back() |= VisitedRight;
565         
566         break;
567         
568       case VisitedRight:
569         SkipToParent();        
570         break;
571         
572       default:
573         assert (false && "Unreachable.");
574     }
575     
576     return *this;
577   }
578   
579   _Self& operator--() {
580     assert (!stack.empty());
581     
582     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
583     assert (Current);
584     
585     switch (getVisitState()) {
586       case VisitedNone:
587         stack.pop_back();
588         break;
589         
590       case VisitedLeft:                
591         stack.back() &= ~Flags; // Set state to "VisitedNone."
592         
593         if (TreeTy* L = Current->getLeft())
594           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
595           
596         break;
597         
598       case VisitedRight:        
599         stack.back() &= ~Flags;
600         stack.back() |= VisitedLeft;
601         
602         if (TreeTy* R = Current->getRight())
603           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
604           
605         break;
606         
607       default:
608         assert (false && "Unreachable.");
609     }
610     
611     return *this;
612   }
613 };
614   
615 template <typename ImutInfo>
616 class ImutAVLTreeInOrderIterator {
617   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
618   InternalIteratorTy InternalItr;
619
620 public:
621   typedef ImutAVLTree<ImutInfo> TreeTy;
622   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
623
624   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) { 
625     if (Root) operator++(); // Advance to first element.
626   }
627   
628   ImutAVLTreeInOrderIterator() : InternalItr() {}
629
630   inline bool operator==(const _Self& x) const {
631     return InternalItr == x.InternalItr;
632   }
633   
634   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
635   
636   inline TreeTy* operator*() const { return *InternalItr; }
637   inline TreeTy* operator->() const { return *InternalItr; }
638   
639   inline _Self& operator++() { 
640     do ++InternalItr;
641     while (!InternalItr.AtEnd() && 
642            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
643
644     return *this;
645   }
646   
647   inline _Self& operator--() { 
648     do --InternalItr;
649     while (!InternalItr.AtBeginning() && 
650            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
651     
652     return *this;
653   }
654   
655   inline void SkipSubTree() {
656     InternalItr.SkipToParent();
657     
658     while (!InternalItr.AtEnd() &&
659            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
660       ++InternalItr;        
661   }
662 };
663     
664 //===----------------------------------------------------------------------===//    
665 // Trait classes for Profile information.
666 //===----------------------------------------------------------------------===//
667
668 /// Generic profile template.  The default behavior is to invoke the
669 /// profile method of an object.  Specializations for primitive integers
670 /// and generic handling of pointers is done below.
671 template <typename T>
672 struct ImutProfileInfo {
673   typedef const T  value_type;
674   typedef const T& value_type_ref;
675   
676   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
677     X.Profile(ID);
678   }  
679 };
680
681 /// Profile traits for integers.
682 template <typename T>
683 struct ImutProfileInteger {    
684   typedef const T  value_type;
685   typedef const T& value_type_ref;
686   
687   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
688     ID.AddInteger(X);
689   }  
690 };
691
692 #define PROFILE_INTEGER_INFO(X)\
693 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
694
695 PROFILE_INTEGER_INFO(char)
696 PROFILE_INTEGER_INFO(unsigned char)
697 PROFILE_INTEGER_INFO(short)
698 PROFILE_INTEGER_INFO(unsigned short)
699 PROFILE_INTEGER_INFO(unsigned)
700 PROFILE_INTEGER_INFO(signed)
701 PROFILE_INTEGER_INFO(long)
702 PROFILE_INTEGER_INFO(unsigned long)
703 PROFILE_INTEGER_INFO(long long)
704 PROFILE_INTEGER_INFO(unsigned long long)
705
706 #undef PROFILE_INTEGER_INFO
707
708 /// Generic profile trait for pointer types.  We treat pointers as
709 /// references to unique objects.
710 template <typename T>
711 struct ImutProfileInfo<T*> {
712   typedef const T*   value_type;
713   typedef value_type value_type_ref;
714   
715   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
716     ID.AddPointer(X);
717   }
718 };
719
720 //===----------------------------------------------------------------------===//    
721 // Trait classes that contain element comparison operators and type
722 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
723 //  inherit from the profile traits (ImutProfileInfo) to include operations
724 //  for element profiling.
725 //===----------------------------------------------------------------------===//
726
727
728 /// ImutContainerInfo - Generic definition of comparison operations for
729 ///   elements of immutable containers that defaults to using
730 ///   std::equal_to<> and std::less<> to perform comparison of elements.
731 template <typename T>
732 struct ImutContainerInfo : public ImutProfileInfo<T> {
733   typedef typename ImutProfileInfo<T>::value_type      value_type;
734   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
735   typedef value_type      key_type;
736   typedef value_type_ref  key_type_ref;
737   
738   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
739   
740   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) { 
741     return std::equal_to<key_type>()(LHS,RHS);
742   }
743   
744   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
745     return std::less<key_type>()(LHS,RHS);
746   }
747 };
748
749 /// ImutContainerInfo - Specialization for pointer values to treat pointers
750 ///  as references to unique objects.  Pointers are thus compared by
751 ///  their addresses.
752 template <typename T>
753 struct ImutContainerInfo<T*> : 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;
758   
759   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
760   
761   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
762     return LHS == RHS;
763   }
764   
765   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
766     return LHS < RHS;
767   }
768 };
769
770 //===----------------------------------------------------------------------===//    
771 // Immutable Set
772 //===----------------------------------------------------------------------===//
773
774 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
775 class ImmutableSet {
776 public:
777   typedef typename ValInfo::value_type      value_type;
778   typedef typename ValInfo::value_type_ref  value_type_ref;
779   
780 private:  
781   typedef ImutAVLTree<ValInfo> TreeTy;
782   TreeTy* Root;
783   
784   ImmutableSet(TreeTy* R) : Root(R) {}
785   
786 public:
787   
788   class Factory {
789     typename TreeTy::Factory F;
790     
791   public:
792     Factory() {}
793     
794     /// GetEmptySet - Returns an immutable set that contains no elements.
795     ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
796     
797     /// Add - Creates a new immutable set that contains all of the values
798     ///  of the original set with the addition of the specified value.  If
799     ///  the original set already included the value, then the original set is
800     ///  returned and no memory is allocated.  The time and space complexity
801     ///  of this operation is logarithmic in the size of the original set.
802     ///  The memory allocated to represent the set is released when the
803     ///  factory object that created the set is destroyed.
804     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
805       return ImmutableSet(F.Add(Old.Root,V));
806     }
807     
808     /// Remove - Creates a new immutable set that contains all of the values
809     ///  of the original set with the exception of the specified value.  If
810     ///  the original set did not contain the value, the original set is
811     ///  returned and no memory is allocated.  The time and space complexity
812     ///  of this operation is logarithmic in the size of the original set.
813     ///  The memory allocated to represent the set is released when the
814     ///  factory object that created the set is destroyed.
815     ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
816       return ImmutableSet(F.Remove(Old.Root,V));
817     }
818     
819   private:
820     Factory(const Factory& RHS) {};
821     void operator=(const Factory& RHS) {};    
822   };
823   
824   friend class Factory;  
825
826   /// contains - Returns true if the set contains the specified value.
827   bool contains(const value_type_ref V) const {
828     return Root ? Root->contains(V) : false;
829   }
830   
831   bool operator==(ImmutableSet RHS) const {
832     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
833   }
834   
835   bool operator!=(ImmutableSet RHS) const {
836     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
837   }
838   
839   /// isEmpty - Return true if the set contains no elements.
840   bool isEmpty() const { return !Root; }
841   
842   template <typename Callback>
843   void foreach(Callback& C) { if (Root) Root->foreach(C); }
844   
845   template <typename Callback>
846   void foreach() { if (Root) { Callback C; Root->foreach(C); } }
847     
848   //===--------------------------------------------------===//    
849   // Iterators.
850   //===--------------------------------------------------===//  
851
852   class iterator {
853     typename TreeTy::iterator itr;
854     
855     iterator() {}
856     iterator(TreeTy* t) : itr(t) {}
857     friend class ImmutableSet<ValT,ValInfo>;
858   public:
859     inline value_type_ref operator*() const { return itr->getValue(); }
860     inline iterator& operator++() { ++itr; return *this; }
861     inline iterator& operator--() { --itr; return *this; }
862     inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
863     inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }        
864   };
865   
866   iterator begin() const { return iterator(Root); }
867   iterator end() const { return iterator(); }  
868   
869   //===--------------------------------------------------===//    
870   // For testing.
871   //===--------------------------------------------------===//  
872   
873   void verify() const { if (Root) Root->verify(); }
874   unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
875 };
876
877 } // end namespace llvm
878
879 #endif