LLVM 24.0.0git
ImmutableSet.h
Go to the documentation of this file.
1//===--- ImmutableSet.h - Immutable (functional) set interface --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
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"
20#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/iterator.h"
25#include "llvm/Support/Debug.h"
28#include <cassert>
29#include <cstdint>
30#include <functional>
31#include <iterator>
32#include <new>
33#include <vector>
34
35namespace llvm {
36
37//===----------------------------------------------------------------------===//
38// Immutable AVL-Tree Definition.
39//===----------------------------------------------------------------------===//
40
41template <typename ImutInfo, bool Canonicalize = true> class ImutAVLFactory;
42template <typename ImutInfo, bool Canonicalize = true>
44
45namespace ImutAVLDetail {
46/// The intrusive doubly-linked chain of same-digest trees in the factory's
47/// canonicalization cache. Held as an (empty) base so that, when
48/// canonicalization is disabled, the empty base optimization removes it
49/// entirely. Kept separate from the cached digest below so that the two
50/// pointers pack without the tail padding that grouping a trailing 32-bit field
51/// with them would introduce.
52template <typename Tree, bool Canonicalize> struct CanonicalLinks {
53 Tree *Prev = nullptr;
54 Tree *Next = nullptr;
55};
56template <typename Tree> struct CanonicalLinks<Tree, false> {};
57
58/// The cached structural digest, used only for canonicalization. Stored as an
59/// LLVM_NO_UNIQUE_ADDRESS member so it occupies no space when disabled and
60/// packs alongside the adjacent 32-bit fields when enabled.
61template <bool Canonicalize> struct CanonicalDigest {
63};
64template <> struct CanonicalDigest<false> {};
65
66/// The factory-side canonicalization cache: digest -> tree chain.
67/// Empty when canonicalization is disabled.
68template <typename Tree, bool Canonicalize> struct CanonicalCache {
70};
71template <typename Tree> struct CanonicalCache<Tree, false> {};
72} // namespace ImutAVLDetail
73
74template <typename ImutInfo, bool Canonicalize = true>
75class ImutAVLTree
76 : private ImutAVLDetail::CanonicalLinks<ImutAVLTree<ImutInfo, Canonicalize>,
77 Canonicalize> {
78public:
79 using key_type_ref = typename ImutInfo::key_type_ref;
80 using value_type = typename ImutInfo::value_type;
81 using value_type_ref = typename ImutInfo::value_type_ref;
84
85 friend class ImutAVLFactory<ImutInfo, Canonicalize>;
86
87public:
88 //===----------------------------------------------------===//
89 // Public Interface.
90 //===----------------------------------------------------===//
91
92 /// Return a pointer to the left subtree. This value
93 /// is NULL if there is no left subtree.
94 ImutAVLTree *getLeft() const { return left; }
95
96 /// Return a pointer to the right subtree. This value is
97 /// NULL if there is no right subtree.
98 ImutAVLTree *getRight() const { return right; }
99
100 /// Returns the height of the tree. A tree with no subtrees has a height of 1.
101 unsigned getHeight() const { return height; }
102
103 /// Returns the data value associated with the tree node.
104 const value_type& getValue() const { return value; }
105
106 /// Finds the subtree associated with the specified key value. This method
107 /// returns NULL if no matching subtree is found.
108 ImutAVLTree* find(key_type_ref K) {
109 ImutAVLTree *T = this;
110 while (T) {
111 key_type_ref CurrentKey = ImutInfo::KeyOfValue(T->getValue());
112 if (ImutInfo::isEqual(K,CurrentKey))
113 return T;
114 else if (ImutInfo::isLess(K,CurrentKey))
115 T = T->getLeft();
116 else
117 T = T->getRight();
118 }
119 return nullptr;
120 }
121
122 /// Find the subtree associated with the highest ranged key value.
123 ImutAVLTree* getMaxElement() {
124 ImutAVLTree *T = this;
125 ImutAVLTree *Right = T->getRight();
126 while (Right) { T = Right; Right = T->getRight(); }
127 return T;
128 }
129
130 /// Returns the number of nodes in the tree, which includes both leaves and
131 // non-leaf nodes.
132 unsigned size() const {
133 unsigned n = 1;
134 if (const ImutAVLTree* L = getLeft())
135 n += L->size();
136 if (const ImutAVLTree* R = getRight())
137 n += R->size();
138 return n;
139 }
140
141 /// Returns an iterator that iterates over the nodes of the tree in an inorder
142 /// traversal. The returned iterator thus refers to the tree node with the
143 /// minimum data element.
144 iterator begin() const { return iterator(this); }
145
146 /// Returns an iterator for the tree that denotes the end of an inorder
147 /// traversal.
148 iterator end() const { return iterator(); }
149
151 // Compare the keys.
152 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(getValue()),
153 ImutInfo::KeyOfValue(V)))
154 return false;
155
156 // Also compare the data values.
157 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(getValue()),
158 ImutInfo::DataOfValue(V)))
159 return false;
160
161 return true;
162 }
163
164 bool isElementEqual(const ImutAVLTree* RHS) const {
165 return isElementEqual(RHS->getValue());
166 }
167
168 /// Compares two trees for structural equality and returns true if they are
169 /// equal. The worst case performance of this operation is linear in the sizes
170 /// of the trees.
171 bool isEqual(const ImutAVLTree& RHS) const {
172 if (&RHS == this)
173 return true;
174
175 iterator LItr = begin(), LEnd = end();
176 iterator RItr = RHS.begin(), REnd = RHS.end();
177
178 while (LItr != LEnd && RItr != REnd) {
179 if (&*LItr == &*RItr) {
180 LItr.skipSubTree();
181 RItr.skipSubTree();
182 continue;
183 }
184
185 if (!LItr->isElementEqual(&*RItr))
186 return false;
187
188 ++LItr;
189 ++RItr;
190 }
191
192 return LItr == LEnd && RItr == REnd;
193 }
194
195 /// Compares two trees for structural inequality. Performance is the same as
196 /// isEqual.
197 bool isNotEqual(const ImutAVLTree& RHS) const { return !isEqual(RHS); }
198
199 /// Returns true if this tree contains a subtree (node) that has an data
200 /// element that matches the specified key. Complexity is logarithmic in the
201 /// size of the tree.
202 bool contains(key_type_ref K) { return (bool) find(K); }
203
204 /// A utility method that checks that the balancing and ordering invariants of
205 /// the tree are satisfied. It is a recursive method that returns the height
206 /// of the tree, which is then consumed by the enclosing validateTree call.
207 /// External callers should ignore the return value. An invalid tree will
208 /// cause an assertion to fire in a debug build.
209 unsigned validateTree() const {
210 unsigned HL = getLeft() ? getLeft()->validateTree() : 0;
211 unsigned HR = getRight() ? getRight()->validateTree() : 0;
212 (void) HL;
213 (void) HR;
214
215 assert(getHeight() == ( HL > HR ? HL : HR ) + 1
216 && "Height calculation wrong");
217
218 assert((HL > HR ? HL-HR : HR-HL) <= 2
219 && "Balancing invariant violated");
220
221 assert((!getLeft() ||
222 ImutInfo::isLess(ImutInfo::KeyOfValue(getLeft()->getValue()),
223 ImutInfo::KeyOfValue(getValue()))) &&
224 "Value in left child is not less that current value");
225
226 assert((!getRight() ||
227 ImutInfo::isLess(ImutInfo::KeyOfValue(getValue()),
228 ImutInfo::KeyOfValue(getRight()->getValue()))) &&
229 "Current value is not less that value of right child");
230
231 return getHeight();
232 }
233
234 //===----------------------------------------------------===//
235 // Internal values.
236 //===----------------------------------------------------===//
237
238private:
239 // Field order places the traversal-hot fields (left, right, value) first so
240 // that in a node that straddles a cache line they land in the earlier line;
241 // the cold factory back-pointer (only touched on create/destroy) goes last.
242 ImutAVLTree *left;
243 ImutAVLTree *right;
244
245 unsigned height : 28;
247 unsigned IsMutable : 1;
249 unsigned IsDigestCached : 1;
251 unsigned IsCanonicalized : 1;
252
253 value_type value;
254 uint32_t refCount = 0;
256 Factory *factory;
257
258 //===----------------------------------------------------===//
259 // Internal methods (node manipulation; used by Factory).
260 //===----------------------------------------------------===//
261
262private:
263 /// Internal constructor that is only called by ImutAVLFactory.
265 unsigned height)
266 : left(l), right(r), height(height), IsMutable(true),
267 IsDigestCached(false), IsCanonicalized(false), value(v), factory(f) {
268 if (left) left->retain();
269 if (right) right->retain();
270 }
271
272 /// Returns true if the left and right subtree references
273 /// (as well as height) can be changed. If this method returns false,
274 /// the tree is truly immutable. Trees returned from an ImutAVLFactory
275 /// object should always have this method return true. Further, if this
276 /// method returns false for an instance of ImutAVLTree, all subtrees
277 /// will also have this method return false. The converse is not true.
278 bool isMutable() const { return IsMutable; }
279
280 /// Returns true if the digest for this tree is cached. This can only be true
281 /// if the tree is immutable.
282 bool hasCachedDigest() const { return IsDigestCached; }
283
284 //===----------------------------------------------------===//
285 // Mutating operations. A tree root can be manipulated as
286 // long as its reference has not "escaped" from internal
287 // methods of a factory object (see below). When a tree
288 // pointer is externally viewable by client code, the
289 // internal "mutable bit" is cleared to mark the tree
290 // immutable. Note that a tree that still has its mutable
291 // bit set may have children (subtrees) that are themselves
292 // immutable.
293 //===----------------------------------------------------===//
294
295 /// Clears the mutable flag for a tree. After this happens,
296 /// it is an error to call setLeft(), setRight(), and setHeight().
297 void markImmutable() {
298 assert(isMutable() && "Mutable flag already removed.");
299 IsMutable = false;
300 }
301
302 /// Clears the NoCachedDigest flag for a tree.
303 void markedCachedDigest() {
304 assert(!hasCachedDigest() && "NoCachedDigest flag already removed.");
305 IsDigestCached = true;
306 }
307
308 /// Changes the height of the tree. Used internally by ImutAVLFactory.
309 void setHeight(unsigned h) {
310 assert(isMutable() && "Only a mutable tree can have its height changed.");
311 height = h;
312 }
313
314 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
316 uint32_t digest = 0;
317
318 if (L)
319 digest += L->computeDigest();
320
321 // Compute digest of stored data.
322 FoldingSetNodeID ID;
323 ImutInfo::Profile(ID,V);
324 digest += ID.computeHash();
325
326 if (R)
327 digest += R->computeDigest();
328
329 return digest;
330 }
331
332 uint32_t computeDigest() {
333 // Check the lowest bit to determine if digest has actually been
334 // pre-computed.
335 if (hasCachedDigest())
336 return digest.Digest;
337
338 uint32_t X = computeDigest(getLeft(), getRight(), getValue());
339 digest.Digest = X;
340 markedCachedDigest();
341 return X;
342 }
343
344 //===----------------------------------------------------===//
345 // Reference count operations.
346 //===----------------------------------------------------===//
347
348public:
349 void retain() { ++refCount; }
350
351 void release() {
352 assert(refCount > 0);
353 if (--refCount == 0)
354 destroy();
355 }
356
358 if (left)
359 left->release();
360 if (right)
361 right->release();
362 if constexpr (Canonicalize) {
363 if (IsCanonicalized) {
364 if (this->Next)
365 this->Next->Prev = this->Prev;
366
367 if (this->Prev)
368 this->Prev->Next = this->Next;
369 else
370 factory->Cache[factory->maskCacheIndex(computeDigest())] = this->Next;
371 }
372 }
373
374 // We need to clear the mutability bit in case we are
375 // destroying the node as part of a sweep in ImutAVLFactory::recoverNodes().
376 IsMutable = false;
377 factory->freeNodes.push_back(this);
378 }
379};
380
381template <typename ImutInfo, bool Canonicalize>
382struct IntrusiveRefCntPtrInfo<ImutAVLTree<ImutInfo, Canonicalize>> {
384 Tree->retain();
385 }
387 Tree->release();
388 }
389};
390
391//===----------------------------------------------------------------------===//
392// Immutable AVL-Tree Factory class.
393//===----------------------------------------------------------------------===//
394
395template <typename ImutInfo, bool Canonicalize>
397 : private ImutAVLDetail::CanonicalCache<ImutAVLTree<ImutInfo, Canonicalize>,
398 Canonicalize> {
399 friend class ImutAVLTree<ImutInfo, Canonicalize>;
400
402 using value_type = typename TreeTy::value_type;
403 using value_type_ref = typename TreeTy::value_type_ref;
404 using key_type_ref = typename TreeTy::key_type_ref;
405
406 uintptr_t Allocator;
407 std::vector<TreeTy*> createdNodes;
408 std::vector<TreeTy*> freeNodes;
409
410 bool ownsAllocator() const {
411 return (Allocator & 0x1) == 0;
412 }
413
414 BumpPtrAllocator& getAllocator() const {
415 return *reinterpret_cast<BumpPtrAllocator*>(Allocator & ~0x1);
416 }
417
418 //===--------------------------------------------------===//
419 // Public interface.
420 //===--------------------------------------------------===//
421
422public:
424 : Allocator(reinterpret_cast<uintptr_t>(new BumpPtrAllocator())) {}
425
427 : Allocator(reinterpret_cast<uintptr_t>(&Alloc) | 0x1) {}
428
430 if (ownsAllocator()) delete &getAllocator();
431 }
432
433 TreeTy* add(TreeTy* T, value_type_ref V) {
434 T = add_internal(V,T);
436 return T;
437 }
438
439 /// Merges \p A and \p B in a single traversal, sharing every subtree that the
440 /// two operands do not overlap. \p Combine(AElem, BElem) produces the element
441 /// stored for a key present in both; \p KeepUnmatched governs keys unique to
442 /// one side (see merge_internal). For merging |B| entries into |A|
443 /// (|B| <= |A|) this costs O(|B| * log(|A|/|B| + 1)) and copies each spine
444 /// node at most once, versus O(|B| * log|A|) repeated \ref add descents.
445 /// \p A and \p B must be immutable. This does not short-circuit equal or
446 /// empty operands (merge_internal handles them correctly but not specially);
447 /// callers that want those fast paths, or size-driven operand ordering,
448 /// should apply them first (see ImmutableSet::Factory::unionSets).
449 template <typename CombineFn>
450 TreeTy *mergeTrees(TreeTy *A, TreeTy *B, CombineFn Combine,
451 bool KeepUnmatched, bool SkipShared = false) {
452 TreeTy *T = merge_internal(A, B, Combine, KeepUnmatched, SkipShared);
454 return T;
455 }
456
457 /// Returns the set union of \p A and \p B (keeping \p A's element on matching
458 /// keys). Shorthand for the fully sharing \ref mergeTrees.
459 TreeTy *unionTrees(TreeTy *A, TreeTy *B) {
460 // With KeepUnmatched=true, unmatched elements are shared as-is and Combine
461 // is invoked only for keys present in both, where it keeps A's element.
462 auto KeepFirst = [](const value_type *L,
463 const value_type *R) -> const value_type & {
464 return L ? *L : *R;
465 };
466 // Set union is idempotent, so identical (pointer-equal) subtrees -- common
467 // once one operand is derived from the other -- can be shared in O(1).
468 return mergeTrees(A, B, KeepFirst, /*KeepUnmatched=*/true,
469 /*SkipShared=*/true);
470 }
471
472 TreeTy* remove(TreeTy* T, key_type_ref V) {
473 T = remove_internal(V,T);
475 return T;
476 }
477
478 TreeTy* getEmptyTree() const { return nullptr; }
479
480protected:
481 //===--------------------------------------------------===//
482 // A bunch of quick helper functions used for reasoning
483 // about the properties of trees and their children.
484 // These have succinct names so that the balancing code
485 // is as terse (and readable) as possible.
486 //===--------------------------------------------------===//
487
488 bool isEmpty(TreeTy* T) const { return !T; }
489 unsigned getHeight(TreeTy* T) const { return T ? T->getHeight() : 0; }
490 TreeTy* getLeft(TreeTy* T) const { return T->getLeft(); }
491 TreeTy* getRight(TreeTy* T) const { return T->getRight(); }
492 value_type_ref getValue(TreeTy* T) const { return T->value; }
493
494 // Make sure the index is not the Tombstone or Entry key of the DenseMap.
495 static unsigned maskCacheIndex(unsigned I) { return (I & ~0x02); }
496
497 unsigned incrementHeight(TreeTy* L, TreeTy* R) const {
498 unsigned hl = getHeight(L);
499 unsigned hr = getHeight(R);
500 return (hl > hr ? hl : hr) + 1;
501 }
502
503 //===--------------------------------------------------===//
504 // "createNode" is used to generate new tree roots that link
505 // to other trees. The function may also simply move links
506 // in an existing root if that root is still marked mutable.
507 // This is necessary because otherwise our balancing code
508 // would leak memory as it would create nodes that are
509 // then discarded later before the finished tree is
510 // returned to the caller.
511 //===--------------------------------------------------===//
512
513 TreeTy* createNode(TreeTy* L, value_type_ref V, TreeTy* R) {
514 BumpPtrAllocator& A = getAllocator();
515 TreeTy* T;
516 if (!freeNodes.empty()) {
517 T = freeNodes.back();
518 freeNodes.pop_back();
519 assert(T != L);
520 assert(T != R);
521 } else {
522 T = (TreeTy*) A.Allocate<TreeTy>();
523 }
524 new (T) TreeTy(this, L, R, V, incrementHeight(L,R));
525 createdNodes.push_back(T);
526 return T;
527 }
528
529 TreeTy* createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
530 return createNode(newLeft, getValue(oldTree), newRight);
531 }
532
533 void recoverNodes(TreeTy *Result) {
534 // Mark Result's nodes immutable and reclaim the intermediates discarded
535 // during balancing, in one pass. Nodes are built bottom-up, so a node
536 // precedes its parents in createdNodes; visiting in reverse thus reaches
537 // each node only once its reference count is final. Unreferenced nodes are
538 // unreachable and destroyed; the rest belong to Result. Result is kept
539 // despite its zero count -- the caller has not taken ownership yet.
540 for (TreeTy *N : llvm::reverse(createdNodes)) {
541 if (!N->isMutable())
542 continue; // Already reclaimed while destroying an unreachable parent.
543 if (N != Result && N->refCount == 0)
544 N->destroy();
545 else
546 N->markImmutable();
547 }
548 createdNodes.clear();
549 }
550
551 /// Used by add_internal and remove_internal to balance a newly created tree.
552 TreeTy* balanceTree(TreeTy* L, value_type_ref V, TreeTy* R) {
553 unsigned hl = getHeight(L);
554 unsigned hr = getHeight(R);
555
556 if (hl > hr + 2) {
557 assert(!isEmpty(L) && "Left tree cannot be empty to have a height >= 2");
558
559 TreeTy *LL = getLeft(L);
560 TreeTy *LR = getRight(L);
561
562 if (getHeight(LL) >= getHeight(LR))
563 return createNode(LL, L, createNode(LR,V,R));
564
565 assert(!isEmpty(LR) && "LR cannot be empty because it has a height >= 1");
566
567 TreeTy *LRL = getLeft(LR);
568 TreeTy *LRR = getRight(LR);
569
570 return createNode(createNode(LL,L,LRL), LR, createNode(LRR,V,R));
571 }
572
573 if (hr > hl + 2) {
574 assert(!isEmpty(R) && "Right tree cannot be empty to have a height >= 2");
575
576 TreeTy *RL = getLeft(R);
577 TreeTy *RR = getRight(R);
578
579 if (getHeight(RR) >= getHeight(RL))
580 return createNode(createNode(L,V,RL), R, RR);
581
582 assert(!isEmpty(RL) && "RL cannot be empty because it has a height >= 1");
583
584 TreeTy *RLL = getLeft(RL);
585 TreeTy *RLR = getRight(RL);
586
587 return createNode(createNode(L,V,RLL), RL, createNode(RLR,R,RR));
588 }
589
590 return createNode(L,V,R);
591 }
592
593 /// Combines \p L and \p R with the value \p V (every key in \p L less than
594 /// \p V, every key in \p R greater) into one balanced tree. Unlike
595 /// balanceTree this tolerates an arbitrary height difference between \p L and
596 /// \p R: it descends the taller side's spine and rebalances on the way back
597 /// up, exactly as an insertion would.
598 TreeTy *joinTrees(TreeTy *L, value_type_ref V, TreeTy *R) {
599 if (getHeight(L) > getHeight(R) + 2)
600 return balanceTree(getLeft(L), getValue(L), joinTrees(getRight(L), V, R));
601 if (getHeight(R) > getHeight(L) + 2)
602 return balanceTree(joinTrees(L, V, getLeft(R)), getValue(R), getRight(R));
603 return createNode(L, V, R);
604 }
605
606 /// Splits \p T into \p L (all keys less than \p K) and \p R (all keys greater
607 /// than \p K). If \p K is present in \p T, \p Match is set to point at its
608 /// element (which is dropped from \p L and \p R); otherwise \p Match is null.
609 void splitLookup(TreeTy *T, key_type_ref K, TreeTy *&L,
610 const value_type *&Match, TreeTy *&R) {
611 if (isEmpty(T)) {
612 L = R = getEmptyTree();
613 Match = nullptr;
614 return;
615 }
616 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
617 if (ImutInfo::isEqual(K, KCurrent)) {
618 L = getLeft(T);
619 R = getRight(T);
620 // Use the tree accessor, which returns a reference to the stored element
621 // (the factory's getValue returns value_type_ref, which is by value for
622 // pointer-like element types).
623 Match = &T->getValue();
624 } else if (ImutInfo::isLess(K, KCurrent)) {
625 TreeTy *LR;
626 splitLookup(getLeft(T), K, L, Match, LR);
627 R = joinTrees(LR, getValue(T), getRight(T));
628 } else {
629 TreeTy *RL;
630 splitLookup(getRight(T), K, RL, Match, R);
631 L = joinTrees(getLeft(T), getValue(T), RL);
632 }
633 }
634
635 /// Rebuilds \p T with the same shape but each element replaced by
636 /// \p Combine applied to it. \p FromB selects which side of \p Combine the
637 /// element is passed on (it is the sole non-null argument).
638 template <typename CombineFn>
639 TreeTy *transformTree(TreeTy *T, CombineFn &Combine, bool FromB) {
640 if (isEmpty(T))
641 return T;
642 TreeTy *L = transformTree(getLeft(T), Combine, FromB);
643 TreeTy *R = transformTree(getRight(T), Combine, FromB);
644 const value_type &E = getValue(T);
645 return createNode(L, FromB ? Combine(nullptr, &E) : Combine(&E, nullptr),
646 R);
647 }
648
649 /// Merges \p A and \p B by recursing over \p A's structure and splitting \p B
650 /// at each of \p A's keys. For a key in both, the stored element is
651 /// Combine(AElem, BElem). \p KeepUnmatched controls keys unique to one side:
652 /// when true, such elements (and whole non-overlapping subtrees) are taken
653 /// unchanged and shared, and \p Combine is invoked only on keys present in
654 /// both (valid when \p Combine is an identity for a missing side, e.g. a set
655 /// union or a lattice join with an identity element); when false every key is
656 /// passed through \p Combine with the absent side null (needed for a join
657 /// that transforms unmatched keys, e.g. liveness downgrading Must to Maybe).
658 template <typename CombineFn>
659 TreeTy *merge_internal(TreeTy *A, TreeTy *B, CombineFn &Combine,
660 bool KeepUnmatched, bool SkipShared) {
661 // When A and B are the same tree (which happens all the time once B is
662 // derived from A by a small edit, since the untouched side is shared by
663 // pointer), an idempotent merge returns it unchanged in O(1). Only valid
664 // when merge(x, x) == x, so the caller opts in via SkipShared.
665 if (SkipShared && A == B)
666 return A;
667 if (isEmpty(A))
668 return KeepUnmatched ? B : transformTree(B, Combine, /*FromB=*/true);
669 if (isEmpty(B))
670 return KeepUnmatched ? A : transformTree(A, Combine, /*FromB=*/false);
671
672 const value_type &AElem = getValue(A);
673 TreeTy *BL, *BR;
674 const value_type *BMatch;
675 splitLookup(B, ImutInfo::KeyOfValue(AElem), BL, BMatch, BR);
676
677 TreeTy *NewL =
678 merge_internal(getLeft(A), BL, Combine, KeepUnmatched, SkipShared);
679 TreeTy *NewR =
680 merge_internal(getRight(A), BR, Combine, KeepUnmatched, SkipShared);
681
682 if (!BMatch) {
683 // Key present only in A.
684 if (KeepUnmatched) {
685 if (NewL == getLeft(A) && NewR == getRight(A))
686 return A;
687 return joinTrees(NewL, AElem, NewR);
688 }
689 return joinTrees(NewL, Combine(&AElem, nullptr), NewR);
690 }
691 // Key present in both: combine the two elements. Preserve sharing when the
692 // combined value is unchanged and neither subtree moved, so that a join
693 // that only touches a few keys does not rebuild the whole spine.
694 auto NewElem = Combine(&AElem, BMatch);
695 if (NewL == getLeft(A) && NewR == getRight(A) &&
696 ImutInfo::isDataEqual(ImutInfo::DataOfValue(NewElem),
697 ImutInfo::DataOfValue(AElem)))
698 return A;
699 return joinTrees(NewL, NewElem, NewR);
700 }
701
702 /// add_internal - Creates a new tree that includes the specified
703 /// data and the data from the original tree. If the original tree
704 /// already contained the data item, the original tree is returned.
705 TreeTy *add_internal(value_type_ref V, TreeTy *T) {
706 if (isEmpty(T))
707 return createNode(T, V, T);
708 assert(!T->isMutable());
709
710 key_type_ref K = ImutInfo::KeyOfValue(V);
711 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
712
713 if (ImutInfo::isEqual(K, KCurrent)) {
714 // If both key and value are same, return the original tree.
715 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(V),
716 ImutInfo::DataOfValue(getValue(T))))
717 return T;
718 // Otherwise create a new node with the new value.
719 return createNode(getLeft(T), V, getRight(T));
720 }
721
722 TreeTy *NewL = getLeft(T);
723 TreeTy *NewR = getRight(T);
724 if (ImutInfo::isLess(K, KCurrent))
725 NewL = add_internal(V, NewL);
726 else
727 NewR = add_internal(V, NewR);
728
729 // If no changes were made, return the original tree. Otherwise, balance the
730 // tree and return the new root.
731 return NewL == getLeft(T) && NewR == getRight(T)
732 ? T
733 : balanceTree(NewL, getValue(T), NewR);
734 }
735
736 /// remove_internal - Creates a new tree that includes all the data
737 /// from the original tree except the specified data. If the
738 /// specified data did not exist in the original tree, the original
739 /// tree is returned.
740 TreeTy *remove_internal(key_type_ref K, TreeTy *T) {
741 if (isEmpty(T))
742 return T;
743
744 assert(!T->isMutable());
745
746 key_type_ref KCurrent = ImutInfo::KeyOfValue(getValue(T));
747
748 if (ImutInfo::isEqual(K, KCurrent))
749 return combineTrees(getLeft(T), getRight(T));
750
751 TreeTy *NewL = getLeft(T);
752 TreeTy *NewR = getRight(T);
753 if (ImutInfo::isLess(K, KCurrent))
754 NewL = remove_internal(K, NewL);
755 else
756 NewR = remove_internal(K, NewR);
757
758 // If no changes were made, return the original tree. Otherwise, balance the
759 // tree and return the new root.
760 return NewL == getLeft(T) && NewR == getRight(T)
761 ? T
762 : balanceTree(NewL, getValue(T), NewR);
763 }
764
765 TreeTy* combineTrees(TreeTy* L, TreeTy* R) {
766 if (isEmpty(L))
767 return R;
768 if (isEmpty(R))
769 return L;
770 TreeTy* OldNode;
771 TreeTy* newRight = removeMinBinding(R,OldNode);
772 return balanceTree(L, getValue(OldNode), newRight);
773 }
774
775 TreeTy* removeMinBinding(TreeTy* T, TreeTy*& Noderemoved) {
776 assert(!isEmpty(T));
777 if (isEmpty(getLeft(T))) {
778 Noderemoved = T;
779 return getRight(T);
780 }
781 return balanceTree(removeMinBinding(getLeft(T), Noderemoved),
782 getValue(T), getRight(T));
783 }
784
785public:
786 TreeTy *getCanonicalTree(TreeTy *TNew) {
787 static_assert(Canonicalize,
788 "getCanonicalTree requires a canonicalizing factory");
789 if (!TNew)
790 return nullptr;
791
792 if (TNew->IsCanonicalized)
793 return TNew;
794
795 // Search the hashtable for another tree with the same digest, and
796 // if find a collision compare those trees by their contents.
797 unsigned digest = TNew->computeDigest();
798 TreeTy *&entry = this->Cache[maskCacheIndex(digest)];
799 if (entry) {
800 for (TreeTy *T = entry; T != nullptr; T = T->Next) {
801 // Compare the contents of 'T' with 'TNew'. isEqual skips subtrees that
802 // are shared by pointer, so for structurally-shared persistent trees
803 // (the common case, e.g. one derived from the other) this is linear in
804 // the number of differing nodes rather than in the tree size.
805 if (!TNew->isEqual(*T))
806 continue;
807 // Trees did match! Return 'T'.
808 if (TNew->refCount == 0)
809 TNew->destroy();
810 return T;
811 }
812 entry->Prev = TNew;
813 TNew->Next = entry;
814 }
815
816 entry = TNew;
817 TNew->IsCanonicalized = true;
818 return TNew;
819 }
820};
821
822//===----------------------------------------------------------------------===//
823// Immutable AVL-Tree Iterator.
824//===----------------------------------------------------------------------===//
825
826/// Bidirectional in-order iterator over the nodes of an ImutAVLTree.
827///
828/// The iterator keeps the chain of ancestors from the root down to the current
829/// node on an explicit stack of plain node pointers, and decides which way to
830/// move next by inspecting whether it is ascending from a node's left or right
831/// child. This avoids storing any per-node visit-state: there is no need to
832/// remember "have I already visited this node's left/right subtree", because
833/// that is recovered by comparing the child we just left against the parent's
834/// left and right pointers.
835///
836/// A node's parent cannot be cached in the node itself, because these trees are
837/// persistent and structurally shared: a single node may appear as the child of
838/// different parents across different tree versions. The ancestor stack is
839/// therefore the per-traversal parent chain.
840template <typename ImutInfo, bool Canonicalize>
842public:
843 using iterator_category = std::bidirectional_iterator_tag;
845 using difference_type = std::ptrdiff_t;
848
850
851private:
852 // Path[0] is the root and Path.back() is the current node. An empty path is
853 // the end iterator. The invariant is that Path always holds the exact chain
854 // of ancestors of the current node, root-most first.
856
857 // Descend along left children, pushing each node; lands on the minimum of the
858 // subtree rooted at T (i.e. the first node in an in-order traversal of T).
859 void descendToMin(TreeTy *T) {
860 for (; T; T = T->getLeft())
861 Path.push_back(T);
862 }
863
864 // Descend along right children, pushing each node; lands on the maximum of
865 // the subtree rooted at T (i.e. the last node in an in-order traversal of T).
866 void descendToMax(TreeTy *T) {
867 for (; T; T = T->getRight())
868 Path.push_back(T);
869 }
870
871 // Pop the current node and ascend until we reach an ancestor from its *left*
872 // child, i.e. the first ancestor whose subtree is not yet fully visited. That
873 // ancestor is the in-order successor of the subtree we just left; if there is
874 // none, Path is emptied (the end iterator). Shared by operator++ and
875 // skipSubTree, whose only difference is whether the current node's right
876 // subtree is descended into first.
877 void ascendFromRightChild() {
878 TreeTy *Child = Path.pop_back_val();
879 while (!Path.empty() && Path.back()->getRight() == Child)
880 Child = Path.pop_back_val();
881 }
882
883 // Mirror of ascendFromRightChild for reverse traversal (operator--).
884 void ascendFromLeftChild() {
885 TreeTy *Child = Path.pop_back_val();
886 while (!Path.empty() && Path.back()->getLeft() == Child)
887 Child = Path.pop_back_val();
888 }
889
890public:
891 ImutAVLTreeInOrderIterator() = default; // end() iterator.
893 descendToMin(const_cast<TreeTy *>(Root));
894 }
895
896 // Two iterators are equal iff they sit on the same node (or are both end()).
897 // Within a single tree a node has a unique root-to-node path, so the current
898 // node alone identifies the position; comparing the whole path is therefore
899 // unnecessary. Comparing iterators from different trees is not meaningful, as
900 // for any standard container.
902 if (Path.empty() || x.Path.empty())
903 return Path.empty() == x.Path.empty();
904 return Path.back() == x.Path.back();
905 }
907 return !(*this == x);
908 }
909
910 TreeTy &operator*() const { return *Path.back(); }
911 TreeTy *operator->() const { return Path.back(); }
912
914 assert(!Path.empty() && "Incrementing the end iterator");
915 if (TreeTy *R = Path.back()->getRight())
916 // The in-order successor is the minimum of the right subtree.
917 descendToMin(R);
918 else
919 // No right subtree: the successor is the nearest ancestor reached from a
920 // left child.
921 ascendFromRightChild();
922 return *this;
923 }
924
926 assert(!Path.empty() && "Decrementing the end iterator");
927 if (TreeTy *L = Path.back()->getLeft())
928 // The in-order predecessor is the maximum of the left subtree.
929 descendToMax(L);
930 else
931 // Mirror of operator++.
932 ascendFromLeftChild();
933 return *this;
934 }
935
936 /// Move to the in-order successor of the entire subtree rooted at the current
937 /// node, i.e. skip the current node together with its right subtree. This is
938 /// exactly the ascent half of operator++.
939 void skipSubTree() {
940 assert(!Path.empty() && "Skipping past the end iterator");
941 ascendFromRightChild();
942 }
943};
944
945/// Generic iterator that wraps a T::TreeTy::iterator and exposes
946/// iterator::getValue() on dereference.
947template <typename T>
950 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
951 typename std::iterator_traits<
952 typename T::TreeTy::iterator>::iterator_category,
953 const typename T::value_type> {
957
959 return this->I->getValue();
960 }
961};
962
963//===----------------------------------------------------------------------===//
964// Trait classes for Profile information.
965//===----------------------------------------------------------------------===//
966
967/// Generic profile template. The default behavior is to invoke the
968/// profile method of an object. Specializations for primitive integers
969/// and generic handling of pointers is done below.
970template <typename T>
972 using value_type = const T;
973 using value_type_ref = const T&;
974
978};
979
980/// Profile traits for integers.
981template <typename T>
983 using value_type = const T;
984 using value_type_ref = const T&;
985
987 ID.AddInteger(X);
988 }
989};
990
991#define PROFILE_INTEGER_INFO(X)\
992template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
993
995PROFILE_INTEGER_INFO(unsigned char)
997PROFILE_INTEGER_INFO(unsigned short)
998PROFILE_INTEGER_INFO(unsigned)
1001PROFILE_INTEGER_INFO(unsigned long)
1002PROFILE_INTEGER_INFO(long long)
1003PROFILE_INTEGER_INFO(unsigned long long)
1004
1005#undef PROFILE_INTEGER_INFO
1006
1007/// Profile traits for booleans.
1008template <>
1010 using value_type = const bool;
1011 using value_type_ref = const bool&;
1012
1014 ID.AddBoolean(X);
1015 }
1016};
1017
1018/// Generic profile trait for pointer types. We treat pointers as
1019/// references to unique objects.
1020template <typename T>
1022 using value_type = const T*;
1024
1026 ID.AddPointer(X);
1027 }
1028};
1029
1030//===----------------------------------------------------------------------===//
1031// Trait classes that contain element comparison operators and type
1032// definitions used by ImutAVLTree, ImmutableSet, and ImmutableMap. These
1033// inherit from the profile traits (ImutProfileInfo) to include operations
1034// for element profiling.
1035//===----------------------------------------------------------------------===//
1036
1037/// Generic definition of comparison operations for elements of immutable
1038/// containers that defaults to using std::equal_to<> and std::less<> to perform
1039/// comparison of elements.
1040template <typename T> struct ImutContainerInfo : ImutProfileInfo<T> {
1047
1050
1052 return std::equal_to<key_type>()(LHS,RHS);
1053 }
1054
1056 return std::less<key_type>()(LHS,RHS);
1057 }
1058
1059 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
1060};
1061
1062/// Specialization for pointer values to treat pointers as references to unique
1063/// objects. Pointers are thus compared by their addresses.
1064template <typename T> struct ImutContainerInfo<T *> : ImutProfileInfo<T *> {
1071
1074
1075 static bool isEqual(key_type_ref LHS, key_type_ref RHS) { return LHS == RHS; }
1076
1077 static bool isLess(key_type_ref LHS, key_type_ref RHS) { return LHS < RHS; }
1078
1079 static bool isDataEqual(data_type_ref, data_type_ref) { return true; }
1080};
1081
1082//===----------------------------------------------------------------------===//
1083// Immutable Set
1084//===----------------------------------------------------------------------===//
1085
1086template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>,
1087 bool Canonicalize = true>
1089public:
1090 using value_type = typename ValInfo::value_type;
1091 using value_type_ref = typename ValInfo::value_type_ref;
1093
1094private:
1096
1097public:
1098 /// Constructs a set from a pointer to a tree root. In general one
1099 /// should use a Factory object to create sets instead of directly
1100 /// invoking the constructor, but there are cases where make this
1101 /// constructor public is useful.
1102 explicit ImmutableSet(TreeTy *R) : Root(R) {}
1103
1104 class Factory {
1105 typename TreeTy::Factory F;
1106
1107 public:
1108 Factory() = default;
1109
1111
1112 Factory(const Factory& RHS) = delete;
1113 void operator=(const Factory& RHS) = delete;
1114
1115 /// Returns an immutable set that contains no elements.
1117 return ImmutableSet(F.getEmptyTree());
1118 }
1119
1120 /// Creates a new immutable set that contains all of the values
1121 /// of the original set with the addition of the specified value. If
1122 /// the original set already included the value, then the original set is
1123 /// returned and no memory is allocated. The time and space complexity
1124 /// of this operation is logarithmic in the size of the original set.
1125 /// The memory allocated to represent the set is released when the
1126 /// factory object that created the set is destroyed.
1128 TreeTy *NewT = F.add(Old.Root.get(), V);
1129 if constexpr (Canonicalize)
1130 return ImmutableSet(F.getCanonicalTree(NewT));
1131 else
1132 return ImmutableSet(NewT);
1133 }
1134
1135 /// Returns the union of \p A and \p B, computed in a single traversal that
1136 /// shares subtrees of both operands wherever possible (see
1137 /// ImutAVLFactory::unionTrees). This is more efficient than repeatedly
1138 /// adding \p B's elements to \p A when \p B is large.
1140 if (A.Root.get() == B.Root.get() || B.isEmpty())
1141 return A;
1142 if (A.isEmpty())
1143 return B;
1144 // Drive the recursion with the taller tree so the shorter one is the one
1145 // being split.
1146 if (A.getHeight() < B.getHeight())
1147 std::swap(A, B);
1148 if constexpr (Canonicalize) {
1149 // The bulk path does not canonicalize the nodes it creates, so fall
1150 // back to per-element insertion for canonicalizing factories.
1151 for (value_type_ref V : B)
1152 A = add(A, V);
1153 return A;
1154 } else {
1155 return ImmutableSet(F.unionTrees(A.Root.get(), B.Root.get()));
1156 }
1157 }
1158
1159 /// Creates a new immutable set that contains all of the values
1160 /// of the original set with the exception of the specified value. If
1161 /// the original set did not contain the value, the original set is
1162 /// returned and no memory is allocated. The time and space complexity
1163 /// of this operation is logarithmic in the size of the original set.
1164 /// The memory allocated to represent the set is released when the
1165 /// factory object that created the set is destroyed.
1167 TreeTy *NewT = F.remove(Old.Root.get(), V);
1168 if constexpr (Canonicalize)
1169 return ImmutableSet(F.getCanonicalTree(NewT));
1170 else
1171 return ImmutableSet(NewT);
1172 }
1173
1174 BumpPtrAllocator& getAllocator() { return F.getAllocator(); }
1175
1177 return const_cast<typename TreeTy::Factory *>(&F);
1178 }
1179 };
1180
1181 friend class Factory;
1182
1183 /// Returns true if the set contains the specified value.
1185 return Root ? Root->contains(V) : false;
1186 }
1187
1188 /// Compares two sets for equality. For a canonicalizing factory, sets with
1189 /// equal contents share the same tree, so this is an O(1) pointer comparison
1190 /// (like ImmutableList); only sets created by the same factory may be
1191 /// compared. Otherwise it is a structural comparison.
1192 bool operator==(const ImmutableSet &RHS) const {
1193 if constexpr (Canonicalize)
1194 return Root == RHS.Root;
1195 else
1196 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get())
1197 : Root == RHS.Root;
1198 }
1199
1200 bool operator!=(const ImmutableSet &RHS) const {
1201 if constexpr (Canonicalize)
1202 return Root != RHS.Root;
1203 else
1204 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1205 : Root != RHS.Root;
1206 }
1207
1209 if (Root) { Root->retain(); }
1210 return Root.get();
1211 }
1212
1213 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1214
1215 /// Return true if the set contains no elements.
1216 bool isEmpty() const { return !Root; }
1217
1218 /// Return true if the set contains exactly one element.
1219 /// This method runs in constant time.
1220 bool isSingleton() const { return getHeight() == 1; }
1221
1222 //===--------------------------------------------------===//
1223 // Iterators.
1224 //===--------------------------------------------------===//
1225
1227
1228 iterator begin() const { return iterator(Root.get()); }
1229 iterator end() const { return iterator(); }
1230
1231 //===--------------------------------------------------===//
1232 // Utility methods.
1233 //===--------------------------------------------------===//
1234
1235 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1236
1237 static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S) {
1238 ID.AddPointer(S.Root.get());
1239 }
1240
1241 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1242
1243 //===--------------------------------------------------===//
1244 // For testing.
1245 //===--------------------------------------------------===//
1246
1247 void validateTree() const { if (Root) Root->validateTree(); }
1248};
1249
1250// NOTE: This may some day replace the current ImmutableSet.
1251template <typename ValT, typename ValInfo = ImutContainerInfo<ValT>,
1252 bool Canonicalize = true>
1254public:
1255 using value_type = typename ValInfo::value_type;
1256 using value_type_ref = typename ValInfo::value_type_ref;
1258 using FactoryTy = typename TreeTy::Factory;
1259
1260private:
1262 FactoryTy *Factory;
1263
1264public:
1265 /// Constructs a set from a pointer to a tree root. In general one
1266 /// should use a Factory object to create sets instead of directly
1267 /// invoking the constructor, but there are cases where make this
1268 /// constructor public is useful.
1269 ImmutableSetRef(TreeTy *R, FactoryTy *F) : Root(R), Factory(F) {}
1270
1272 return ImmutableSetRef(0, F);
1273 }
1274
1276 return ImmutableSetRef(Factory->add(Root.get(), V), Factory);
1277 }
1278
1280 return ImmutableSetRef(Factory->remove(Root.get(), V), Factory);
1281 }
1282
1283 /// Returns true if the set contains the specified value.
1285 return Root ? Root->contains(V) : false;
1286 }
1287
1290 if constexpr (Canonicalize)
1291 return SetTy(Factory->getCanonicalTree(Root.get()));
1292 else
1293 return SetTy(Root.get());
1294 }
1295
1296 TreeTy *getRootWithoutRetain() const { return Root.get(); }
1297
1298 bool operator==(const ImmutableSetRef &RHS) const {
1299 return Root && RHS.Root ? Root->isEqual(*RHS.Root.get()) : Root == RHS.Root;
1300 }
1301
1302 bool operator!=(const ImmutableSetRef &RHS) const {
1303 return Root && RHS.Root ? Root->isNotEqual(*RHS.Root.get())
1304 : Root != RHS.Root;
1305 }
1306
1307 /// Return true if the set contains no elements.
1308 bool isEmpty() const { return !Root; }
1309
1310 /// Return true if the set contains exactly one element.
1311 /// This method runs in constant time.
1312 bool isSingleton() const { return getHeight() == 1; }
1313
1314 //===--------------------------------------------------===//
1315 // Iterators.
1316 //===--------------------------------------------------===//
1317
1319
1320 iterator begin() const { return iterator(Root.get()); }
1321 iterator end() const { return iterator(); }
1322
1323 //===--------------------------------------------------===//
1324 // Utility methods.
1325 //===--------------------------------------------------===//
1326
1327 unsigned getHeight() const { return Root ? Root->getHeight() : 0; }
1328
1329 static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S) {
1330 ID.AddPointer(S.Root.get());
1331 }
1332
1333 void Profile(FoldingSetNodeID &ID) const { return Profile(ID, *this); }
1334
1335 //===--------------------------------------------------===//
1336 // For testing.
1337 //===--------------------------------------------------===//
1338
1339 void validateTree() const { if (Root) Root->validateTree(); }
1340};
1341
1342} // end namespace llvm
1343
1344#endif // LLVM_ADT_IMMUTABLESET_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Uniform Intrinsic Combine
This file defines the BumpPtrAllocator interface.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_PREFERRED_TYPE(T)
\macro LLVM_PREFERRED_TYPE Adjust type of bit-field in debug info.
Definition Compiler.h:758
#define LLVM_NO_UNIQUE_ADDRESS
Definition Compiler.h:493
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
Definition Compiler.h:366
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:240
This file defines the DenseMap class.
This file defines a hash set that can be used to remove duplication of nodes in a graph.
#define PROFILE_INTEGER_INFO(X)
This file defines the RefCountedBase, ThreadSafeRefCountedBase, and IntrusiveRefCntPtr classes.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
Value * RHS
Value * LHS
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
unsigned getHeight() const
bool operator==(const ImmutableSetRef &RHS) const
ImmutableSet< ValT, ValInfo, Canonicalize > asImmutableSet() const
ImutAVLTree< ValInfo, Canonicalize > TreeTy
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
bool operator!=(const ImmutableSetRef &RHS) const
typename ValInfo::value_type_ref value_type_ref
ImmutableSetRef(TreeTy *R, FactoryTy *F)
Constructs a set from a pointer to a tree root.
void Profile(FoldingSetNodeID &ID) const
bool isEmpty() const
Return true if the set contains no elements.
iterator end() const
TreeTy * getRootWithoutRetain() const
void validateTree() const
typename TreeTy::Factory FactoryTy
static ImmutableSetRef getEmptySet(FactoryTy *F)
ImmutableSetRef remove(value_type_ref V)
typename ValInfo::value_type value_type
iterator begin() const
ImutAVLValueIterator< ImmutableSetRef > iterator
static void Profile(FoldingSetNodeID &ID, const ImmutableSetRef &S)
bool isSingleton() const
Return true if the set contains exactly one element.
ImmutableSetRef add(value_type_ref V)
ImmutableSet unionSets(ImmutableSet A, ImmutableSet B)
Returns the union of A and B, computed in a single traversal that shares subtrees of both operands wh...
Factory(BumpPtrAllocator &Alloc)
void operator=(const Factory &RHS)=delete
ImmutableSet add(ImmutableSet Old, value_type_ref V)
Creates a new immutable set that contains all of the values of the original set with the addition of ...
BumpPtrAllocator & getAllocator()
Factory(const Factory &RHS)=delete
ImmutableSet remove(ImmutableSet Old, value_type_ref V)
Creates a new immutable set that contains all of the values of the original set with the exception of...
ImmutableSet getEmptySet()
Returns an immutable set that contains no elements.
TreeTy::Factory * getTreeFactory() const
TreeTy * getRootWithoutRetain() const
bool isEmpty() const
Return true if the set contains no elements.
bool isSingleton() const
Return true if the set contains exactly one element.
static void Profile(FoldingSetNodeID &ID, const ImmutableSet &S)
bool contains(value_type_ref V) const
Returns true if the set contains the specified value.
iterator end() const
ImutAVLTree< ValInfo, Canonicalize > TreeTy
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool operator!=(const ImmutableSet &RHS) const
iterator begin() const
typename ValInfo::value_type_ref value_type_ref
unsigned getHeight() const
ImutAVLValueIterator< ImmutableSet > iterator
bool operator==(const ImmutableSet &RHS) const
Compares two sets for equality.
void validateTree() const
void Profile(FoldingSetNodeID &ID) const
typename ValInfo::value_type value_type
TreeTy * add_internal(value_type_ref V, TreeTy *T)
add_internal - Creates a new tree that includes the specified data and the data from the original tre...
ImutAVLFactory(BumpPtrAllocator &Alloc)
unsigned incrementHeight(TreeTy *L, TreeTy *R) const
TreeTy * remove(TreeTy *T, key_type_ref V)
TreeTy * getLeft(TreeTy *T) const
TreeTy * transformTree(TreeTy *T, CombineFn &Combine, bool FromB)
Rebuilds T with the same shape but each element replaced by Combine applied to it.
TreeTy * mergeTrees(TreeTy *A, TreeTy *B, CombineFn Combine, bool KeepUnmatched, bool SkipShared=false)
Merges A and B in a single traversal, sharing every subtree that the two operands do not overlap.
TreeTy * getEmptyTree() const
TreeTy * createNode(TreeTy *newLeft, TreeTy *oldTree, TreeTy *newRight)
unsigned getHeight(TreeTy *T) const
value_type_ref getValue(TreeTy *T) const
TreeTy * joinTrees(TreeTy *L, value_type_ref V, TreeTy *R)
Combines L and R with the value V (every key in L less than V, every key in R greater) into one balan...
bool isEmpty(TreeTy *T) const
TreeTy * combineTrees(TreeTy *L, TreeTy *R)
TreeTy * balanceTree(TreeTy *L, value_type_ref V, TreeTy *R)
Used by add_internal and remove_internal to balance a newly created tree.
void recoverNodes(TreeTy *Result)
TreeTy * add(TreeTy *T, value_type_ref V)
TreeTy * remove_internal(key_type_ref K, TreeTy *T)
remove_internal - Creates a new tree that includes all the data from the original tree except the spe...
TreeTy * getCanonicalTree(TreeTy *TNew)
TreeTy * removeMinBinding(TreeTy *T, TreeTy *&Noderemoved)
TreeTy * unionTrees(TreeTy *A, TreeTy *B)
Returns the set union of A and B (keeping A's element on matching keys).
void splitLookup(TreeTy *T, key_type_ref K, TreeTy *&L, const value_type *&Match, TreeTy *&R)
Splits T into L (all keys less than K) and R (all keys greater than K).
TreeTy * getRight(TreeTy *T) const
TreeTy * merge_internal(TreeTy *A, TreeTy *B, CombineFn &Combine, bool KeepUnmatched, bool SkipShared)
Merges A and B by recursing over A's structure and splitting B at each of A's keys.
TreeTy * createNode(TreeTy *L, value_type_ref V, TreeTy *R)
static unsigned maskCacheIndex(unsigned I)
Bidirectional in-order iterator over the nodes of an ImutAVLTree.
bool operator!=(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTree< ImutInfo, Canonicalize > value_type
ImutAVLTree< ImutInfo, Canonicalize > TreeTy
ImutAVLTreeInOrderIterator & operator++()
void skipSubTree()
Move to the in-order successor of the entire subtree rooted at the current node, i....
ImutAVLTreeInOrderIterator & operator--()
std::bidirectional_iterator_tag iterator_category
bool operator==(const ImutAVLTreeInOrderIterator &x) const
ImutAVLTreeInOrderIterator(const TreeTy *Root)
unsigned getHeight() const
Returns the height of the tree. A tree with no subtrees has a height of 1.
iterator end() const
Returns an iterator for the tree that denotes the end of an inorder traversal.
typename ValInfo::key_type_ref key_type_ref
ImutAVLTreeInOrderIterator< ValInfo, Canonicalize > iterator
ImutAVLTree * find(key_type_ref K)
Finds the subtree associated with the specified key value.
typename ValInfo::value_type value_type
bool isNotEqual(const ImutAVLTree &RHS) const
Compares two trees for structural inequality.
bool contains(key_type_ref K)
Returns true if this tree contains a subtree (node) that has an data element that matches the specifi...
unsigned size() const
Returns the number of nodes in the tree, which includes both leaves and.
ImutAVLTree * getRight() const
Return a pointer to the right subtree.
ImutAVLTree * getMaxElement()
Find the subtree associated with the highest ranged key value.
ImutAVLFactory< ValInfo, Canonicalize > Factory
bool isElementEqual(const ImutAVLTree *RHS) const
LLVM_ATTRIBUTE_NOINLINE void destroy()
bool isEqual(const ImutAVLTree &RHS) const
Compares two trees for structural equality and returns true if they are equal.
unsigned validateTree() const
A utility method that checks that the balancing and ordering invariants of the tree are satisfied.
const value_type & getValue() const
Returns the data value associated with the tree node.
bool isElementEqual(value_type_ref V) const
typename ValInfo::value_type_ref value_type_ref
iterator begin() const
Returns an iterator that iterates over the nodes of the tree in an inorder traversal.
ImutAVLTree * getLeft() const
Return a pointer to the left subtree.
A smart pointer to a reference-counted object that inherits from RefCountedBase or ThreadSafeRefCount...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This is an optimization pass for GlobalISel generic memory operations.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
static void Profile(const T &X, FoldingSetNodeID &ID)
Definition FoldingSet.h:235
The factory-side canonicalization cache: digest -> tree chain.
DenseMap< unsigned, Tree * > Cache
The cached structural digest, used only for canonicalization.
Generic iterator that wraps a T::TreeTy::iterator and exposes iterator::getValue() on dereference.
ImutAVLValueIterator::reference operator*() const
ImutAVLValueIterator(typename T::TreeTy *Tree)
static bool isDataEqual(data_type_ref, data_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T * >::value_type_ref value_type_ref
typename ImutProfileInfo< T * >::value_type value_type
static data_type_ref DataOfValue(value_type_ref)
static bool isLess(key_type_ref LHS, key_type_ref RHS)
Generic definition of comparison operations for elements of immutable containers that defaults to usi...
static bool isLess(key_type_ref LHS, key_type_ref RHS)
typename ImutProfileInfo< T >::value_type value_type
static bool isEqual(key_type_ref LHS, key_type_ref RHS)
static bool isDataEqual(data_type_ref, data_type_ref)
static data_type_ref DataOfValue(value_type_ref)
static key_type_ref KeyOfValue(value_type_ref D)
value_type_ref key_type_ref
typename ImutProfileInfo< T >::value_type_ref value_type_ref
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Generic profile template.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
Profile traits for integers.
static void Profile(FoldingSetNodeID &ID, value_type_ref X)
static void retain(ImutAVLTree< ImutInfo, Canonicalize > *Tree)
Class you can specialize to provide custom retain/release functionality for a type.