ImmutableSet.h revision 263508
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_IMMUTABLESET_H
15#define LLVM_ADT_IMMUTABLESET_H
16
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/FoldingSet.h"
19#include "llvm/Support/Allocator.h"
20#include "llvm/Support/DataTypes.h"
21#include "llvm/Support/ErrorHandling.h"
22#include <cassert>
23#include <functional>
24#include <vector>
25
26namespace llvm {
27
28//===----------------------------------------------------------------------===//
29// Immutable AVL-Tree Definition.
30//===----------------------------------------------------------------------===//
31
32template <typename ImutInfo> class ImutAVLFactory;
33template <typename ImutInfo> class ImutIntervalAVLFactory;
34template <typename ImutInfo> class ImutAVLTreeInOrderIterator;
35template <typename ImutInfo> class ImutAVLTreeGenericIterator;
36
37template <typename ImutInfo >
38class ImutAVLTree {
39public:
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
220private:
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
240private:
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
330public:
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[factory->maskCacheIndex(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
363template <typename ImutInfo >
364class 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
389public:
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
416protected:
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  // Make sure the index is not the Tombstone or Entry key of the DenseMap.
432  static inline unsigned maskCacheIndex(unsigned I) {
433    return (I & ~0x02);
434  }
435
436  unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
437    unsigned hl = getHeight(L);
438    unsigned hr = getHeight(R);
439    return (hl > hr ? hl : hr) + 1;
440  }
441
442  static bool compareTreeWithSection(TreeTy* T,
443                                     typename TreeTy::iterator& TI,
444                                     typename TreeTy::iterator& TE) {
445    typename TreeTy::iterator I = T->begin(), E = T->end();
446    for ( ; I!=E ; ++I, ++TI) {
447      if (TI == TE || !I->isElementEqual(*TI))
448        return false;
449    }
450    return true;
451  }
452
453  //===--------------------------------------------------===//
454  // "createNode" is used to generate new tree roots that link
455  // to other trees.  The functon may also simply move links
456  // in an existing root if that root is still marked mutable.
457  // This is necessary because otherwise our balancing code
458  // would leak memory as it would create nodes that are
459  // then discarded later before the finished tree is
460  // returned to the caller.
461  //===--------------------------------------------------===//
462
463  TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
464    BumpPtrAllocator& A = getAllocator();
465    TreeTy* T;
466    if (!freeNodes.empty()) {
467      T = freeNodes.back();
468      freeNodes.pop_back();
469      assert(T != L);
470      assert(T != R);
471    } else {
472      T = (TreeTy*) A.Allocate<TreeTy>();
473    }
474    new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
475    createdNodes.push_back(T);
476    return T;
477  }
478
479  TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
480    return createNode(newLeft, getValue(oldTree), newRight);
481  }
482
483  void recoverNodes() {
484    for (unsigned i = 0, n = createdNodes.size(); i < n; ++i) {
485      TreeTy *N = createdNodes[i];
486      if (N->isMutable() && N->refCount == 0)
487        N->destroy();
488    }
489    createdNodes.clear();
490  }
491
492  /// balanceTree - Used by add_internal and remove_internal to
493  ///  balance a newly created tree.
494  TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
495    unsigned hl = getHeight(L);
496    unsigned hr = getHeight(R);
497
498    if (hl > hr + 2) {
499      assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
500
501      TreeTy *LL = getLeft(L);
502      TreeTy *LR = getRight(L);
503
504      if (getHeight(LL) >= getHeight(LR))
505        return createNode(LL, L, createNode(LR,V,R));
506
507      assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
508
509      TreeTy *LRL = getLeft(LR);
510      TreeTy *LRR = getRight(LR);
511
512      return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
513    }
514
515    if (hr > hl + 2) {
516      assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
517
518      TreeTy *RL = getLeft(R);
519      TreeTy *RR = getRight(R);
520
521      if (getHeight(RR) >= getHeight(RL))
522        return createNode(createNode(L,V,RL), R, RR);
523
524      assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
525
526      TreeTy *RLL = getLeft(RL);
527      TreeTy *RLR = getRight(RL);
528
529      return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
530    }
531
532    return createNode(L,V,R);
533  }
534
535  /// add_internal - Creates a new tree that includes the specified
536  ///  data and the data from the original tree.  If the original tree
537  ///  already contained the data item, the original tree is returned.
538  TreeTy* add_internal(value_type_ref V, TreeTy* T) {
539    if (isEmpty(T))
540      return createNode(T, V, T);
541    assert(!T->isMutable());
542
543    key_type_ref K = ImutInfo::KeyOfValue(V);
544    key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
545
546    if (ImutInfo::isEqual(K,KCurrent))
547      return createNode(getLeft(T), V, getRight(T));
548    else if (ImutInfo::isLess(K,KCurrent))
549      return balanceTree(add_internal(V, getLeft(T)), getValue(T), getRight(T));
550    else
551      return balanceTree(getLeft(T), getValue(T), add_internal(V, getRight(T)));
552  }
553
554  /// remove_internal - Creates a new tree that includes all the data
555  ///  from the original tree except the specified data.  If the
556  ///  specified data did not exist in the original tree, the original
557  ///  tree is returned.
558  TreeTy* remove_internal(key_type_ref K, TreeTy* T) {
559    if (isEmpty(T))
560      return T;
561
562    assert(!T->isMutable());
563
564    key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
565
566    if (ImutInfo::isEqual(K,KCurrent)) {
567      return combineTrees(getLeft(T), getRight(T));
568    } else if (ImutInfo::isLess(K,KCurrent)) {
569      return balanceTree(remove_internal(K, getLeft(T)),
570                                            getValue(T), getRight(T));
571    } else {
572      return balanceTree(getLeft(T), getValue(T),
573                         remove_internal(K, getRight(T)));
574    }
575  }
576
577  TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
578    if (isEmpty(L))
579      return R;
580    if (isEmpty(R))
581      return L;
582    TreeTy* OldNode;
583    TreeTy* newRight = removeMinBinding(R,OldNode);
584    return balanceTree(L, getValue(OldNode), newRight);
585  }
586
587  TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
588    assert(!isEmpty(T));
589    if (isEmpty(getLeft(T))) {
590      Noderemoved = T;
591      return getRight(T);
592    }
593    return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
594                       getValue(T), getRight(T));
595  }
596
597  /// markImmutable - Clears the mutable bits of a root and all of its
598  ///  descendants.
599  void markImmutable(TreeTy* T) {
600    if (!T || !T->isMutable())
601      return;
602    T->markImmutable();
603    markImmutable(getLeft(T));
604    markImmutable(getRight(T));
605  }
606
607public:
608  TreeTy *getCanonicalTree(TreeTy *TNew) {
609    if (!TNew)
610      return 0;
611
612    if (TNew->IsCanonicalized)
613      return TNew;
614
615    // Search the hashtable for another tree with the same digest, and
616    // if find a collision compare those trees by their contents.
617    unsigned digest = TNew->computeDigest();
618    TreeTy *&entry = Cache[maskCacheIndex(digest)];
619    do {
620      if (!entry)
621        break;
622      for (TreeTy *T = entry ; T != 0; T = T->next) {
623        // Compare the Contents('T') with Contents('TNew')
624        typename TreeTy::iterator TI = T->begin(), TE = T->end();
625        if (!compareTreeWithSection(TNew, TI, TE))
626          continue;
627        if (TI != TE)
628          continue; // T has more contents than TNew.
629        // Trees did match!  Return 'T'.
630        if (TNew->refCount == 0)
631          TNew->destroy();
632        return T;
633      }
634      entry->prev = TNew;
635      TNew->next = entry;
636    }
637    while (false);
638
639    entry = TNew;
640    TNew->IsCanonicalized = true;
641    return TNew;
642  }
643};
644
645//===----------------------------------------------------------------------===//
646// Immutable AVL-Tree Iterators.
647//===----------------------------------------------------------------------===//
648
649template <typename ImutInfo>
650class ImutAVLTreeGenericIterator {
651  SmallVector<uintptr_t,20> stack;
652public:
653  enum VisitFlag { VisitedNone=0x0, VisitedLeft=0x1, VisitedRight=0x3,
654                   Flags=0x3 };
655
656  typedef ImutAVLTree<ImutInfo> TreeTy;
657  typedef ImutAVLTreeGenericIterator<ImutInfo> _Self;
658
659  inline ImutAVLTreeGenericIterator() {}
660  inline ImutAVLTreeGenericIterator(const TreeTy* Root) {
661    if (Root) stack.push_back(reinterpret_cast<uintptr_t>(Root));
662  }
663
664  TreeTy* operator*() const {
665    assert(!stack.empty());
666    return reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
667  }
668
669  uintptr_t getVisitState() const {
670    assert(!stack.empty());
671    return stack.back() & Flags;
672  }
673
674
675  bool atEnd() const { return stack.empty(); }
676
677  bool atBeginning() const {
678    return stack.size() == 1 && getVisitState() == VisitedNone;
679  }
680
681  void skipToParent() {
682    assert(!stack.empty());
683    stack.pop_back();
684    if (stack.empty())
685      return;
686    switch (getVisitState()) {
687      case VisitedNone:
688        stack.back() |= VisitedLeft;
689        break;
690      case VisitedLeft:
691        stack.back() |= VisitedRight;
692        break;
693      default:
694        llvm_unreachable("Unreachable.");
695    }
696  }
697
698  inline bool operator==(const _Self& x) const {
699    if (stack.size() != x.stack.size())
700      return false;
701    for (unsigned i = 0 ; i < stack.size(); i++)
702      if (stack[i] != x.stack[i])
703        return false;
704    return true;
705  }
706
707  inline bool operator!=(const _Self& x) const { return !operator==(x); }
708
709  _Self& operator++() {
710    assert(!stack.empty());
711    TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
712    assert(Current);
713    switch (getVisitState()) {
714      case VisitedNone:
715        if (TreeTy* L = Current->getLeft())
716          stack.push_back(reinterpret_cast<uintptr_t>(L));
717        else
718          stack.back() |= VisitedLeft;
719        break;
720      case VisitedLeft:
721        if (TreeTy* R = Current->getRight())
722          stack.push_back(reinterpret_cast<uintptr_t>(R));
723        else
724          stack.back() |= VisitedRight;
725        break;
726      case VisitedRight:
727        skipToParent();
728        break;
729      default:
730        llvm_unreachable("Unreachable.");
731    }
732    return *this;
733  }
734
735  _Self& operator--() {
736    assert(!stack.empty());
737    TreeTy* Current = reinterpret_cast<TreeTy*>(stack.back() & ~Flags);
738    assert(Current);
739    switch (getVisitState()) {
740      case VisitedNone:
741        stack.pop_back();
742        break;
743      case VisitedLeft:
744        stack.back() &= ~Flags; // Set state to "VisitedNone."
745        if (TreeTy* L = Current->getLeft())
746          stack.push_back(reinterpret_cast<uintptr_t>(L) | VisitedRight);
747        break;
748      case VisitedRight:
749        stack.back() &= ~Flags;
750        stack.back() |= VisitedLeft;
751        if (TreeTy* R = Current->getRight())
752          stack.push_back(reinterpret_cast<uintptr_t>(R) | VisitedRight);
753        break;
754      default:
755        llvm_unreachable("Unreachable.");
756    }
757    return *this;
758  }
759};
760
761template <typename ImutInfo>
762class ImutAVLTreeInOrderIterator {
763  typedef ImutAVLTreeGenericIterator<ImutInfo> InternalIteratorTy;
764  InternalIteratorTy InternalItr;
765
766public:
767  typedef ImutAVLTree<ImutInfo> TreeTy;
768  typedef ImutAVLTreeInOrderIterator<ImutInfo> _Self;
769
770  ImutAVLTreeInOrderIterator(const TreeTy* Root) : InternalItr(Root) {
771    if (Root) operator++(); // Advance to first element.
772  }
773
774  ImutAVLTreeInOrderIterator() : InternalItr() {}
775
776  inline bool operator==(const _Self& x) const {
777    return InternalItr == x.InternalItr;
778  }
779
780  inline bool operator!=(const _Self& x) const { return !operator==(x); }
781
782  inline TreeTy* operator*() const { return *InternalItr; }
783  inline TreeTy* operator->() const { return *InternalItr; }
784
785  inline _Self& operator++() {
786    do ++InternalItr;
787    while (!InternalItr.atEnd() &&
788           InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
789
790    return *this;
791  }
792
793  inline _Self& operator--() {
794    do --InternalItr;
795    while (!InternalItr.atBeginning() &&
796           InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft);
797
798    return *this;
799  }
800
801  inline void skipSubTree() {
802    InternalItr.skipToParent();
803
804    while (!InternalItr.atEnd() &&
805           InternalItr.getVisitState() != InternalIteratorTy::VisitedLeft)
806      ++InternalItr;
807  }
808};
809
810//===----------------------------------------------------------------------===//
811// Trait classes for Profile information.
812//===----------------------------------------------------------------------===//
813
814/// Generic profile template.  The default behavior is to invoke the
815/// profile method of an object.  Specializations for primitive integers
816/// and generic handling of pointers is done below.
817template <typename T>
818struct ImutProfileInfo {
819  typedef const T  value_type;
820  typedef const T& value_type_ref;
821
822  static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
823    FoldingSetTrait<T>::Profile(X,ID);
824  }
825};
826
827/// Profile traits for integers.
828template <typename T>
829struct ImutProfileInteger {
830  typedef const T  value_type;
831  typedef const T& value_type_ref;
832
833  static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
834    ID.AddInteger(X);
835  }
836};
837
838#define PROFILE_INTEGER_INFO(X)\
839template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
840
841PROFILE_INTEGER_INFO(char)
842PROFILE_INTEGER_INFO(unsigned char)
843PROFILE_INTEGER_INFO(short)
844PROFILE_INTEGER_INFO(unsigned short)
845PROFILE_INTEGER_INFO(unsigned)
846PROFILE_INTEGER_INFO(signed)
847PROFILE_INTEGER_INFO(long)
848PROFILE_INTEGER_INFO(unsigned long)
849PROFILE_INTEGER_INFO(long long)
850PROFILE_INTEGER_INFO(unsigned long long)
851
852#undef PROFILE_INTEGER_INFO
853
854/// Profile traits for booleans.
855template <>
856struct ImutProfileInfo<bool> {
857  typedef const bool  value_type;
858  typedef const bool& value_type_ref;
859
860  static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
861    ID.AddBoolean(X);
862  }
863};
864
865
866/// Generic profile trait for pointer types.  We treat pointers as
867/// references to unique objects.
868template <typename T>
869struct ImutProfileInfo<T*> {
870  typedef const T*   value_type;
871  typedef value_type value_type_ref;
872
873  static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
874    ID.AddPointer(X);
875  }
876};
877
878//===----------------------------------------------------------------------===//
879// Trait classes that contain element comparison operators and type
880//  definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap.  These
881//  inherit from the profile traits (ImutProfileInfo) to include operations
882//  for element profiling.
883//===----------------------------------------------------------------------===//
884
885
886/// ImutContainerInfo - Generic definition of comparison operations for
887///   elements of immutable containers that defaults to using
888///   std::equal_to<> and std::less<> to perform comparison of elements.
889template <typename T>
890struct ImutContainerInfo : public ImutProfileInfo<T> {
891  typedef typename ImutProfileInfo<T>::value_type      value_type;
892  typedef typename ImutProfileInfo<T>::value_type_ref  value_type_ref;
893  typedef value_type      key_type;
894  typedef value_type_ref  key_type_ref;
895  typedef bool            data_type;
896  typedef bool            data_type_ref;
897
898  static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
899  static inline data_type_ref DataOfValue(value_type_ref) { return true; }
900
901  static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
902    return std::equal_to<key_type>()(LHS,RHS);
903  }
904
905  static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
906    return std::less<key_type>()(LHS,RHS);
907  }
908
909  static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
910};
911
912/// ImutContainerInfo - Specialization for pointer values to treat pointers
913///  as references to unique objects.  Pointers are thus compared by
914///  their addresses.
915template <typename T>
916struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
917  typedef typename ImutProfileInfo<T*>::value_type      value_type;
918  typedef typename ImutProfileInfo<T*>::value_type_ref  value_type_ref;
919  typedef value_type      key_type;
920  typedef value_type_ref  key_type_ref;
921  typedef bool            data_type;
922  typedef bool            data_type_ref;
923
924  static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
925  static inline data_type_ref DataOfValue(value_type_ref) { return true; }
926
927  static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
928    return LHS == RHS;
929  }
930
931  static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
932    return LHS < RHS;
933  }
934
935  static inline bool isDataEqual(data_type_ref,data_type_ref) { return true; }
936};
937
938//===----------------------------------------------------------------------===//
939// Immutable Set
940//===----------------------------------------------------------------------===//
941
942template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
943class ImmutableSet {
944public:
945  typedef typename ValInfo::value_type      value_type;
946  typedef typename ValInfo::value_type_ref  value_type_ref;
947  typedef ImutAVLTree<ValInfo> TreeTy;
948
949private:
950  TreeTy *Root;
951
952public:
953  /// Constructs a set from a pointer to a tree root.  In general one
954  /// should use a Factory object to create sets instead of directly
955  /// invoking the constructor, but there are cases where make this
956  /// constructor public is useful.
957  explicit ImmutableSet(TreeTy* R) : Root(R) {
958    if (Root) { Root->retain(); }
959  }
960  ImmutableSet(const ImmutableSet &X) : Root(X.Root) {
961    if (Root) { Root->retain(); }
962  }
963  ImmutableSet &operator=(const ImmutableSet &X) {
964    if (Root != X.Root) {
965      if (X.Root) { X.Root->retain(); }
966      if (Root) { Root->release(); }
967      Root = X.Root;
968    }
969    return *this;
970  }
971  ~ImmutableSet() {
972    if (Root) { Root->release(); }
973  }
974
975  class Factory {
976    typename TreeTy::Factory F;
977    const bool Canonicalize;
978
979  public:
980    Factory(bool canonicalize = true)
981      : Canonicalize(canonicalize) {}
982
983    Factory(BumpPtrAllocator& Alloc, bool canonicalize = true)
984      : F(Alloc), Canonicalize(canonicalize) {}
985
986    /// getEmptySet - Returns an immutable set that contains no elements.
987    ImmutableSet getEmptySet() {
988      return ImmutableSet(F.getEmptyTree());
989    }
990
991    /// add - Creates a new immutable set that contains all of the values
992    ///  of the original set with the addition of the specified value.  If
993    ///  the original set already included the value, then the original set is
994    ///  returned and no memory is allocated.  The time and space complexity
995    ///  of this operation is logarithmic in the size of the original set.
996    ///  The memory allocated to represent the set is released when the
997    ///  factory object that created the set is destroyed.
998    ImmutableSet add(ImmutableSet Old, value_type_ref V) {
999      TreeTy *NewT = F.add(Old.Root, V);
1000      return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1001    }
1002
1003    /// remove - Creates a new immutable set that contains all of the values
1004    ///  of the original set with the exception of the specified value.  If
1005    ///  the original set did not contain the value, the original set is
1006    ///  returned and no memory is allocated.  The time and space complexity
1007    ///  of this operation is logarithmic in the size of the original set.
1008    ///  The memory allocated to represent the set is released when the
1009    ///  factory object that created the set is destroyed.
1010    ImmutableSet remove(ImmutableSet Old, value_type_ref V) {
1011      TreeTy *NewT = F.remove(Old.Root, V);
1012      return ImmutableSet(Canonicalize ? F.getCanonicalTree(NewT) : NewT);
1013    }
1014
1015    BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1016
1017    typename TreeTy::Factory *getTreeFactory() const {
1018      return const_cast<typename TreeTy::Factory *>(&F);
1019    }
1020
1021  private:
1022    Factory(const Factory& RHS) LLVM_DELETED_FUNCTION;
1023    void operator=(const Factory& RHS) LLVM_DELETED_FUNCTION;
1024  };
1025
1026  friend class Factory;
1027
1028  /// Returns true if the set contains the specified value.
1029  bool contains(value_type_ref V) const {
1030    return Root ? Root->contains(V) : false;
1031  }
1032
1033  bool operator==(const ImmutableSet &RHS) const {
1034    return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1035  }
1036
1037  bool operator!=(const ImmutableSet &RHS) const {
1038    return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1039  }
1040
1041  TreeTy *getRoot() {
1042    if (Root) { Root->retain(); }
1043    return Root;
1044  }
1045
1046  TreeTy *getRootWithoutRetain() const {
1047    return Root;
1048  }
1049
1050  /// isEmpty - Return true if the set contains no elements.
1051  bool isEmpty() const { return !Root; }
1052
1053  /// isSingleton - Return true if the set contains exactly one element.
1054  ///   This method runs in constant time.
1055  bool isSingleton() const { return getHeight() == 1; }
1056
1057  template <typename Callback>
1058  void foreach(Callback& C) { if (Root) Root->foreach(C); }
1059
1060  template <typename Callback>
1061  void foreach() { if (Root) { Callback C; Root->foreach(C); } }
1062
1063  //===--------------------------------------------------===//
1064  // Iterators.
1065  //===--------------------------------------------------===//
1066
1067  class iterator {
1068    typename TreeTy::iterator itr;
1069
1070    iterator() {}
1071    iterator(TreeTy* t) : itr(t) {}
1072    friend class ImmutableSet<ValT,ValInfo>;
1073
1074  public:
1075    typedef ptrdiff_t difference_type;
1076    typedef typename ImmutableSet<ValT,ValInfo>::value_type value_type;
1077    typedef typename ImmutableSet<ValT,ValInfo>::value_type_ref reference;
1078    typedef typename iterator::value_type *pointer;
1079    typedef std::bidirectional_iterator_tag iterator_category;
1080
1081    typename iterator::reference operator*() const { return itr->getValue(); }
1082    typename iterator::pointer   operator->() const { return &(operator*()); }
1083
1084    iterator& operator++() { ++itr; return *this; }
1085    iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1086    iterator& operator--() { --itr; return *this; }
1087    iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
1088
1089    bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1090    bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1091  };
1092
1093  iterator begin() const { return iterator(Root); }
1094  iterator end() const { return iterator(); }
1095
1096  //===--------------------------------------------------===//
1097  // Utility methods.
1098  //===--------------------------------------------------===//
1099
1100  unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1101
1102  static inline void Profile(FoldingSetNodeID& ID, const ImmutableSet& S) {
1103    ID.AddPointer(S.Root);
1104  }
1105
1106  inline void Profile(FoldingSetNodeID& ID) const {
1107    return Profile(ID,*this);
1108  }
1109
1110  //===--------------------------------------------------===//
1111  // For testing.
1112  //===--------------------------------------------------===//
1113
1114  void validateTree() const { if (Root) Root->validateTree(); }
1115};
1116
1117// NOTE: This may some day replace the current ImmutableSet.
1118template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
1119class ImmutableSetRef {
1120public:
1121  typedef typename ValInfo::value_type      value_type;
1122  typedef typename ValInfo::value_type_ref  value_type_ref;
1123  typedef ImutAVLTree<ValInfo> TreeTy;
1124  typedef typename TreeTy::Factory          FactoryTy;
1125
1126private:
1127  TreeTy *Root;
1128  FactoryTy *Factory;
1129
1130public:
1131  /// Constructs a set from a pointer to a tree root.  In general one
1132  /// should use a Factory object to create sets instead of directly
1133  /// invoking the constructor, but there are cases where make this
1134  /// constructor public is useful.
1135  explicit ImmutableSetRef(TreeTy* R, FactoryTy *F)
1136    : Root(R),
1137      Factory(F) {
1138    if (Root) { Root->retain(); }
1139  }
1140  ImmutableSetRef(const ImmutableSetRef &X)
1141    : Root(X.Root),
1142      Factory(X.Factory) {
1143    if (Root) { Root->retain(); }
1144  }
1145  ImmutableSetRef &operator=(const ImmutableSetRef &X) {
1146    if (Root != X.Root) {
1147      if (X.Root) { X.Root->retain(); }
1148      if (Root) { Root->release(); }
1149      Root = X.Root;
1150      Factory = X.Factory;
1151    }
1152    return *this;
1153  }
1154  ~ImmutableSetRef() {
1155    if (Root) { Root->release(); }
1156  }
1157
1158  static inline ImmutableSetRef getEmptySet(FactoryTy *F) {
1159    return ImmutableSetRef(0, F);
1160  }
1161
1162  ImmutableSetRef add(value_type_ref V) {
1163    return ImmutableSetRef(Factory->add(Root, V), Factory);
1164  }
1165
1166  ImmutableSetRef remove(value_type_ref V) {
1167    return ImmutableSetRef(Factory->remove(Root, V), Factory);
1168  }
1169
1170  /// Returns true if the set contains the specified value.
1171  bool contains(value_type_ref V) const {
1172    return Root ? Root->contains(V) : false;
1173  }
1174
1175  ImmutableSet<ValT> asImmutableSet(bool canonicalize = true) const {
1176    return ImmutableSet<ValT>(canonicalize ?
1177                              Factory->getCanonicalTree(Root) : Root);
1178  }
1179
1180  TreeTy *getRootWithoutRetain() const {
1181    return Root;
1182  }
1183
1184  bool operator==(const ImmutableSetRef &RHS) const {
1185    return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
1186  }
1187
1188  bool operator!=(const ImmutableSetRef &RHS) const {
1189    return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
1190  }
1191
1192  /// isEmpty - Return true if the set contains no elements.
1193  bool isEmpty() const { return !Root; }
1194
1195  /// isSingleton - Return true if the set contains exactly one element.
1196  ///   This method runs in constant time.
1197  bool isSingleton() const { return getHeight() == 1; }
1198
1199  //===--------------------------------------------------===//
1200  // Iterators.
1201  //===--------------------------------------------------===//
1202
1203  class iterator {
1204    typename TreeTy::iterator itr;
1205    iterator(TreeTy* t) : itr(t) {}
1206    friend class ImmutableSetRef<ValT,ValInfo>;
1207  public:
1208    iterator() {}
1209    inline value_type_ref operator*() const { return itr->getValue(); }
1210    inline iterator& operator++() { ++itr; return *this; }
1211    inline iterator  operator++(int) { iterator tmp(*this); ++itr; return tmp; }
1212    inline iterator& operator--() { --itr; return *this; }
1213    inline iterator  operator--(int) { iterator tmp(*this); --itr; return tmp; }
1214    inline bool operator==(const iterator& RHS) const { return RHS.itr == itr; }
1215    inline bool operator!=(const iterator& RHS) const { return RHS.itr != itr; }
1216    inline value_type *operator->() const { return &(operator*()); }
1217  };
1218
1219  iterator begin() const { return iterator(Root); }
1220  iterator end() const { return iterator(); }
1221
1222  //===--------------------------------------------------===//
1223  // Utility methods.
1224  //===--------------------------------------------------===//
1225
1226  unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1227
1228  static inline void Profile(FoldingSetNodeID& ID, const ImmutableSetRef& S) {
1229    ID.AddPointer(S.Root);
1230  }
1231
1232  inline void Profile(FoldingSetNodeID& ID) const {
1233    return Profile(ID,*this);
1234  }
1235
1236  //===--------------------------------------------------===//
1237  // For testing.
1238  //===--------------------------------------------------===//
1239
1240  void validateTree() const { if (Root) Root->validateTree(); }
1241};
1242
1243} // end namespace llvm
1244
1245#endif
1246