Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:43:04

0001 //===- llvm/ADT/FoldingSet.h - Uniquing Hash Set ----------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 ///
0009 /// \file
0010 /// This file defines a hash set that can be used to remove duplication of nodes
0011 /// in a graph.  This code was originally created by Chris Lattner for use with
0012 /// SelectionDAGCSEMap, but was isolated to provide use across the llvm code
0013 /// set.
0014 //===----------------------------------------------------------------------===//
0015 
0016 #ifndef LLVM_ADT_FOLDINGSET_H
0017 #define LLVM_ADT_FOLDINGSET_H
0018 
0019 #include "llvm/ADT/Hashing.h"
0020 #include "llvm/ADT/STLForwardCompat.h"
0021 #include "llvm/ADT/SmallVector.h"
0022 #include "llvm/ADT/iterator.h"
0023 #include "llvm/Support/Allocator.h"
0024 #include "llvm/Support/xxhash.h"
0025 #include <cassert>
0026 #include <cstddef>
0027 #include <cstdint>
0028 #include <type_traits>
0029 #include <utility>
0030 
0031 namespace llvm {
0032 
0033 /// This folding set used for two purposes:
0034 ///   1. Given information about a node we want to create, look up the unique
0035 ///      instance of the node in the set.  If the node already exists, return
0036 ///      it, otherwise return the bucket it should be inserted into.
0037 ///   2. Given a node that has already been created, remove it from the set.
0038 ///
0039 /// This class is implemented as a single-link chained hash table, where the
0040 /// "buckets" are actually the nodes themselves (the next pointer is in the
0041 /// node).  The last node points back to the bucket to simplify node removal.
0042 ///
0043 /// Any node that is to be included in the folding set must be a subclass of
0044 /// FoldingSetNode.  The node class must also define a Profile method used to
0045 /// establish the unique bits of data for the node.  The Profile method is
0046 /// passed a FoldingSetNodeID object which is used to gather the bits.  Just
0047 /// call one of the Add* functions defined in the FoldingSetBase::NodeID class.
0048 /// NOTE: That the folding set does not own the nodes and it is the
0049 /// responsibility of the user to dispose of the nodes.
0050 ///
0051 /// Eg.
0052 ///    class MyNode : public FoldingSetNode {
0053 ///    private:
0054 ///      std::string Name;
0055 ///      unsigned Value;
0056 ///    public:
0057 ///      MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
0058 ///       ...
0059 ///      void Profile(FoldingSetNodeID &ID) const {
0060 ///        ID.AddString(Name);
0061 ///        ID.AddInteger(Value);
0062 ///      }
0063 ///      ...
0064 ///    };
0065 ///
0066 /// To define the folding set itself use the FoldingSet template;
0067 ///
0068 /// Eg.
0069 ///    FoldingSet<MyNode> MyFoldingSet;
0070 ///
0071 /// Four public methods are available to manipulate the folding set;
0072 ///
0073 /// 1) If you have an existing node that you want add to the set but unsure
0074 /// that the node might already exist then call;
0075 ///
0076 ///    MyNode *M = MyFoldingSet.GetOrInsertNode(N);
0077 ///
0078 /// If The result is equal to the input then the node has been inserted.
0079 /// Otherwise, the result is the node existing in the folding set, and the
0080 /// input can be discarded (use the result instead.)
0081 ///
0082 /// 2) If you are ready to construct a node but want to check if it already
0083 /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
0084 /// check;
0085 ///
0086 ///   FoldingSetNodeID ID;
0087 ///   ID.AddString(Name);
0088 ///   ID.AddInteger(Value);
0089 ///   void *InsertPoint;
0090 ///
0091 ///    MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
0092 ///
0093 /// If found then M will be non-NULL, else InsertPoint will point to where it
0094 /// should be inserted using InsertNode.
0095 ///
0096 /// 3) If you get a NULL result from FindNodeOrInsertPos then you can insert a
0097 /// new node with InsertNode;
0098 ///
0099 ///    MyFoldingSet.InsertNode(M, InsertPoint);
0100 ///
0101 /// 4) Finally, if you want to remove a node from the folding set call;
0102 ///
0103 ///    bool WasRemoved = MyFoldingSet.RemoveNode(M);
0104 ///
0105 /// The result indicates whether the node existed in the folding set.
0106 
0107 class FoldingSetNodeID;
0108 class StringRef;
0109 
0110 //===----------------------------------------------------------------------===//
0111 /// FoldingSetBase - Implements the folding set functionality.  The main
0112 /// structure is an array of buckets.  Each bucket is indexed by the hash of
0113 /// the nodes it contains.  The bucket itself points to the nodes contained
0114 /// in the bucket via a singly linked list.  The last node in the list points
0115 /// back to the bucket to facilitate node removal.
0116 ///
0117 class FoldingSetBase {
0118 protected:
0119   /// Buckets - Array of bucket chains.
0120   void **Buckets;
0121 
0122   /// NumBuckets - Length of the Buckets array.  Always a power of 2.
0123   unsigned NumBuckets;
0124 
0125   /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
0126   /// is greater than twice the number of buckets.
0127   unsigned NumNodes;
0128 
0129   explicit FoldingSetBase(unsigned Log2InitSize = 6);
0130   FoldingSetBase(FoldingSetBase &&Arg);
0131   FoldingSetBase &operator=(FoldingSetBase &&RHS);
0132   ~FoldingSetBase();
0133 
0134 public:
0135   //===--------------------------------------------------------------------===//
0136   /// Node - This class is used to maintain the singly linked bucket list in
0137   /// a folding set.
0138   class Node {
0139   private:
0140     // NextInFoldingSetBucket - next link in the bucket list.
0141     void *NextInFoldingSetBucket = nullptr;
0142 
0143   public:
0144     Node() = default;
0145 
0146     // Accessors
0147     void *getNextInBucket() const { return NextInFoldingSetBucket; }
0148     void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
0149   };
0150 
0151   /// clear - Remove all nodes from the folding set.
0152   void clear();
0153 
0154   /// size - Returns the number of nodes in the folding set.
0155   unsigned size() const { return NumNodes; }
0156 
0157   /// empty - Returns true if there are no nodes in the folding set.
0158   bool empty() const { return NumNodes == 0; }
0159 
0160   /// capacity - Returns the number of nodes permitted in the folding set
0161   /// before a rebucket operation is performed.
0162   unsigned capacity() {
0163     // We allow a load factor of up to 2.0,
0164     // so that means our capacity is NumBuckets * 2
0165     return NumBuckets * 2;
0166   }
0167 
0168 protected:
0169   /// Functions provided by the derived class to compute folding properties.
0170   /// This is effectively a vtable for FoldingSetBase, except that we don't
0171   /// actually store a pointer to it in the object.
0172   struct FoldingSetInfo {
0173     /// GetNodeProfile - Instantiations of the FoldingSet template implement
0174     /// this function to gather data bits for the given node.
0175     void (*GetNodeProfile)(const FoldingSetBase *Self, Node *N,
0176                            FoldingSetNodeID &ID);
0177 
0178     /// NodeEquals - Instantiations of the FoldingSet template implement
0179     /// this function to compare the given node with the given ID.
0180     bool (*NodeEquals)(const FoldingSetBase *Self, Node *N,
0181                        const FoldingSetNodeID &ID, unsigned IDHash,
0182                        FoldingSetNodeID &TempID);
0183 
0184     /// ComputeNodeHash - Instantiations of the FoldingSet template implement
0185     /// this function to compute a hash value for the given node.
0186     unsigned (*ComputeNodeHash)(const FoldingSetBase *Self, Node *N,
0187                                 FoldingSetNodeID &TempID);
0188   };
0189 
0190 private:
0191   /// GrowHashTable - Double the size of the hash table and rehash everything.
0192   void GrowHashTable(const FoldingSetInfo &Info);
0193 
0194   /// GrowBucketCount - resize the hash table and rehash everything.
0195   /// NewBucketCount must be a power of two, and must be greater than the old
0196   /// bucket count.
0197   void GrowBucketCount(unsigned NewBucketCount, const FoldingSetInfo &Info);
0198 
0199 protected:
0200   // The below methods are protected to encourage subclasses to provide a more
0201   // type-safe API.
0202 
0203   /// reserve - Increase the number of buckets such that adding the
0204   /// EltCount-th node won't cause a rebucket operation. reserve is permitted
0205   /// to allocate more space than requested by EltCount.
0206   void reserve(unsigned EltCount, const FoldingSetInfo &Info);
0207 
0208   /// RemoveNode - Remove a node from the folding set, returning true if one
0209   /// was removed or false if the node was not in the folding set.
0210   bool RemoveNode(Node *N);
0211 
0212   /// GetOrInsertNode - If there is an existing simple Node exactly
0213   /// equal to the specified node, return it.  Otherwise, insert 'N' and return
0214   /// it instead.
0215   Node *GetOrInsertNode(Node *N, const FoldingSetInfo &Info);
0216 
0217   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
0218   /// return it.  If not, return the insertion token that will make insertion
0219   /// faster.
0220   Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos,
0221                             const FoldingSetInfo &Info);
0222 
0223   /// InsertNode - Insert the specified node into the folding set, knowing that
0224   /// it is not already in the folding set.  InsertPos must be obtained from
0225   /// FindNodeOrInsertPos.
0226   void InsertNode(Node *N, void *InsertPos, const FoldingSetInfo &Info);
0227 };
0228 
0229 //===----------------------------------------------------------------------===//
0230 
0231 /// DefaultFoldingSetTrait - This class provides default implementations
0232 /// for FoldingSetTrait implementations.
0233 template<typename T> struct DefaultFoldingSetTrait {
0234   static void Profile(const T &X, FoldingSetNodeID &ID) {
0235     X.Profile(ID);
0236   }
0237   static void Profile(T &X, FoldingSetNodeID &ID) {
0238     X.Profile(ID);
0239   }
0240 
0241   // Equals - Test if the profile for X would match ID, using TempID
0242   // to compute a temporary ID if necessary. The default implementation
0243   // just calls Profile and does a regular comparison. Implementations
0244   // can override this to provide more efficient implementations.
0245   static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
0246                             FoldingSetNodeID &TempID);
0247 
0248   // ComputeHash - Compute a hash value for X, using TempID to
0249   // compute a temporary ID if necessary. The default implementation
0250   // just calls Profile and does a regular hash computation.
0251   // Implementations can override this to provide more efficient
0252   // implementations.
0253   static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID);
0254 };
0255 
0256 /// FoldingSetTrait - This trait class is used to define behavior of how
0257 /// to "profile" (in the FoldingSet parlance) an object of a given type.
0258 /// The default behavior is to invoke a 'Profile' method on an object, but
0259 /// through template specialization the behavior can be tailored for specific
0260 /// types.  Combined with the FoldingSetNodeWrapper class, one can add objects
0261 /// to FoldingSets that were not originally designed to have that behavior.
0262 template <typename T, typename Enable = void>
0263 struct FoldingSetTrait : public DefaultFoldingSetTrait<T> {};
0264 
0265 /// DefaultContextualFoldingSetTrait - Like DefaultFoldingSetTrait, but
0266 /// for ContextualFoldingSets.
0267 template<typename T, typename Ctx>
0268 struct DefaultContextualFoldingSetTrait {
0269   static void Profile(T &X, FoldingSetNodeID &ID, Ctx Context) {
0270     X.Profile(ID, Context);
0271   }
0272 
0273   static inline bool Equals(T &X, const FoldingSetNodeID &ID, unsigned IDHash,
0274                             FoldingSetNodeID &TempID, Ctx Context);
0275   static inline unsigned ComputeHash(T &X, FoldingSetNodeID &TempID,
0276                                      Ctx Context);
0277 };
0278 
0279 /// ContextualFoldingSetTrait - Like FoldingSetTrait, but for
0280 /// ContextualFoldingSets.
0281 template<typename T, typename Ctx> struct ContextualFoldingSetTrait
0282   : public DefaultContextualFoldingSetTrait<T, Ctx> {};
0283 
0284 //===--------------------------------------------------------------------===//
0285 /// FoldingSetNodeIDRef - This class describes a reference to an interned
0286 /// FoldingSetNodeID, which can be a useful to store node id data rather
0287 /// than using plain FoldingSetNodeIDs, since the 32-element SmallVector
0288 /// is often much larger than necessary, and the possibility of heap
0289 /// allocation means it requires a non-trivial destructor call.
0290 class FoldingSetNodeIDRef {
0291   const unsigned *Data = nullptr;
0292   size_t Size = 0;
0293 
0294 public:
0295   FoldingSetNodeIDRef() = default;
0296   FoldingSetNodeIDRef(const unsigned *D, size_t S) : Data(D), Size(S) {}
0297 
0298   // Compute a strong hash value used to lookup the node in the FoldingSetBase.
0299   // The hash value is not guaranteed to be deterministic across processes.
0300   unsigned ComputeHash() const {
0301     return static_cast<unsigned>(hash_combine_range(Data, Data + Size));
0302   }
0303 
0304   // Compute a deterministic hash value across processes that is suitable for
0305   // on-disk serialization.
0306   unsigned computeStableHash() const {
0307     return static_cast<unsigned>(xxh3_64bits(ArrayRef(
0308         reinterpret_cast<const uint8_t *>(Data), sizeof(unsigned) * Size)));
0309   }
0310 
0311   bool operator==(FoldingSetNodeIDRef) const;
0312 
0313   bool operator!=(FoldingSetNodeIDRef RHS) const { return !(*this == RHS); }
0314 
0315   /// Used to compare the "ordering" of two nodes as defined by the
0316   /// profiled bits and their ordering defined by memcmp().
0317   bool operator<(FoldingSetNodeIDRef) const;
0318 
0319   const unsigned *getData() const { return Data; }
0320   size_t getSize() const { return Size; }
0321 };
0322 
0323 //===--------------------------------------------------------------------===//
0324 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
0325 /// a node.  When all the bits are gathered this class is used to produce a
0326 /// hash value for the node.
0327 class FoldingSetNodeID {
0328   /// Bits - Vector of all the data bits that make the node unique.
0329   /// Use a SmallVector to avoid a heap allocation in the common case.
0330   SmallVector<unsigned, 32> Bits;
0331 
0332 public:
0333   FoldingSetNodeID() = default;
0334 
0335   FoldingSetNodeID(FoldingSetNodeIDRef Ref)
0336     : Bits(Ref.getData(), Ref.getData() + Ref.getSize()) {}
0337 
0338   /// Add* - Add various data types to Bit data.
0339   void AddPointer(const void *Ptr) {
0340     // Note: this adds pointers to the hash using sizes and endianness that
0341     // depend on the host. It doesn't matter, however, because hashing on
0342     // pointer values is inherently unstable. Nothing should depend on the
0343     // ordering of nodes in the folding set.
0344     static_assert(sizeof(uintptr_t) <= sizeof(unsigned long long),
0345                   "unexpected pointer size");
0346     AddInteger(reinterpret_cast<uintptr_t>(Ptr));
0347   }
0348   void AddInteger(signed I) { Bits.push_back(I); }
0349   void AddInteger(unsigned I) { Bits.push_back(I); }
0350   void AddInteger(long I) { AddInteger((unsigned long)I); }
0351   void AddInteger(unsigned long I) {
0352     if (sizeof(long) == sizeof(int))
0353       AddInteger(unsigned(I));
0354     else if (sizeof(long) == sizeof(long long)) {
0355       AddInteger((unsigned long long)I);
0356     } else {
0357       llvm_unreachable("unexpected sizeof(long)");
0358     }
0359   }
0360   void AddInteger(long long I) { AddInteger((unsigned long long)I); }
0361   void AddInteger(unsigned long long I) {
0362     AddInteger(unsigned(I));
0363     AddInteger(unsigned(I >> 32));
0364   }
0365 
0366   void AddBoolean(bool B) { AddInteger(B ? 1U : 0U); }
0367   void AddString(StringRef String);
0368   void AddNodeID(const FoldingSetNodeID &ID);
0369 
0370   template <typename T>
0371   inline void Add(const T &x) { FoldingSetTrait<T>::Profile(x, *this); }
0372 
0373   /// clear - Clear the accumulated profile, allowing this FoldingSetNodeID
0374   /// object to be used to compute a new profile.
0375   inline void clear() { Bits.clear(); }
0376 
0377   // Compute a strong hash value for this FoldingSetNodeID, used to lookup the
0378   // node in the FoldingSetBase. The hash value is not guaranteed to be
0379   // deterministic across processes.
0380   unsigned ComputeHash() const {
0381     return FoldingSetNodeIDRef(Bits.data(), Bits.size()).ComputeHash();
0382   }
0383 
0384   // Compute a deterministic hash value across processes that is suitable for
0385   // on-disk serialization.
0386   unsigned computeStableHash() const {
0387     return FoldingSetNodeIDRef(Bits.data(), Bits.size()).computeStableHash();
0388   }
0389 
0390   /// operator== - Used to compare two nodes to each other.
0391   bool operator==(const FoldingSetNodeID &RHS) const;
0392   bool operator==(const FoldingSetNodeIDRef RHS) const;
0393 
0394   bool operator!=(const FoldingSetNodeID &RHS) const { return !(*this == RHS); }
0395   bool operator!=(const FoldingSetNodeIDRef RHS) const { return !(*this ==RHS);}
0396 
0397   /// Used to compare the "ordering" of two nodes as defined by the
0398   /// profiled bits and their ordering defined by memcmp().
0399   bool operator<(const FoldingSetNodeID &RHS) const;
0400   bool operator<(const FoldingSetNodeIDRef RHS) const;
0401 
0402   /// Intern - Copy this node's data to a memory region allocated from the
0403   /// given allocator and return a FoldingSetNodeIDRef describing the
0404   /// interned data.
0405   FoldingSetNodeIDRef Intern(BumpPtrAllocator &Allocator) const;
0406 };
0407 
0408 // Convenience type to hide the implementation of the folding set.
0409 using FoldingSetNode = FoldingSetBase::Node;
0410 template<class T> class FoldingSetIterator;
0411 template<class T> class FoldingSetBucketIterator;
0412 
0413 // Definitions of FoldingSetTrait and ContextualFoldingSetTrait functions, which
0414 // require the definition of FoldingSetNodeID.
0415 template<typename T>
0416 inline bool
0417 DefaultFoldingSetTrait<T>::Equals(T &X, const FoldingSetNodeID &ID,
0418                                   unsigned /*IDHash*/,
0419                                   FoldingSetNodeID &TempID) {
0420   FoldingSetTrait<T>::Profile(X, TempID);
0421   return TempID == ID;
0422 }
0423 template<typename T>
0424 inline unsigned
0425 DefaultFoldingSetTrait<T>::ComputeHash(T &X, FoldingSetNodeID &TempID) {
0426   FoldingSetTrait<T>::Profile(X, TempID);
0427   return TempID.ComputeHash();
0428 }
0429 template<typename T, typename Ctx>
0430 inline bool
0431 DefaultContextualFoldingSetTrait<T, Ctx>::Equals(T &X,
0432                                                  const FoldingSetNodeID &ID,
0433                                                  unsigned /*IDHash*/,
0434                                                  FoldingSetNodeID &TempID,
0435                                                  Ctx Context) {
0436   ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
0437   return TempID == ID;
0438 }
0439 template<typename T, typename Ctx>
0440 inline unsigned
0441 DefaultContextualFoldingSetTrait<T, Ctx>::ComputeHash(T &X,
0442                                                       FoldingSetNodeID &TempID,
0443                                                       Ctx Context) {
0444   ContextualFoldingSetTrait<T, Ctx>::Profile(X, TempID, Context);
0445   return TempID.ComputeHash();
0446 }
0447 
0448 //===----------------------------------------------------------------------===//
0449 /// FoldingSetImpl - An implementation detail that lets us share code between
0450 /// FoldingSet and ContextualFoldingSet.
0451 template <class Derived, class T> class FoldingSetImpl : public FoldingSetBase {
0452 protected:
0453   explicit FoldingSetImpl(unsigned Log2InitSize)
0454       : FoldingSetBase(Log2InitSize) {}
0455 
0456   FoldingSetImpl(FoldingSetImpl &&Arg) = default;
0457   FoldingSetImpl &operator=(FoldingSetImpl &&RHS) = default;
0458   ~FoldingSetImpl() = default;
0459 
0460 public:
0461   using iterator = FoldingSetIterator<T>;
0462 
0463   iterator begin() { return iterator(Buckets); }
0464   iterator end() { return iterator(Buckets+NumBuckets); }
0465 
0466   using const_iterator = FoldingSetIterator<const T>;
0467 
0468   const_iterator begin() const { return const_iterator(Buckets); }
0469   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
0470 
0471   using bucket_iterator = FoldingSetBucketIterator<T>;
0472 
0473   bucket_iterator bucket_begin(unsigned hash) {
0474     return bucket_iterator(Buckets + (hash & (NumBuckets-1)));
0475   }
0476 
0477   bucket_iterator bucket_end(unsigned hash) {
0478     return bucket_iterator(Buckets + (hash & (NumBuckets-1)), true);
0479   }
0480 
0481   /// reserve - Increase the number of buckets such that adding the
0482   /// EltCount-th node won't cause a rebucket operation. reserve is permitted
0483   /// to allocate more space than requested by EltCount.
0484   void reserve(unsigned EltCount) {
0485     return FoldingSetBase::reserve(EltCount, Derived::getFoldingSetInfo());
0486   }
0487 
0488   /// RemoveNode - Remove a node from the folding set, returning true if one
0489   /// was removed or false if the node was not in the folding set.
0490   bool RemoveNode(T *N) {
0491     return FoldingSetBase::RemoveNode(N);
0492   }
0493 
0494   /// GetOrInsertNode - If there is an existing simple Node exactly
0495   /// equal to the specified node, return it.  Otherwise, insert 'N' and
0496   /// return it instead.
0497   T *GetOrInsertNode(T *N) {
0498     return static_cast<T *>(
0499         FoldingSetBase::GetOrInsertNode(N, Derived::getFoldingSetInfo()));
0500   }
0501 
0502   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
0503   /// return it.  If not, return the insertion token that will make insertion
0504   /// faster.
0505   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
0506     return static_cast<T *>(FoldingSetBase::FindNodeOrInsertPos(
0507         ID, InsertPos, Derived::getFoldingSetInfo()));
0508   }
0509 
0510   /// InsertNode - Insert the specified node into the folding set, knowing that
0511   /// it is not already in the folding set.  InsertPos must be obtained from
0512   /// FindNodeOrInsertPos.
0513   void InsertNode(T *N, void *InsertPos) {
0514     FoldingSetBase::InsertNode(N, InsertPos, Derived::getFoldingSetInfo());
0515   }
0516 
0517   /// InsertNode - Insert the specified node into the folding set, knowing that
0518   /// it is not already in the folding set.
0519   void InsertNode(T *N) {
0520     T *Inserted = GetOrInsertNode(N);
0521     (void)Inserted;
0522     assert(Inserted == N && "Node already inserted!");
0523   }
0524 };
0525 
0526 //===----------------------------------------------------------------------===//
0527 /// FoldingSet - This template class is used to instantiate a specialized
0528 /// implementation of the folding set to the node class T.  T must be a
0529 /// subclass of FoldingSetNode and implement a Profile function.
0530 ///
0531 /// Note that this set type is movable and move-assignable. However, its
0532 /// moved-from state is not a valid state for anything other than
0533 /// move-assigning and destroying. This is primarily to enable movable APIs
0534 /// that incorporate these objects.
0535 template <class T>
0536 class FoldingSet : public FoldingSetImpl<FoldingSet<T>, T> {
0537   using Super = FoldingSetImpl<FoldingSet, T>;
0538   using Node = typename Super::Node;
0539 
0540   /// GetNodeProfile - Each instantiation of the FoldingSet needs to provide a
0541   /// way to convert nodes into a unique specifier.
0542   static void GetNodeProfile(const FoldingSetBase *, Node *N,
0543                              FoldingSetNodeID &ID) {
0544     T *TN = static_cast<T *>(N);
0545     FoldingSetTrait<T>::Profile(*TN, ID);
0546   }
0547 
0548   /// NodeEquals - Instantiations may optionally provide a way to compare a
0549   /// node with a specified ID.
0550   static bool NodeEquals(const FoldingSetBase *, Node *N,
0551                          const FoldingSetNodeID &ID, unsigned IDHash,
0552                          FoldingSetNodeID &TempID) {
0553     T *TN = static_cast<T *>(N);
0554     return FoldingSetTrait<T>::Equals(*TN, ID, IDHash, TempID);
0555   }
0556 
0557   /// ComputeNodeHash - Instantiations may optionally provide a way to compute a
0558   /// hash value directly from a node.
0559   static unsigned ComputeNodeHash(const FoldingSetBase *, Node *N,
0560                                   FoldingSetNodeID &TempID) {
0561     T *TN = static_cast<T *>(N);
0562     return FoldingSetTrait<T>::ComputeHash(*TN, TempID);
0563   }
0564 
0565   static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
0566     static constexpr FoldingSetBase::FoldingSetInfo Info = {
0567         GetNodeProfile, NodeEquals, ComputeNodeHash};
0568     return Info;
0569   }
0570   friend Super;
0571 
0572 public:
0573   explicit FoldingSet(unsigned Log2InitSize = 6) : Super(Log2InitSize) {}
0574   FoldingSet(FoldingSet &&Arg) = default;
0575   FoldingSet &operator=(FoldingSet &&RHS) = default;
0576 };
0577 
0578 //===----------------------------------------------------------------------===//
0579 /// ContextualFoldingSet - This template class is a further refinement
0580 /// of FoldingSet which provides a context argument when calling
0581 /// Profile on its nodes.  Currently, that argument is fixed at
0582 /// initialization time.
0583 ///
0584 /// T must be a subclass of FoldingSetNode and implement a Profile
0585 /// function with signature
0586 ///   void Profile(FoldingSetNodeID &, Ctx);
0587 template <class T, class Ctx>
0588 class ContextualFoldingSet
0589     : public FoldingSetImpl<ContextualFoldingSet<T, Ctx>, T> {
0590   // Unfortunately, this can't derive from FoldingSet<T> because the
0591   // construction of the vtable for FoldingSet<T> requires
0592   // FoldingSet<T>::GetNodeProfile to be instantiated, which in turn
0593   // requires a single-argument T::Profile().
0594 
0595   using Super = FoldingSetImpl<ContextualFoldingSet, T>;
0596   using Node = typename Super::Node;
0597 
0598   Ctx Context;
0599 
0600   static const Ctx &getContext(const FoldingSetBase *Base) {
0601     return static_cast<const ContextualFoldingSet*>(Base)->Context;
0602   }
0603 
0604   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
0605   /// way to convert nodes into a unique specifier.
0606   static void GetNodeProfile(const FoldingSetBase *Base, Node *N,
0607                              FoldingSetNodeID &ID) {
0608     T *TN = static_cast<T *>(N);
0609     ContextualFoldingSetTrait<T, Ctx>::Profile(*TN, ID, getContext(Base));
0610   }
0611 
0612   static bool NodeEquals(const FoldingSetBase *Base, Node *N,
0613                          const FoldingSetNodeID &ID, unsigned IDHash,
0614                          FoldingSetNodeID &TempID) {
0615     T *TN = static_cast<T *>(N);
0616     return ContextualFoldingSetTrait<T, Ctx>::Equals(*TN, ID, IDHash, TempID,
0617                                                      getContext(Base));
0618   }
0619 
0620   static unsigned ComputeNodeHash(const FoldingSetBase *Base, Node *N,
0621                                   FoldingSetNodeID &TempID) {
0622     T *TN = static_cast<T *>(N);
0623     return ContextualFoldingSetTrait<T, Ctx>::ComputeHash(*TN, TempID,
0624                                                           getContext(Base));
0625   }
0626 
0627   static const FoldingSetBase::FoldingSetInfo &getFoldingSetInfo() {
0628     static constexpr FoldingSetBase::FoldingSetInfo Info = {
0629         GetNodeProfile, NodeEquals, ComputeNodeHash};
0630     return Info;
0631   }
0632   friend Super;
0633 
0634 public:
0635   explicit ContextualFoldingSet(Ctx Context, unsigned Log2InitSize = 6)
0636       : Super(Log2InitSize), Context(Context) {}
0637 
0638   Ctx getContext() const { return Context; }
0639 };
0640 
0641 //===----------------------------------------------------------------------===//
0642 /// FoldingSetVector - This template class combines a FoldingSet and a vector
0643 /// to provide the interface of FoldingSet but with deterministic iteration
0644 /// order based on the insertion order. T must be a subclass of FoldingSetNode
0645 /// and implement a Profile function.
0646 template <class T, class VectorT = SmallVector<T*, 8>>
0647 class FoldingSetVector {
0648   FoldingSet<T> Set;
0649   VectorT Vector;
0650 
0651 public:
0652   explicit FoldingSetVector(unsigned Log2InitSize = 6) : Set(Log2InitSize) {}
0653 
0654   using iterator = pointee_iterator<typename VectorT::iterator>;
0655 
0656   iterator begin() { return Vector.begin(); }
0657   iterator end()   { return Vector.end(); }
0658 
0659   using const_iterator = pointee_iterator<typename VectorT::const_iterator>;
0660 
0661   const_iterator begin() const { return Vector.begin(); }
0662   const_iterator end()   const { return Vector.end(); }
0663 
0664   /// clear - Remove all nodes from the folding set.
0665   void clear() { Set.clear(); Vector.clear(); }
0666 
0667   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
0668   /// return it.  If not, return the insertion token that will make insertion
0669   /// faster.
0670   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
0671     return Set.FindNodeOrInsertPos(ID, InsertPos);
0672   }
0673 
0674   /// GetOrInsertNode - If there is an existing simple Node exactly
0675   /// equal to the specified node, return it.  Otherwise, insert 'N' and
0676   /// return it instead.
0677   T *GetOrInsertNode(T *N) {
0678     T *Result = Set.GetOrInsertNode(N);
0679     if (Result == N) Vector.push_back(N);
0680     return Result;
0681   }
0682 
0683   /// InsertNode - Insert the specified node into the folding set, knowing that
0684   /// it is not already in the folding set.  InsertPos must be obtained from
0685   /// FindNodeOrInsertPos.
0686   void InsertNode(T *N, void *InsertPos) {
0687     Set.InsertNode(N, InsertPos);
0688     Vector.push_back(N);
0689   }
0690 
0691   /// InsertNode - Insert the specified node into the folding set, knowing that
0692   /// it is not already in the folding set.
0693   void InsertNode(T *N) {
0694     Set.InsertNode(N);
0695     Vector.push_back(N);
0696   }
0697 
0698   /// size - Returns the number of nodes in the folding set.
0699   unsigned size() const { return Set.size(); }
0700 
0701   /// empty - Returns true if there are no nodes in the folding set.
0702   bool empty() const { return Set.empty(); }
0703 };
0704 
0705 //===----------------------------------------------------------------------===//
0706 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
0707 /// folding sets, which knows how to walk the folding set hash table.
0708 class FoldingSetIteratorImpl {
0709 protected:
0710   FoldingSetNode *NodePtr;
0711 
0712   FoldingSetIteratorImpl(void **Bucket);
0713 
0714   void advance();
0715 
0716 public:
0717   bool operator==(const FoldingSetIteratorImpl &RHS) const {
0718     return NodePtr == RHS.NodePtr;
0719   }
0720   bool operator!=(const FoldingSetIteratorImpl &RHS) const {
0721     return NodePtr != RHS.NodePtr;
0722   }
0723 };
0724 
0725 template <class T> class FoldingSetIterator : public FoldingSetIteratorImpl {
0726 public:
0727   explicit FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
0728 
0729   T &operator*() const {
0730     return *static_cast<T*>(NodePtr);
0731   }
0732 
0733   T *operator->() const {
0734     return static_cast<T*>(NodePtr);
0735   }
0736 
0737   inline FoldingSetIterator &operator++() {          // Preincrement
0738     advance();
0739     return *this;
0740   }
0741   FoldingSetIterator operator++(int) {        // Postincrement
0742     FoldingSetIterator tmp = *this; ++*this; return tmp;
0743   }
0744 };
0745 
0746 //===----------------------------------------------------------------------===//
0747 /// FoldingSetBucketIteratorImpl - This is the common bucket iterator support
0748 /// shared by all folding sets, which knows how to walk a particular bucket
0749 /// of a folding set hash table.
0750 class FoldingSetBucketIteratorImpl {
0751 protected:
0752   void *Ptr;
0753 
0754   explicit FoldingSetBucketIteratorImpl(void **Bucket);
0755 
0756   FoldingSetBucketIteratorImpl(void **Bucket, bool) : Ptr(Bucket) {}
0757 
0758   void advance() {
0759     void *Probe = static_cast<FoldingSetNode*>(Ptr)->getNextInBucket();
0760     uintptr_t x = reinterpret_cast<uintptr_t>(Probe) & ~0x1;
0761     Ptr = reinterpret_cast<void*>(x);
0762   }
0763 
0764 public:
0765   bool operator==(const FoldingSetBucketIteratorImpl &RHS) const {
0766     return Ptr == RHS.Ptr;
0767   }
0768   bool operator!=(const FoldingSetBucketIteratorImpl &RHS) const {
0769     return Ptr != RHS.Ptr;
0770   }
0771 };
0772 
0773 template <class T>
0774 class FoldingSetBucketIterator : public FoldingSetBucketIteratorImpl {
0775 public:
0776   explicit FoldingSetBucketIterator(void **Bucket) :
0777     FoldingSetBucketIteratorImpl(Bucket) {}
0778 
0779   FoldingSetBucketIterator(void **Bucket, bool) :
0780     FoldingSetBucketIteratorImpl(Bucket, true) {}
0781 
0782   T &operator*() const { return *static_cast<T*>(Ptr); }
0783   T *operator->() const { return static_cast<T*>(Ptr); }
0784 
0785   inline FoldingSetBucketIterator &operator++() { // Preincrement
0786     advance();
0787     return *this;
0788   }
0789   FoldingSetBucketIterator operator++(int) {      // Postincrement
0790     FoldingSetBucketIterator tmp = *this; ++*this; return tmp;
0791   }
0792 };
0793 
0794 //===----------------------------------------------------------------------===//
0795 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
0796 /// types in an enclosing object so that they can be inserted into FoldingSets.
0797 template <typename T>
0798 class FoldingSetNodeWrapper : public FoldingSetNode {
0799   T data;
0800 
0801 public:
0802   template <typename... Ts>
0803   explicit FoldingSetNodeWrapper(Ts &&... Args)
0804       : data(std::forward<Ts>(Args)...) {}
0805 
0806   void Profile(FoldingSetNodeID &ID) { FoldingSetTrait<T>::Profile(data, ID); }
0807 
0808   T &getValue() { return data; }
0809   const T &getValue() const { return data; }
0810 
0811   operator T&() { return data; }
0812   operator const T&() const { return data; }
0813 };
0814 
0815 //===----------------------------------------------------------------------===//
0816 /// FastFoldingSetNode - This is a subclass of FoldingSetNode which stores
0817 /// a FoldingSetNodeID value rather than requiring the node to recompute it
0818 /// each time it is needed. This trades space for speed (which can be
0819 /// significant if the ID is long), and it also permits nodes to drop
0820 /// information that would otherwise only be required for recomputing an ID.
0821 class FastFoldingSetNode : public FoldingSetNode {
0822   FoldingSetNodeID FastID;
0823 
0824 protected:
0825   explicit FastFoldingSetNode(const FoldingSetNodeID &ID) : FastID(ID) {}
0826 
0827 public:
0828   void Profile(FoldingSetNodeID &ID) const { ID.AddNodeID(FastID); }
0829 };
0830 
0831 //===----------------------------------------------------------------------===//
0832 // Partial specializations of FoldingSetTrait.
0833 
0834 template<typename T> struct FoldingSetTrait<T*> {
0835   static inline void Profile(T *X, FoldingSetNodeID &ID) {
0836     ID.AddPointer(X);
0837   }
0838 };
0839 template <typename T1, typename T2>
0840 struct FoldingSetTrait<std::pair<T1, T2>> {
0841   static inline void Profile(const std::pair<T1, T2> &P,
0842                              FoldingSetNodeID &ID) {
0843     ID.Add(P.first);
0844     ID.Add(P.second);
0845   }
0846 };
0847 
0848 template <typename T>
0849 struct FoldingSetTrait<T, std::enable_if_t<std::is_enum<T>::value>> {
0850   static void Profile(const T &X, FoldingSetNodeID &ID) {
0851     ID.AddInteger(llvm::to_underlying(X));
0852   }
0853 };
0854 
0855 } // end namespace llvm
0856 
0857 #endif // LLVM_ADT_FOLDINGSET_H