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