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