LLVM 22.0.0git
ValueMap.h
Go to the documentation of this file.
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"
31#include "llvm/IR/ValueHandle.h"
33#include "llvm/Support/Mutex.h"
34#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <iterator>
38#include <mutex>
39#include <optional>
40#include <type_traits>
41#include <utility>
42
43namespace llvm {
44
45template <typename KeyT, typename ValueT, typename Config>
47template <typename DenseMapT, typename KeyT> class ValueMapIterator;
48template <typename DenseMapT, typename KeyT> class ValueMapConstIterator;
49
50/// This class defines the default behavior for configurable aspects of
51/// ValueMap<>. User Configs should inherit from this class to be as compatible
52/// as possible with future versions of ValueMap.
53template <typename KeyT, typename MutexT = sys::Mutex> struct ValueMapConfig {
54 using mutex_type = MutexT;
55
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 };
59
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.
64 struct ExtraData {};
65
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*/) {}
70
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*/) {
77 return nullptr;
78 }
79};
80
81/// See the file comment.
82template <typename KeyT, typename ValueT,
83 typename Config = ValueMapConfig<KeyT>>
84class ValueMap {
85 friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
86
90 /// Map {(InlinedAt, old atom number) -> new atom number}.
92 using ExtraData = typename Config::ExtraData;
93
94 MapT Map;
95 std::optional<MDMapT> MDMap;
96 ExtraData Data;
97
98public:
99 using key_type = KeyT;
100 using mapped_type = ValueT;
101 using value_type = std::pair<KeyT, ValueT>;
103
104 explicit ValueMap(unsigned NumInitBuckets = 64)
105 : Map(NumInitBuckets), Data() {}
106 explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
107 : Map(NumInitBuckets), Data(Data) {}
108 // ValueMap can't be copied nor moved, because the callbacks store pointer to
109 // it.
110 ValueMap(const ValueMap &) = delete;
111 ValueMap(ValueMap &&) = delete;
112 ValueMap &operator=(const ValueMap &) = delete;
114
115 bool hasMD() const { return bool(MDMap); }
116 MDMapT &MD() {
117 if (!MDMap)
118 MDMap.emplace();
119 return *MDMap;
120 }
121 std::optional<MDMapT> &getMDMap() { return MDMap; }
122 /// Map {(InlinedAt, old atom number) -> new atom number}.
123 DMAtomT AtomMap;
124
125 /// Get the mapped metadata, if it's in the map.
126 std::optional<Metadata *> getMappedMD(const Metadata *MD) const {
127 if (!MDMap)
128 return std::nullopt;
129 auto Where = MDMap->find(MD);
130 if (Where == MDMap->end())
131 return std::nullopt;
132 return Where->second.get();
133 }
134
137
138 inline iterator begin() { return iterator(Map.begin()); }
139 inline iterator end() { return iterator(Map.end()); }
140 inline const_iterator begin() const { return const_iterator(Map.begin()); }
141 inline const_iterator end() const { return const_iterator(Map.end()); }
142
143 bool empty() const { return Map.empty(); }
144 size_type size() const { return Map.size(); }
145
146 /// Grow the map so that it has at least Size buckets. Does not shrink
147 void reserve(size_t Size) { Map.reserve(Size); }
148
149 void clear() {
150 Map.clear();
151 MDMap.reset();
152 AtomMap.clear();
153 }
154
155 /// Return 1 if the specified key is in the map, 0 otherwise.
156 size_type count(const KeyT &Val) const {
157 return Map.find_as(Val) == Map.end() ? 0 : 1;
158 }
159
160 iterator find(const KeyT &Val) { return iterator(Map.find_as(Val)); }
161 const_iterator find(const KeyT &Val) const {
162 return const_iterator(Map.find_as(Val));
163 }
164
165 /// lookup - Return the entry for the specified key, or a default
166 /// constructed value if no such entry exists.
167 ValueT lookup(const KeyT &Val) const {
168 typename MapT::const_iterator I = Map.find_as(Val);
169 return I != Map.end() ? I->second : ValueT();
170 }
171
172 // Inserts key,value pair into the map if the key isn't already in the map.
173 // If the key is already in the map, it returns false and doesn't update the
174 // value.
175 std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
176 auto MapResult = Map.insert(std::make_pair(Wrap(KV.first), KV.second));
177 return std::make_pair(iterator(MapResult.first), MapResult.second);
178 }
179
180 std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
181 auto MapResult =
182 Map.insert(std::make_pair(Wrap(KV.first), std::move(KV.second)));
183 return std::make_pair(iterator(MapResult.first), MapResult.second);
184 }
185
186 /// insert - Range insertion of pairs.
187 template <typename InputIt> void insert(InputIt I, InputIt E) {
188 for (; I != E; ++I)
189 insert(*I);
190 }
191
192 bool erase(const KeyT &Val) {
193 typename MapT::iterator I = Map.find_as(Val);
194 if (I == Map.end())
195 return false;
196
197 Map.erase(I);
198 return true;
199 }
200 void erase(iterator I) { return Map.erase(I.base()); }
201
203 return Map.FindAndConstruct(Wrap(Key));
204 }
205
206 ValueT &operator[](const KeyT &Key) { return Map[Wrap(Key)]; }
207
208 /// isPointerIntoBucketsArray - Return true if the specified pointer points
209 /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
210 /// value in the ValueMap).
211 bool isPointerIntoBucketsArray(const void *Ptr) const {
212 return Map.isPointerIntoBucketsArray(Ptr);
213 }
214
215 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
216 /// array. In conjunction with the previous method, this can be used to
217 /// determine whether an insertion caused the ValueMap to reallocate.
218 const void *getPointerIntoBucketsArray() const {
219 return Map.getPointerIntoBucketsArray();
220 }
221
222private:
223 // Takes a key being looked up in the map and wraps it into a
224 // ValueMapCallbackVH, the actual key type of the map. We use a helper
225 // function because ValueMapCVH is constructed with a second parameter.
226 ValueMapCVH Wrap(KeyT key) const {
227 // The only way the resulting CallbackVH could try to modify *this (making
228 // the const_cast incorrect) is if it gets inserted into the map. But then
229 // this function must have been called from a non-const method, making the
230 // const_cast ok.
231 return ValueMapCVH(key, const_cast<ValueMap *>(this));
232 }
233};
234
235// This CallbackVH updates its ValueMap when the contained Value changes,
236// according to the user's preferences expressed through the Config object.
237template <typename KeyT, typename ValueT, typename Config>
238class ValueMapCallbackVH final : public CallbackVH {
239 friend class ValueMap<KeyT, ValueT, Config>;
240 friend struct DenseMapInfo<ValueMapCallbackVH>;
241
242 using ValueMapT = ValueMap<KeyT, ValueT, Config>;
243 using KeySansPointerT = std::remove_pointer_t<KeyT>;
244
245 ValueMapT *Map;
246
247 ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
248 : CallbackVH(const_cast<Value *>(static_cast<const Value *>(Key))),
249 Map(Map) {}
250
251 // Private constructor used to create empty/tombstone DenseMap keys.
252 ValueMapCallbackVH(Value *V) : CallbackVH(V), Map(nullptr) {}
253
254public:
256
257 void deleted() override {
258 // Make a copy that won't get changed even when *this is destroyed.
259 ValueMapCallbackVH Copy(*this);
260 typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
261 std::unique_lock<typename Config::mutex_type> Guard;
262 if (M)
263 Guard = std::unique_lock<typename Config::mutex_type>(*M);
264 Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
265 Copy.Map->Map.erase(Copy); // Definitely destroys *this.
266 }
267
268 void allUsesReplacedWith(Value *new_key) override {
269 assert(isa<KeySansPointerT>(new_key) &&
270 "Invalid RAUW on key of ValueMap<>");
271 // Make a copy that won't get changed even when *this is destroyed.
272 ValueMapCallbackVH Copy(*this);
273 typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
274 std::unique_lock<typename Config::mutex_type> Guard;
275 if (M)
276 Guard = std::unique_lock<typename Config::mutex_type>(*M);
277
278 KeyT typed_new_key = cast<KeySansPointerT>(new_key);
279 // Can destroy *this:
280 Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
281 if (Config::FollowRAUW) {
282 typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
283 // I could == Copy.Map->Map.end() if the onRAUW callback already
284 // removed the old mapping.
285 if (I != Copy.Map->Map.end()) {
286 ValueT Target(std::move(I->second));
287 Copy.Map->Map.erase(I); // Definitely destroys *this.
288 Copy.Map->insert(std::make_pair(typed_new_key, std::move(Target)));
289 }
290 }
291 }
292};
293
294template <typename KeyT, typename ValueT, typename Config>
295struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config>> {
297
298 static inline VH getEmptyKey() {
300 }
301
302 static inline VH getTombstoneKey() {
304 }
305
306 static unsigned getHashValue(const VH &Val) {
308 }
309
310 static unsigned getHashValue(const KeyT &Val) {
312 }
313
314 static bool isEqual(const VH &LHS, const VH &RHS) { return LHS == RHS; }
315
316 static bool isEqual(const KeyT &LHS, const VH &RHS) {
317 return LHS == RHS.getValPtr();
318 }
319};
320
321template <typename DenseMapT, typename KeyT> class ValueMapIterator {
322 using BaseT = typename DenseMapT::iterator;
323 using ValueT = typename DenseMapT::mapped_type;
324
325 BaseT I;
326
327public:
328 using iterator_category = std::forward_iterator_tag;
329 using value_type = std::pair<KeyT, typename DenseMapT::mapped_type>;
330 using difference_type = std::ptrdiff_t;
333
335 ValueMapIterator(BaseT I) : I(I) {}
336
337 BaseT base() const { return I; }
338
340 const KeyT first;
341 ValueT &second;
342
343 ValueTypeProxy *operator->() { return this; }
344
345 operator std::pair<KeyT, ValueT>() const {
346 return std::make_pair(first, second);
347 }
348 };
349
350 ValueTypeProxy operator*() const {
351 ValueTypeProxy Result = {I->first.Unwrap(), I->second};
352 return Result;
353 }
354
355 ValueTypeProxy operator->() const { return operator*(); }
356
357 bool operator==(const ValueMapIterator &RHS) const { return I == RHS.I; }
358 bool operator!=(const ValueMapIterator &RHS) const { return I != RHS.I; }
359
360 inline ValueMapIterator &operator++() { // Preincrement
361 ++I;
362 return *this;
363 }
364 ValueMapIterator operator++(int) { // Postincrement
365 ValueMapIterator tmp = *this;
366 ++*this;
367 return tmp;
368 }
369};
370
371template <typename DenseMapT, typename KeyT> class ValueMapConstIterator {
372 using BaseT = typename DenseMapT::const_iterator;
373 using ValueT = typename DenseMapT::mapped_type;
374
375 BaseT I;
376
377public:
378 using iterator_category = std::forward_iterator_tag;
379 using value_type = std::pair<KeyT, typename DenseMapT::mapped_type>;
380 using difference_type = std::ptrdiff_t;
383
385 ValueMapConstIterator(BaseT I) : I(I) {}
388
389 BaseT base() const { return I; }
390
392 const KeyT first;
393 const ValueT &second;
394 ValueTypeProxy *operator->() { return this; }
395 operator std::pair<KeyT, ValueT>() const {
396 return std::make_pair(first, second);
397 }
398 };
399
400 ValueTypeProxy operator*() const {
401 ValueTypeProxy Result = {I->first.Unwrap(), I->second};
402 return Result;
403 }
404
405 ValueTypeProxy operator->() const { return operator*(); }
406
407 bool operator==(const ValueMapConstIterator &RHS) const { return I == RHS.I; }
408 bool operator!=(const ValueMapConstIterator &RHS) const { return I != RHS.I; }
409
410 inline ValueMapConstIterator &operator++() { // Preincrement
411 ++I;
412 return *this;
413 }
414 ValueMapConstIterator operator++(int) { // Postincrement
415 ValueMapConstIterator tmp = *this;
416 ++*this;
417 return tmp;
418 }
419};
420
421} // end namespace llvm
422
423#endif // LLVM_IR_VALUEMAP_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines DenseMapInfo traits for DenseMap.
This file defines the DenseMap class.
#define I(x, y, z)
Definition MD5.cpp:58
Value * RHS
Value * LHS
CallbackVH(const CallbackVH &)=default
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
Definition DenseMap.h:74
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT, true > const_iterator
Definition DenseMap.h:75
Root of the metadata hierarchy.
Definition Metadata.h:64
Target - Wrapper for Target specific information.
Value * getValPtr() const
void allUsesReplacedWith(Value *new_key) override
Callback for Value RAUW.
Definition ValueMap.h:268
void deleted() override
Callback for Value destruction.
Definition ValueMap.h:257
ValueMapConstIterator operator++(int)
Definition ValueMap.h:414
ValueMapConstIterator & operator++()
Definition ValueMap.h:410
bool operator!=(const ValueMapConstIterator &RHS) const
Definition ValueMap.h:408
ValueTypeProxy operator*() const
Definition ValueMap.h:400
std::pair< KeyT, typename MapT::mapped_type > value_type
Definition ValueMap.h:379
bool operator==(const ValueMapConstIterator &RHS) const
Definition ValueMap.h:407
ValueMapConstIterator(ValueMapIterator< DenseMapT, KeyT > Other)
Definition ValueMap.h:386
std::forward_iterator_tag iterator_category
Definition ValueMap.h:378
ValueTypeProxy operator->() const
Definition ValueMap.h:405
ValueTypeProxy operator*() const
Definition ValueMap.h:350
ValueMapIterator(BaseT I)
Definition ValueMap.h:335
std::forward_iterator_tag iterator_category
Definition ValueMap.h:328
BaseT base() const
Definition ValueMap.h:337
ValueMapIterator & operator++()
Definition ValueMap.h:360
std::pair< KeyT, typename MapT::mapped_type > value_type
Definition ValueMap.h:329
bool operator!=(const ValueMapIterator &RHS) const
Definition ValueMap.h:358
bool operator==(const ValueMapIterator &RHS) const
Definition ValueMap.h:357
ValueTypeProxy operator->() const
Definition ValueMap.h:355
ValueMapIterator operator++(int)
Definition ValueMap.h:364
See the file comment.
Definition ValueMap.h:84
void insert(InputIt I, InputIt E)
insert - Range insertion of pairs.
Definition ValueMap.h:187
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition ValueMap.h:167
ValueMapIterator< MapT, const Value * > iterator
Definition ValueMap.h:135
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the ValueMap's...
Definition ValueMap.h:211
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition ValueMap.h:156
bool empty() const
Definition ValueMap.h:143
std::pair< const Value *, WeakTrackingVH > value_type
Definition ValueMap.h:101
std::optional< MDMapT > & getMDMap()
Definition ValueMap.h:121
ValueMap & operator=(ValueMap &&)=delete
value_type & FindAndConstruct(const KeyT &Key)
Definition ValueMap.h:202
bool hasMD() const
Definition ValueMap.h:115
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator begin()
Definition ValueMap.h:138
std::optional< Metadata * > getMappedMD(const Metadata *MD) const
Get the mapped metadata, if it's in the map.
Definition ValueMap.h:126
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition ValueMap.h:175
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition ValueMap.h:218
MDMapT & MD()
Definition ValueMap.h:116
std::pair< iterator, bool > insert(std::pair< KeyT, ValueT > &&KV)
Definition ValueMap.h:180
size_type size() const
Definition ValueMap.h:144
ValueMapConstIterator< MapT, const Value * > const_iterator
Definition ValueMap.h:136
const_iterator find(const KeyT &Val) const
Definition ValueMap.h:161
ValueMap(unsigned NumInitBuckets=64)
Definition ValueMap.h:104
ValueT & operator[](const KeyT &Key)
Definition ValueMap.h:206
iterator end()
Definition ValueMap.h:139
void reserve(size_t Size)
Grow the map so that it has at least Size buckets. Does not shrink.
Definition ValueMap.h:147
ValueMap(const ExtraData &Data, unsigned NumInitBuckets=64)
Definition ValueMap.h:106
const_iterator end() const
Definition ValueMap.h:141
void erase(iterator I)
Definition ValueMap.h:200
const_iterator begin() const
Definition ValueMap.h:140
bool erase(const KeyT &Val)
Definition ValueMap.h:192
ValueMap & operator=(const ValueMap &)=delete
ValueMap(const ValueMap &)=delete
ValueMap(ValueMap &&)=delete
LLVM Value Representation.
Definition Value.h:75
This is an optimization pass for GlobalISel generic memory operations.
auto cast_or_null(const Y &Val)
Definition Casting.h:715
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:548
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
@ Other
Any other memory.
Definition ModRef.h:68
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:560
ValueMapCallbackVH< KeyT, ValueT, Config > VH
Definition ValueMap.h:296
static bool isEqual(const KeyT &LHS, const VH &RHS)
Definition ValueMap.h:316
static bool isEqual(const VH &LHS, const VH &RHS)
Definition ValueMap.h:314
An information struct used to provide DenseMap with the various necessary components for a given valu...
This class defines the default behavior for configurable aspects of ValueMap<>.
Definition ValueMap.h:53
static mutex_type * getMutex(const ExtraDataT &)
Returns a mutex that should be acquired around any changes to the map.
Definition ValueMap.h:76
static void onDelete(const ExtraDataT &, KeyT)
Definition ValueMap.h:69
static void onRAUW(const ExtraDataT &, KeyT, KeyT)
Definition ValueMap.h:67