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