LLVM 24.0.0git
EquivalenceClasses.h
Go to the documentation of this file.
1//===- llvm/ADT/EquivalenceClasses.h - Generic Equiv. Classes ---*- 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/// Generic implementation of equivalence classes through the use Tarjan's
11/// efficient union-find algorithm.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_EQUIVALENCECLASSES_H
16#define LLVM_ADT_EQUIVALENCECLASSES_H
17
18#include "llvm/ADT/DenseMap.h"
19#include "llvm/ADT/STLExtras.h"
24#include <cassert>
25#include <cstddef>
26#include <cstdint>
27#include <iterator>
28
29namespace llvm {
30
31/// This represents a collection of equivalence classes and supports three
32/// efficient operations: insert an element into a class of its own, union two
33/// classes, and find the class for a given element. In addition to these
34/// modification methods, it is possible to iterate over all of the equivalence
35/// classes and all of the elements in a class.
36///
37/// This implementation is an efficient implementation that only stores one copy
38/// of the element being indexed per entry in the set, and allows any arbitrary
39/// type to be indexed (as long as it can be implements DenseMapInfo).
40///
41/// Here is a simple example using integers:
42///
43/// \code
44/// EquivalenceClasses<int> EC;
45/// EC.unionSets(1, 2); // insert 1, 2 into the same set
46/// EC.insert(4); EC.insert(5); // insert 4, 5 into own sets
47/// EC.unionSets(5, 1); // merge the set for 1 with 5's set.
48///
49/// for (EquivalenceClasses<int>::iterator I = EC.begin(), E = EC.end();
50/// I != E; ++I) { // Iterate over all of the equivalence sets.
51/// if (!I->isLeader()) continue; // Ignore non-leader sets.
52/// for (EquivalenceClasses<int>::member_iterator MI = EC.member_begin(I);
53/// MI != EC.member_end(); ++MI) // Loop over members in this set.
54/// cerr << *MI << " "; // Print member.
55/// cerr << "\n"; // Finish set.
56/// }
57/// \endcode
58///
59/// This example prints:
60/// 4
61/// 5 1 2
62///
63template <class ElemTy> class LLVM_ATTRIBUTE_WARN_UNUSED EquivalenceClasses {
64public:
65 /// The EquivalenceClasses data structure is just a set of these.
66 /// Each of these represents a relation for a value. First it stores the
67 /// value itself. Next, it provides a "next pointer", which is used to
68 /// enumerate all of the elements in the unioned set. Finally, it defines
69 /// either a "end of list pointer" or "leader pointer" depending on whether
70 /// the value itself is a leader. A "leader pointer" points to the node that
71 /// is the leader for this element, if the node is not a leader. A "end of
72 /// list pointer" points to the last node in the list of members of this list.
73 /// Whether or not a node is a leader is determined by a bit stolen from one
74 /// of the pointers.
75 class ECValue {
76 friend class EquivalenceClasses;
77
78 mutable const ECValue *Leader, *Next;
79 ElemTy Data;
80
81 // ECValue ctor - Start out with EndOfList pointing to this node, Next is
82 // Null, isLeader = true.
83 ECValue(const ElemTy &Elt)
84 : Leader(this),
85 Next(reinterpret_cast<ECValue *>(static_cast<intptr_t>(1))),
86 Data(Elt) {}
87
88 const ECValue *getLeader() const {
89 if (isLeader())
90 return this;
91 if (Leader->isLeader())
92 return Leader;
93 // Path compression.
94 return Leader = Leader->getLeader();
95 }
96
97 const ECValue *getEndOfList() const {
98 assert(isLeader() && "Cannot get the end of a list for a non-leader!");
99 return Leader;
100 }
101
102 void setNext(const ECValue *NewNext) const {
103 assert(getNext() == nullptr && "Already has a next pointer!");
104 Next = reinterpret_cast<const ECValue *>(
105 reinterpret_cast<intptr_t>(NewNext) |
106 static_cast<intptr_t>(isLeader()));
107 }
108
109 public:
110 ECValue(const ECValue &RHS)
111 : Leader(this),
112 Next(reinterpret_cast<ECValue *>(static_cast<intptr_t>(1))),
113 Data(RHS.Data) {
114 // Only support copying of singleton nodes.
115 assert(RHS.isLeader() && RHS.getNext() == nullptr && "Not a singleton!");
116 }
117
118 bool isLeader() const { return (intptr_t)Next & 1; }
119 const ElemTy &getData() const { return Data; }
120
121 const ECValue *getNext() const {
122 return reinterpret_cast<ECValue *>(reinterpret_cast<intptr_t>(Next) &
123 ~static_cast<intptr_t>(1));
124 }
125 };
126
127private:
128 /// This implicitly provides a mapping from ElemTy values to the ECValues, it
129 /// just keeps the key as part of the value.
131
132 /// List of all members, used to provide a deterministic iteration order.
134
135 mutable BumpPtrAllocator ECValueAllocator;
136
137public:
140
142 TheMapping.clear();
143 Members.clear();
144 for (const auto &E : RHS)
145 if (E->isLeader()) {
146 member_iterator MI = RHS.member_begin(*E);
147 member_iterator LeaderIt = member_begin(insert(*MI));
148 for (++MI; MI != member_end(); ++MI)
149 unionSets(LeaderIt, member_begin(insert(*MI)));
150 }
151 return *this;
152 }
153
154 //===--------------------------------------------------------------------===//
155 // Inspection methods
156 //
157
158 /// iterator* - Provides a way to iterate over all values in the set.
160
161 iterator begin() const { return Members.begin(); }
162 iterator end() const { return Members.end(); }
163
164 bool empty() const { return TheMapping.empty(); }
165
166 /// member_* Iterate over the members of an equivalence class.
167 class member_iterator;
168 member_iterator member_begin(const ECValue &ECV) const {
169 // Only leaders provide anything to iterate over.
170 return member_iterator(ECV.isLeader() ? &ECV : nullptr);
171 }
172
173 member_iterator member_end() const { return member_iterator(nullptr); }
174
175 iterator_range<member_iterator> members(const ECValue &ECV) const {
176 return make_range(member_begin(ECV), member_end());
177 }
178
182
183 /// Returns true if \p V is contained an equivalence class.
184 [[nodiscard]] bool contains(const ElemTy &V) const {
185 return TheMapping.contains(V);
186 }
187
188 /// Return the leader for the specified value that is in the set. It is an
189 /// error to call this method for a value that is not yet in the set. For
190 /// that, call getOrInsertLeaderValue(V).
191 const ElemTy &getLeaderValue(const ElemTy &V) const {
192 member_iterator MI = findLeader(V);
193 assert(MI != member_end() && "Value is not in the set!");
194 return *MI;
195 }
196
197 /// Return the leader for the specified value that is in the set. If the
198 /// member is not in the set, it is inserted, then returned.
200 member_iterator MI = findLeader(insert(V));
201 assert(MI != member_end() && "Value is not in the set!");
202 return *MI;
203 }
204
205 /// Return the number of equivalence classes in this set. Note that this is a
206 /// linear time operation.
207 unsigned getNumClasses() const {
208 unsigned NC = 0;
209 for (const auto &E : *this)
210 if (E->isLeader())
211 ++NC;
212 return NC;
213 }
214
215 //===--------------------------------------------------------------------===//
216 // Mutation methods
217
218 /// Insert a new value into the union/find set, ignoring the request if the
219 /// value already exists.
220 const ECValue &insert(const ElemTy &Data) {
221 auto [I, Inserted] = TheMapping.try_emplace(Data);
222 if (!Inserted)
223 return *I->second;
224
225 auto *ECV = new (ECValueAllocator) ECValue(Data);
226 I->second = ECV;
227 Members.push_back(ECV);
228 return *ECV;
229 }
230
231 /// Erase a value from the union/find set, return true if erase succeeded, or
232 /// false when the value was not found.
233 bool erase(const ElemTy &V) {
234 if (!TheMapping.contains(V))
235 return false;
236 const ECValue *Cur = TheMapping[V];
237 const ECValue *Next = Cur->getNext();
238 // If the current element is the leader and has a successor element,
239 // update the successor element's 'Leader' field to be the last element,
240 // set the successor element's stolen bit, and set the 'Leader' field of
241 // all other elements in same class to be the successor element.
242 if (Cur->isLeader() && Next) {
243 Next->Leader = Cur->Leader;
244 Next->Next = reinterpret_cast<const ECValue *>(
245 reinterpret_cast<intptr_t>(Next->Next) | static_cast<intptr_t>(1));
246
247 const ECValue *NewLeader = Next;
248 while ((Next = Next->getNext())) {
249 Next->Leader = NewLeader;
250 }
251 } else if (!Cur->isLeader()) {
252 const ECValue *Leader = findLeader(V).Node;
253 const ECValue *Pre = Leader;
254 while (Pre->getNext() != Cur) {
255 Pre = Pre->getNext();
256 }
257 if (!Next) {
258 // If the current element is the last element(not leader), set the
259 // successor of the current element's predecessor to null while
260 // preserving the leader bit, and set the 'Leader' field of the class
261 // leader to the predecessor element.
262 Pre->Next = reinterpret_cast<const ECValue *>(
263 static_cast<intptr_t>(Pre->isLeader()));
264 Leader->Leader = Pre;
265 } else {
266 // If the current element is in the middle of class, then simply
267 // connect the predecessor element and the successor element.
268 Pre->Next = reinterpret_cast<const ECValue *>(
269 reinterpret_cast<intptr_t>(Next) |
270 static_cast<intptr_t>(Pre->isLeader()));
271 Next->Leader = Pre;
272 }
273 }
274
275 // Update 'TheMapping' and 'Members'.
276 assert(TheMapping.contains(V) && "Can't find input in TheMapping!");
277 TheMapping.erase(V);
278 auto I = find(Members, Cur);
279 assert(I != Members.end() && "Can't find input in members!");
280 Members.erase(I);
281 return true;
282 }
283
284 /// Given a value in the set, return a member iterator for the
285 /// equivalence class it is in. This does the path-compression part that
286 /// makes union-find "union findy". This returns an end iterator if the value
287 /// is not in the equivalence class.
288 member_iterator findLeader(const ElemTy &V) const {
289 auto I = TheMapping.find(V);
290 if (I == TheMapping.end())
291 return member_iterator(nullptr);
292 return findLeader(*I->second);
293 }
294 member_iterator findLeader(const ECValue &ECV) const {
295 return member_iterator(ECV.getLeader());
296 }
297
298 /// Erase the class containing \p V, i.e. erase all members of the class from
299 /// the set.
300 void eraseClass(const ElemTy &V) {
301 if (!TheMapping.contains(V))
302 return;
304 for (member_iterator MI = LeaderI.begin(), ME = LeaderI.end(); MI != ME;) {
305 const ElemTy &ToErase = *MI;
306 ++MI;
307 const ECValue *Cur = TheMapping[ToErase];
308 TheMapping.erase(ToErase);
309 auto I = find(Members, Cur);
310 assert(I != Members.end() && "Can't find input in members!");
311 Members.erase(I);
312 }
313 }
314
315 /// Merge the two equivalence sets for the specified values, inserting
316 /// them if they do not already exist in the equivalence set.
317 member_iterator unionSets(const ElemTy &V1, const ElemTy &V2) {
318 const ECValue &V1I = insert(V1), &V2I = insert(V2);
319 return unionSets(findLeader(V1I), findLeader(V2I));
320 }
321 member_iterator unionSets(member_iterator L1, member_iterator L2) {
322 assert(L1 != member_end() && L2 != member_end() && "Illegal inputs!");
323 if (L1 == L2)
324 return L1; // Unifying the same two sets, noop.
325
326 // Otherwise, this is a real union operation. Set the end of the L1 list to
327 // point to the L2 leader node.
328 const ECValue &L1LV = *L1.Node, &L2LV = *L2.Node;
329 L1LV.getEndOfList()->setNext(&L2LV);
330
331 // Update L1LV's end of list pointer.
332 L1LV.Leader = L2LV.getEndOfList();
333
334 // Clear L2's leader flag:
335 L2LV.Next = L2LV.getNext();
336
337 // L2's leader is now L1.
338 L2LV.Leader = &L1LV;
339 return L1;
340 }
341
342 // isEquivalent - Return true if V1 is equivalent to V2. This can happen if
343 // V1 is equal to V2 or if they belong to one equivalence class.
344 bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const {
345 // Fast path: any element is equivalent to itself.
346 if (V1 == V2)
347 return true;
348 auto It = findLeader(V1);
349 return It != member_end() && It == findLeader(V2);
350 }
351
353 friend class EquivalenceClasses;
354
355 const ECValue *Node;
356
357 public:
358 using iterator_category = std::forward_iterator_tag;
359 using value_type = const ElemTy;
360 using size_type = std::size_t;
361 using difference_type = std::ptrdiff_t;
364
365 explicit member_iterator() = default;
366 explicit member_iterator(const ECValue *N) : Node(N) {}
367
369 assert(Node != nullptr && "Dereferencing end()!");
370 return Node->getData();
371 }
372 pointer operator->() const { return &operator*(); }
373
375 assert(Node != nullptr && "++'d off the end of the list!");
376 Node = Node->getNext();
377 return *this;
378 }
379
380 member_iterator operator++(int) { // postincrement operators.
381 member_iterator tmp = *this;
382 ++*this;
383 return tmp;
384 }
385
386 bool operator==(const member_iterator &RHS) const {
387 return Node == RHS.Node;
388 }
389 bool operator!=(const member_iterator &RHS) const {
390 return Node != RHS.Node;
391 }
392 };
393};
394
395} // end namespace llvm
396
397#endif // LLVM_ADT_EQUIVALENCECLASSES_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_ATTRIBUTE_WARN_UNUSED
Definition Compiler.h:240
This file defines the DenseMap class.
IRTranslator LLVM IR MI
#define I(x, y, z)
Definition MD5.cpp:57
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
static const BasicSubtargetSubTypeKV * find(StringRef S, ArrayRef< BasicSubtargetSubTypeKV > A)
Find KV in array using binary search.
Value * RHS
The EquivalenceClasses data structure is just a set of these.
bool operator!=(const member_iterator &RHS) const
bool operator==(const member_iterator &RHS) const
member_iterator member_begin(const ECValue &ECV) const
iterator_range< member_iterator > members(const ECValue &ECV) const
bool contains(const ElemTy &V) const
Returns true if V is contained an equivalence class.
member_iterator findLeader(const ECValue &ECV) const
const ElemTy & getOrInsertLeaderValue(const ElemTy &V)
Return the leader for the specified value that is in the set.
const ECValue & insert(const BasicBlock *&Data)
bool isEquivalent(const ElemTy &V1, const ElemTy &V2) const
const ElemTy & getLeaderValue(const ElemTy &V) const
Return the leader for the specified value that is in the set.
iterator_range< member_iterator > members(const ElemTy &V) const
EquivalenceClasses & operator=(const EquivalenceClasses &RHS)
typename SmallVector< const ECValue * >::const_iterator iterator
iterator* - Provides a way to iterate over all values in the set.
member_iterator findLeader(const BasicBlock *&V) const
unsigned getNumClasses() const
Return the number of equivalence classes in this set.
member_iterator unionSets(member_iterator L1, member_iterator L2)
void eraseClass(const ElemTy &V)
Erase the class containing V, i.e.
member_iterator unionSets(const BasicBlock *&V1, const BasicBlock *&V2)
bool erase(const ElemTy &V)
Erase a value from the union/find set, return true if erase succeeded, or false when the value was no...
EquivalenceClasses(const EquivalenceClasses &RHS)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
A range adaptor for a pair of iterators.
IteratorT end() const
IteratorT begin() const
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Next
Definition InstrProf.h:147
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
Definition Allocator.h:391
#define N
#define NC
Definition regutils.h:42