Make default ctor for ImmutableSet::iterator public.
[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 "llvm/Support/DataTypes.h"
20 #include <cassert>
21 #include <functional>
22
23 namespace llvm {
24
25 //===----------------------------------------------------------------------===//
26 // Immutable AVL-Tree Definition.
27 //===----------------------------------------------------------------------===//
28
29 template <typename ImutInfo> class ImutAVLFactory;
30 template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
31 template <typename ImutInfo> class ImutAVLTreeGenericIterator;
32
33 template <typename ImutInfo >
34 class ImutAVLTree : public FoldingSetNode {
35 public:
36   typedef typename ImutInfo::key_type_ref   key_type_ref;
37   typedef typename ImutInfo::value_type     value_type;
38   typedef typename ImutInfo::value_type_ref value_type_ref;
39
40   typedef ImutAVLFactory<ImutInfo>          Factory;
41   friend class ImutAVLFactory<ImutInfo>;
42
43   friend class ImutAVLTreeGenericIterator<ImutInfo>;
44   friend class FoldingSet<ImutAVLTree>;
45
46   typedef ImutAVLTreeInOrderIterator<ImutInfo>  iterator;
47
48   //===----------------------------------------------------===//
49   // Public Interface.
50   //===----------------------------------------------------===//
51
52   /// getLeft - Returns a pointer to the left subtree.  This value
53   ///  is NULL if there is no left subtree.
54   ImutAVLTree *getLeft() const {
55     return reinterpret_cast<ImutAVLTree*>(Left & ~LeftFlags);
56   }
57
58   /// getRight - Returns a pointer to the right subtree.  This value is
59   ///  NULL if there is no right subtree.
60   ImutAVLTree* getRight() const { return Right; }
61
62   /// getHeight - Returns the height of the tree.  A tree with no subtrees
63   ///  has a height of 1.
64   unsigned getHeight() const { return Height; }
65
66   /// getValue - Returns the data value associated with the tree node.
67   const value_type& getValue() const { return Value; }
68
69   /// find - Finds the subtree associated with the specified key value.
70   ///  This method returns NULL if no matching subtree is found.
71   ImutAVLTree* find(key_type_ref K) {
72     ImutAVLTree *T = this;
73
74     while (T) {
75       key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
76
77       if (ImutInfo::isEqual(K,CurrentKey))
78         return T;
79       else if (ImutInfo::isLess(K,CurrentKey))
80         T = T->getLeft();
81       else
82         T = T->getRight();
83     }
84
85     return NULL;
86   }
87   
88   /// getMaxElement - Find the subtree associated with the highest ranged
89   ///  key value.
90   ImutAVLTree* getMaxElement() {
91     ImutAVLTree *T = this;
92     ImutAVLTree *Right = T->getRight();    
93     while (Right) { T = Right; Right = T->getRight(); }
94     return T;
95   }
96
97   /// size - Returns the number of nodes in the tree, which includes
98   ///  both leaves and non-leaf nodes.
99   unsigned size() const {
100     unsigned n = 1;
101
102     if (const ImutAVLTree* L = getLeft())  n += L->size();
103     if (const ImutAVLTree* R = getRight()) n += R->size();
104
105     return n;
106   }
107
108   /// begin - Returns an iterator that iterates over the nodes of the tree
109   ///  in an inorder traversal.  The returned iterator thus refers to the
110   ///  the tree node with the minimum data element.
111   iterator begin() const { return iterator(this); }
112
113   /// end - Returns an iterator for the tree that denotes the end of an
114   ///  inorder traversal.
115   iterator end() const { return iterator(); }
116
117   bool ElementEqual(value_type_ref V) const {
118     // Compare the keys.
119     if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
120                            ImutInfo::KeyOfValue(V)))
121       return false;
122
123     // Also compare the data values.
124     if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
125                                ImutInfo::DataOfValue(V)))
126       return false;
127
128     return true;
129   }
130
131   bool ElementEqual(const ImutAVLTree* RHS) const {
132     return ElementEqual(RHS->getValue());
133   }
134
135   /// isEqual - Compares two trees for structural equality and returns true
136   ///   if they are equal.  This worst case performance of this operation is
137   //    linear in the sizes of the trees.
138   bool isEqual(const ImutAVLTree& RHS) const {
139     if (&RHS == this)
140       return true;
141
142     iterator LItr = begin(), LEnd = end();
143     iterator RItr = RHS.begin(), REnd = RHS.end();
144
145     while (LItr != LEnd && RItr != REnd) {
146       if (*LItr == *RItr) {
147         LItr.SkipSubTree();
148         RItr.SkipSubTree();
149         continue;
150       }
151
152       if (!LItr->ElementEqual(*RItr))
153         return false;
154
155       ++LItr;
156       ++RItr;
157     }
158
159     return LItr == LEnd && RItr == REnd;
160   }
161
162   /// isNotEqual - Compares two trees for structural inequality.  Performance
163   ///  is the same is isEqual.
164   bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
165
166   /// contains - Returns true if this tree contains a subtree (node) that
167   ///  has an data element that matches the specified key.  Complexity
168   ///  is logarithmic in the size of the tree.
169   bool contains(key_type_ref K) { return (bool) find(K); }
170
171   /// foreach - A member template the accepts invokes operator() on a functor
172   ///  object (specifed by Callback) for every node/subtree in the tree.
173   ///  Nodes are visited using an inorder traversal.
174   template <typename Callback>
175   void foreach(Callback& C) {
176     if (ImutAVLTree* L = getLeft()) L->foreach(C);
177
178     C(Value);
179
180     if (ImutAVLTree* R = getRight()) R->foreach(C);
181   }
182
183   /// verify - A utility method that checks that the balancing and
184   ///  ordering invariants of the tree are satisifed.  It is a recursive
185   ///  method that returns the height of the tree, which is then consumed
186   ///  by the enclosing verify call.  External callers should ignore the
187   ///  return value.  An invalid tree will cause an assertion to fire in
188   ///  a debug build.
189   unsigned verify() const {
190     unsigned HL = getLeft() ? getLeft()->verify() : 0;
191     unsigned HR = getRight() ? getRight()->verify() : 0;
192
193     assert (getHeight() == ( HL > HR ? HL : HR ) + 1
194             && "Height calculation wrong.");
195
196     assert ((HL > HR ? HL-HR : HR-HL) <= 2
197             && "Balancing invariant violated.");
198
199
200     assert (!getLeft()
201             || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
202                                 ImutInfo::KeyOfValue(getValue()))
203             && "Value in left child is not less that current value.");
204
205
206     assert (!getRight()
207             || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
208                                 ImutInfo::KeyOfValue(getRight()->getValue()))
209             && "Current value is not less that value of right child.");
210
211     return getHeight();
212   }
213
214   /// Profile - Profiling for ImutAVLTree.
215   void Profile(llvm::FoldingSetNodeID& ID) {
216     ID.AddInteger(ComputeDigest());
217   }
218
219   //===----------------------------------------------------===//
220   // Internal Values.
221   //===----------------------------------------------------===//
222
223 private:
224   uintptr_t        Left;
225   ImutAVLTree*     Right;
226   unsigned         Height;
227   value_type       Value;
228   uint32_t         Digest;
229
230   //===----------------------------------------------------===//
231   // Internal methods (node manipulation; used by Factory).
232   //===----------------------------------------------------===//
233
234 private:
235
236   enum { Mutable = 0x1, NoCachedDigest = 0x2, LeftFlags = 0x3 };
237
238   /// ImutAVLTree - Internal constructor that is only called by
239   ///   ImutAVLFactory.
240   ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
241   : Left(reinterpret_cast<uintptr_t>(l) | (Mutable | NoCachedDigest)),
242     Right(r), Height(height), Value(v), Digest(0) {}
243
244
245   /// isMutable - Returns true if the left and right subtree references
246   ///  (as well as height) can be changed.  If this method returns false,
247   ///  the tree is truly immutable.  Trees returned from an ImutAVLFactory
248   ///  object should always have this method return true.  Further, if this
249   ///  method returns false for an instance of ImutAVLTree, all subtrees
250   ///  will also have this method return false.  The converse is not true.
251   bool isMutable() const { return Left & Mutable; }
252   
253   /// hasCachedDigest - Returns true if the digest for this tree is cached.
254   ///  This can only be true if the tree is immutable.
255   bool hasCachedDigest() const { return !(Left & NoCachedDigest); }
256
257   //===----------------------------------------------------===//
258   // Mutating operations.  A tree root can be manipulated as
259   // long as its reference has not "escaped" from internal
260   // methods of a factory object (see below).  When a tree
261   // pointer is externally viewable by client code, the
262   // internal "mutable bit" is cleared to mark the tree
263   // immutable.  Note that a tree that still has its mutable
264   // bit set may have children (subtrees) that are themselves
265   // immutable.
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().
270   void MarkImmutable() {
271     assert(isMutable() && "Mutable flag already removed.");
272     Left &= ~Mutable;
273   }
274   
275   /// MarkedCachedDigest - Clears the NoCachedDigest flag for a tree.
276   void MarkedCachedDigest() {
277     assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
278     Left &= ~NoCachedDigest;
279   }
280
281   /// setLeft - Changes the reference of the left subtree.  Used internally
282   ///   by ImutAVLFactory.
283   void setLeft(ImutAVLTree* NewLeft) {
284     assert(isMutable() &&
285            "Only a mutable tree can have its left subtree changed.");
286     Left = reinterpret_cast<uintptr_t>(NewLeft) | LeftFlags;
287   }
288
289   /// setRight - Changes the reference of the right subtree.  Used internally
290   ///  by ImutAVLFactory.
291   void setRight(ImutAVLTree* NewRight) {
292     assert(isMutable() &&
293            "Only a mutable tree can have its right subtree changed.");
294
295     Right = NewRight;
296     // Set the NoCachedDigest flag.
297     Left = Left | NoCachedDigest;
298
299   }
300
301   /// setHeight - Changes the height of the tree.  Used internally by
302   ///  ImutAVLFactory.
303   void setHeight(unsigned h) {
304     assert(isMutable() && "Only a mutable tree can have its height changed.");
305     Height = h;
306   }
307
308   static inline
309   uint32_t ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
310     uint32_t digest = 0;
311
312     if (L)
313       digest += L->ComputeDigest();
314
315     // Compute digest of stored data.
316     FoldingSetNodeID ID;
317     ImutInfo::Profile(ID,V);
318     digest += ID.ComputeHash();
319
320     if (R)
321       digest += R->ComputeDigest();
322
323     return digest;
324   }
325
326   inline uint32_t ComputeDigest() {
327     // Check the lowest bit to determine if digest has actually been
328     // pre-computed.
329     if (hasCachedDigest())
330       return Digest;
331
332     uint32_t X = ComputeDigest(getLeft(), getRight(), getValue());
333     Digest = X;
334     return X;
335   }
336 };
337
338 //===----------------------------------------------------------------------===//
339 // Immutable AVL-Tree Factory class.
340 //===----------------------------------------------------------------------===//
341
342 template <typename ImutInfo >
343 class ImutAVLFactory {
344   typedef ImutAVLTree<ImutInfo> TreeTy;
345   typedef typename TreeTy::value_type_ref value_type_ref;
346   typedef typename TreeTy::key_type_ref   key_type_ref;
347
348   typedef FoldingSet<TreeTy> CacheTy;
349
350   CacheTy Cache;
351   uintptr_t Allocator;
352
353   bool ownsAllocator() const {
354     return Allocator & 0x1 ? false : true;
355   }
356
357   BumpPtrAllocator& getAllocator() const {
358     return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
359   }
360
361   //===--------------------------------------------------===//
362   // Public interface.
363   //===--------------------------------------------------===//
364
365 public:
366   ImutAVLFactory()
367     : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
368
369   ImutAVLFactory(BumpPtrAllocator& Alloc)
370     : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
371
372   ~ImutAVLFactory() {
373     if (ownsAllocator()) delete &getAllocator();
374   }
375
376   TreeTy* Add(TreeTy* T, value_type_ref V) {
377     T = Add_internal(V,T);
378     MarkImmutable(T);
379     return T;
380   }
381
382   TreeTy* Remove(TreeTy* T, key_type_ref V) {
383     T = Remove_internal(V,T);
384     MarkImmutable(T);
385     return T;
386   }
387
388   TreeTy* GetEmptyTree() const { return NULL; }
389
390   //===--------------------------------------------------===//
391   // A bunch of quick helper functions used for reasoning
392   // about the properties of trees and their children.
393   // These have succinct names so that the balancing code
394   // is as terse (and readable) as possible.
395   //===--------------------------------------------------===//
396 private:
397
398   bool           isEmpty(TreeTy* T) const { return !T; }
399   unsigned        Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
400   TreeTy*           Left(TreeTy* T) const { return T->getLeft(); }
401   TreeTy*          Right(TreeTy* T) const { return T->getRight(); }
402   value_type_ref   Value(TreeTy* T) const { return T->Value; }
403
404   unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
405     unsigned hl = Height(L);
406     unsigned hr = Height(R);
407     return ( hl > hr ? hl : hr ) + 1;
408   }
409
410   static bool CompareTreeWithSection(TreeTy* T,
411                                      typename TreeTy::iterator& TI,
412                                      typename TreeTy::iterator& TE) {
413
414     typename TreeTy::iterator I = T->begin(), E = T->end();
415
416     for ( ; I!=E ; ++I, ++TI)
417       if (TI == TE || !I->ElementEqual(*TI))
418         return false;
419
420     return true;
421   }
422
423   //===--------------------------------------------------===//
424   // "CreateNode" is used to generate new tree roots that link
425   // to other trees.  The functon may also simply move links
426   // in an existing root if that root is still marked mutable.
427   // This is necessary because otherwise our balancing code
428   // would leak memory as it would create nodes that are
429   // then discarded later before the finished tree is
430   // returned to the caller.
431   //===--------------------------------------------------===//
432
433   TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {
434     // Search the FoldingSet bucket for a Tree with the same digest.
435     FoldingSetNodeID ID;
436     unsigned digest = TreeTy::ComputeDigest(L, R, V);
437     ID.AddInteger(digest);
438     unsigned hash = ID.ComputeHash();
439
440     typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
441     typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
442
443     for (; I != E; ++I) {
444       TreeTy* T = &*I;
445
446       if (T->ComputeDigest() != digest)
447         continue;
448
449       // We found a collision.  Perform a comparison of Contents('T')
450       // with Contents('L')+'V'+Contents('R').
451       typename TreeTy::iterator TI = T->begin(), TE = T->end();
452
453       // First compare Contents('L') with the (initial) contents of T.
454       if (!CompareTreeWithSection(L, TI, TE))
455         continue;
456
457       // Now compare the new data element.
458       if (TI == TE || !TI->ElementEqual(V))
459         continue;
460
461       ++TI;
462
463       // Now compare the remainder of 'T' with 'R'.
464       if (!CompareTreeWithSection(R, TI, TE))
465         continue;
466
467       if (TI != TE)
468         continue; // Contents('R') did not match suffix of 'T'.
469
470       // Trees did match!  Return 'T'.
471       return T;
472     }
473
474     // No tree with the contents: Contents('L')+'V'+Contents('R').
475     // Create it.  Allocate the new tree node and insert it into the cache.
476     BumpPtrAllocator& A = getAllocator();
477     TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
478     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
479
480     // We do not insert 'T' into the FoldingSet here.  This is because
481     // this tree is still mutable and things may get rebalanced.
482     // Because our digest is associative and based on the contents of
483     // the set, this should hopefully not cause any strange bugs.
484     // 'T' is inserted by 'MarkImmutable'.
485     return T;
486   }
487
488   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
489     assert (!isEmpty(OldTree));
490
491     if (OldTree->isMutable()) {
492       OldTree->setLeft(L);
493       OldTree->setRight(R);
494       OldTree->setHeight(IncrementHeight(L,R));
495       return OldTree;
496     }
497     else
498       return CreateNode(L, Value(OldTree), R);
499   }
500
501   /// Balance - Used by Add_internal and Remove_internal to
502   ///  balance a newly created tree.
503   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
504
505     unsigned hl = Height(L);
506     unsigned hr = Height(R);
507
508     if (hl > hr + 2) {
509       assert (!isEmpty(L) &&
510               "Left tree cannot be empty to have a height >= 2.");
511
512       TreeTy* LL = Left(L);
513       TreeTy* LR = Right(L);
514
515       if (Height(LL) >= Height(LR))
516         return CreateNode(LL, L, CreateNode(LR,V,R));
517
518       assert (!isEmpty(LR) &&
519               "LR cannot be empty because it has a height >= 1.");
520
521       TreeTy* LRL = Left(LR);
522       TreeTy* LRR = Right(LR);
523
524       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
525     }
526     else if (hr > hl + 2) {
527       assert (!isEmpty(R) &&
528               "Right tree cannot be empty to have a height >= 2.");
529
530       TreeTy* RL = Left(R);
531       TreeTy* RR = Right(R);
532
533       if (Height(RR) >= Height(RL))
534         return CreateNode(CreateNode(L,V,RL), R, RR);
535
536       assert (!isEmpty(RL) &&
537               "RL cannot be empty because it has a height >= 1.");
538
539       TreeTy* RLL = Left(RL);
540       TreeTy* RLR = Right(RL);
541
542       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
543     }
544     else
545       return CreateNode(L,V,R);
546   }
547
548   /// Add_internal - Creates a new tree that includes the specified
549   ///  data and the data from the original tree.  If the original tree
550   ///  already contained the data item, the original tree is returned.
551   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
552     if (isEmpty(T))
553       return CreateNode(T, V, T);
554
555     assert (!T->isMutable());
556
557     key_type_ref K = ImutInfo::KeyOfValue(V);
558     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
559
560     if (ImutInfo::isEqual(K,KCurrent))
561       return CreateNode(Left(T), V, Right(T));
562     else if (ImutInfo::isLess(K,KCurrent))
563       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
564     else
565       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
566   }
567
568   /// Remove_internal - Creates a new tree that includes all the data
569   ///  from the original tree except the specified data.  If the
570   ///  specified data did not exist in the original tree, the original
571   ///  tree is returned.
572   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
573     if (isEmpty(T))
574       return T;
575
576     assert (!T->isMutable());
577
578     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
579
580     if (ImutInfo::isEqual(K,KCurrent))
581       return CombineLeftRightTrees(Left(T),Right(T));
582     else if (ImutInfo::isLess(K,KCurrent))
583       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
584     else
585       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
586   }
587
588   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
589     if (isEmpty(L)) return R;
590     if (isEmpty(R)) return L;
591
592     TreeTy* OldNode;
593     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
594     return Balance(L,Value(OldNode),NewRight);
595   }
596
597   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
598     assert (!isEmpty(T));
599
600     if (isEmpty(Left(T))) {
601       NodeRemoved = T;
602       return Right(T);
603     }
604
605     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
606   }
607
608   /// MarkImmutable - Clears the mutable bits of a root and all of its
609   ///  descendants.
610   void MarkImmutable(TreeTy* T) {
611     if (!T || !T->isMutable())
612       return;
613
614     T->MarkImmutable();
615     MarkImmutable(Left(T));
616     MarkImmutable(Right(T));
617
618     // Now that the node is immutable it can safely be inserted
619     // into the node cache.
620     llvm::FoldingSetNodeID ID;
621     ID.AddInteger(T->ComputeDigest());
622     Cache.InsertNode(T, (void*) &*Cache.bucket_end(ID.ComputeHash()));
623   }
624 };
625
626
627 //===----------------------------------------------------------------------===//
628 // Immutable AVL-Tree Iterators.
629 //===----------------------------------------------------------------------===//
630
631 template <typename ImutInfo>
632 class ImutAVLTreeGenericIterator {
633   SmallVector<uintptr_t,20> stack;
634 public:
635   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
636                    Flags=0x3 };
637
638   typedef ImutAVLTree<ImutInfo> TreeTy;
639   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
640
641   inline ImutAVLTreeGenericIterator() {}
642   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
643     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
644   }
645
646   TreeTy* operator*() const {
647     assert (!stack.empty());
648     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
649   }
650
651   uintptr_t getVisitState() {
652     assert (!stack.empty());
653     return stack.back() & Flags;
654   }
655
656
657   bool AtEnd() const { return stack.empty(); }
658
659   bool AtBeginning() const {
660     return stack.size() == 1 && getVisitState() == VisitedNone;
661   }
662
663   void SkipToParent() {
664     assert (!stack.empty());
665     stack.pop_back();
666
667     if (stack.empty())
668       return;
669
670     switch (getVisitState()) {
671       case VisitedNone:
672         stack.back() |= VisitedLeft;
673         break;
674       case VisitedLeft:
675         stack.back() |= VisitedRight;
676         break;
677       default:
678         assert (false && "Unreachable.");
679     }
680   }
681
682   inline bool operator==(const _Self& x) const {
683     if (stack.size() != x.stack.size())
684       return false;
685
686     for (unsigned i = 0 ; i < stack.size(); i++)
687       if (stack[i] != x.stack[i])
688         return false;
689
690     return true;
691   }
692
693   inline bool operator!=(const _Self& x) const { return !operator==(x); }
694
695   _Self& operator++() {
696     assert (!stack.empty());
697
698     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
699     assert (Current);
700
701     switch (getVisitState()) {
702       case VisitedNone:
703         if (TreeTy* L = Current->getLeft())
704           stack.push_back(reinterpret_cast<uintptr_t>(L));
705         else
706           stack.back() |= VisitedLeft;
707
708         break;
709
710       case VisitedLeft:
711         if (TreeTy* R = Current->getRight())
712           stack.push_back(reinterpret_cast<uintptr_t>(R));
713         else
714           stack.back() |= VisitedRight;
715
716         break;
717
718       case VisitedRight:
719         SkipToParent();
720         break;
721
722       default:
723         assert (false && "Unreachable.");
724     }
725
726     return *this;
727   }
728
729   _Self& operator--() {
730     assert (!stack.empty());
731
732     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
733     assert (Current);
734
735     switch (getVisitState()) {
736       case VisitedNone:
737         stack.pop_back();
738         break;
739
740       case VisitedLeft:
741         stack.back() &= ~Flags; // Set state to "VisitedNone."
742
743         if (TreeTy* L = Current->getLeft())
744           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
745
746         break;
747
748       case VisitedRight:
749         stack.back() &= ~Flags;
750         stack.back() |= VisitedLeft;
751
752         if (TreeTy* R = Current->getRight())
753           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
754
755         break;
756
757       default:
758         assert (false && "Unreachable.");
759     }
760
761     return *this;
762   }
763 };
764
765 template <typename ImutInfo>
766 class ImutAVLTreeInOrderIterator {
767   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
768   InternalIteratorTy InternalItr;
769
770 public:
771   typedef ImutAVLTree<ImutInfo> TreeTy;
772   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
773
774   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
775     if (Root) operator++(); // Advance to first element.
776   }
777
778   ImutAVLTreeInOrderIterator() : InternalItr() {}
779
780   inline bool operator==(const _Self& x) const {
781     return InternalItr == x.InternalItr;
782   }
783
784   inline bool operator!=(const _Self& x) const { return !operator==(x); }
785
786   inline TreeTy* operator*() const { return *InternalItr; }
787   inline TreeTy* operator->() const { return *InternalItr; }
788
789   inline _Self& operator++() {
790     do ++InternalItr;
791     while (!InternalItr.AtEnd() &&
792            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
793
794     return *this;
795   }
796
797   inline _Self& operator--() {
798     do --InternalItr;
799     while (!InternalItr.AtBeginning() &&
800            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
801
802     return *this;
803   }
804
805   inline void SkipSubTree() {
806     InternalItr.SkipToParent();
807
808     while (!InternalItr.AtEnd() &&
809            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
810       ++InternalItr;
811   }
812 };
813
814 //===----------------------------------------------------------------------===//
815 // Trait classes for Profile information.
816 //===----------------------------------------------------------------------===//
817
818 /// Generic profile template.  The default behavior is to invoke the
819 /// profile method of an object.  Specializations for primitive integers
820 /// and generic handling of pointers is done below.
821 template <typename T>
822 struct ImutProfileInfo {
823   typedef const T  value_type;
824   typedef const T& value_type_ref;
825
826   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
827     FoldingSetTrait<T>::Profile(X,ID);
828   }
829 };
830
831 /// Profile traits for integers.
832 template <typename T>
833 struct ImutProfileInteger {
834   typedef const T  value_type;
835   typedef const T& value_type_ref;
836
837   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
838     ID.AddInteger(X);
839   }
840 };
841
842 #define PROFILE_INTEGER_INFO(X)\
843 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
844
845 PROFILE_INTEGER_INFO(char)
846 PROFILE_INTEGER_INFO(unsigned char)
847 PROFILE_INTEGER_INFO(short)
848 PROFILE_INTEGER_INFO(unsigned short)
849 PROFILE_INTEGER_INFO(unsigned)
850 PROFILE_INTEGER_INFO(signed)
851 PROFILE_INTEGER_INFO(long)
852 PROFILE_INTEGER_INFO(unsigned long)
853 PROFILE_INTEGER_INFO(long long)
854 PROFILE_INTEGER_INFO(unsigned long long)
855
856 #undef PROFILE_INTEGER_INFO
857
858 /// Generic profile trait for pointer types.  We treat pointers as
859 /// references to unique objects.
860 template <typename T>
861 struct ImutProfileInfo<T*> {
862   typedef const T*   value_type;
863   typedef value_type value_type_ref;
864
865   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
866     ID.AddPointer(X);
867   }
868 };
869
870 //===----------------------------------------------------------------------===//
871 // Trait classes that contain element comparison operators and type
872 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
873 //  inherit from the profile traits (ImutProfileInfo) to include operations
874 //  for element profiling.
875 //===----------------------------------------------------------------------===//
876
877
878 /// ImutContainerInfo - Generic definition of comparison operations for
879 ///   elements of immutable containers that defaults to using
880 ///   std::equal_to<> and std::less<> to perform comparison of elements.
881 template <typename T>
882 struct ImutContainerInfo : public ImutProfileInfo<T> {
883   typedef typename ImutProfileInfo<T>::value_type      value_type;
884   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
885   typedef value_type      key_type;
886   typedef value_type_ref  key_type_ref;
887   typedef bool            data_type;
888   typedef bool            data_type_ref;
889
890   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
891   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
892
893   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
894     return std::equal_to<key_type>()(LHS,RHS);
895   }
896
897   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
898     return std::less<key_type>()(LHS,RHS);
899   }
900
901   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
902 };
903
904 /// ImutContainerInfo - Specialization for pointer values to treat pointers
905 ///  as references to unique objects.  Pointers are thus compared by
906 ///  their addresses.
907 template <typename T>
908 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
909   typedef typename ImutProfileInfo<T*>::value_type      value_type;
910   typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
911   typedef value_type      key_type;
912   typedef value_type_ref  key_type_ref;
913   typedef bool            data_type;
914   typedef bool            data_type_ref;
915
916   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
917   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
918
919   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
920     return LHS == RHS;
921   }
922
923   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
924     return LHS < RHS;
925   }
926
927   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
928 };
929
930 //===----------------------------------------------------------------------===//
931 // Immutable Set
932 //===----------------------------------------------------------------------===//
933
934 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
935 class ImmutableSet {
936 public:
937   typedef typename ValInfo::value_type      value_type;
938   typedef typename ValInfo::value_type_ref  value_type_ref;
939   typedef ImutAVLTree<ValInfo> TreeTy;
940
941 private:
942   TreeTy* Root;
943
944 public:
945   /// Constructs a set from a pointer to a tree root.  In general one
946   /// should use a Factory object to create sets instead of directly
947   /// invoking the constructor, but there are cases where make this
948   /// constructor public is useful.
949   explicit ImmutableSet(TreeTy* R) : Root(R) {}
950
951   class Factory {
952     typename TreeTy::Factory F;
953
954   public:
955     Factory() {}
956
957     Factory(BumpPtrAllocator& Alloc)
958       : F(Alloc) {}
959
960     /// GetEmptySet - Returns an immutable set that contains no elements.
961     ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
962
963     /// Add - Creates a new immutable set that contains all of the values
964     ///  of the original set with the addition of the specified value.  If
965     ///  the original set already included the value, then the original set is
966     ///  returned and no memory is allocated.  The time and space complexity
967     ///  of this operation is logarithmic in the size of the original set.
968     ///  The memory allocated to represent the set is released when the
969     ///  factory object that created the set is destroyed.
970     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
971       return ImmutableSet(F.Add(Old.Root,V));
972     }
973
974     /// Remove - Creates a new immutable set that contains all of the values
975     ///  of the original set with the exception of the specified value.  If
976     ///  the original set did not contain the value, the original set is
977     ///  returned and no memory is allocated.  The time and space complexity
978     ///  of this operation is logarithmic in the size of the original set.
979     ///  The memory allocated to represent the set is released when the
980     ///  factory object that created the set is destroyed.
981     ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
982       return ImmutableSet(F.Remove(Old.Root,V));
983     }
984
985     BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
986
987   private:
988     Factory(const Factory& RHS) {};
989     void operator=(const Factory& RHS) {};
990   };
991
992   friend class Factory;
993
994   /// contains - Returns true if the set contains the specified value.
995   bool contains(value_type_ref V) const {
996     return Root ? Root->contains(V) : false;
997   }
998
999   bool operator==(ImmutableSet RHS) const {
1000     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1001   }
1002
1003   bool operator!=(ImmutableSet RHS) const {
1004     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1005   }
1006
1007   TreeTy* getRoot() const { return Root; }
1008
1009   /// isEmpty - Return true if the set contains no elements.
1010   bool isEmpty() const { return !Root; }
1011
1012   /// isSingleton - Return true if the set contains exactly one element.
1013   ///   This method runs in constant time.
1014   bool isSingleton() const { return getHeight() == 1; }
1015
1016   template <typename Callback>
1017   void foreach(Callback& C) { if (Root) Root->foreach(C); }
1018
1019   template <typename Callback>
1020   void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1021
1022   //===--------------------------------------------------===//
1023   // Iterators.
1024   //===--------------------------------------------------===//
1025
1026   class iterator {
1027     typename TreeTy::iterator itr;
1028     iterator(TreeTy* t) : itr(t) {}
1029     friend class ImmutableSet<ValT,ValInfo>;
1030   public:
1031     iterator() {}
1032     inline value_type_ref operator*() const { return itr->getValue(); }
1033     inline iterator& operator++() { ++itr; return *this; }
1034     inline iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1035     inline iterator& operator--() { --itr; return *this; }
1036     inline iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
1037     inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1038     inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1039     inline value_type *operator->() const { return &(operator*()); }
1040   };
1041
1042   iterator begin() const { return iterator(Root); }
1043   iterator end() const { return iterator(); }
1044
1045   //===--------------------------------------------------===//
1046   // Utility methods.
1047   //===--------------------------------------------------===//
1048
1049   inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1050
1051   static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1052     ID.AddPointer(S.Root);
1053   }
1054
1055   inline void Profile(FoldingSetNodeID& ID) const {
1056     return Profile(ID,*this);
1057   }
1058
1059   //===--------------------------------------------------===//
1060   // For testing.
1061   //===--------------------------------------------------===//
1062
1063   void verify() const { if (Root) Root->verify(); }
1064 };
1065
1066 } // end namespace llvm
1067
1068 #endif