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