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