1 //===- ValueMap.h - Safe map from Values to data ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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.
24 //===----------------------------------------------------------------------===//
26 #ifndef LLVM_IR_VALUEMAP_H
27 #define LLVM_IR_VALUEMAP_H
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/IR/TrackingMDRef.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/Support/Mutex.h"
34 #include "llvm/Support/UniqueLock.h"
35 #include "llvm/Support/type_traits.h"
41 template<typename KeyT, typename ValueT, typename Config>
42 class ValueMapCallbackVH;
44 template<typename DenseMapT, typename KeyT>
45 class ValueMapIterator;
46 template<typename DenseMapT, typename KeyT>
47 class ValueMapConstIterator;
49 /// This class defines the default behavior for configurable aspects of
50 /// ValueMap<>. User Configs should inherit from this class to be as compatible
51 /// as possible with future versions of ValueMap.
52 template<typename KeyT, typename MutexT = sys::Mutex>
53 struct ValueMapConfig {
54 typedef MutexT mutex_type;
56 /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
57 /// false, the ValueMap will leave the original mapping in place.
58 enum { FollowRAUW = true };
60 // All methods will be called with a first argument of type ExtraData. The
61 // default implementations in this class take a templated first argument so
62 // that users' subclasses can use any type they want without having to
63 // override all the defaults.
66 template<typename ExtraDataT>
67 static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
68 template<typename ExtraDataT>
69 static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
71 /// Returns a mutex that should be acquired around any changes to the map.
72 /// This is only acquired from the CallbackVH (and held around calls to onRAUW
73 /// and onDelete) and not inside other ValueMap methods. NULL means that no
74 /// mutex is necessary.
75 template<typename ExtraDataT>
76 static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; }
79 /// See the file comment.
80 template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT> >
82 friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
83 typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH;
84 typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH> > MapT;
85 typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
86 typedef typename Config::ExtraData ExtraData;
88 Optional<MDMapT> MDMap;
91 bool MayMapMetadata = true;
93 ValueMap(const ValueMap&) = delete;
94 ValueMap& operator=(const ValueMap&) = delete;
96 typedef KeyT key_type;
97 typedef ValueT mapped_type;
98 typedef std::pair<KeyT, ValueT> value_type;
99 typedef unsigned size_type;
101 explicit ValueMap(unsigned NumInitBuckets = 64)
102 : Map(NumInitBuckets), Data() {}
103 explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
104 : Map(NumInitBuckets), Data(Data) {}
106 bool hasMD() const { return bool(MDMap); }
112 Optional<MDMapT> &getMDMap() { return MDMap; }
114 bool mayMapMetadata() const { return MayMapMetadata; }
115 void enableMapMetadata() { MayMapMetadata = true; }
116 void disableMapMetadata() { MayMapMetadata = false; }
118 /// Get the mapped metadata, if it's in the map.
119 Optional<Metadata *> getMappedMD(const Metadata *MD) const {
122 auto Where = MDMap->find(MD);
123 if (Where == MDMap->end())
125 return Where->second.get();
128 typedef ValueMapIterator<MapT, KeyT> iterator;
129 typedef ValueMapConstIterator<MapT, KeyT> const_iterator;
130 inline iterator begin() { return iterator(Map.begin()); }
131 inline iterator end() { return iterator(Map.end()); }
132 inline const_iterator begin() const { return const_iterator(Map.begin()); }
133 inline const_iterator end() const { return const_iterator(Map.end()); }
135 bool empty() const { return Map.empty(); }
136 size_type size() const { return Map.size(); }
138 /// Grow the map so that it has at least Size buckets. Does not shrink
139 void resize(size_t Size) { Map.resize(Size); }
146 /// Return 1 if the specified key is in the map, 0 otherwise.
147 size_type count(const KeyT &Val) const {
148 return Map.find_as(Val) == Map.end() ? 0 : 1;
151 iterator find(const KeyT &Val) {
152 return iterator(Map.find_as(Val));
154 const_iterator find(const KeyT &Val) const {
155 return const_iterator(Map.find_as(Val));
158 /// lookup - Return the entry for the specified key, or a default
159 /// constructed value if no such entry exists.
160 ValueT lookup(const KeyT &Val) const {
161 typename MapT::const_iterator I = Map.find_as(Val);
162 return I != Map.end() ? I->second : ValueT();
165 // Inserts key,value pair into the map if the key isn't already in the map.
166 // If the key is already in the map, it returns false and doesn't update the
168 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
169 auto MapResult = Map.insert(std::make_pair(Wrap(KV.first), KV.second));
170 return std::make_pair(iterator(MapResult.first), MapResult.second);
173 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
175 Map.insert(std::make_pair(Wrap(KV.first), std::move(KV.second)));
176 return std::make_pair(iterator(MapResult.first), MapResult.second);
179 /// insert - Range insertion of pairs.
180 template<typename InputIt>
181 void insert(InputIt I, InputIt E) {
187 bool erase(const KeyT &Val) {
188 typename MapT::iterator I = Map.find_as(Val);
195 void erase(iterator I) {
196 return Map.erase(I.base());
199 value_type& FindAndConstruct(const KeyT &Key) {
200 return Map.FindAndConstruct(Wrap(Key));
203 ValueT &operator[](const KeyT &Key) {
204 return Map[Wrap(Key)];
207 /// isPointerIntoBucketsArray - Return true if the specified pointer points
208 /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
209 /// value in the ValueMap).
210 bool isPointerIntoBucketsArray(const void *Ptr) const {
211 return Map.isPointerIntoBucketsArray(Ptr);
214 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
215 /// array. In conjunction with the previous method, this can be used to
216 /// determine whether an insertion caused the ValueMap to reallocate.
217 const void *getPointerIntoBucketsArray() const {
218 return Map.getPointerIntoBucketsArray();
222 // Takes a key being looked up in the map and wraps it into a
223 // ValueMapCallbackVH, the actual key type of the map. We use a helper
224 // function because ValueMapCVH is constructed with a second parameter.
225 ValueMapCVH Wrap(KeyT key) const {
226 // The only way the resulting CallbackVH could try to modify *this (making
227 // the const_cast incorrect) is if it gets inserted into the map. But then
228 // this function must have been called from a non-const method, making the
230 return ValueMapCVH(key, const_cast<ValueMap*>(this));
234 // This CallbackVH updates its ValueMap when the contained Value changes,
235 // according to the user's preferences expressed through the Config object.
236 template <typename KeyT, typename ValueT, typename Config>
237 class ValueMapCallbackVH final : public CallbackVH {
238 friend class ValueMap<KeyT, ValueT, Config>;
239 friend struct DenseMapInfo<ValueMapCallbackVH>;
240 typedef ValueMap<KeyT, ValueT, Config> ValueMapT;
241 typedef typename std::remove_pointer<KeyT>::type KeySansPointerT;
245 ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
246 : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
249 // Private constructor used to create empty/tombstone DenseMap keys.
250 ValueMapCallbackVH(Value *V) : CallbackVH(V), Map(nullptr) {}
253 KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
255 void deleted() override {
256 // Make a copy that won't get changed even when *this is destroyed.
257 ValueMapCallbackVH Copy(*this);
258 typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
259 unique_lock<typename Config::mutex_type> Guard;
261 Guard = unique_lock<typename Config::mutex_type>(*M);
262 Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
263 Copy.Map->Map.erase(Copy); // Definitely destroys *this.
265 void allUsesReplacedWith(Value *new_key) override {
266 assert(isa<KeySansPointerT>(new_key) &&
267 "Invalid RAUW on key of ValueMap<>");
268 // Make a copy that won't get changed even when *this is destroyed.
269 ValueMapCallbackVH Copy(*this);
270 typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
271 unique_lock<typename Config::mutex_type> Guard;
273 Guard = unique_lock<typename Config::mutex_type>(*M);
275 KeyT typed_new_key = cast<KeySansPointerT>(new_key);
276 // Can destroy *this:
277 Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
278 if (Config::FollowRAUW) {
279 typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
280 // I could == Copy.Map->Map.end() if the onRAUW callback already
281 // removed the old mapping.
282 if (I != Copy.Map->Map.end()) {
283 ValueT Target(std::move(I->second));
284 Copy.Map->Map.erase(I); // Definitely destroys *this.
285 Copy.Map->insert(std::make_pair(typed_new_key, std::move(Target)));
291 template<typename KeyT, typename ValueT, typename Config>
292 struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config> > {
293 typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH;
295 static inline VH getEmptyKey() {
296 return VH(DenseMapInfo<Value *>::getEmptyKey());
298 static inline VH getTombstoneKey() {
299 return VH(DenseMapInfo<Value *>::getTombstoneKey());
301 static unsigned getHashValue(const VH &Val) {
302 return DenseMapInfo<KeyT>::getHashValue(Val.Unwrap());
304 static unsigned getHashValue(const KeyT &Val) {
305 return DenseMapInfo<KeyT>::getHashValue(Val);
307 static bool isEqual(const VH &LHS, const VH &RHS) {
310 static bool isEqual(const KeyT &LHS, const VH &RHS) {
311 return LHS == RHS.getValPtr();
316 template<typename DenseMapT, typename KeyT>
317 class ValueMapIterator :
318 public std::iterator<std::forward_iterator_tag,
319 std::pair<KeyT, typename DenseMapT::mapped_type>,
321 typedef typename DenseMapT::iterator BaseT;
322 typedef typename DenseMapT::mapped_type ValueT;
325 ValueMapIterator() : I() {}
327 ValueMapIterator(BaseT I) : I(I) {}
329 BaseT base() const { return I; }
331 struct ValueTypeProxy {
334 ValueTypeProxy *operator->() { return this; }
335 operator std::pair<KeyT, ValueT>() const {
336 return std::make_pair(first, second);
340 ValueTypeProxy operator*() const {
341 ValueTypeProxy Result = {I->first.Unwrap(), I->second};
345 ValueTypeProxy operator->() const {
349 bool operator==(const ValueMapIterator &RHS) const {
352 bool operator!=(const ValueMapIterator &RHS) const {
356 inline ValueMapIterator& operator++() { // Preincrement
360 ValueMapIterator operator++(int) { // Postincrement
361 ValueMapIterator tmp = *this; ++*this; return tmp;
365 template<typename DenseMapT, typename KeyT>
366 class ValueMapConstIterator :
367 public std::iterator<std::forward_iterator_tag,
368 std::pair<KeyT, typename DenseMapT::mapped_type>,
370 typedef typename DenseMapT::const_iterator BaseT;
371 typedef typename DenseMapT::mapped_type ValueT;
374 ValueMapConstIterator() : I() {}
375 ValueMapConstIterator(BaseT I) : I(I) {}
376 ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other)
379 BaseT base() const { return I; }
381 struct ValueTypeProxy {
383 const ValueT& second;
384 ValueTypeProxy *operator->() { return this; }
385 operator std::pair<KeyT, ValueT>() const {
386 return std::make_pair(first, second);
390 ValueTypeProxy operator*() const {
391 ValueTypeProxy Result = {I->first.Unwrap(), I->second};
395 ValueTypeProxy operator->() const {
399 bool operator==(const ValueMapConstIterator &RHS) const {
402 bool operator!=(const ValueMapConstIterator &RHS) const {
406 inline ValueMapConstIterator& operator++() { // Preincrement
410 ValueMapConstIterator operator++(int) { // Postincrement
411 ValueMapConstIterator tmp = *this; ++*this; return tmp;
415 } // end namespace llvm