1 //===-- llvm/ADT/FoldingSet.h - Uniquing Hash Set ---------------*- C++ -*-===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a hash set that can be used to remove duplication of nodes
11 // in a graph. This code was originally created by Chris Lattner for use with
12 // SelectionDAGCSEMap, but was isolated to provide use across the llvm code set.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_ADT_FOLDINGSET_H
17 #define LLVM_ADT_FOLDINGSET_H
18
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/Allocator.h"
22 #include "llvm/Support/DataTypes.h"
23
24 namespace llvm {
25 class APFloat;
26 class APInt;
27
28 /// This folding set used for two purposes:
29 /// 1. Given information about a node we want to create, look up the unique
30 /// instance of the node in the set. If the node already exists, return
31 /// it, otherwise return the bucket it should be inserted into.
32 /// 2. Given a node that has already been created, remove it from the set.
33 ///
34 /// This class is implemented as a single-link chained hash table, where the
35 /// "buckets" are actually the nodes themselves (the next pointer is in the
36 /// node). The last node points back to the bucket to simplify node removal.
37 ///
38 /// Any node that is to be included in the folding set must be a subclass of
39 /// FoldingSetNode. The node class must also define a Profile method used to
40 /// establish the unique bits of data for the node. The Profile method is
41 /// passed a FoldingSetNodeID object which is used to gather the bits. Just
42 /// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
43 /// NOTE: That the folding set does not own the nodes and it is the
44 /// responsibility of the user to dispose of the nodes.
45 ///
46 /// Eg.
47 /// class MyNode : public FoldingSetNode {
48 /// private:
49 /// std::string Name;
50 /// unsigned Value;
51 /// public:
52 /// MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
53 /// ...
54 /// void Profile(FoldingSetNodeID &ID) const {
55 /// ID.AddString(Name);
56 /// ID.AddInteger(Value);
57 /// }
58 /// ...
59 /// };
60 ///
61 /// To define the folding set itself use the FoldingSet template;
62 ///
63 /// Eg.
64 /// FoldingSet<MyNode> MyFoldingSet;
65 ///
66 /// Four public methods are available to manipulate the folding set;
67 ///
68 /// 1) If you have an existing node that you want add to the set but unsure
69 /// that the node might already exist then call;
70 ///
71 /// MyNode *M = MyFoldingSet.GetOrInsertNode(N);
72 ///
73 /// If The result is equal to the input then the node has been inserted.
74 /// Otherwise, the result is the node existing in the folding set, and the
75 /// input can be discarded (use the result instead.)
76 ///
77 /// 2) If you are ready to construct a node but want to check if it already
78 /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
79 /// check;
80 ///
81 /// FoldingSetNodeID ID;
82 /// ID.AddString(Name);
83 /// ID.AddInteger(Value);
84 /// void *InsertPoint;
85 ///
86 /// MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
87 ///
88 /// If found then M with be non-NULL, else InsertPoint will point to where it
89 /// should be inserted using InsertNode.
90 ///
91 /// 3) If you get a NULL result from FindNodeOrInsertPos then you can as a new
92 /// node with FindNodeOrInsertPos;
93 ///
94 /// InsertNode(N, InsertPoint);
95 ///
96 /// 4) Finally, if you want to remove a node from the folding set call;
97 ///
98 /// bool WasRemoved = RemoveNode(N);
99 ///
100 /// The result indicates whether the node existed in the folding set.
101
102 class FoldingSetNodeID;
103
104 //===----------------------------------------------------------------------===//
105 /// FoldingSetImpl - Implements the folding set functionality. The main
106 /// structure is an array of buckets. Each bucket is indexed by the hash of
107 /// the nodes it contains. The bucket itself points to the nodes contained
108 /// in the bucket via a singly linked list. The last node in the list points
109 /// back to the bucket to facilitate node removal.
110 ///
111 class FoldingSetImpl {
112 protected:
113 /// Buckets - Array of bucket chains.
114 ///
115 void **Buckets;
116
117 /// NumBuckets - Length of the Buckets array. Always a power of 2.
118 ///
119 unsigned NumBuckets;
120
121 /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
122 /// is greater than twice the number of buckets.
123 unsigned NumNodes;
124
125 public:
126 explicit FoldingSetImpl(unsigned Log2InitSize = 6);
127 virtual ~FoldingSetImpl();
128
129 //===--------------------------------------------------------------------===//
130 /// Node - This class is used to maintain the singly linked bucket list in
131 /// a folding set.
132 ///
133 class Node {
134 private:
135 // NextInFoldingSetBucket - next link in the bucket list.
136 void *NextInFoldingSetBucket;
137
138 public:
139
Node()140 Node() : NextInFoldingSetBucket(nullptr) {}
141
142 // Accessors
getNextInBucket()143 void *getNextInBucket() const { return NextInFoldingSetBucket; }
SetNextInBucket(void * N)144 void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
145 };
146
147 /// clear - Remove all nodes from the folding set.
148 void clear();
149
150 /// RemoveNode - Remove a node from the folding set, returning true if one
151 /// was removed or false if the node was not in the folding set.
152 bool RemoveNode(Node *N);
153
154 /// GetOrInsertNode - If there is an existing simple Node exactly
155 /// equal to the specified node, return it. Otherwise, insert 'N' and return
156 /// it instead.
157 Node *GetOrInsertNode(Node *N);
158
159 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
160 /// return it. If not, return the insertion token that will make insertion
161 /// faster.
162 Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
163
164 /// InsertNode - Insert the specified node into the folding set, knowing that
165 /// it is not already in the folding set. InsertPos must be obtained from
166 /// FindNodeOrInsertPos.
167 void InsertNode(Node *N, void *InsertPos);
168
169 /// InsertNode - Insert the specified node into the folding set, knowing that
170 /// it is not already in the folding set.
InsertNode(Node * N)171 void InsertNode(Node *N) {
172 Node *Inserted = GetOrInsertNode(N);
173 (void)Inserted;
174 assert(Inserted == N && "Node already inserted!");
175 }
176
177 /// size - Returns the number of nodes in the folding set.
size()178 unsigned size() const { return NumNodes; }
179
180 /// empty - Returns true if there are no nodes in the folding set.
empty()181 bool empty() const { return NumNodes == 0; }
182
183 private:
184
185 /// GrowHashTable - Double the size of the hash table and rehash everything.
186 ///
187 void GrowHashTable();
188
189 protected:
190
191 /// GetNodeProfile - Instantiations of the FoldingSet template implement
192 /// this function to gather data bits for the given node.
193 virtual void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const = 0;
194 /// NodeEquals - Instantiations of the FoldingSet template implement
195 /// this function to compare the given node with the given ID.
196 virtual bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
197 FoldingSetNodeID &TempID) const=0;
198 /// ComputeNodeHash - Instantiations of the FoldingSet template implement
199 /// this function to compute a hash value for the given node.
200 virtual unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const = 0;
201 };
202
203 //===----------------------------------------------------------------------===//
204
205 template<typename T> struct FoldingSetTrait;
206
207 /// DefaultFoldingSetTrait - This class provides default implementations
208 /// for FoldingSetTrait implementations.
209 ///
210 template<typename T> struct DefaultFoldingSetTrait {
ProfileDefaultFoldingSetTrait211 static void Profile(const T &X, FoldingSetNodeID &ID) {
212 X.Profile(ID);
213 }
ProfileDefaultFoldingSetTrait214 static void Profile(T &X, FoldingSetNodeID &ID) {
215 X.Profile(ID);
216 }
217
218 // Equals - Test if the profile for X would match ID, using TempID
219 // to compute a temporary ID if necessary. The default implementation
220 // just calls Profile and does a regular comparison. Implementations
221 // can override this to provide more efficient implementations.
222 static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
223 FoldingSetNodeID &TempID);
224
225 // ComputeHash - Compute a hash value for X, using TempID to
226 // compute a temporary ID if necessary. The default implementation
227 // just calls Profile and does a regular hash computation.
228 // Implementations can override this to provide more efficient
229 // implementations.
230 static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
231 };
232
233 /// FoldingSetTrait - This trait class is used to define behavior of how
234 /// to "profile" (in the FoldingSet parlance) an object of a given type.
235 /// The default behavior is to invoke a 'Profile' method on an object, but
236 /// through template specialization the behavior can be tailored for specific
237 /// types. Combined with the FoldingSetNodeWrapper class, one can add objects
238 /// to FoldingSets that were not originally designed to have that behavior.
239 template<typename T> struct FoldingSetTrait
240 : public DefaultFoldingSetTrait<T> {};
241
242 template<typename T, typename Ctx> struct ContextualFoldingSetTrait;
243
244 /// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
245 /// for ContextualFoldingSets.
246 template<typename T, typename Ctx>
247 struct DefaultContextualFoldingSetTrait {
ProfileDefaultContextualFoldingSetTrait248 static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
249 X.Profile(ID, Context);
250 }
251 static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
252 FoldingSetNodeID &TempID, Ctx Context);
253 static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
254 Ctx Context);
255 };
256
257 /// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
258 /// ContextualFoldingSets.
259 template<typename T, typename Ctx> struct ContextualFoldingSetTrait
260 : public DefaultContextualFoldingSetTrait<T, Ctx> {};
261
262 //===--------------------------------------------------------------------===//
263 /// FoldingSetNodeIDRef - This class describes a reference to an interned
264 /// FoldingSetNodeID, which can be a useful to store node id data rather
265 /// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
266 /// is often much larger than necessary, and the possibility of heap
267 /// allocation means it requires a non-trivial destructor call.
268 class FoldingSetNodeIDRef {
269 const unsigned *Data;
270 size_t Size;
271 public:
FoldingSetNodeIDRef()272 FoldingSetNodeIDRef() : Data(nullptr), Size(0) {}
FoldingSetNodeIDRef(const unsigned * D,size_t S)273 FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
274
275 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeIDRef,
276 /// used to lookup the node in the FoldingSetImpl.
277 unsigned ComputeHash() const;
278
279 bool operator==(FoldingSetNodeIDRef) const;
280
281 bool operator!=(FoldingSetNodeIDRef RHS) const { return !(*this == RHS); }
282
283 /// Used to compare the "ordering" of two nodes as defined by the
284 /// profiled bits and their ordering defined by memcmp().
285 bool operator<(FoldingSetNodeIDRef) const;
286
getData()287 const unsigned *getData() const { return Data; }
getSize()288 size_t getSize() const { return Size; }
289 };
290
291 //===--------------------------------------------------------------------===//
292 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
293 /// a node. When all the bits are gathered this class is used to produce a
294 /// hash value for the node.
295 ///
296 class FoldingSetNodeID {
297 /// Bits - Vector of all the data bits that make the node unique.
298 /// Use a SmallVector to avoid a heap allocation in the common case.
299 SmallVector<unsigned, 32> Bits;
300
301 public:
FoldingSetNodeID()302 FoldingSetNodeID() {}
303
FoldingSetNodeID(FoldingSetNodeIDRef Ref)304 FoldingSetNodeID(FoldingSetNodeIDRef Ref)
305 : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
306
307 /// Add* - Add various data types to Bit data.
308 ///
309 void AddPointer(const void *Ptr);
310 void AddInteger(signed I);
311 void AddInteger(unsigned I);
312 void AddInteger(long I);
313 void AddInteger(unsigned long I);
314 void AddInteger(long long I);
315 void AddInteger(unsigned long long I);
AddBoolean(bool B)316 void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
317 void AddString(StringRef String);
318 void AddNodeID(const FoldingSetNodeID &ID);
319
320 template <typename T>
Add(const T & x)321 inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
322
323 /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
324 /// object to be used to compute a new profile.
clear()325 inline void clear() { Bits.clear(); }
326
327 /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
328 /// to lookup the node in the FoldingSetImpl.
329 unsigned ComputeHash() const;
330
331 /// operator== - Used to compare two nodes to each other.
332 ///
333 bool operator==(const FoldingSetNodeID &RHS) const;
334 bool operator==(const FoldingSetNodeIDRef RHS) const;
335
336 bool operator!=(const FoldingSetNodeID &RHS) const { return !(*this == RHS); }
337 bool operator!=(const FoldingSetNodeIDRef RHS) const { return !(*this ==RHS);}
338
339 /// Used to compare the "ordering" of two nodes as defined by the
340 /// profiled bits and their ordering defined by memcmp().
341 bool operator<(const FoldingSetNodeID &RHS) const;
342 bool operator<(const FoldingSetNodeIDRef RHS) const;
343
344 /// Intern - Copy this node's data to a memory region allocated from the
345 /// given allocator and return a FoldingSetNodeIDRef describing the
346 /// interned data.
347 FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const;
348 };
349
350 // Convenience type to hide the implementation of the folding set.
351 typedef FoldingSetImpl::Node FoldingSetNode;
352 template<class T> class FoldingSetIterator;
353 template<class T> class FoldingSetBucketIterator;
354
355 // Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
356 // require the definition of FoldingSetNodeID.
357 template<typename T>
358 inline bool
Equals(T & X,const FoldingSetNodeID & ID,unsigned,FoldingSetNodeID & TempID)359 DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
360 unsigned /*IDHash*/,
361 FoldingSetNodeID &TempID) {
362 FoldingSetTrait<T>::Profile(X, TempID);
363 return TempID == ID;
364 }
365 template<typename T>
366 inline unsigned
ComputeHash(T & X,FoldingSetNodeID & TempID)367 DefaultFoldingSetTrait<T>::ComputeHash(T &X, FoldingSetNodeID &TempID) {
368 FoldingSetTrait<T>::Profile(X, TempID);
369 return TempID.ComputeHash();
370 }
371 template<typename T, typename Ctx>
372 inline bool
Equals(T & X,const FoldingSetNodeID & ID,unsigned,FoldingSetNodeID & TempID,Ctx Context)373 DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
374 const FoldingSetNodeID &ID,
375 unsigned /*IDHash*/,
376 FoldingSetNodeID &TempID,
377 Ctx Context) {
378 ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
379 return TempID == ID;
380 }
381 template<typename T, typename Ctx>
382 inline unsigned
ComputeHash(T & X,FoldingSetNodeID & TempID,Ctx Context)383 DefaultContextualFoldingSetTrait<T, Ctx>::ComputeHash(T &X,
384 FoldingSetNodeID &TempID,
385 Ctx Context) {
386 ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
387 return TempID.ComputeHash();
388 }
389
390 //===----------------------------------------------------------------------===//
391 /// FoldingSet - This template class is used to instantiate a specialized
392 /// implementation of the folding set to the node class T. T must be a
393 /// subclass of FoldingSetNode and implement a Profile function.
394 ///
395 template<class T> class FoldingSet : public FoldingSetImpl {
396 private:
397 /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
398 /// way to convert nodes into a unique specifier.
GetNodeProfile(Node * N,FoldingSetNodeID & ID)399 void GetNodeProfile(Node *N, FoldingSetNodeID &ID) const override {
400 T *TN = static_cast<T *>(N);
401 FoldingSetTrait<T>::Profile(*TN, ID);
402 }
403 /// NodeEquals - Instantiations may optionally provide a way to compare a
404 /// node with a specified ID.
NodeEquals(Node * N,const FoldingSetNodeID & ID,unsigned IDHash,FoldingSetNodeID & TempID)405 bool NodeEquals(Node *N, const FoldingSetNodeID &ID, unsigned IDHash,
406 FoldingSetNodeID &TempID) const override {
407 T *TN = static_cast<T *>(N);
408 return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
409 }
410 /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
411 /// hash value directly from a node.
ComputeNodeHash(Node * N,FoldingSetNodeID & TempID)412 unsigned ComputeNodeHash(Node *N, FoldingSetNodeID &TempID) const override {
413 T *TN = static_cast<T *>(N);
414 return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
415 }
416
417 public:
418 explicit FoldingSet(unsigned Log2InitSize = 6)
FoldingSetImpl(Log2InitSize)419 : FoldingSetImpl(Log2InitSize)
420 {}
421
422 typedef FoldingSetIterator<T> iterator;
begin()423 iterator begin() { return iterator(Buckets); }
end()424 iterator end() { return iterator(Buckets+NumBuckets); }
425
426 typedef FoldingSetIterator<const T> const_iterator;
begin()427 const_iterator begin() const { return const_iterator(Buckets); }
end()428 const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
429
430 typedef FoldingSetBucketIterator<T> bucket_iterator;
431
bucket_begin(unsigned hash)432 bucket_iterator bucket_begin(unsigned hash) {
433 return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
434 }
435
bucket_end(unsigned hash)436 bucket_iterator bucket_end(unsigned hash) {
437 return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
438 }
439
440 /// GetOrInsertNode - If there is an existing simple Node exactly
441 /// equal to the specified node, return it. Otherwise, insert 'N' and
442 /// return it instead.
GetOrInsertNode(Node * N)443 T *GetOrInsertNode(Node *N) {
444 return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
445 }
446
447 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
448 /// return it. If not, return the insertion token that will make insertion
449 /// faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)450 T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
451 return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
452 }
453 };
454
455 //===----------------------------------------------------------------------===//
456 /// ContextualFoldingSet - This template class is a further refinement
457 /// of FoldingSet which provides a context argument when calling
458 /// Profile on its nodes. Currently, that argument is fixed at
459 /// initialization time.
460 ///
461 /// T must be a subclass of FoldingSetNode and implement a Profile
462 /// function with signature
463 /// void Profile(llvm::FoldingSetNodeID &, Ctx);
464 template <class T, class Ctx>
465 class ContextualFoldingSet : public FoldingSetImpl {
466 // Unfortunately, this can't derive from FoldingSet<T> because the
467 // construction vtable for FoldingSet<T> requires
468 // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
469 // requires a single-argument T::Profile().
470
471 private:
472 Ctx Context;
473
474 /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
475 /// way to convert nodes into a unique specifier.
GetNodeProfile(FoldingSetImpl::Node * N,FoldingSetNodeID & ID)476 void GetNodeProfile(FoldingSetImpl::Node *N,
477 FoldingSetNodeID &ID) const override {
478 T *TN = static_cast<T *>(N);
479 ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, Context);
480 }
NodeEquals(FoldingSetImpl::Node * N,const FoldingSetNodeID & ID,unsigned IDHash,FoldingSetNodeID & TempID)481 bool NodeEquals(FoldingSetImpl::Node *N, const FoldingSetNodeID &ID,
482 unsigned IDHash, FoldingSetNodeID &TempID) const override {
483 T *TN = static_cast<T *>(N);
484 return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
485 Context);
486 }
ComputeNodeHash(FoldingSetImpl::Node * N,FoldingSetNodeID & TempID)487 unsigned ComputeNodeHash(FoldingSetImpl::Node *N,
488 FoldingSetNodeID &TempID) const override {
489 T *TN = static_cast<T *>(N);
490 return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID, Context);
491 }
492
493 public:
494 explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
FoldingSetImpl(Log2InitSize)495 : FoldingSetImpl(Log2InitSize), Context(Context)
496 {}
497
getContext()498 Ctx getContext() const { return Context; }
499
500
501 typedef FoldingSetIterator<T> iterator;
begin()502 iterator begin() { return iterator(Buckets); }
end()503 iterator end() { return iterator(Buckets+NumBuckets); }
504
505 typedef FoldingSetIterator<const T> const_iterator;
begin()506 const_iterator begin() const { return const_iterator(Buckets); }
end()507 const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
508
509 typedef FoldingSetBucketIterator<T> bucket_iterator;
510
bucket_begin(unsigned hash)511 bucket_iterator bucket_begin(unsigned hash) {
512 return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
513 }
514
bucket_end(unsigned hash)515 bucket_iterator bucket_end(unsigned hash) {
516 return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
517 }
518
519 /// GetOrInsertNode - If there is an existing simple Node exactly
520 /// equal to the specified node, return it. Otherwise, insert 'N'
521 /// and return it instead.
GetOrInsertNode(Node * N)522 T *GetOrInsertNode(Node *N) {
523 return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
524 }
525
526 /// FindNodeOrInsertPos - Look up the node specified by ID. If it
527 /// exists, return it. If not, return the insertion token that will
528 /// make insertion faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)529 T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
530 return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
531 }
532 };
533
534 //===----------------------------------------------------------------------===//
535 /// FoldingSetVectorIterator - This implements an iterator for
536 /// FoldingSetVector. It is only necessary because FoldingSetIterator provides
537 /// a value_type of T, while the vector in FoldingSetVector exposes
538 /// a value_type of T*. Fortunately, FoldingSetIterator doesn't expose very
539 /// much besides operator* and operator->, so we just wrap the inner vector
540 /// iterator and perform the extra dereference.
541 template <class T, class VectorIteratorT>
542 class FoldingSetVectorIterator {
543 // Provide a typedef to workaround the lack of correct injected class name
544 // support in older GCCs.
545 typedef FoldingSetVectorIterator<T, VectorIteratorT> SelfT;
546
547 VectorIteratorT Iterator;
548
549 public:
FoldingSetVectorIterator(VectorIteratorT I)550 FoldingSetVectorIterator(VectorIteratorT I) : Iterator(I) {}
551
552 bool operator==(const SelfT &RHS) const {
553 return Iterator == RHS.Iterator;
554 }
555 bool operator!=(const SelfT &RHS) const {
556 return Iterator != RHS.Iterator;
557 }
558
559 T &operator*() const { return **Iterator; }
560
561 T *operator->() const { return *Iterator; }
562
563 inline SelfT &operator++() {
564 ++Iterator;
565 return *this;
566 }
567 SelfT operator++(int) {
568 SelfT tmp = *this;
569 ++*this;
570 return tmp;
571 }
572 };
573
574 //===----------------------------------------------------------------------===//
575 /// FoldingSetVector - This template class combines a FoldingSet and a vector
576 /// to provide the interface of FoldingSet but with deterministic iteration
577 /// order based on the insertion order. T must be a subclass of FoldingSetNode
578 /// and implement a Profile function.
579 template <class T, class VectorT = SmallVector<T*, 8> >
580 class FoldingSetVector {
581 FoldingSet<T> Set;
582 VectorT Vector;
583
584 public:
585 explicit FoldingSetVector(unsigned Log2InitSize = 6)
Set(Log2InitSize)586 : Set(Log2InitSize) {
587 }
588
589 typedef FoldingSetVectorIterator<T, typename VectorT::iterator> iterator;
begin()590 iterator begin() { return Vector.begin(); }
end()591 iterator end() { return Vector.end(); }
592
593 typedef FoldingSetVectorIterator<const T, typename VectorT::const_iterator>
594 const_iterator;
begin()595 const_iterator begin() const { return Vector.begin(); }
end()596 const_iterator end() const { return Vector.end(); }
597
598 /// clear - Remove all nodes from the folding set.
clear()599 void clear() { Set.clear(); Vector.clear(); }
600
601 /// FindNodeOrInsertPos - Look up the node specified by ID. If it exists,
602 /// return it. If not, return the insertion token that will make insertion
603 /// faster.
FindNodeOrInsertPos(const FoldingSetNodeID & ID,void * & InsertPos)604 T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
605 return Set.FindNodeOrInsertPos(ID, InsertPos);
606 }
607
608 /// GetOrInsertNode - If there is an existing simple Node exactly
609 /// equal to the specified node, return it. Otherwise, insert 'N' and
610 /// return it instead.
GetOrInsertNode(T * N)611 T *GetOrInsertNode(T *N) {
612 T *Result = Set.GetOrInsertNode(N);
613 if (Result == N) Vector.push_back(N);
614 return Result;
615 }
616
617 /// InsertNode - Insert the specified node into the folding set, knowing that
618 /// it is not already in the folding set. InsertPos must be obtained from
619 /// FindNodeOrInsertPos.
InsertNode(T * N,void * InsertPos)620 void InsertNode(T *N, void *InsertPos) {
621 Set.InsertNode(N, InsertPos);
622 Vector.push_back(N);
623 }
624
625 /// InsertNode - Insert the specified node into the folding set, knowing that
626 /// it is not already in the folding set.
InsertNode(T * N)627 void InsertNode(T *N) {
628 Set.InsertNode(N);
629 Vector.push_back(N);
630 }
631
632 /// size - Returns the number of nodes in the folding set.
size()633 unsigned size() const { return Set.size(); }
634
635 /// empty - Returns true if there are no nodes in the folding set.
empty()636 bool empty() const { return Set.empty(); }
637 };
638
639 //===----------------------------------------------------------------------===//
640 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
641 /// folding sets, which knows how to walk the folding set hash table.
642 class FoldingSetIteratorImpl {
643 protected:
644 FoldingSetNode *NodePtr;
645 FoldingSetIteratorImpl(void **Bucket);
646 void advance();
647
648 public:
649 bool operator==(const FoldingSetIteratorImpl &RHS) const {
650 return NodePtr == RHS.NodePtr;
651 }
652 bool operator!=(const FoldingSetIteratorImpl &RHS) const {
653 return NodePtr != RHS.NodePtr;
654 }
655 };
656
657
658 template<class T>
659 class FoldingSetIterator : public FoldingSetIteratorImpl {
660 public:
FoldingSetIterator(void ** Bucket)661 explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
662
663 T &operator*() const {
664 return *static_cast<T*>(NodePtr);
665 }
666
667 T *operator->() const {
668 return static_cast<T*>(NodePtr);
669 }
670
671 inline FoldingSetIterator &operator++() { // Preincrement
672 advance();
673 return *this;
674 }
675 FoldingSetIterator operator++(int) { // Postincrement
676 FoldingSetIterator tmp = *this; ++*this; return tmp;
677 }
678 };
679
680 //===----------------------------------------------------------------------===//
681 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
682 /// shared by all folding sets, which knows how to walk a particular bucket
683 /// of a folding set hash table.
684
685 class FoldingSetBucketIteratorImpl {
686 protected:
687 void *Ptr;
688
689 explicit FoldingSetBucketIteratorImpl(void **Bucket);
690
FoldingSetBucketIteratorImpl(void ** Bucket,bool)691 FoldingSetBucketIteratorImpl(void **Bucket, bool)
692 : Ptr(Bucket) {}
693
advance()694 void advance() {
695 void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
696 uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
697 Ptr = reinterpret_cast<void*>(x);
698 }
699
700 public:
701 bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
702 return Ptr == RHS.Ptr;
703 }
704 bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
705 return Ptr != RHS.Ptr;
706 }
707 };
708
709
710 template<class T>
711 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
712 public:
FoldingSetBucketIterator(void ** Bucket)713 explicit FoldingSetBucketIterator(void **Bucket) :
714 FoldingSetBucketIteratorImpl(Bucket) {}
715
FoldingSetBucketIterator(void ** Bucket,bool)716 FoldingSetBucketIterator(void **Bucket, bool) :
717 FoldingSetBucketIteratorImpl(Bucket, true) {}
718
719 T &operator*() const { return *static_cast<T*>(Ptr); }
720 T *operator->() const { return static_cast<T*>(Ptr); }
721
722 inline FoldingSetBucketIterator &operator++() { // Preincrement
723 advance();
724 return *this;
725 }
726 FoldingSetBucketIterator operator++(int) { // Postincrement
727 FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
728 }
729 };
730
731 //===----------------------------------------------------------------------===//
732 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
733 /// types in an enclosing object so that they can be inserted into FoldingSets.
734 template <typename T>
735 class FoldingSetNodeWrapper : public FoldingSetNode {
736 T data;
737 public:
FoldingSetNodeWrapper(const T & x)738 explicit FoldingSetNodeWrapper(const T &x) : data(x) {}
~FoldingSetNodeWrapper()739 virtual ~FoldingSetNodeWrapper() {}
740
741 template<typename A1>
FoldingSetNodeWrapper(const A1 & a1)742 explicit FoldingSetNodeWrapper(const A1 &a1)
743 : data(a1) {}
744
745 template <typename A1, typename A2>
FoldingSetNodeWrapper(const A1 & a1,const A2 & a2)746 explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2)
747 : data(a1,a2) {}
748
749 template <typename A1, typename A2, typename A3>
FoldingSetNodeWrapper(const A1 & a1,const A2 & a2,const A3 & a3)750 explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3)
751 : data(a1,a2,a3) {}
752
753 template <typename A1, typename A2, typename A3, typename A4>
FoldingSetNodeWrapper(const A1 & a1,const A2 & a2,const A3 & a3,const A4 & a4)754 explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3,
755 const A4 &a4)
756 : data(a1,a2,a3,a4) {}
757
758 template <typename A1, typename A2, typename A3, typename A4, typename A5>
FoldingSetNodeWrapper(const A1 & a1,const A2 & a2,const A3 & a3,const A4 & a4,const A5 & a5)759 explicit FoldingSetNodeWrapper(const A1 &a1, const A2 &a2, const A3 &a3,
760 const A4 &a4, const A5 &a5)
761 : data(a1,a2,a3,a4,a5) {}
762
763
Profile(FoldingSetNodeID & ID)764 void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
765
getValue()766 T &getValue() { return data; }
getValue()767 const T &getValue() const { return data; }
768
769 operator T&() { return data; }
770 operator const T&() const { return data; }
771 };
772
773 //===----------------------------------------------------------------------===//
774 /// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
775 /// a FoldingSetNodeID value rather than requiring the node to recompute it
776 /// each time it is needed. This trades space for speed (which can be
777 /// significant if the ID is long), and it also permits nodes to drop
778 /// information that would otherwise only be required for recomputing an ID.
779 class FastFoldingSetNode : public FoldingSetNode {
780 FoldingSetNodeID FastID;
781 protected:
FastFoldingSetNode(const FoldingSetNodeID & ID)782 explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
783 public:
Profile(FoldingSetNodeID & ID)784 void Profile(FoldingSetNodeID &ID) const {
785 ID.AddNodeID(FastID);
786 }
787 };
788
789 //===----------------------------------------------------------------------===//
790 // Partial specializations of FoldingSetTrait.
791
792 template<typename T> struct FoldingSetTrait<T*> {
793 static inline void Profile(T *X, FoldingSetNodeID &ID) {
794 ID.AddPointer(X);
795 }
796 };
797 template <typename T1, typename T2>
798 struct FoldingSetTrait<std::pair<T1, T2>> {
799 static inline void Profile(const std::pair<T1, T2> &P,
800 llvm::FoldingSetNodeID &ID) {
801 ID.Add(P.first);
802 ID.Add(P.second);
803 }
804 };
805 } // End of namespace llvm.
806
807 #endif
808