Add params() to FunctionType. NFC.
[oota-llvm.git] / include / llvm / IR / ValueMap.h
1 //===- ValueMap.h - Safe map from Values to data ----------------*- 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 the ValueMap class.  ValueMap maps Value* or any subclass
11 // to an arbitrary other type.  It provides the DenseMap interface but updates
12 // itself to remain safe when keys are RAUWed or deleted.  By default, when a
13 // key is RAUWed from V1 to V2, the old mapping V1->target is removed, and a new
14 // mapping V2->target is added.  If V2 already existed, its old target is
15 // overwritten.  When a key is deleted, its mapping is removed.
16 //
17 // You can override a ValueMap's Config parameter to control exactly what
18 // happens on RAUW and destruction and to get called back on each event.  It's
19 // legal to call back into the ValueMap from a Config's callbacks.  Config
20 // parameters should inherit from ValueMapConfig<KeyT> to get default
21 // implementations of all the methods ValueMap uses.  See ValueMapConfig for
22 // documentation of the functions you can override.
23 //
24 //===----------------------------------------------------------------------===//
25
26 #ifndef LLVM_IR_VALUEMAP_H
27 #define LLVM_IR_VALUEMAP_H
28
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/IR/ValueHandle.h"
31 #include "llvm/Support/Mutex.h"
32 #include "llvm/Support/UniqueLock.h"
33 #include "llvm/Support/type_traits.h"
34 #include <iterator>
35
36 namespace llvm {
37
38 template<typename KeyT, typename ValueT, typename Config>
39 class ValueMapCallbackVH;
40
41 template<typename DenseMapT, typename KeyT>
42 class ValueMapIterator;
43 template<typename DenseMapT, typename KeyT>
44 class ValueMapConstIterator;
45
46 /// This class defines the default behavior for configurable aspects of
47 /// ValueMap<>.  User Configs should inherit from this class to be as compatible
48 /// as possible with future versions of ValueMap.
49 template<typename KeyT, typename MutexT = sys::Mutex>
50 struct ValueMapConfig {
51   typedef MutexT mutex_type;
52
53   /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
54   /// false, the ValueMap will leave the original mapping in place.
55   enum { FollowRAUW = true };
56
57   // All methods will be called with a first argument of type ExtraData.  The
58   // default implementations in this class take a templated first argument so
59   // that users' subclasses can use any type they want without having to
60   // override all the defaults.
61   struct ExtraData {};
62
63   template<typename ExtraDataT>
64   static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
65   template<typename ExtraDataT>
66   static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
67
68   /// Returns a mutex that should be acquired around any changes to the map.
69   /// This is only acquired from the CallbackVH (and held around calls to onRAUW
70   /// and onDelete) and not inside other ValueMap methods.  NULL means that no
71   /// mutex is necessary.
72   template<typename ExtraDataT>
73   static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; }
74 };
75
76 /// See the file comment.
77 template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT> >
78 class ValueMap {
79   friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
80   typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH;
81   typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH> > MapT;
82   typedef typename Config::ExtraData ExtraData;
83   MapT Map;
84   ExtraData Data;
85   ValueMap(const ValueMap&) LLVM_DELETED_FUNCTION;
86   ValueMap& operator=(const ValueMap&) LLVM_DELETED_FUNCTION;
87 public:
88   typedef KeyT key_type;
89   typedef ValueT mapped_type;
90   typedef std::pair<KeyT, ValueT> value_type;
91   typedef unsigned size_type;
92
93   explicit ValueMap(unsigned NumInitBuckets = 64)
94     : Map(NumInitBuckets), Data() {}
95   explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
96     : Map(NumInitBuckets), Data(Data) {}
97
98   ~ValueMap() {}
99
100   typedef ValueMapIterator<MapT, KeyT> iterator;
101   typedef ValueMapConstIterator<MapT, KeyT> const_iterator;
102   inline iterator begin() { return iterator(Map.begin()); }
103   inline iterator end() { return iterator(Map.end()); }
104   inline const_iterator begin() const { return const_iterator(Map.begin()); }
105   inline const_iterator end() const { return const_iterator(Map.end()); }
106
107   bool empty() const { return Map.empty(); }
108   size_type size() const { return Map.size(); }
109
110   /// Grow the map so that it has at least Size buckets. Does not shrink
111   void resize(size_t Size) { Map.resize(Size); }
112
113   void clear() { Map.clear(); }
114
115   /// Return 1 if the specified key is in the map, 0 otherwise.
116   size_type count(const KeyT &Val) const {
117     return Map.find_as(Val) == Map.end() ? 0 : 1;
118   }
119
120   iterator find(const KeyT &Val) {
121     return iterator(Map.find_as(Val));
122   }
123   const_iterator find(const KeyT &Val) const {
124     return const_iterator(Map.find_as(Val));
125   }
126
127   /// lookup - Return the entry for the specified key, or a default
128   /// constructed value if no such entry exists.
129   ValueT lookup(const KeyT &Val) const {
130     typename MapT::const_iterator I = Map.find_as(Val);
131     return I != Map.end() ? I->second : ValueT();
132   }
133
134   // Inserts key,value pair into the map if the key isn't already in the map.
135   // If the key is already in the map, it returns false and doesn't update the
136   // value.
137   std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
138     std::pair<typename MapT::iterator, bool> map_result=
139       Map.insert(std::make_pair(Wrap(KV.first), KV.second));
140     return std::make_pair(iterator(map_result.first), map_result.second);
141   }
142
143   /// insert - Range insertion of pairs.
144   template<typename InputIt>
145   void insert(InputIt I, InputIt E) {
146     for (; I != E; ++I)
147       insert(*I);
148   }
149
150
151   bool erase(const KeyT &Val) {
152     typename MapT::iterator I = Map.find_as(Val);
153     if (I == Map.end())
154       return false;
155
156     Map.erase(I);
157     return true;
158   }
159   void erase(iterator I) {
160     return Map.erase(I.base());
161   }
162
163   value_type& FindAndConstruct(const KeyT &Key) {
164     return Map.FindAndConstruct(Wrap(Key));
165   }
166
167   ValueT &operator[](const KeyT &Key) {
168     return Map[Wrap(Key)];
169   }
170
171   /// isPointerIntoBucketsArray - Return true if the specified pointer points
172   /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
173   /// value in the ValueMap).
174   bool isPointerIntoBucketsArray(const void *Ptr) const {
175     return Map.isPointerIntoBucketsArray(Ptr);
176   }
177
178   /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
179   /// array.  In conjunction with the previous method, this can be used to
180   /// determine whether an insertion caused the ValueMap to reallocate.
181   const void *getPointerIntoBucketsArray() const {
182     return Map.getPointerIntoBucketsArray();
183   }
184
185 private:
186   // Takes a key being looked up in the map and wraps it into a
187   // ValueMapCallbackVH, the actual key type of the map.  We use a helper
188   // function because ValueMapCVH is constructed with a second parameter.
189   ValueMapCVH Wrap(KeyT key) const {
190     // The only way the resulting CallbackVH could try to modify *this (making
191     // the const_cast incorrect) is if it gets inserted into the map.  But then
192     // this function must have been called from a non-const method, making the
193     // const_cast ok.
194     return ValueMapCVH(key, const_cast<ValueMap*>(this));
195   }
196 };
197
198 // This CallbackVH updates its ValueMap when the contained Value changes,
199 // according to the user's preferences expressed through the Config object.
200 template<typename KeyT, typename ValueT, typename Config>
201 class ValueMapCallbackVH : public CallbackVH {
202   friend class ValueMap<KeyT, ValueT, Config>;
203   friend struct DenseMapInfo<ValueMapCallbackVH>;
204   typedef ValueMap<KeyT, ValueT, Config> ValueMapT;
205   typedef typename std::remove_pointer<KeyT>::type KeySansPointerT;
206
207   ValueMapT *Map;
208
209   ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
210       : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
211         Map(Map) {}
212
213 public:
214   KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
215
216   void deleted() override {
217     // Make a copy that won't get changed even when *this is destroyed.
218     ValueMapCallbackVH Copy(*this);
219     typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
220     unique_lock<typename Config::mutex_type> Guard;
221     if (M)
222       Guard = unique_lock<typename Config::mutex_type>(*M);
223     Config::onDelete(Copy.Map->Data, Copy.Unwrap());  // May destroy *this.
224     Copy.Map->Map.erase(Copy);  // Definitely destroys *this.
225   }
226   void allUsesReplacedWith(Value *new_key) override {
227     assert(isa<KeySansPointerT>(new_key) &&
228            "Invalid RAUW on key of ValueMap<>");
229     // Make a copy that won't get changed even when *this is destroyed.
230     ValueMapCallbackVH Copy(*this);
231     typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
232     unique_lock<typename Config::mutex_type> Guard;
233     if (M)
234       Guard = unique_lock<typename Config::mutex_type>(*M);
235
236     KeyT typed_new_key = cast<KeySansPointerT>(new_key);
237     // Can destroy *this:
238     Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
239     if (Config::FollowRAUW) {
240       typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
241       // I could == Copy.Map->Map.end() if the onRAUW callback already
242       // removed the old mapping.
243       if (I != Copy.Map->Map.end()) {
244         ValueT Target(I->second);
245         Copy.Map->Map.erase(I);  // Definitely destroys *this.
246         Copy.Map->insert(std::make_pair(typed_new_key, Target));
247       }
248     }
249   }
250 };
251
252 template<typename KeyT, typename ValueT, typename Config>
253 struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config> > {
254   typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH;
255   typedef DenseMapInfo<KeyT> PointerInfo;
256
257   static inline VH getEmptyKey() {
258     return VH(PointerInfo::getEmptyKey(), nullptr);
259   }
260   static inline VH getTombstoneKey() {
261     return VH(PointerInfo::getTombstoneKey(), nullptr);
262   }
263   static unsigned getHashValue(const VH &Val) {
264     return PointerInfo::getHashValue(Val.Unwrap());
265   }
266   static unsigned getHashValue(const KeyT &Val) {
267     return PointerInfo::getHashValue(Val);
268   }
269   static bool isEqual(const VH &LHS, const VH &RHS) {
270     return LHS == RHS;
271   }
272   static bool isEqual(const KeyT &LHS, const VH &RHS) {
273     return LHS == RHS.getValPtr();
274   }
275 };
276
277
278 template<typename DenseMapT, typename KeyT>
279 class ValueMapIterator :
280     public std::iterator<std::forward_iterator_tag,
281                          std::pair<KeyT, typename DenseMapT::mapped_type>,
282                          ptrdiff_t> {
283   typedef typename DenseMapT::iterator BaseT;
284   typedef typename DenseMapT::mapped_type ValueT;
285   BaseT I;
286 public:
287   ValueMapIterator() : I() {}
288
289   ValueMapIterator(BaseT I) : I(I) {}
290
291   BaseT base() const { return I; }
292
293   struct ValueTypeProxy {
294     const KeyT first;
295     ValueT& second;
296     ValueTypeProxy *operator->() { return this; }
297     operator std::pair<KeyT, ValueT>() const {
298       return std::make_pair(first, second);
299     }
300   };
301
302   ValueTypeProxy operator*() const {
303     ValueTypeProxy Result = {I->first.Unwrap(), I->second};
304     return Result;
305   }
306
307   ValueTypeProxy operator->() const {
308     return operator*();
309   }
310
311   bool operator==(const ValueMapIterator &RHS) const {
312     return I == RHS.I;
313   }
314   bool operator!=(const ValueMapIterator &RHS) const {
315     return I != RHS.I;
316   }
317
318   inline ValueMapIterator& operator++() {  // Preincrement
319     ++I;
320     return *this;
321   }
322   ValueMapIterator operator++(int) {  // Postincrement
323     ValueMapIterator tmp = *this; ++*this; return tmp;
324   }
325 };
326
327 template<typename DenseMapT, typename KeyT>
328 class ValueMapConstIterator :
329     public std::iterator<std::forward_iterator_tag,
330                          std::pair<KeyT, typename DenseMapT::mapped_type>,
331                          ptrdiff_t> {
332   typedef typename DenseMapT::const_iterator BaseT;
333   typedef typename DenseMapT::mapped_type ValueT;
334   BaseT I;
335 public:
336   ValueMapConstIterator() : I() {}
337   ValueMapConstIterator(BaseT I) : I(I) {}
338   ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other)
339     : I(Other.base()) {}
340
341   BaseT base() const { return I; }
342
343   struct ValueTypeProxy {
344     const KeyT first;
345     const ValueT& second;
346     ValueTypeProxy *operator->() { return this; }
347     operator std::pair<KeyT, ValueT>() const {
348       return std::make_pair(first, second);
349     }
350   };
351
352   ValueTypeProxy operator*() const {
353     ValueTypeProxy Result = {I->first.Unwrap(), I->second};
354     return Result;
355   }
356
357   ValueTypeProxy operator->() const {
358     return operator*();
359   }
360
361   bool operator==(const ValueMapConstIterator &RHS) const {
362     return I == RHS.I;
363   }
364   bool operator!=(const ValueMapConstIterator &RHS) const {
365     return I != RHS.I;
366   }
367
368   inline ValueMapConstIterator& operator++() {  // Preincrement
369     ++I;
370     return *this;
371   }
372   ValueMapConstIterator operator++(int) {  // Postincrement
373     ValueMapConstIterator tmp = *this; ++*this; return tmp;
374   }
375 };
376
377 } // end namespace llvm
378
379 #endif