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