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