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