Don't attribute in file headers anymore. See llvmdev for the
[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 is distributed under the University of Illinois Open Source
6 // 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 private:
203
204   /// Profile - Generates a FoldingSet profile for a tree node before it is
205   ///   created.  This is used by the ImutAVLFactory when creating
206   ///   trees.
207   static inline
208   void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
209                value_type_ref V) {    
210     ID.AddPointer(L);
211     ID.AddPointer(R);
212     ImutInfo::Profile(ID,V);
213   }
214   
215 public:
216
217   /// Profile - Generates a FoldingSet profile for an existing tree node.
218   void Profile(FoldingSetNodeID& ID) {
219     Profile(ID,getSafeLeft(),getRight(),getValue());    
220   }
221   
222   //===----------------------------------------------------===//    
223   // Internal methods (node manipulation; used by Factory).
224   //===----------------------------------------------------===//
225   
226 private:
227   
228   enum { Mutable = 0x1 };
229   
230   /// ImutAVLTree - Internal constructor that is only called by
231   ///   ImutAVLFactory.
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) {}
235   
236   
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; }
244   
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);
250   }
251   
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
260   // immutable.
261   //===----------------------------------------------------===//
262   
263   
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.");
269     Left &= ~Mutable;
270   }
271   
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.");
277     
278     Left = reinterpret_cast<uintptr_t>(NewLeft) | Mutable;
279   }
280   
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.");
286     
287     Right = NewRight;
288   }
289   
290   /// setHeight - Changes the height of the tree.  Used internally by
291   ///  ImutAVLFactory.
292   void setHeight(unsigned h) {
293     assert (isMutable() && "Only a mutable tree can have its height changed.");
294     Height = h;
295   }
296 };
297
298 //===----------------------------------------------------------------------===//    
299 // Immutable AVL-Tree Factory class.
300 //===----------------------------------------------------------------------===//
301
302 template <typename ImutInfo >  
303 class ImutAVLFactory {
304   typedef ImutAVLTree<ImutInfo> TreeTy;
305   typedef typename TreeTy::value_type_ref value_type_ref;
306   typedef typename TreeTy::key_type_ref   key_type_ref;
307   
308   typedef FoldingSet<TreeTy> CacheTy;
309   
310   CacheTy Cache;  
311   BumpPtrAllocator Allocator;    
312   
313   //===--------------------------------------------------===//    
314   // Public interface.
315   //===--------------------------------------------------===//
316   
317 public:
318   ImutAVLFactory() {}
319   
320   TreeTy* Add(TreeTy* T, value_type_ref V) {
321     T = Add_internal(V,T);
322     MarkImmutable(T);
323     return T;
324   }
325   
326   TreeTy* Remove(TreeTy* T, key_type_ref V) {
327     T = Remove_internal(V,T);
328     MarkImmutable(T);
329     return T;
330   }
331   
332   TreeTy* GetEmptyTree() const { return NULL; }
333   
334   BumpPtrAllocator& getAllocator() { return Allocator; }
335   
336   //===--------------------------------------------------===//    
337   // A bunch of quick helper functions used for reasoning
338   // about the properties of trees and their children.
339   // These have succinct names so that the balancing code
340   // is as terse (and readable) as possible.
341   //===--------------------------------------------------===//
342 private:
343   
344   bool           isEmpty(TreeTy* T) const { return !T; }
345   unsigned        Height(TreeTy* T) const { return T ? T->getHeight() : 0; }  
346   TreeTy*           Left(TreeTy* T) const { return T->getSafeLeft(); }
347   TreeTy*          Right(TreeTy* T) const { return T->getRight(); }  
348   value_type_ref   Value(TreeTy* T) const { return T->Value; }
349   
350   unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
351     unsigned hl = Height(L);
352     unsigned hr = Height(R);
353     return ( hl > hr ? hl : hr ) + 1;
354   }
355   
356   //===--------------------------------------------------===//    
357   // "CreateNode" is used to generate new tree roots that link
358   // to other trees.  The functon may also simply move links
359   // in an existing root if that root is still marked mutable.
360   // This is necessary because otherwise our balancing code
361   // would leak memory as it would create nodes that are
362   // then discarded later before the finished tree is
363   // returned to the caller.
364   //===--------------------------------------------------===//
365   
366   TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
367     FoldingSetNodeID ID;      
368     TreeTy::Profile(ID,L,R,V);      
369     void* InsertPos;
370     
371     if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
372       return T;
373     
374     assert (InsertPos != NULL);
375     
376     // Allocate the new tree node and insert it into the cache.
377     TreeTy* T = (TreeTy*) Allocator.Allocate<TreeTy>();    
378     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
379     Cache.InsertNode(T,InsertPos);
380
381     return T;      
382   }
383   
384   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {      
385     assert (!isEmpty(OldTree));
386     
387     if (OldTree->isMutable()) {
388       OldTree->setLeft(L);
389       OldTree->setRight(R);
390       OldTree->setHeight(IncrementHeight(L,R));
391       return OldTree;
392     }
393     else return CreateNode(L, Value(OldTree), R);
394   }
395   
396   /// Balance - Used by Add_internal and Remove_internal to
397   ///  balance a newly created tree.
398   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
399     
400     unsigned hl = Height(L);
401     unsigned hr = Height(R);
402     
403     if (hl > hr + 2) {
404       assert (!isEmpty(L) &&
405               "Left tree cannot be empty to have a height >= 2.");
406       
407       TreeTy* LL = Left(L);
408       TreeTy* LR = Right(L);
409       
410       if (Height(LL) >= Height(LR))
411         return CreateNode(LL, L, CreateNode(LR,V,R));
412       
413       assert (!isEmpty(LR) &&
414               "LR cannot be empty because it has a height >= 1.");
415       
416       TreeTy* LRL = Left(LR);
417       TreeTy* LRR = Right(LR);
418       
419       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));                              
420     }
421     else if (hr > hl + 2) {
422       assert (!isEmpty(R) &&
423               "Right tree cannot be empty to have a height >= 2.");
424       
425       TreeTy* RL = Left(R);
426       TreeTy* RR = Right(R);
427       
428       if (Height(RR) >= Height(RL))
429         return CreateNode(CreateNode(L,V,RL), R, RR);
430       
431       assert (!isEmpty(RL) &&
432               "RL cannot be empty because it has a height >= 1.");
433       
434       TreeTy* RLL = Left(RL);
435       TreeTy* RLR = Right(RL);
436       
437       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
438     }
439     else
440       return CreateNode(L,V,R);
441   }
442   
443   /// Add_internal - Creates a new tree that includes the specified
444   ///  data and the data from the original tree.  If the original tree
445   ///  already contained the data item, the original tree is returned.
446   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
447     if (isEmpty(T))
448       return CreateNode(T, V, T);
449     
450     assert (!T->isMutable());
451     
452     key_type_ref K = ImutInfo::KeyOfValue(V);
453     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
454     
455     if (ImutInfo::isEqual(K,KCurrent))
456       return CreateNode(Left(T), V, Right(T));
457     else if (ImutInfo::isLess(K,KCurrent))
458       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
459     else
460       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
461   }
462   
463   /// Remove_interal - Creates a new tree that includes all the data
464   ///  from the original tree except the specified data.  If the
465   ///  specified data did not exist in the original tree, the original
466   ///  tree is returned.
467   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
468     if (isEmpty(T))
469       return T;
470     
471     assert (!T->isMutable());
472     
473     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
474     
475     if (ImutInfo::isEqual(K,KCurrent))
476       return CombineLeftRightTrees(Left(T),Right(T));
477     else if (ImutInfo::isLess(K,KCurrent))
478       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
479     else
480       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
481   }
482   
483   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
484     if (isEmpty(L)) return R;      
485     if (isEmpty(R)) return L;
486     
487     TreeTy* OldNode;          
488     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
489     return Balance(L,Value(OldNode),NewRight);
490   }
491   
492   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
493     assert (!isEmpty(T));
494     
495     if (isEmpty(Left(T))) {
496       NodeRemoved = T;
497       return Right(T);
498     }
499     
500     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
501   }    
502   
503   /// MarkImmutable - Clears the mutable bits of a root and all of its
504   ///  descendants.
505   void MarkImmutable(TreeTy* T) {
506     if (!T || !T->isMutable())
507       return;
508     
509     T->MarkImmutable();
510     MarkImmutable(Left(T));
511     MarkImmutable(Right(T));
512   }
513 };
514   
515   
516 //===----------------------------------------------------------------------===//    
517 // Immutable AVL-Tree Iterators.
518 //===----------------------------------------------------------------------===//  
519
520 template <typename ImutInfo>
521 class ImutAVLTreeGenericIterator {
522   SmallVector<uintptr_t,20> stack;
523 public:
524   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3, 
525                    Flags=0x3 };
526   
527   typedef ImutAVLTree<ImutInfo> TreeTy;      
528   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
529
530   inline ImutAVLTreeGenericIterator() {}
531   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
532     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
533   }  
534   
535   TreeTy* operator*() const {
536     assert (!stack.empty());    
537     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
538   }
539   
540   uintptr_t getVisitState() {
541     assert (!stack.empty());
542     return stack.back() & Flags;
543   }
544   
545   
546   bool AtEnd() const { return stack.empty(); }
547
548   bool AtBeginning() const { 
549     return stack.size() == 1 && getVisitState() == VisitedNone;
550   }
551   
552   void SkipToParent() {
553     assert (!stack.empty());
554     stack.pop_back();
555     
556     if (stack.empty())
557       return;
558     
559     switch (getVisitState()) {
560       case VisitedNone:
561         stack.back() |= VisitedLeft;
562         break;
563       case VisitedLeft:
564         stack.back() |= VisitedRight;
565         break;
566       default:
567         assert (false && "Unreachable.");            
568     }
569   }
570   
571   inline bool operator==(const _Self& x) const {
572     if (stack.size() != x.stack.size())
573       return false;
574     
575     for (unsigned i = 0 ; i < stack.size(); i++)
576       if (stack[i] != x.stack[i])
577         return false;
578     
579     return true;
580   }
581   
582   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
583   
584   _Self& operator++() {
585     assert (!stack.empty());
586     
587     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
588     assert (Current);
589     
590     switch (getVisitState()) {
591       case VisitedNone:
592         if (TreeTy* L = Current->getLeft())
593           stack.push_back(reinterpret_cast<uintptr_t>(L));
594         else
595           stack.back() |= VisitedLeft;
596         
597         break;
598         
599       case VisitedLeft:
600         if (TreeTy* R = Current->getRight())
601           stack.push_back(reinterpret_cast<uintptr_t>(R));
602         else
603           stack.back() |= VisitedRight;
604         
605         break;
606         
607       case VisitedRight:
608         SkipToParent();        
609         break;
610         
611       default:
612         assert (false && "Unreachable.");
613     }
614     
615     return *this;
616   }
617   
618   _Self& operator--() {
619     assert (!stack.empty());
620     
621     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
622     assert (Current);
623     
624     switch (getVisitState()) {
625       case VisitedNone:
626         stack.pop_back();
627         break;
628         
629       case VisitedLeft:                
630         stack.back() &= ~Flags; // Set state to "VisitedNone."
631         
632         if (TreeTy* L = Current->getLeft())
633           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
634           
635         break;
636         
637       case VisitedRight:        
638         stack.back() &= ~Flags;
639         stack.back() |= VisitedLeft;
640         
641         if (TreeTy* R = Current->getRight())
642           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
643           
644         break;
645         
646       default:
647         assert (false && "Unreachable.");
648     }
649     
650     return *this;
651   }
652 };
653   
654 template <typename ImutInfo>
655 class ImutAVLTreeInOrderIterator {
656   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
657   InternalIteratorTy InternalItr;
658
659 public:
660   typedef ImutAVLTree<ImutInfo> TreeTy;
661   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
662
663   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) { 
664     if (Root) operator++(); // Advance to first element.
665   }
666   
667   ImutAVLTreeInOrderIterator() : InternalItr() {}
668
669   inline bool operator==(const _Self& x) const {
670     return InternalItr == x.InternalItr;
671   }
672   
673   inline bool operator!=(const _Self& x) const { return !operator==(x); }  
674   
675   inline TreeTy* operator*() const { return *InternalItr; }
676   inline TreeTy* operator->() const { return *InternalItr; }
677   
678   inline _Self& operator++() { 
679     do ++InternalItr;
680     while (!InternalItr.AtEnd() && 
681            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
682
683     return *this;
684   }
685   
686   inline _Self& operator--() { 
687     do --InternalItr;
688     while (!InternalItr.AtBeginning() && 
689            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
690     
691     return *this;
692   }
693   
694   inline void SkipSubTree() {
695     InternalItr.SkipToParent();
696     
697     while (!InternalItr.AtEnd() &&
698            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
699       ++InternalItr;        
700   }
701 };
702     
703 //===----------------------------------------------------------------------===//    
704 // Trait classes for Profile information.
705 //===----------------------------------------------------------------------===//
706
707 /// Generic profile template.  The default behavior is to invoke the
708 /// profile method of an object.  Specializations for primitive integers
709 /// and generic handling of pointers is done below.
710 template <typename T>
711 struct ImutProfileInfo {
712   typedef const T  value_type;
713   typedef const T& value_type_ref;
714   
715   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
716     X.Profile(ID);
717   }  
718 };
719
720 /// Profile traits for integers.
721 template <typename T>
722 struct ImutProfileInteger {    
723   typedef const T  value_type;
724   typedef const T& value_type_ref;
725   
726   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
727     ID.AddInteger(X);
728   }  
729 };
730
731 #define PROFILE_INTEGER_INFO(X)\
732 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
733
734 PROFILE_INTEGER_INFO(char)
735 PROFILE_INTEGER_INFO(unsigned char)
736 PROFILE_INTEGER_INFO(short)
737 PROFILE_INTEGER_INFO(unsigned short)
738 PROFILE_INTEGER_INFO(unsigned)
739 PROFILE_INTEGER_INFO(signed)
740 PROFILE_INTEGER_INFO(long)
741 PROFILE_INTEGER_INFO(unsigned long)
742 PROFILE_INTEGER_INFO(long long)
743 PROFILE_INTEGER_INFO(unsigned long long)
744
745 #undef PROFILE_INTEGER_INFO
746
747 /// Generic profile trait for pointer types.  We treat pointers as
748 /// references to unique objects.
749 template <typename T>
750 struct ImutProfileInfo<T*> {
751   typedef const T*   value_type;
752   typedef value_type value_type_ref;
753   
754   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
755     ID.AddPointer(X);
756   }
757 };
758
759 //===----------------------------------------------------------------------===//    
760 // Trait classes that contain element comparison operators and type
761 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
762 //  inherit from the profile traits (ImutProfileInfo) to include operations
763 //  for element profiling.
764 //===----------------------------------------------------------------------===//
765
766
767 /// ImutContainerInfo - Generic definition of comparison operations for
768 ///   elements of immutable containers that defaults to using
769 ///   std::equal_to<> and std::less<> to perform comparison of elements.
770 template <typename T>
771 struct ImutContainerInfo : public ImutProfileInfo<T> {
772   typedef typename ImutProfileInfo<T>::value_type      value_type;
773   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
774   typedef value_type      key_type;
775   typedef value_type_ref  key_type_ref;
776   
777   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
778   
779   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) { 
780     return std::equal_to<key_type>()(LHS,RHS);
781   }
782   
783   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
784     return std::less<key_type>()(LHS,RHS);
785   }
786 };
787
788 /// ImutContainerInfo - Specialization for pointer values to treat pointers
789 ///  as references to unique objects.  Pointers are thus compared by
790 ///  their addresses.
791 template <typename T>
792 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
793   typedef typename ImutProfileInfo<T*>::value_type      value_type;
794   typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
795   typedef value_type      key_type;
796   typedef value_type_ref  key_type_ref;
797   
798   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
799   
800   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
801     return LHS == RHS;
802   }
803   
804   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
805     return LHS < RHS;
806   }
807 };
808
809 //===----------------------------------------------------------------------===//    
810 // Immutable Set
811 //===----------------------------------------------------------------------===//
812
813 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
814 class ImmutableSet {
815 public:
816   typedef typename ValInfo::value_type      value_type;
817   typedef typename ValInfo::value_type_ref  value_type_ref;
818   
819 private:  
820   typedef ImutAVLTree<ValInfo> TreeTy;
821   TreeTy* Root;
822   
823   ImmutableSet(TreeTy* R) : Root(R) {}
824   
825 public:
826   
827   class Factory {
828     typename TreeTy::Factory F;
829     
830   public:
831     Factory() {}
832     
833     /// GetEmptySet - Returns an immutable set that contains no elements.
834     ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
835     
836     /// Add - Creates a new immutable set that contains all of the values
837     ///  of the original set with the addition of the specified value.  If
838     ///  the original set already included the value, then the original set is
839     ///  returned and no memory is allocated.  The time and space complexity
840     ///  of this operation is logarithmic in the size of the original set.
841     ///  The memory allocated to represent the set is released when the
842     ///  factory object that created the set is destroyed.
843     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
844       return ImmutableSet(F.Add(Old.Root,V));
845     }
846     
847     /// Remove - Creates a new immutable set that contains all of the values
848     ///  of the original set with the exception of the specified value.  If
849     ///  the original set did not contain the value, the original set is
850     ///  returned and no memory is allocated.  The time and space complexity
851     ///  of this operation is logarithmic in the size of the original set.
852     ///  The memory allocated to represent the set is released when the
853     ///  factory object that created the set is destroyed.
854     ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
855       return ImmutableSet(F.Remove(Old.Root,V));
856     }
857     
858     BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
859
860   private:
861     Factory(const Factory& RHS) {};
862     void operator=(const Factory& RHS) {};    
863   };
864   
865   friend class Factory;  
866
867   /// contains - Returns true if the set contains the specified value.
868   bool contains(const value_type_ref V) const {
869     return Root ? Root->contains(V) : false;
870   }
871   
872   bool operator==(ImmutableSet RHS) const {
873     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
874   }
875   
876   bool operator!=(ImmutableSet RHS) const {
877     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
878   }
879   
880   /// isEmpty - Return true if the set contains no elements.
881   bool isEmpty() const { return !Root; }
882   
883   template <typename Callback>
884   void foreach(Callback& C) { if (Root) Root->foreach(C); }
885   
886   template <typename Callback>
887   void foreach() { if (Root) { Callback C; Root->foreach(C); } }
888     
889   //===--------------------------------------------------===//    
890   // Iterators.
891   //===--------------------------------------------------===//  
892
893   class iterator {
894     typename TreeTy::iterator itr;
895     
896     iterator() {}
897     iterator(TreeTy* t) : itr(t) {}
898     friend class ImmutableSet<ValT,ValInfo>;
899   public:
900     inline value_type_ref operator*() const { return itr->getValue(); }
901     inline iterator& operator++() { ++itr; return *this; }
902     inline iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
903     inline iterator& operator--() { --itr; return *this; }
904     inline iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
905     inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
906     inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }        
907   };
908   
909   iterator begin() const { return iterator(Root); }
910   iterator end() const { return iterator(); }  
911   
912   //===--------------------------------------------------===//    
913   // For testing.
914   //===--------------------------------------------------===//  
915   
916   void verify() const { if (Root) Root->verify(); }
917   unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
918 };
919
920 } // end namespace llvm
921
922 #endif