FoldingSet.h 32 KB

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