FoldingSet.h 30 KB

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