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