1 //===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Ted Kremenek and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ImutAVLTree and ImmutableSet classes.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_ADT_IMSET_H
15 #define LLVM_ADT_IMSET_H
17 #include "llvm/Support/Allocator.h"
18 #include "llvm/ADT/FoldingSet.h"
23 //===----------------------------------------------------------------------===//
24 // Immutable AVL-Tree Definition.
25 //===----------------------------------------------------------------------===//
27 template <typename ImutInfo> class ImutAVLFactory;
29 template <typename ImutInfo >
30 class ImutAVLTree : public FoldingSetNode {
31 struct ComputeIsEqual;
33 typedef typename ImutInfo::key_type_ref key_type_ref;
34 typedef typename ImutInfo::value_type value_type;
35 typedef typename ImutInfo::value_type_ref value_type_ref;
36 typedef ImutAVLFactory<ImutInfo> Factory;
37 friend class ImutAVLFactory<ImutInfo>;
39 //===----------------------------------------------------===//
41 //===----------------------------------------------------===//
43 ImutAVLTree* getLeft() const { return reinterpret_cast<ImutAVLTree*>(Left); }
45 ImutAVLTree* getRight() const { return Right; }
47 unsigned getHeight() const { return Height; }
49 const value_type& getValue() const { return Value; }
51 ImutAVLTree* find(key_type_ref K) {
52 ImutAVLTree *T = this;
55 key_type_ref CurrentKey = ImutInfo::KeyOfValue(Value(T));
57 if (ImutInfo::isEqual(K,CurrentKey))
59 else if (ImutInfo::isLess(K,CurrentKey))
68 unsigned size() const {
71 if (const ImutAVLTree* L = getLeft()) n += L->size();
72 if (const ImutAVLTree* R = getRight()) n += R->size();
79 bool isEqual(const ImutAVLTree& RHS) const {
84 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
86 bool contains(const key_type_ref K) { return (bool) find(K); }
88 template <typename Callback>
89 void foreach(Callback& C) {
90 if (ImutAVLTree* L = getLeft()) L->foreach(C);
94 if (ImutAVLTree* R = getRight()) R->foreach(C);
97 unsigned verify() const {
98 unsigned HL = getLeft() ? getLeft()->verify() : 0;
99 unsigned HR = getRight() ? getRight()->verify() : 0;
101 assert (getHeight() == ( HL > HR ? HL : HR ) + 1
102 && "Height calculation wrong.");
104 assert ((HL > HR ? HL-HR : HR-HL) <= 2
105 && "Balancing invariant violated.");
109 || ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
110 ImutInfo::KeyOfValue(getValue()))
111 && "Value in left child is not less that current value.");
115 || ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
116 ImutInfo::KeyOfValue(getRight()->getValue()))
117 && "Current value is not less that value of right child.");
122 //===----------------------------------------------------===//
124 //===----------------------------------------------------===//
132 //===----------------------------------------------------===//
133 // Profiling or FoldingSet.
134 //===----------------------------------------------------===//
137 void Profile(FoldingSetNodeID& ID, ImutAVLTree* L, ImutAVLTree* R,
138 unsigned H, value_type_ref V) {
142 ImutInfo::Profile(ID,V);
147 void Profile(FoldingSetNodeID& ID) {
148 Profile(ID,getSafeLeft(),getRight(),getHeight(),getValue());
151 //===----------------------------------------------------===//
152 // Internal methods (node manipulation; used by Factory).
153 //===----------------------------------------------------===//
157 ImutAVLTree(ImutAVLTree* l, ImutAVLTree* r, value_type_ref v, unsigned height)
158 : Left(reinterpret_cast<uintptr_t>(l) | 0x1),
159 Right(r), Height(height), Value(v) {}
161 bool isMutable() const { return Left & 0x1; }
163 ImutAVLTree* getSafeLeft() const {
164 return reinterpret_cast<ImutAVLTree*>(Left & ~0x1);
167 // Mutating operations. A tree root can be manipulated as long as
168 // its reference has not "escaped" from internal methods of a
169 // factory object (see below). When a tree pointer is externally
170 // viewable by client code, the internal "mutable bit" is cleared
171 // to mark the tree immutable. Note that a tree that still has
172 // its mutable bit set may have children (subtrees) that are themselves
175 void RemoveMutableFlag() {
176 assert (Left & 0x1 && "Mutable flag already removed.");
180 void setLeft(ImutAVLTree* NewLeft) {
181 assert (isMutable());
182 Left = reinterpret_cast<uintptr_t>(NewLeft) | 0x1;
185 void setRight(ImutAVLTree* NewRight) {
186 assert (isMutable());
190 void setHeight(unsigned h) {
191 assert (isMutable());
196 //===----------------------------------------------------------------------===//
197 // Immutable AVL-Tree Factory class.
198 //===----------------------------------------------------------------------===//
200 template <typename ImutInfo >
201 class ImutAVLFactory {
202 typedef ImutAVLTree<ImutInfo> TreeTy;
203 typedef typename TreeTy::value_type_ref value_type_ref;
204 typedef typename TreeTy::key_type_ref key_type_ref;
206 typedef FoldingSet<TreeTy> CacheTy;
209 BumpPtrAllocator Allocator;
211 //===--------------------------------------------------===//
213 //===--------------------------------------------------===//
218 TreeTy* Add(TreeTy* T, value_type_ref V) {
219 T = Add_internal(V,T);
224 TreeTy* Remove(TreeTy* T, key_type_ref V) {
225 T = Remove_internal(V,T);
230 TreeTy* GetEmptyTree() const { return NULL; }
232 //===--------------------------------------------------===//
233 // A bunch of quick helper functions used for reasoning
234 // about the properties of trees and their children.
235 // These have succinct names so that the balancing code
236 // is as terse (and readable) as possible.
237 //===--------------------------------------------------===//
240 bool isEmpty(TreeTy* T) const {
244 unsigned Height(TreeTy* T) const {
245 return T ? T->getHeight() : 0;
248 TreeTy* Left(TreeTy* T) const {
250 return T->getSafeLeft();
253 TreeTy* Right(TreeTy* T) const {
255 return T->getRight();
258 value_type_ref Value(TreeTy* T) const {
263 unsigned IncrementHeight(TreeTy* L, TreeTy* R) const {
264 unsigned hl = Height(L);
265 unsigned hr = Height(R);
266 return ( hl > hr ? hl : hr ) + 1;
269 //===--------------------------------------------------===//
270 // "Create" is used to generate new tree roots that link
271 // to other trees. The functon may also simply move links
272 // in an existing root if that root is still marked mutable.
273 // This is necessary because otherwise our balancing code
274 // would leak memory as it would create nodes that are
275 // then discarded later before the finished tree is
276 // returned to the caller.
277 //===--------------------------------------------------===//
279 TreeTy* Create(TreeTy* L, value_type_ref V, TreeTy* R) {
281 unsigned height = IncrementHeight(L,R);
283 TreeTy::Profile(ID,L,R,height,V);
286 if (TreeTy* T = Cache.FindNodeOrInsertPos(ID,InsertPos))
289 assert (InsertPos != NULL);
291 // FIXME: more intelligent calculation of alignment.
292 TreeTy* T = (TreeTy*) Allocator.Allocate(sizeof(*T),16);
293 new (T) TreeTy(L,R,V,height);
295 Cache.InsertNode(T,InsertPos);
299 TreeTy* Create(TreeTy* L, TreeTy* OldTree, TreeTy* R) {
300 assert (!isEmpty(OldTree));
302 if (OldTree->isMutable()) {
304 OldTree->setRight(R);
305 OldTree->setHeight(IncrementHeight(L,R));
308 else return Create(L, Value(OldTree), R);
311 /// Balance - Used by Add_internal and Remove_internal to
312 /// balance a newly created tree.
313 TreeTy* Balance(TreeTy* L, value_type_ref V, TreeTy* R) {
315 unsigned hl = Height(L);
316 unsigned hr = Height(R);
319 assert (!isEmpty(L) &&
320 "Left tree cannot be empty to have a height >= 2.");
322 TreeTy* LL = Left(L);
323 TreeTy* LR = Right(L);
325 if (Height(LL) >= Height(LR))
326 return Create(LL, L, Create(LR,V,R));
328 assert (!isEmpty(LR) &&
329 "LR cannot be empty because it has a height >= 1.");
331 TreeTy* LRL = Left(LR);
332 TreeTy* LRR = Right(LR);
334 return Create(Create(LL,L,LRL), LR, Create(LRR,V,R));
336 else if (hr > hl + 2) {
337 assert (!isEmpty(R) &&
338 "Right tree cannot be empty to have a height >= 2.");
340 TreeTy* RL = Left(R);
341 TreeTy* RR = Right(R);
343 if (Height(RR) >= Height(RL))
344 return Create(Create(L,V,RL), R, RR);
346 assert (!isEmpty(RL) &&
347 "RL cannot be empty because it has a height >= 1.");
349 TreeTy* RLL = Left(RL);
350 TreeTy* RLR = Right(RL);
352 return Create(Create(L,V,RLL), RL, Create(RLR,R,RR));
355 return Create(L,V,R);
358 /// Add_internal - Creates a new tree that includes the specified
359 /// data and the data from the original tree. If the original tree
360 /// already contained the data item, the original tree is returned.
361 TreeTy* Add_internal(value_type_ref V, TreeTy* T) {
363 return Create(T, V, T);
365 assert (!T->isMutable());
367 key_type_ref K = ImutInfo::KeyOfValue(V);
368 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
370 if (ImutInfo::isEqual(K,KCurrent))
371 return Create(Left(T), V, Right(T));
372 else if (ImutInfo::isLess(K,KCurrent))
373 return Balance(Add_internal(V,Left(T)), Value(T), Right(T));
375 return Balance(Left(T), Value(T), Add_internal(V,Right(T)));
378 /// Remove_interal - Creates a new tree that includes all the data
379 /// from the original tree except the specified data. If the
380 /// specified data did not exist in the original tree, the original
381 /// tree is returned.
382 TreeTy* Remove_internal(key_type_ref K, TreeTy* T) {
386 assert (!T->isMutable());
388 key_type_ref KCurrent = ImutInfo::KeyOfValue(Value(T));
390 if (ImutInfo::isEqual(K,KCurrent))
391 return CombineLeftRightTrees(Left(T),Right(T));
392 else if (ImutInfo::isLess(K,KCurrent))
393 return Balance(Remove_internal(K,Left(T)), Value(T), Right(T));
395 return Balance(Left(T), Value(T), Remove_internal(K,Right(T)));
398 TreeTy* CombineLeftRightTrees(TreeTy* L, TreeTy* R) {
399 if (isEmpty(L)) return R;
400 if (isEmpty(R)) return L;
403 TreeTy* NewRight = RemoveMinBinding(R,OldNode);
404 return Balance(L,Value(OldNode),NewRight);
407 TreeTy* RemoveMinBinding(TreeTy* T, TreeTy*& NodeRemoved) {
408 assert (!isEmpty(T));
410 if (isEmpty(Left(T))) {
415 return Balance(RemoveMinBinding(Left(T),NodeRemoved),Value(T),Right(T));
418 /// MarkImmutable - Clears the mutable bits of a root and all of its
420 void MarkImmutable(TreeTy* T) {
421 if (!T || !T->isMutable())
424 T->RemoveMutableFlag();
425 MarkImmutable(Left(T));
426 MarkImmutable(Right(T));
431 //===----------------------------------------------------------------------===//
432 // Trait classes for Profile information.
433 //===----------------------------------------------------------------------===//
435 /// Generic profile template. The default behavior is to invoke the
436 /// profile method of an object. Specializations for primitive integers
437 /// and generic handling of pointers is done below.
438 template <typename T>
439 struct ImutProfileInfo {
440 typedef const T value_type;
441 typedef const T& value_type_ref;
443 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
448 /// Profile traits for integers.
449 template <typename T>
450 struct ImutProfileInteger {
451 typedef const T value_type;
452 typedef const T& value_type_ref;
454 static inline void Profile(FoldingSetNodeID& ID, value_type_ref X) {
459 #define PROFILE_INTEGER_INFO(X)\
460 template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
462 PROFILE_INTEGER_INFO(char)
463 PROFILE_INTEGER_INFO(unsigned char)
464 PROFILE_INTEGER_INFO(short)
465 PROFILE_INTEGER_INFO(unsigned short)
466 PROFILE_INTEGER_INFO(unsigned)
467 PROFILE_INTEGER_INFO(signed)
468 PROFILE_INTEGER_INFO(long)
469 PROFILE_INTEGER_INFO(unsigned long)
470 PROFILE_INTEGER_INFO(long long)
471 PROFILE_INTEGER_INFO(unsigned long long)
473 #undef PROFILE_INTEGER_INFO
475 /// Generic profile trait for pointer types. We treat pointers as
476 /// references to unique objects.
477 template <typename T>
478 struct ImutProfileInfo<T*> {
479 typedef const T* value_type;
480 typedef value_type value_type_ref;
482 static inline void Profile(FoldingSetNodeID &ID, value_type_ref X) {
487 //===----------------------------------------------------------------------===//
488 // Trait classes that contain element comparison operators and type
489 // definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
490 // inherit from the profile traits (ImutProfileInfo) to include operations
491 // for element profiling.
492 //===----------------------------------------------------------------------===//
495 /// ImutContainerInfo - Generic definition of comparison operations for
496 /// elements of immutable containers that defaults to using
497 /// std::equal_to<> and std::less<> to perform comparison of elements.
498 template <typename T>
499 struct ImutContainerInfo : public ImutProfileInfo<T> {
500 typedef typename ImutProfileInfo<T>::value_type value_type;
501 typedef typename ImutProfileInfo<T>::value_type_ref value_type_ref;
502 typedef value_type key_type;
503 typedef value_type_ref key_type_ref;
505 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
507 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
508 return std::equal_to<key_type>()(LHS,RHS);
511 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
512 return std::less<key_type>()(LHS,RHS);
516 /// ImutContainerInfo - Specialization for pointer values to treat pointers
517 /// as references to unique objects. Pointers are thus compared by
519 template <typename T>
520 struct ImutContainerInfo<T*> : public ImutProfileInfo<T*> {
521 typedef typename ImutProfileInfo<T*>::value_type value_type;
522 typedef typename ImutProfileInfo<T*>::value_type_ref value_type_ref;
523 typedef value_type key_type;
524 typedef value_type_ref key_type_ref;
526 static inline key_type_ref KeyOfValue(value_type_ref D) { return D; }
528 static inline bool isEqual(key_type_ref LHS, key_type_ref RHS) {
532 static inline bool isLess(key_type_ref LHS, key_type_ref RHS) {
537 //===----------------------------------------------------------------------===//
539 //===----------------------------------------------------------------------===//
541 template <typename ValT, typename ValInfo = ImutContainerInfo<ValT> >
544 typedef typename ValInfo::value_type value_type;
545 typedef typename ValInfo::value_type_ref value_type_ref;
548 typedef ImutAVLTree<ValInfo> TreeTy;
551 ImmutableSet(TreeTy* R) : Root(R) {}
556 typename TreeTy::Factory F;
561 ImmutableSet GetEmptySet() { return ImmutableSet(F.GetEmptyTree()); }
563 ImmutableSet Add(ImmutableSet Old, value_type_ref V) {
564 return ImmutableSet(F.Add(Old.Root,V));
567 ImmutableSet Remove(ImmutableSet Old, value_type_ref V) {
568 return ImmutableSet(F.Remove(Old.Root,V));
572 Factory(const Factory& RHS) {};
573 void operator=(const Factory& RHS) {};
576 friend class Factory;
578 bool contains(const value_type_ref V) const {
579 return Root ? Root->contains(V) : false;
582 bool operator==(ImmutableSet RHS) const {
583 return Root && RHS.Root ? Root->isEqual(*RHS.Root) : Root == RHS.Root;
586 bool operator!=(ImmutableSet RHS) const {
587 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root) : Root != RHS.Root;
590 bool isEmpty() const { return !Root; }
592 template <typename Callback>
593 void foreach(Callback& C) { if (Root) Root->foreach(C); }
595 template <typename Callback>
596 void foreach() { if (Root) { Callback C; Root->foreach(C); } }
598 //===--------------------------------------------------===//
600 //===--------------------------------------------------===//
602 void verify() const { if (Root) Root->verify(); }
603 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
606 } // end namespace llvm