Tidy up assertion syntax. No functionality change.
[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/System/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     assert(!getLeft()
200            || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
201                                ImutInfo::KeyOfValue(getValue()))
202            && "Value in left child is not less that current value");
203
204
205     assert(!getRight()
206            || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
207                                ImutInfo::KeyOfValue(getRight()->getValue()))
208            && "Current value is not less that value of right child");
209
210     return getHeight();
211   }
212
213   /// Profile - Profiling for ImutAVLTree.
214   void Profile(llvm::FoldingSetNodeID& ID) {
215     ID.AddInteger(ComputeDigest());
216   }
217
218   //===----------------------------------------------------===//
219   // Internal Values.
220   //===----------------------------------------------------===//
221
222 private:
223   uintptr_t        Left;
224   ImutAVLTree*     Right;
225   unsigned         Height;
226   value_type       Value;
227   uint32_t         Digest;
228
229   //===----------------------------------------------------===//
230   // Internal methods (node manipulation; used by Factory).
231   //===----------------------------------------------------===//
232
233 private:
234
235   enum { Mutable = 0x1, NoCachedDigest = 0x2, LeftFlags = 0x3 };
236
237   /// ImutAVLTree - Internal constructor that is only called by
238   ///   ImutAVLFactory.
239   ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
240   : Left(reinterpret_cast<uintptr_t>(l) | (Mutable | NoCachedDigest)),
241     Right(r), Height(height), Value(v), Digest(0) {}
242
243
244   /// isMutable - Returns true if the left and right subtree references
245   ///  (as well as height) can be changed.  If this method returns false,
246   ///  the tree is truly immutable.  Trees returned from an ImutAVLFactory
247   ///  object should always have this method return true.  Further, if this
248   ///  method returns false for an instance of ImutAVLTree, all subtrees
249   ///  will also have this method return false.  The converse is not true.
250   bool isMutable() const { return Left & Mutable; }
251   
252   /// hasCachedDigest - Returns true if the digest for this tree is cached.
253   ///  This can only be true if the tree is immutable.
254   bool hasCachedDigest() const { return !(Left & NoCachedDigest); }
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   /// MarkImmutable - Clears the mutable flag for a tree.  After this happens,
268   ///   it is an error to call setLeft(), setRight(), and setHeight().
269   void MarkImmutable() {
270     assert(isMutable() && "Mutable flag already removed.");
271     Left &= ~Mutable;
272   }
273   
274   /// MarkedCachedDigest - Clears the NoCachedDigest flag for a tree.
275   void MarkedCachedDigest() {
276     assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
277     Left &= ~NoCachedDigest;
278   }
279
280   /// setLeft - Changes the reference of the left subtree.  Used internally
281   ///   by ImutAVLFactory.
282   void setLeft(ImutAVLTree* NewLeft) {
283     assert(isMutable() &&
284            "Only a mutable tree can have its left subtree changed.");
285     Left = reinterpret_cast<uintptr_t>(NewLeft) | LeftFlags;
286   }
287
288   /// setRight - Changes the reference of the right subtree.  Used internally
289   ///  by ImutAVLFactory.
290   void setRight(ImutAVLTree* NewRight) {
291     assert(isMutable() &&
292            "Only a mutable tree can have its right subtree changed.");
293
294     Right = NewRight;
295     // Set the NoCachedDigest flag.
296     Left = Left | NoCachedDigest;
297
298   }
299
300   /// setHeight - Changes the height of the tree.  Used internally by
301   ///  ImutAVLFactory.
302   void setHeight(unsigned h) {
303     assert(isMutable() && "Only a mutable tree can have its height changed.");
304     Height = h;
305   }
306
307   static inline
308   uint32_t ComputeDigest(ImutAVLTree* L, ImutAVLTree* R, value_type_ref V) {
309     uint32_t digest = 0;
310
311     if (L)
312       digest += L->ComputeDigest();
313
314     // Compute digest of stored data.
315     FoldingSetNodeID ID;
316     ImutInfo::Profile(ID,V);
317     digest += ID.ComputeHash();
318
319     if (R)
320       digest += R->ComputeDigest();
321
322     return digest;
323   }
324
325   inline uint32_t ComputeDigest() {
326     // Check the lowest bit to determine if digest has actually been
327     // pre-computed.
328     if (hasCachedDigest())
329       return Digest;
330
331     uint32_t X = ComputeDigest(getLeft(), getRight(), getValue());
332     Digest = X;
333     MarkedCachedDigest();
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     BumpPtrAllocator& A = getAllocator();
435     TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
436     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
437     return T;
438   }
439
440   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
441     assert(!isEmpty(OldTree));
442
443     if (OldTree->isMutable()) {
444       OldTree->setLeft(L);
445       OldTree->setRight(R);
446       OldTree->setHeight(IncrementHeight(L,R));
447       return OldTree;
448     }
449     else
450       return CreateNode(L, Value(OldTree), R);
451   }
452
453   /// Balance - Used by Add_internal and Remove_internal to
454   ///  balance a newly created tree.
455   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
456
457     unsigned hl = Height(L);
458     unsigned hr = Height(R);
459
460     if (hl > hr + 2) {
461       assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
462
463       TreeTy* LL = Left(L);
464       TreeTy* LR = Right(L);
465
466       if (Height(LL) >= Height(LR))
467         return CreateNode(LL, L, CreateNode(LR,V,R));
468
469       assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
470
471       TreeTy* LRL = Left(LR);
472       TreeTy* LRR = Right(LR);
473
474       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
475     }
476     else if (hr > hl + 2) {
477       assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
478
479       TreeTy* RL = Left(R);
480       TreeTy* RR = Right(R);
481
482       if (Height(RR) >= Height(RL))
483         return CreateNode(CreateNode(L,V,RL), R, RR);
484
485       assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
486
487       TreeTy* RLL = Left(RL);
488       TreeTy* RLR = Right(RL);
489
490       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
491     }
492     else
493       return CreateNode(L,V,R);
494   }
495
496   /// Add_internal - Creates a new tree that includes the specified
497   ///  data and the data from the original tree.  If the original tree
498   ///  already contained the data item, the original tree is returned.
499   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
500     if (isEmpty(T))
501       return CreateNode(T, V, T);
502
503     assert(!T->isMutable());
504
505     key_type_ref K = ImutInfo::KeyOfValue(V);
506     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
507
508     if (ImutInfo::isEqual(K,KCurrent))
509       return CreateNode(Left(T), V, Right(T));
510     else if (ImutInfo::isLess(K,KCurrent))
511       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
512     else
513       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
514   }
515
516   /// Remove_internal - Creates a new tree that includes all the data
517   ///  from the original tree except the specified data.  If the
518   ///  specified data did not exist in the original tree, the original
519   ///  tree is returned.
520   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
521     if (isEmpty(T))
522       return T;
523
524     assert(!T->isMutable());
525
526     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
527
528     if (ImutInfo::isEqual(K,KCurrent))
529       return CombineLeftRightTrees(Left(T),Right(T));
530     else if (ImutInfo::isLess(K,KCurrent))
531       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
532     else
533       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
534   }
535
536   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
537     if (isEmpty(L)) return R;
538     if (isEmpty(R)) return L;
539
540     TreeTy* OldNode;
541     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
542     return Balance(L,Value(OldNode),NewRight);
543   }
544
545   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
546     assert(!isEmpty(T));
547
548     if (isEmpty(Left(T))) {
549       NodeRemoved = T;
550       return Right(T);
551     }
552
553     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
554   }
555
556   /// MarkImmutable - Clears the mutable bits of a root and all of its
557   ///  descendants.
558   void MarkImmutable(TreeTy* T) {
559     if (!T || !T->isMutable())
560       return;
561
562     T->MarkImmutable();
563     MarkImmutable(Left(T));
564     MarkImmutable(Right(T));
565   }
566   
567 public:
568   TreeTy *GetCanonicalTree(TreeTy *TNew) {
569     if (!TNew)
570       return NULL;    
571     
572     // Search the FoldingSet bucket for a Tree with the same digest.
573     FoldingSetNodeID ID;
574     unsigned digest = TNew->ComputeDigest();
575     ID.AddInteger(digest);
576     unsigned hash = ID.ComputeHash();
577     
578     typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
579     typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
580     
581     for (; I != E; ++I) {
582       TreeTy *T = &*I;
583       
584       if (T->ComputeDigest() != digest)
585         continue;
586       
587       // We found a collision.  Perform a comparison of Contents('T')
588       // with Contents('L')+'V'+Contents('R').
589       typename TreeTy::iterator TI = T->begin(), TE = T->end();
590       
591       // First compare Contents('L') with the (initial) contents of T.
592       if (!CompareTreeWithSection(TNew->getLeft(), TI, TE))
593         continue;
594       
595       // Now compare the new data element.
596       if (TI == TE || !TI->ElementEqual(TNew->getValue()))
597         continue;
598       
599       ++TI;
600       
601       // Now compare the remainder of 'T' with 'R'.
602       if (!CompareTreeWithSection(TNew->getRight(), TI, TE))
603         continue;
604       
605       if (TI != TE)
606         continue; // Contents('R') did not match suffix of 'T'.
607       
608       // Trees did match!  Return 'T'.
609       return T;
610     }
611
612     // 'TNew' is the only tree of its kind.  Return it.
613     Cache.InsertNode(TNew, (void*) &*Cache.bucket_end(hash));
614     return TNew;
615   }
616 };
617
618
619 //===----------------------------------------------------------------------===//
620 // Immutable AVL-Tree Iterators.
621 //===----------------------------------------------------------------------===//
622
623 template <typename ImutInfo>
624 class ImutAVLTreeGenericIterator {
625   SmallVector<uintptr_t,20> stack;
626 public:
627   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
628                    Flags=0x3 };
629
630   typedef ImutAVLTree<ImutInfo> TreeTy;
631   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
632
633   inline ImutAVLTreeGenericIterator() {}
634   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
635     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
636   }
637
638   TreeTy* operator*() const {
639     assert(!stack.empty());
640     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
641   }
642
643   uintptr_t getVisitState() {
644     assert(!stack.empty());
645     return stack.back() & Flags;
646   }
647
648
649   bool AtEnd() const { return stack.empty(); }
650
651   bool AtBeginning() const {
652     return stack.size() == 1 && getVisitState() == VisitedNone;
653   }
654
655   void SkipToParent() {
656     assert(!stack.empty());
657     stack.pop_back();
658
659     if (stack.empty())
660       return;
661
662     switch (getVisitState()) {
663       case VisitedNone:
664         stack.back() |= VisitedLeft;
665         break;
666       case VisitedLeft:
667         stack.back() |= VisitedRight;
668         break;
669       default:
670         assert(false && "Unreachable.");
671     }
672   }
673
674   inline bool operator==(const _Self& x) const {
675     if (stack.size() != x.stack.size())
676       return false;
677
678     for (unsigned i = 0 ; i < stack.size(); i++)
679       if (stack[i] != x.stack[i])
680         return false;
681
682     return true;
683   }
684
685   inline bool operator!=(const _Self& x) const { return !operator==(x); }
686
687   _Self& operator++() {
688     assert(!stack.empty());
689
690     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
691     assert(Current);
692
693     switch (getVisitState()) {
694       case VisitedNone:
695         if (TreeTy* L = Current->getLeft())
696           stack.push_back(reinterpret_cast<uintptr_t>(L));
697         else
698           stack.back() |= VisitedLeft;
699
700         break;
701
702       case VisitedLeft:
703         if (TreeTy* R = Current->getRight())
704           stack.push_back(reinterpret_cast<uintptr_t>(R));
705         else
706           stack.back() |= VisitedRight;
707
708         break;
709
710       case VisitedRight:
711         SkipToParent();
712         break;
713
714       default:
715         assert(false && "Unreachable.");
716     }
717
718     return *this;
719   }
720
721   _Self& operator--() {
722     assert(!stack.empty());
723
724     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
725     assert(Current);
726
727     switch (getVisitState()) {
728       case VisitedNone:
729         stack.pop_back();
730         break;
731
732       case VisitedLeft:
733         stack.back() &= ~Flags; // Set state to "VisitedNone."
734
735         if (TreeTy* L = Current->getLeft())
736           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
737
738         break;
739
740       case VisitedRight:
741         stack.back() &= ~Flags;
742         stack.back() |= VisitedLeft;
743
744         if (TreeTy* R = Current->getRight())
745           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
746
747         break;
748
749       default:
750         assert(false && "Unreachable.");
751     }
752
753     return *this;
754   }
755 };
756
757 template <typename ImutInfo>
758 class ImutAVLTreeInOrderIterator {
759   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
760   InternalIteratorTy InternalItr;
761
762 public:
763   typedef ImutAVLTree<ImutInfo> TreeTy;
764   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
765
766   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
767     if (Root) operator++(); // Advance to first element.
768   }
769
770   ImutAVLTreeInOrderIterator() : InternalItr() {}
771
772   inline bool operator==(const _Self& x) const {
773     return InternalItr == x.InternalItr;
774   }
775
776   inline bool operator!=(const _Self& x) const { return !operator==(x); }
777
778   inline TreeTy* operator*() const { return *InternalItr; }
779   inline TreeTy* operator->() const { return *InternalItr; }
780
781   inline _Self& operator++() {
782     do ++InternalItr;
783     while (!InternalItr.AtEnd() &&
784            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
785
786     return *this;
787   }
788
789   inline _Self& operator--() {
790     do --InternalItr;
791     while (!InternalItr.AtBeginning() &&
792            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
793
794     return *this;
795   }
796
797   inline void SkipSubTree() {
798     InternalItr.SkipToParent();
799
800     while (!InternalItr.AtEnd() &&
801            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
802       ++InternalItr;
803   }
804 };
805
806 //===----------------------------------------------------------------------===//
807 // Trait classes for Profile information.
808 //===----------------------------------------------------------------------===//
809
810 /// Generic profile template.  The default behavior is to invoke the
811 /// profile method of an object.  Specializations for primitive integers
812 /// and generic handling of pointers is done below.
813 template <typename T>
814 struct ImutProfileInfo {
815   typedef const T  value_type;
816   typedef const T& value_type_ref;
817
818   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
819     FoldingSetTrait<T>::Profile(X,ID);
820   }
821 };
822
823 /// Profile traits for integers.
824 template <typename T>
825 struct ImutProfileInteger {
826   typedef const T  value_type;
827   typedef const T& value_type_ref;
828
829   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
830     ID.AddInteger(X);
831   }
832 };
833
834 #define PROFILE_INTEGER_INFO(X)\
835 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
836
837 PROFILE_INTEGER_INFO(char)
838 PROFILE_INTEGER_INFO(unsigned char)
839 PROFILE_INTEGER_INFO(short)
840 PROFILE_INTEGER_INFO(unsigned short)
841 PROFILE_INTEGER_INFO(unsigned)
842 PROFILE_INTEGER_INFO(signed)
843 PROFILE_INTEGER_INFO(long)
844 PROFILE_INTEGER_INFO(unsigned long)
845 PROFILE_INTEGER_INFO(long long)
846 PROFILE_INTEGER_INFO(unsigned long long)
847
848 #undef PROFILE_INTEGER_INFO
849
850 /// Generic profile trait for pointer types.  We treat pointers as
851 /// references to unique objects.
852 template <typename T>
853 struct ImutProfileInfo<T*> {
854   typedef const T*   value_type;
855   typedef value_type value_type_ref;
856
857   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
858     ID.AddPointer(X);
859   }
860 };
861
862 //===----------------------------------------------------------------------===//
863 // Trait classes that contain element comparison operators and type
864 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
865 //  inherit from the profile traits (ImutProfileInfo) to include operations
866 //  for element profiling.
867 //===----------------------------------------------------------------------===//
868
869
870 /// ImutContainerInfo - Generic definition of comparison operations for
871 ///   elements of immutable containers that defaults to using
872 ///   std::equal_to<> and std::less<> to perform comparison of elements.
873 template <typename T>
874 struct ImutContainerInfo : public ImutProfileInfo<T> {
875   typedef typename ImutProfileInfo<T>::value_type      value_type;
876   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
877   typedef value_type      key_type;
878   typedef value_type_ref  key_type_ref;
879   typedef bool            data_type;
880   typedef bool            data_type_ref;
881
882   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
883   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
884
885   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
886     return std::equal_to<key_type>()(LHS,RHS);
887   }
888
889   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
890     return std::less<key_type>()(LHS,RHS);
891   }
892
893   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
894 };
895
896 /// ImutContainerInfo - Specialization for pointer values to treat pointers
897 ///  as references to unique objects.  Pointers are thus compared by
898 ///  their addresses.
899 template <typename T>
900 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
901   typedef typename ImutProfileInfo<T*>::value_type      value_type;
902   typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
903   typedef value_type      key_type;
904   typedef value_type_ref  key_type_ref;
905   typedef bool            data_type;
906   typedef bool            data_type_ref;
907
908   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
909   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
910
911   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
912     return LHS == RHS;
913   }
914
915   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
916     return LHS < RHS;
917   }
918
919   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
920 };
921
922 //===----------------------------------------------------------------------===//
923 // Immutable Set
924 //===----------------------------------------------------------------------===//
925
926 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
927 class ImmutableSet {
928 public:
929   typedef typename ValInfo::value_type      value_type;
930   typedef typename ValInfo::value_type_ref  value_type_ref;
931   typedef ImutAVLTree<ValInfo> TreeTy;
932
933 private:
934   TreeTy *Root;
935   
936 public:
937   /// Constructs a set from a pointer to a tree root.  In general one
938   /// should use a Factory object to create sets instead of directly
939   /// invoking the constructor, but there are cases where make this
940   /// constructor public is useful.
941   explicit ImmutableSet(TreeTy* R) : Root(R) {}
942
943   class Factory {
944     typename TreeTy::Factory F;
945     const bool Canonicalize;
946
947   public:
948     Factory(bool canonicalize = true)
949       : Canonicalize(canonicalize) {}
950
951     Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
952       : F(Alloc), Canonicalize(canonicalize) {}
953
954     /// GetEmptySet - Returns an immutable set that contains no elements.
955     ImmutableSet GetEmptySet() {
956       return ImmutableSet(F.GetEmptyTree());
957     }
958
959     /// Add - Creates a new immutable set that contains all of the values
960     ///  of the original set with the addition of the specified value.  If
961     ///  the original set already included the value, then the original set is
962     ///  returned and no memory is allocated.  The time and space complexity
963     ///  of this operation is logarithmic in the size of the original set.
964     ///  The memory allocated to represent the set is released when the
965     ///  factory object that created the set is destroyed.
966     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
967       TreeTy *NewT = F.Add(Old.Root, V);
968       return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
969     }
970
971     /// Remove - Creates a new immutable set that contains all of the values
972     ///  of the original set with the exception of the specified value.  If
973     ///  the original set did not contain the value, the original set is
974     ///  returned and no memory is allocated.  The time and space complexity
975     ///  of this operation is logarithmic in the size of the original set.
976     ///  The memory allocated to represent the set is released when the
977     ///  factory object that created the set is destroyed.
978     ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
979       TreeTy *NewT = F.Remove(Old.Root, V);
980       return ImmutableSet(Canonicalize ? F.GetCanonicalTree(NewT) : NewT);
981     }
982
983     BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
984
985   private:
986     Factory(const Factory& RHS); // DO NOT IMPLEMENT
987     void operator=(const Factory& RHS); // DO NOT IMPLEMENT
988   };
989
990   friend class Factory;
991
992   /// contains - Returns true if the set contains the specified value.
993   bool contains(value_type_ref V) const {
994     return Root ? Root->contains(V) : false;
995   }
996
997   bool operator==(ImmutableSet RHS) const {
998     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
999   }
1000
1001   bool operator!=(ImmutableSet RHS) const {
1002     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1003   }
1004
1005   TreeTy *getRoot() { 
1006     return Root;
1007   }
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