Make ImmutableMap/ImmutableSet quicker by only canonicalizing the tree after an
[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     MarkedCachedDigest();
335     return X;
336   }
337 };
338
339 //===----------------------------------------------------------------------===//
340 // Immutable AVL-Tree Factory class.
341 //===----------------------------------------------------------------------===//
342
343 template <typename ImutInfo >
344 class ImutAVLFactory {
345   typedef ImutAVLTree<ImutInfo> TreeTy;
346   typedef typename TreeTy::value_type_ref value_type_ref;
347   typedef typename TreeTy::key_type_ref   key_type_ref;
348
349   typedef FoldingSet<TreeTy> CacheTy;
350
351   CacheTy Cache;
352   uintptr_t Allocator;
353
354   bool ownsAllocator() const {
355     return Allocator & 0x1 ? false : true;
356   }
357
358   BumpPtrAllocator& getAllocator() const {
359     return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
360   }
361
362   //===--------------------------------------------------===//
363   // Public interface.
364   //===--------------------------------------------------===//
365
366 public:
367   ImutAVLFactory()
368     : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
369
370   ImutAVLFactory(BumpPtrAllocator& Alloc)
371     : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
372
373   ~ImutAVLFactory() {
374     if (ownsAllocator()) delete &getAllocator();
375   }
376
377   TreeTy* Add(TreeTy* T, value_type_ref V) {
378     T = Add_internal(V,T);
379     MarkImmutable(T);
380     return T;
381   }
382
383   TreeTy* Remove(TreeTy* T, key_type_ref V) {
384     T = Remove_internal(V,T);
385     MarkImmutable(T);
386     return T;
387   }
388
389   TreeTy* GetEmptyTree() const { return NULL; }
390
391   //===--------------------------------------------------===//
392   // A bunch of quick helper functions used for reasoning
393   // about the properties of trees and their children.
394   // These have succinct names so that the balancing code
395   // is as terse (and readable) as possible.
396   //===--------------------------------------------------===//
397 private:
398
399   bool           isEmpty(TreeTy* T) const { return !T; }
400   unsigned        Height(TreeTy* T) const { return T ? T->getHeight() : 0; }
401   TreeTy*           Left(TreeTy* T) const { return T->getLeft(); }
402   TreeTy*          Right(TreeTy* T) const { return T->getRight(); }
403   value_type_ref   Value(TreeTy* T) const { return T->Value; }
404
405   unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
406     unsigned hl = Height(L);
407     unsigned hr = Height(R);
408     return ( hl > hr ? hl : hr ) + 1;
409   }
410
411   static bool CompareTreeWithSection(TreeTy* T,
412                                      typename TreeTy::iterator& TI,
413                                      typename TreeTy::iterator& TE) {
414
415     typename TreeTy::iterator I = T->begin(), E = T->end();
416
417     for ( ; I!=E ; ++I, ++TI)
418       if (TI == TE || !I->ElementEqual(*TI))
419         return false;
420
421     return true;
422   }
423
424   //===--------------------------------------------------===//
425   // "CreateNode" is used to generate new tree roots that link
426   // to other trees.  The functon may also simply move links
427   // in an existing root if that root is still marked mutable.
428   // This is necessary because otherwise our balancing code
429   // would leak memory as it would create nodes that are
430   // then discarded later before the finished tree is
431   // returned to the caller.
432   //===--------------------------------------------------===//
433
434   TreeTy* CreateNode(TreeTy* L, value_type_ref V, TreeTy* R) {   
435     BumpPtrAllocator& A = getAllocator();
436     TreeTy* T = (TreeTy*) A.Allocate<TreeTy>();
437     new (T) TreeTy(L,R,V,IncrementHeight(L,R));
438     return T;
439   }
440
441   TreeTy* CreateNode(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
442     assert (!isEmpty(OldTree));
443
444     if (OldTree->isMutable()) {
445       OldTree->setLeft(L);
446       OldTree->setRight(R);
447       OldTree->setHeight(IncrementHeight(L,R));
448       return OldTree;
449     }
450     else
451       return CreateNode(L, Value(OldTree), R);
452   }
453
454   /// Balance - Used by Add_internal and Remove_internal to
455   ///  balance a newly created tree.
456   TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
457
458     unsigned hl = Height(L);
459     unsigned hr = Height(R);
460
461     if (hl > hr + 2) {
462       assert (!isEmpty(L) &&
463               "Left tree cannot be empty to have a height >= 2.");
464
465       TreeTy* LL = Left(L);
466       TreeTy* LR = Right(L);
467
468       if (Height(LL) >= Height(LR))
469         return CreateNode(LL, L, CreateNode(LR,V,R));
470
471       assert (!isEmpty(LR) &&
472               "LR cannot be empty because it has a height >= 1.");
473
474       TreeTy* LRL = Left(LR);
475       TreeTy* LRR = Right(LR);
476
477       return CreateNode(CreateNode(LL,L,LRL), LR, CreateNode(LRR,V,R));
478     }
479     else if (hr > hl + 2) {
480       assert (!isEmpty(R) &&
481               "Right tree cannot be empty to have a height >= 2.");
482
483       TreeTy* RL = Left(R);
484       TreeTy* RR = Right(R);
485
486       if (Height(RR) >= Height(RL))
487         return CreateNode(CreateNode(L,V,RL), R, RR);
488
489       assert (!isEmpty(RL) &&
490               "RL cannot be empty because it has a height >= 1.");
491
492       TreeTy* RLL = Left(RL);
493       TreeTy* RLR = Right(RL);
494
495       return CreateNode(CreateNode(L,V,RLL), RL, CreateNode(RLR,R,RR));
496     }
497     else
498       return CreateNode(L,V,R);
499   }
500
501   /// Add_internal - Creates a new tree that includes the specified
502   ///  data and the data from the original tree.  If the original tree
503   ///  already contained the data item, the original tree is returned.
504   TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
505     if (isEmpty(T))
506       return CreateNode(T, V, T);
507
508     assert (!T->isMutable());
509
510     key_type_ref K = ImutInfo::KeyOfValue(V);
511     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
512
513     if (ImutInfo::isEqual(K,KCurrent))
514       return CreateNode(Left(T), V, Right(T));
515     else if (ImutInfo::isLess(K,KCurrent))
516       return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
517     else
518       return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
519   }
520
521   /// Remove_internal - Creates a new tree that includes all the data
522   ///  from the original tree except the specified data.  If the
523   ///  specified data did not exist in the original tree, the original
524   ///  tree is returned.
525   TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
526     if (isEmpty(T))
527       return T;
528
529     assert (!T->isMutable());
530
531     key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
532
533     if (ImutInfo::isEqual(K,KCurrent))
534       return CombineLeftRightTrees(Left(T),Right(T));
535     else if (ImutInfo::isLess(K,KCurrent))
536       return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
537     else
538       return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
539   }
540
541   TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
542     if (isEmpty(L)) return R;
543     if (isEmpty(R)) return L;
544
545     TreeTy* OldNode;
546     TreeTy* NewRight = RemoveMinBinding(R,OldNode);
547     return Balance(L,Value(OldNode),NewRight);
548   }
549
550   TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
551     assert (!isEmpty(T));
552
553     if (isEmpty(Left(T))) {
554       NodeRemoved = T;
555       return Right(T);
556     }
557
558     return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
559   }
560
561   /// MarkImmutable - Clears the mutable bits of a root and all of its
562   ///  descendants.
563   void MarkImmutable(TreeTy* T) {
564     if (!T || !T->isMutable())
565       return;
566
567     T->MarkImmutable();
568     MarkImmutable(Left(T));
569     MarkImmutable(Right(T));
570   }
571   
572 public:
573   TreeTy *GetCanonicalTree(TreeTy *TNew) {
574     if (!TNew)
575       return NULL;    
576     
577     // Search the FoldingSet bucket for a Tree with the same digest.
578     FoldingSetNodeID ID;
579     unsigned digest = TNew->ComputeDigest();
580     ID.AddInteger(digest);
581     unsigned hash = ID.ComputeHash();
582     
583     typename CacheTy::bucket_iterator I = Cache.bucket_begin(hash);
584     typename CacheTy::bucket_iterator E = Cache.bucket_end(hash);
585     
586     for (; I != E; ++I) {
587       TreeTy *T = &*I;
588       
589       if (T->ComputeDigest() != digest)
590         continue;
591       
592       // We found a collision.  Perform a comparison of Contents('T')
593       // with Contents('L')+'V'+Contents('R').
594       typename TreeTy::iterator TI = T->begin(), TE = T->end();
595       
596       // First compare Contents('L') with the (initial) contents of T.
597       if (!CompareTreeWithSection(TNew->getLeft(), TI, TE))
598         continue;
599       
600       // Now compare the new data element.
601       if (TI == TE || !TI->ElementEqual(TNew->getValue()))
602         continue;
603       
604       ++TI;
605       
606       // Now compare the remainder of 'T' with 'R'.
607       if (!CompareTreeWithSection(TNew->getRight(), TI, TE))
608         continue;
609       
610       if (TI != TE)
611         continue; // Contents('R') did not match suffix of 'T'.
612       
613       // Trees did match!  Return 'T'.
614       return T;
615     }
616
617     // 'TNew' is the only tree of its kind.  Return it.
618     Cache.InsertNode(TNew, (void*) &*Cache.bucket_end(hash));
619     return TNew;
620   }
621 };
622
623
624 //===----------------------------------------------------------------------===//
625 // Immutable AVL-Tree Iterators.
626 //===----------------------------------------------------------------------===//
627
628 template <typename ImutInfo>
629 class ImutAVLTreeGenericIterator {
630   SmallVector<uintptr_t,20> stack;
631 public:
632   enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
633                    Flags=0x3 };
634
635   typedef ImutAVLTree<ImutInfo> TreeTy;
636   typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
637
638   inline ImutAVLTreeGenericIterator() {}
639   inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
640     if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
641   }
642
643   TreeTy* operator*() const {
644     assert (!stack.empty());
645     return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
646   }
647
648   uintptr_t getVisitState() {
649     assert (!stack.empty());
650     return stack.back() & Flags;
651   }
652
653
654   bool AtEnd() const { return stack.empty(); }
655
656   bool AtBeginning() const {
657     return stack.size() == 1 && getVisitState() == VisitedNone;
658   }
659
660   void SkipToParent() {
661     assert (!stack.empty());
662     stack.pop_back();
663
664     if (stack.empty())
665       return;
666
667     switch (getVisitState()) {
668       case VisitedNone:
669         stack.back() |= VisitedLeft;
670         break;
671       case VisitedLeft:
672         stack.back() |= VisitedRight;
673         break;
674       default:
675         assert (false && "Unreachable.");
676     }
677   }
678
679   inline bool operator==(const _Self& x) const {
680     if (stack.size() != x.stack.size())
681       return false;
682
683     for (unsigned i = 0 ; i < stack.size(); i++)
684       if (stack[i] != x.stack[i])
685         return false;
686
687     return true;
688   }
689
690   inline bool operator!=(const _Self& x) const { return !operator==(x); }
691
692   _Self& operator++() {
693     assert (!stack.empty());
694
695     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
696     assert (Current);
697
698     switch (getVisitState()) {
699       case VisitedNone:
700         if (TreeTy* L = Current->getLeft())
701           stack.push_back(reinterpret_cast<uintptr_t>(L));
702         else
703           stack.back() |= VisitedLeft;
704
705         break;
706
707       case VisitedLeft:
708         if (TreeTy* R = Current->getRight())
709           stack.push_back(reinterpret_cast<uintptr_t>(R));
710         else
711           stack.back() |= VisitedRight;
712
713         break;
714
715       case VisitedRight:
716         SkipToParent();
717         break;
718
719       default:
720         assert (false && "Unreachable.");
721     }
722
723     return *this;
724   }
725
726   _Self& operator--() {
727     assert (!stack.empty());
728
729     TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
730     assert (Current);
731
732     switch (getVisitState()) {
733       case VisitedNone:
734         stack.pop_back();
735         break;
736
737       case VisitedLeft:
738         stack.back() &= ~Flags; // Set state to "VisitedNone."
739
740         if (TreeTy* L = Current->getLeft())
741           stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
742
743         break;
744
745       case VisitedRight:
746         stack.back() &= ~Flags;
747         stack.back() |= VisitedLeft;
748
749         if (TreeTy* R = Current->getRight())
750           stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
751
752         break;
753
754       default:
755         assert (false && "Unreachable.");
756     }
757
758     return *this;
759   }
760 };
761
762 template <typename ImutInfo>
763 class ImutAVLTreeInOrderIterator {
764   typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
765   InternalIteratorTy InternalItr;
766
767 public:
768   typedef ImutAVLTree<ImutInfo> TreeTy;
769   typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
770
771   ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
772     if (Root) operator++(); // Advance to first element.
773   }
774
775   ImutAVLTreeInOrderIterator() : InternalItr() {}
776
777   inline bool operator==(const _Self& x) const {
778     return InternalItr == x.InternalItr;
779   }
780
781   inline bool operator!=(const _Self& x) const { return !operator==(x); }
782
783   inline TreeTy* operator*() const { return *InternalItr; }
784   inline TreeTy* operator->() const { return *InternalItr; }
785
786   inline _Self& operator++() {
787     do ++InternalItr;
788     while (!InternalItr.AtEnd() &&
789            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
790
791     return *this;
792   }
793
794   inline _Self& operator--() {
795     do --InternalItr;
796     while (!InternalItr.AtBeginning() &&
797            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
798
799     return *this;
800   }
801
802   inline void SkipSubTree() {
803     InternalItr.SkipToParent();
804
805     while (!InternalItr.AtEnd() &&
806            InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
807       ++InternalItr;
808   }
809 };
810
811 //===----------------------------------------------------------------------===//
812 // Trait classes for Profile information.
813 //===----------------------------------------------------------------------===//
814
815 /// Generic profile template.  The default behavior is to invoke the
816 /// profile method of an object.  Specializations for primitive integers
817 /// and generic handling of pointers is done below.
818 template <typename T>
819 struct ImutProfileInfo {
820   typedef const T  value_type;
821   typedef const T& value_type_ref;
822
823   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
824     FoldingSetTrait<T>::Profile(X,ID);
825   }
826 };
827
828 /// Profile traits for integers.
829 template <typename T>
830 struct ImutProfileInteger {
831   typedef const T  value_type;
832   typedef const T& value_type_ref;
833
834   static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
835     ID.AddInteger(X);
836   }
837 };
838
839 #define PROFILE_INTEGER_INFO(X)\
840 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
841
842 PROFILE_INTEGER_INFO(char)
843 PROFILE_INTEGER_INFO(unsigned char)
844 PROFILE_INTEGER_INFO(short)
845 PROFILE_INTEGER_INFO(unsigned short)
846 PROFILE_INTEGER_INFO(unsigned)
847 PROFILE_INTEGER_INFO(signed)
848 PROFILE_INTEGER_INFO(long)
849 PROFILE_INTEGER_INFO(unsigned long)
850 PROFILE_INTEGER_INFO(long long)
851 PROFILE_INTEGER_INFO(unsigned long long)
852
853 #undef PROFILE_INTEGER_INFO
854
855 /// Generic profile trait for pointer types.  We treat pointers as
856 /// references to unique objects.
857 template <typename T>
858 struct ImutProfileInfo<T*> {
859   typedef const T*   value_type;
860   typedef value_type value_type_ref;
861
862   static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
863     ID.AddPointer(X);
864   }
865 };
866
867 //===----------------------------------------------------------------------===//
868 // Trait classes that contain element comparison operators and type
869 //  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
870 //  inherit from the profile traits (ImutProfileInfo) to include operations
871 //  for element profiling.
872 //===----------------------------------------------------------------------===//
873
874
875 /// ImutContainerInfo - Generic definition of comparison operations for
876 ///   elements of immutable containers that defaults to using
877 ///   std::equal_to<> and std::less<> to perform comparison of elements.
878 template <typename T>
879 struct ImutContainerInfo : public ImutProfileInfo<T> {
880   typedef typename ImutProfileInfo<T>::value_type      value_type;
881   typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
882   typedef value_type      key_type;
883   typedef value_type_ref  key_type_ref;
884   typedef bool            data_type;
885   typedef bool            data_type_ref;
886
887   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
888   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
889
890   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
891     return std::equal_to<key_type>()(LHS,RHS);
892   }
893
894   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
895     return std::less<key_type>()(LHS,RHS);
896   }
897
898   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
899 };
900
901 /// ImutContainerInfo - Specialization for pointer values to treat pointers
902 ///  as references to unique objects.  Pointers are thus compared by
903 ///  their addresses.
904 template <typename T>
905 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
906   typedef typename ImutProfileInfo<T*>::value_type      value_type;
907   typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
908   typedef value_type      key_type;
909   typedef value_type_ref  key_type_ref;
910   typedef bool            data_type;
911   typedef bool            data_type_ref;
912
913   static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
914   static inline data_type_ref DataOfValue(value_type_ref) { return true; }
915
916   static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
917     return LHS == RHS;
918   }
919
920   static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
921     return LHS < RHS;
922   }
923
924   static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
925 };
926
927 //===----------------------------------------------------------------------===//
928 // Immutable Set
929 //===----------------------------------------------------------------------===//
930
931 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
932 class ImmutableSet {
933 public:
934   typedef typename ValInfo::value_type      value_type;
935   typedef typename ValInfo::value_type_ref  value_type_ref;
936   typedef ImutAVLTree<ValInfo> TreeTy;
937
938 private:
939   TreeTy *Root;
940   
941 public:
942   /// Constructs a set from a pointer to a tree root.  In general one
943   /// should use a Factory object to create sets instead of directly
944   /// invoking the constructor, but there are cases where make this
945   /// constructor public is useful.
946   explicit ImmutableSet(TreeTy* R) : Root(R) {}
947
948   class Factory {
949     typename TreeTy::Factory F;
950
951   public:
952     Factory() {}
953
954     Factory(BumpPtrAllocator& Alloc)
955       : F(Alloc) {}
956
957     /// GetEmptySet - Returns an immutable set that contains no elements.
958     ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
959
960     /// Add - Creates a new immutable set that contains all of the values
961     ///  of the original set with the addition of the specified value.  If
962     ///  the original set already included the value, then the original set is
963     ///  returned and no memory is allocated.  The time and space complexity
964     ///  of this operation is logarithmic in the size of the original set.
965     ///  The memory allocated to represent the set is released when the
966     ///  factory object that created the set is destroyed.
967     ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
968       return ImmutableSet(F.GetCanonicalTree(F.Add(Old.Root,V)));
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       return ImmutableSet(F.GetCanonicalTree(F.Remove(Old.Root,V)));
980     }
981
982     BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
983
984   private:
985     Factory(const Factory& RHS) {};
986     void operator=(const Factory& RHS) {};
987   };
988
989   friend class Factory;
990
991   /// contains - Returns true if the set contains the specified value.
992   bool contains(value_type_ref V) const {
993     return Root ? Root->contains(V) : false;
994   }
995
996   bool operator==(ImmutableSet RHS) const {
997     return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
998   }
999
1000   bool operator!=(ImmutableSet RHS) const {
1001     return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1002   }
1003
1004   TreeTy *getRoot() { 
1005     return Root;
1006   }
1007
1008   /// isEmpty - Return true if the set contains no elements.
1009   bool isEmpty() const { return !Root; }
1010
1011   /// isSingleton - Return true if the set contains exactly one element.
1012   ///   This method runs in constant time.
1013   bool isSingleton() const { return getHeight() == 1; }
1014
1015   template <typename Callback>
1016   void foreach(Callback& C) { if (Root) Root->foreach(C); }
1017
1018   template <typename Callback>
1019   void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1020
1021   //===--------------------------------------------------===//
1022   // Iterators.
1023   //===--------------------------------------------------===//
1024
1025   class iterator {
1026     typename TreeTy::iterator itr;
1027     iterator(TreeTy* t) : itr(t) {}
1028     friend class ImmutableSet<ValT,ValInfo>;
1029   public:
1030     iterator() {}
1031     inline value_type_ref operator*() const { return itr->getValue(); }
1032     inline iterator& operator++() { ++itr; return *this; }
1033     inline iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1034     inline iterator& operator--() { --itr; return *this; }
1035     inline iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
1036     inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1037     inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1038     inline value_type *operator->() const { return &(operator*()); }
1039   };
1040
1041   iterator begin() const { return iterator(Root); }
1042   iterator end() const { return iterator(); }
1043
1044   //===--------------------------------------------------===//
1045   // Utility methods.
1046   //===--------------------------------------------------===//
1047
1048   inline unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1049
1050   static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1051     ID.AddPointer(S.Root);
1052   }
1053
1054   inline void Profile(FoldingSetNodeID& ID) const {
1055     return Profile(ID,*this);
1056   }
1057
1058   //===--------------------------------------------------===//
1059   // For testing.
1060   //===--------------------------------------------------===//
1061
1062   void verify() const { if (Root) Root->verify(); }
1063 };
1064
1065 } // end namespace llvm
1066
1067 #endif