Made 'FoldingSetNodeID' a proper class instead of a nested class in
[oota-llvm.git] / include / llvm / ADT / FoldingSet.h
1 //===-- llvm/ADT/FoldingSet.h - Uniquing Hash Set ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a hash set that can be used to remove duplication of nodes
11 // in a graph.  This code was originally created by Chris Lattner for use with
12 // SelectionDAGCSEMap, but was isolated to provide use across the llvm code set. 
13 //
14 //===----------------------------------------------------------------------===//
15
16 #ifndef LLVM_ADT_FOLDINGSET_H
17 #define LLVM_ADT_FOLDINGSET_H
18
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include <string>
22
23 namespace llvm {
24   class APFloat;
25
26 /// This folding set used for two purposes:
27 ///   1. Given information about a node we want to create, look up the unique
28 ///      instance of the node in the set.  If the node already exists, return
29 ///      it, otherwise return the bucket it should be inserted into.
30 ///   2. Given a node that has already been created, remove it from the set.
31 /// 
32 /// This class is implemented as a single-link chained hash table, where the
33 /// "buckets" are actually the nodes themselves (the next pointer is in the
34 /// node).  The last node points back to the bucket to simplified node removal.
35 ///
36 /// Any node that is to be included in the folding set must be a subclass of
37 /// FoldingSetNode.  The node class must also define a Profile method used to
38 /// establish the unique bits of data for the node.  The Profile method is
39 /// passed a FoldingSetNodeID object which is used to gather the bits.  Just 
40 /// call one of the Add* functions defined in the FoldingSetImpl::NodeID class.
41 /// NOTE: That the folding set does not own the nodes and it is the
42 /// responsibility of the user to dispose of the nodes.
43 ///
44 /// Eg.
45 ///    class MyNode : public FoldingSetNode {
46 ///    private:
47 ///      std::string Name;
48 ///      unsigned Value;
49 ///    public:
50 ///      MyNode(const char *N, unsigned V) : Name(N), Value(V) {}
51 ///       ...
52 ///      void Profile(FoldingSetNodeID &ID) {
53 ///        ID.AddString(Name);
54 ///        ID.AddInteger(Value);
55 ///       }
56 ///       ...
57 ///     };
58 ///
59 /// To define the folding set itself use the FoldingSet template;
60 ///
61 /// Eg.
62 ///    FoldingSet<MyNode> MyFoldingSet;
63 ///
64 /// Four public methods are available to manipulate the folding set; 
65 ///
66 /// 1) If you have an existing node that you want add to the set but unsure
67 /// that the node might already exist then call;
68 ///
69 ///    MyNode *M = MyFoldingSet.GetOrInsertNode(N);
70 ///
71 /// If The result is equal to the input then the node has been inserted.
72 /// Otherwise, the result is the node existing in the folding set, and the
73 /// input can be discarded (use the result instead.)
74 ///
75 /// 2) If you are ready to construct a node but want to check if it already
76 /// exists, then call FindNodeOrInsertPos with a FoldingSetNodeID of the bits to
77 /// check;
78 ///
79 ///   FoldingSetNodeID ID;
80 ///   ID.AddString(Name);
81 ///   ID.AddInteger(Value);
82 ///   void *InsertPoint;
83 ///
84 ///    MyNode *M = MyFoldingSet.FindNodeOrInsertPos(ID, InsertPoint);
85 ///
86 /// If found then M with be non-NULL, else InsertPoint will point to where it
87 /// should be inserted using InsertNode.
88 ///
89 /// 3) If you get a NULL result from FindNodeOrInsertPos then you can as a new
90 /// node with FindNodeOrInsertPos;
91 ///
92 ///    InsertNode(N, InsertPoint);
93 ///
94 /// 4) Finally, if you want to remove a node from the folding set call;
95 ///
96 ///    bool WasRemoved = RemoveNode(N);
97 ///
98 /// The result indicates whether the node existed in the folding set.
99   
100 class FoldingSetNodeID;
101   
102 //===----------------------------------------------------------------------===//
103 /// FoldingSetImpl - Implements the folding set functionality.  The main
104 /// structure is an array of buckets.  Each bucket is indexed by the hash of
105 /// the nodes it contains.  The bucket itself points to the nodes contained
106 /// in the bucket via a singly linked list.  The last node in the list points
107 /// back to the bucket to facilitate node removal.
108 /// 
109 class FoldingSetImpl {
110 protected:
111   /// Buckets - Array of bucket chains.
112   ///
113   void **Buckets;
114   
115   /// NumBuckets - Length of the Buckets array.  Always a power of 2.
116   ///
117   unsigned NumBuckets;
118   
119   /// NumNodes - Number of nodes in the folding set. Growth occurs when NumNodes
120   /// is greater than twice the number of buckets.
121   unsigned NumNodes;
122   
123 public:
124   explicit FoldingSetImpl(unsigned Log2InitSize = 6);
125   virtual ~FoldingSetImpl();
126   
127   //===--------------------------------------------------------------------===//
128   /// Node - This class is used to maintain the singly linked bucket list in
129   /// a folding set.
130   ///
131   class Node {
132   private:
133     // NextInFoldingSetBucket - next link in the bucket list.
134     void *NextInFoldingSetBucket;
135     
136   public:
137
138     Node() : NextInFoldingSetBucket(0) {}
139     
140     // Accessors
141     void *getNextInBucket() const { return NextInFoldingSetBucket; }
142     void SetNextInBucket(void *N) { NextInFoldingSetBucket = N; }
143   };
144
145   /// RemoveNode - Remove a node from the folding set, returning true if one
146   /// was removed or false if the node was not in the folding set.
147   bool RemoveNode(Node *N);
148   
149   /// GetOrInsertNode - If there is an existing simple Node exactly
150   /// equal to the specified node, return it.  Otherwise, insert 'N' and return
151   /// it instead.
152   Node *GetOrInsertNode(Node *N);
153   
154   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
155   /// return it.  If not, return the insertion token that will make insertion
156   /// faster.
157   Node *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos);
158   
159   /// InsertNode - Insert the specified node into the folding set, knowing that
160   /// it is not already in the folding set.  InsertPos must be obtained from 
161   /// FindNodeOrInsertPos.
162   void InsertNode(Node *N, void *InsertPos);
163   
164   /// size - Returns the number of nodes in the folding set.
165   unsigned size() const { return NumNodes; }
166   
167 private:
168
169   /// GrowHashTable - Double the size of the hash table and rehash everything.
170   ///
171   void GrowHashTable();
172   
173 protected:
174
175   /// GetNodeProfile - Instantiations of the FoldingSet template implement
176   /// this function to gather data bits for the given node.
177   virtual void GetNodeProfile(FoldingSetNodeID &ID, Node *N) const = 0;
178 };
179
180 //===--------------------------------------------------------------------===//
181 /// FoldingSetNodeID - This class is used to gather all the unique data bits of
182 /// a node.  When all the bits are gathered this class is used to produce a
183 /// hash value for the node.  
184 ///
185 class FoldingSetNodeID {
186   /// Bits - Vector of all the data bits that make the node unique.
187   /// Use a SmallVector to avoid a heap allocation in the common case.
188   SmallVector<unsigned, 32> Bits;
189   
190 public:
191   FoldingSetNodeID() {}
192   
193   /// getRawData - Return the ith entry in the Bits data.
194   ///
195   unsigned getRawData(unsigned i) const {
196     return Bits[i];
197   }
198   
199   /// Add* - Add various data types to Bit data.
200   ///
201   void AddPointer(const void *Ptr);
202   void AddInteger(signed I);
203   void AddInteger(unsigned I);
204   void AddInteger(int64_t I);
205   void AddInteger(uint64_t I);
206   void AddFloat(float F);
207   void AddDouble(double D);
208   void AddAPFloat(const APFloat& apf);
209   void AddString(const std::string &String);
210   
211   /// ComputeHash - Compute a strong hash value for this FoldingSetNodeID, used
212   ///  to lookup the node in the FoldingSetImpl.
213   unsigned ComputeHash() const;
214   
215   /// operator== - Used to compare two nodes to each other.
216   ///
217   bool operator==(const FoldingSetNodeID &RHS) const;
218 };  
219
220 // Convenience type to hide the implementation of the folding set.
221 typedef FoldingSetImpl::Node FoldingSetNode;
222 template<class T> class FoldingSetIterator;
223
224 //===----------------------------------------------------------------------===//
225 /// FoldingSetTrait - This trait class is used to define behavior of how
226 ///  to "profile" (in the FoldingSet parlance) an object of a given type.
227 ///  The default behavior is to invoke a 'Profile' method on an object, but
228 ///  through template specialization the behavior can be tailored for specific
229 ///  types.  Combined with the FoldingSetNodeWrapper classs, one can add objects
230 ///  to FoldingSets that were not originally designed to have that behavior.
231 ///
232 template<typename T> struct FoldingSetTrait {
233   static inline void Profile(const T& X, FoldingSetNodeID& ID) { X.Profile(ID);}
234   static inline void Profile(T& X, FoldingSetNodeID& ID) { X.Profile(ID); }
235 };
236   
237 //===----------------------------------------------------------------------===//
238 /// FoldingSet - This template class is used to instantiate a specialized
239 /// implementation of the folding set to the node class T.  T must be a 
240 /// subclass of FoldingSetNode and implement a Profile function.
241 ///
242 template<class T> class FoldingSet : public FoldingSetImpl {
243 private:
244   /// GetNodeProfile - Each instantiatation of the FoldingSet needs to provide a
245   /// way to convert nodes into a unique specifier.
246   virtual void GetNodeProfile(FoldingSetNodeID &ID, Node *N) const {
247     T *TN = static_cast<T *>(N);
248     FoldingSetTrait<T>::Profile(*TN,ID);
249   }
250   
251 public:
252   explicit FoldingSet(unsigned Log2InitSize = 6)
253   : FoldingSetImpl(Log2InitSize)
254   {}
255   
256   typedef FoldingSetIterator<T> iterator;
257   iterator begin() { return iterator(Buckets); }
258   iterator end() { return iterator(Buckets+NumBuckets); }
259
260   typedef FoldingSetIterator<const T> const_iterator;
261   const_iterator begin() const { return const_iterator(Buckets); }
262   const_iterator end() const { return const_iterator(Buckets+NumBuckets); }
263
264   /// GetOrInsertNode - If there is an existing simple Node exactly
265   /// equal to the specified node, return it.  Otherwise, insert 'N' and
266   /// return it instead.
267   T *GetOrInsertNode(Node *N) {
268     return static_cast<T *>(FoldingSetImpl::GetOrInsertNode(N));
269   }
270   
271   /// FindNodeOrInsertPos - Look up the node specified by ID.  If it exists,
272   /// return it.  If not, return the insertion token that will make insertion
273   /// faster.
274   T *FindNodeOrInsertPos(const FoldingSetNodeID &ID, void *&InsertPos) {
275     return static_cast<T *>(FoldingSetImpl::FindNodeOrInsertPos(ID, InsertPos));
276   }
277 };
278
279 //===----------------------------------------------------------------------===//
280 /// FoldingSetIteratorImpl - This is the common iterator support shared by all
281 /// folding sets, which knows how to walk the folding set hash table.
282 class FoldingSetIteratorImpl {
283 protected:
284   FoldingSetNode *NodePtr;
285   FoldingSetIteratorImpl(void **Bucket);
286   void advance();
287   
288 public:
289   bool operator==(const FoldingSetIteratorImpl &RHS) const {
290     return NodePtr == RHS.NodePtr;
291   }
292   bool operator!=(const FoldingSetIteratorImpl &RHS) const {
293     return NodePtr != RHS.NodePtr;
294   }
295 };
296
297
298 template<class T>
299 class FoldingSetIterator : public FoldingSetIteratorImpl {
300 public:
301   FoldingSetIterator(void **Bucket) : FoldingSetIteratorImpl(Bucket) {}
302   
303   T &operator*() const {
304     return *static_cast<T*>(NodePtr);
305   }
306   
307   T *operator->() const {
308     return static_cast<T*>(NodePtr);
309   }
310   
311   inline FoldingSetIterator& operator++() {          // Preincrement
312     advance();
313     return *this;
314   }
315   FoldingSetIterator operator++(int) {        // Postincrement
316     FoldingSetIterator tmp = *this; ++*this; return tmp;
317   }
318 };
319   
320 //===----------------------------------------------------------------------===//
321 /// FoldingSetNodeWrapper - This template class is used to "wrap" arbitrary
322 /// types in an enclosing object so that they can be inserted into FoldingSets.
323 template <typename T>
324 class FoldingSetNodeWrapper : public FoldingSetNode {
325   T data;
326 public:
327   FoldingSetNodeWrapper(const T& x) : data(x) {}
328   virtual ~FoldingSetNodeWrapper();
329   
330   template<typename A1>
331   explicit FoldingSetNodeWrapper(const A1& a1)
332     : data(a1) {}
333   
334   template <typename A1, typename A2>
335   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2)
336     : data(a1,a2) {}
337   
338   template <typename A1, typename A2, typename A3>
339   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3)
340     : data(a1,a2,a3) {}
341   
342   template <typename A1, typename A2, typename A3, typename A4>
343   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
344                                  const A4& a4)
345     : data(a1,a2,a3,a4) {}
346   
347   template <typename A1, typename A2, typename A3, typename A4, typename A5>
348   explicit FoldingSetNodeWrapper(const A1& a1, const A2& a2, const A3& a3,
349                                  const A4& a4, const A5& a5)
350   : data(a1,a2,a3,a4,a5) {}
351
352   
353   void Profile(FoldingSetNodeID& ID) { FoldingSetTrait<T>::Profile(data, ID); }
354
355   operator T&() { return data; }
356   operator const T&() const { return data; }
357 };
358
359 } // End of namespace llvm.
360
361
362 #endif
363