14#ifndef LLVM_ADT_IMMUTABLESET_H
15#define LLVM_ADT_IMMUTABLESET_H
41template <
typename ImutInfo,
bool Canonicalize = true>
class ImutAVLFactory;
42template <
typename ImutInfo,
bool Canonicalize = true>
74template <
typename ImutInfo,
bool Canonicalize = true>
97 ImutAVLTree *
getLeft()
const {
return left; }
112 ImutAVLTree *
T =
this;
114 key_type_ref CurrentKey = ImutInfo::KeyOfValue(
T->getValue());
115 if (ImutInfo::isEqual(
K,CurrentKey))
117 else if (ImutInfo::isLess(
K,CurrentKey))
127 ImutAVLTree *
T =
this;
128 ImutAVLTree *
Right =
T->getRight();
137 if (
const ImutAVLTree* L =
getLeft())
139 if (
const ImutAVLTree* R =
getRight())
155 if (!ImutInfo::isEqual(ImutInfo::KeyOfValue(
getValue()),
156 ImutInfo::KeyOfValue(
V)))
160 if (!ImutInfo::isDataEqual(ImutInfo::DataOfValue(
getValue()),
161 ImutInfo::DataOfValue(
V)))
181 while (LItr != LEnd && RItr != REnd) {
182 if (&*LItr == &*RItr) {
195 return LItr == LEnd && RItr == REnd;
219 &&
"Height calculation wrong");
221 assert((HL > HR ? HL-HR : HR-HL) <= 2
222 &&
"Balancing invariant violated");
226 ImutInfo::KeyOfValue(
getValue()))) &&
227 "Value in left child is not less that current value");
230 ImutInfo::isLess(ImutInfo::KeyOfValue(
getValue()),
232 "Current value is not less that value of right child");
248 unsigned height : 28;
250 unsigned IsMutable : 1;
252 unsigned IsDigestCached : 1;
254 unsigned IsCanonicalized : 1;
269 : left(l), right(r), height(height), IsMutable(
true),
270 IsDigestCached(
false), IsCanonicalized(
false), value(v), factory(f) {
281 bool isMutable()
const {
return IsMutable; }
285 bool hasCachedDigest()
const {
return IsDigestCached; }
300 void markImmutable() {
301 assert(isMutable() &&
"Mutable flag already removed.");
306 void markedCachedDigest() {
307 assert(!hasCachedDigest() &&
"NoCachedDigest flag already removed.");
308 IsDigestCached =
true;
312 void setHeight(
unsigned h) {
313 assert(isMutable() &&
"Only a mutable tree can have its height changed.");
317 static uint32_t computeDigest(ImutAVLTree *L, ImutAVLTree *R,
322 digest +=
L->computeDigest();
326 ImutInfo::Profile(ID,
V);
327 digest +=
ID.computeHash();
330 digest +=
R->computeDigest();
335 uint32_t computeDigest() {
338 if (hasCachedDigest())
339 return digest.Digest;
343 markedCachedDigest();
365 if constexpr (Canonicalize) {
366 if (IsCanonicalized) {
373 factory->Cache[factory->maskCacheIndex(computeDigest())] = this->
Next;
380 factory->freeNodes.push_back(
this);
384template <
typename ImutInfo,
bool Canonicalize>
398template <
typename ImutInfo,
bool Canonicalize>
410 std::vector<TreeTy*> createdNodes;
411 std::vector<TreeTy*> freeNodes;
413 bool ownsAllocator()
const {
414 return (Allocator & 0x1) == 0;
433 if (ownsAllocator())
delete &getAllocator();
436 TreeTy*
add(TreeTy*
T, value_type_ref
V) {
452 template <
typename CombineFn>
454 bool KeepUnmatched,
bool SkipShared =
false) {
465 auto KeepFirst = [](
const value_type *L,
466 const value_type *R) ->
const value_type & {
493 TreeTy*
getLeft(TreeTy*
T)
const {
return T->getLeft(); }
495 value_type_ref
getValue(TreeTy*
T)
const {
return T->value; }
503 return (hl > hr ? hl : hr) + 1;
519 if (!freeNodes.empty()) {
520 T = freeNodes.back();
521 freeNodes.pop_back();
525 T = (TreeTy*)
A.Allocate<TreeTy>();
528 createdNodes.push_back(
T);
532 TreeTy*
createNode(TreeTy* newLeft, TreeTy* oldTree, TreeTy* newRight) {
546 if (
N != Result &&
N->refCount == 0)
551 createdNodes.clear();
560 assert(!
isEmpty(L) &&
"Left tree cannot be empty to have a height >= 2");
568 assert(!
isEmpty(LR) &&
"LR cannot be empty because it has a height >= 1");
577 assert(!
isEmpty(R) &&
"Right tree cannot be empty to have a height >= 2");
585 assert(!
isEmpty(RL) &&
"RL cannot be empty because it has a height >= 1");
613 const value_type *&Match, TreeTy *&R) {
619 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
620 if (ImutInfo::isEqual(
K, KCurrent)) {
626 Match = &
T->getValue();
627 }
else if (ImutInfo::isLess(
K, KCurrent)) {
641 template <
typename CombineFn>
661 template <
typename CombineFn>
663 bool KeepUnmatched,
bool SkipShared) {
668 if (SkipShared &&
A ==
B)
677 const value_type *BMatch;
678 splitLookup(
B, ImutInfo::KeyOfValue(AElem), BL, BMatch, BR);
697 auto NewElem =
Combine(&AElem, BMatch);
699 ImutInfo::isDataEqual(ImutInfo::DataOfValue(NewElem),
700 ImutInfo::DataOfValue(AElem)))
713 key_type_ref
K = ImutInfo::KeyOfValue(
V);
714 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
716 if (ImutInfo::isEqual(
K, KCurrent)) {
718 if (ImutInfo::isDataEqual(ImutInfo::DataOfValue(
V),
727 if (ImutInfo::isLess(
K, KCurrent))
749 key_type_ref KCurrent = ImutInfo::KeyOfValue(
getValue(
T));
751 if (ImutInfo::isEqual(
K, KCurrent))
756 if (ImutInfo::isLess(
K, KCurrent))
790 static_assert(Canonicalize,
791 "getCanonicalTree requires a canonicalizing factory");
795 if (TNew->IsCanonicalized)
800 unsigned digest = TNew->computeDigest();
803 for (TreeTy *
T = entry;
T !=
nullptr;
T =
T->Next) {
811 if (TNew->refCount == 0)
820 TNew->IsCanonicalized =
true;
843template <
typename ImutInfo,
bool Canonicalize>
863 for (;
T;
T =
T->getLeft())
870 for (;
T;
T =
T->getRight())
880 void ascendFromRightChild() {
881 TreeTy *Child = Path.pop_back_val();
882 while (!Path.empty() && Path.back()->getRight() == Child)
883 Child = Path.pop_back_val();
887 void ascendFromLeftChild() {
888 TreeTy *Child = Path.pop_back_val();
889 while (!Path.empty() && Path.back()->getLeft() == Child)
890 Child = Path.pop_back_val();
896 descendToMin(
const_cast<TreeTy *
>(Root));
905 if (Path.empty() || x.Path.empty())
906 return Path.empty() == x.Path.empty();
907 return Path.back() == x.Path.back();
910 return !(*
this == x);
917 assert(!Path.empty() &&
"Incrementing the end iterator");
918 if (
TreeTy *R = Path.back()->getRight())
924 ascendFromRightChild();
929 assert(!Path.empty() &&
"Decrementing the end iterator");
930 if (
TreeTy *L = Path.back()->getLeft())
935 ascendFromLeftChild();
943 assert(!Path.empty() &&
"Skipping past the end iterator");
944 ascendFromRightChild();
953 ImutAVLValueIterator<T>, typename T::TreeTy::iterator,
954 typename std::iterator_traits<
955 typename T::TreeTy::iterator>::iterator_category,
956 const typename T::value_type> {
962 return this->
I->getValue();
994#define PROFILE_INTEGER_INFO(X)\
995template<> struct ImutProfileInfo<X> : ImutProfileInteger<X> {};
1008#undef PROFILE_INTEGER_INFO
1023template <
typename T>
1055 return std::equal_to<key_type>()(
LHS,
RHS);
1059 return std::less<key_type>()(
LHS,
RHS);
1089template <
typename ValT,
typename ValInfo = ImutContainerInfo<ValT>,
1090 bool Canonicalize = true>
1131 TreeTy *NewT = F.add(Old.Root.get(),
V);
1132 if constexpr (Canonicalize)
1143 if (
A.Root.get() ==
B.Root.get() ||
B.isEmpty())
1149 if (
A.getHeight() <
B.getHeight())
1151 if constexpr (Canonicalize) {
1170 TreeTy *NewT = F.remove(Old.Root.get(),
V);
1171 if constexpr (Canonicalize)
1188 return Root ? Root->contains(
V) :
false;
1196 if constexpr (Canonicalize)
1197 return Root ==
RHS.Root;
1199 return Root &&
RHS.Root ? Root->isEqual(*
RHS.Root.get())
1204 if constexpr (Canonicalize)
1205 return Root !=
RHS.Root;
1207 return Root &&
RHS.Root ? Root->isNotEqual(*
RHS.Root.get())
1212 if (Root) { Root->retain(); }
1238 unsigned getHeight()
const {
return Root ? Root->getHeight() : 0; }
1241 ID.AddPointer(S.Root.get());
1254template <
typename ValT,
typename ValInfo = ImutContainerInfo<ValT>,
1255 bool Canonicalize = true>
1288 return Root ? Root->contains(
V) :
false;
1293 if constexpr (Canonicalize)
1294 return SetTy(Factory->getCanonicalTree(Root.get()));
1296 return SetTy(Root.get());
1302 return Root &&
RHS.Root ? Root->isEqual(*
RHS.Root.get()) : Root ==
RHS.Root;
1306 return Root &&
RHS.Root ? Root->isNotEqual(*
RHS.Root.get())
1330 unsigned getHeight()
const {
return Root ? Root->getHeight() : 0; }
1333 ID.AddPointer(S.Root.get());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
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.
#define LLVM_NO_UNIQUE_ADDRESS
#define LLVM_ATTRIBUTE_NOINLINE
LLVM_ATTRIBUTE_NOINLINE - On compilers where we have a directive to do so, mark a method "not for inl...
#define LLVM_ATTRIBUTE_WARN_UNUSED
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.
This file defines the SmallVector class.
This class is used to gather all the unique data bits of a node.
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.
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
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.
ImutAVLTree< ValInfo, Canonicalize > TreeTy
ImmutableSet(TreeTy *R)
Constructs a set from a pointer to a tree root.
bool operator!=(const ImmutableSet &RHS) 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++()
TreeTy & operator*() const
void skipSubTree()
Move to the in-order successor of the entire subtree rooted at the current node, i....
ImutAVLTreeInOrderIterator & operator--()
ImutAVLTreeInOrderIterator()=default
std::ptrdiff_t difference_type
TreeTy * operator->() const
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.
iterator_adaptor_base()=default
This is an optimization pass for GlobalISel generic memory operations.
auto reverse(ContainerTy &&C)
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static void Profile(const T &X, FoldingSetNodeID &ID)
The factory-side canonicalization cache: digest -> tree chain.
DenseMap< unsigned, Tree * > Cache
The cached structural digest, used only for canonicalization.
The intrusive doubly-linked chain of same-digest trees in the factory's canonicalization cache.
Generic iterator that wraps a T::TreeTy::iterator and exposes iterator::getValue() on dereference.
ImutAVLValueIterator()=default
ImutAVLValueIterator::reference operator*() const
ImutAVLValueIterator(typename T::TreeTy *Tree)
static bool isDataEqual(data_type_ref, data_type_ref)
value_type_ref key_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)
value_type value_type_ref
const bool & value_type_ref
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.