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 44 namespace llvm { 45 46 template<typename KeyT, typename ValueT, typename Config> 47 class ValueMapCallbackVH; 48 template<typename DenseMapT, typename KeyT> 49 class ValueMapIterator; 50 template<typename DenseMapT, typename KeyT> 51 class 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. 56 template<typename KeyT, typename MutexT = sys::Mutex> 57 struct 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> onRAUWValueMapConfig71 static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {} 72 template<typename ExtraDataT> onDeleteValueMapConfig73 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> getMutexValueMapConfig80 static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; } 81 }; 82 83 /// See the file comment. 84 template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT>> 85 class 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 97 public: 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) Map(NumInitBuckets)104 : Map(NumInitBuckets), Data() {} 105 explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64) Map(NumInitBuckets)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 hasMD()114 bool hasMD() const { return bool(MDMap); } MD()115 MDMapT &MD() { 116 if (!MDMap) 117 MDMap.emplace(); 118 return *MDMap; 119 } getMDMap()120 Optional<MDMapT> &getMDMap() { return MDMap; } 121 122 /// Get the mapped metadata, if it's in the map. getMappedMD(const Metadata * MD)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 begin()135 inline iterator begin() { return iterator(Map.begin()); } end()136 inline iterator end() { return iterator(Map.end()); } begin()137 inline const_iterator begin() const { return const_iterator(Map.begin()); } end()138 inline const_iterator end() const { return const_iterator(Map.end()); } 139 empty()140 bool empty() const { return Map.empty(); } size()141 size_type size() const { return Map.size(); } 142 143 /// Grow the map so that it has at least Size buckets. Does not shrink resize(size_t Size)144 void resize(size_t Size) { Map.resize(Size); } 145 clear()146 void clear() { 147 Map.clear(); 148 MDMap.reset(); 149 } 150 151 /// Return 1 if the specified key is in the map, 0 otherwise. count(const KeyT & Val)152 size_type count(const KeyT &Val) const { 153 return Map.find_as(Val) == Map.end() ? 0 : 1; 154 } 155 find(const KeyT & Val)156 iterator find(const KeyT &Val) { 157 return iterator(Map.find_as(Val)); 158 } find(const KeyT & Val)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. lookup(const KeyT & Val)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. insert(const std::pair<KeyT,ValueT> & KV)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 insert(std::pair<KeyT,ValueT> && KV)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> insert(InputIt I,InputIt E)186 void insert(InputIt I, InputIt E) { 187 for (; I != E; ++I) 188 insert(*I); 189 } 190 erase(const KeyT & Val)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 } erase(iterator I)199 void erase(iterator I) { 200 return Map.erase(I.base()); 201 } 202 FindAndConstruct(const KeyT & Key)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). isPointerIntoBucketsArray(const void * Ptr)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. getPointerIntoBucketsArray()221 const void *getPointerIntoBucketsArray() const { 222 return Map.getPointerIntoBucketsArray(); 223 } 224 225 private: 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. Wrap(KeyT key)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. 240 template <typename KeyT, typename ValueT, typename Config> 241 class 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 = typename std::remove_pointer<KeyT>::type; 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 257 public: 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 297 template<typename KeyT, typename ValueT, typename Config> 298 struct 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 326 template<typename DenseMapT, typename KeyT> 327 class ValueMapIterator : 328 public std::iterator<std::forward_iterator_tag, 329 std::pair<KeyT, typename DenseMapT::mapped_type>, 330 ptrdiff_t> { 331 using BaseT = typename DenseMapT::iterator; 332 using ValueT = typename DenseMapT::mapped_type; 333 334 BaseT I; 335 336 public: 337 ValueMapIterator() : I() {} 338 ValueMapIterator(BaseT I) : I(I) {} 339 340 BaseT base() const { return I; } 341 342 struct ValueTypeProxy { 343 const KeyT first; 344 ValueT& second; 345 346 ValueTypeProxy *operator->() { return this; } 347 348 operator std::pair<KeyT, ValueT>() const { 349 return std::make_pair(first, second); 350 } 351 }; 352 353 ValueTypeProxy operator*() const { 354 ValueTypeProxy Result = {I->first.Unwrap(), I->second}; 355 return Result; 356 } 357 358 ValueTypeProxy operator->() const { 359 return operator*(); 360 } 361 362 bool operator==(const ValueMapIterator &RHS) const { 363 return I == RHS.I; 364 } 365 bool operator!=(const ValueMapIterator &RHS) const { 366 return I != RHS.I; 367 } 368 369 inline ValueMapIterator& operator++() { // Preincrement 370 ++I; 371 return *this; 372 } 373 ValueMapIterator operator++(int) { // Postincrement 374 ValueMapIterator tmp = *this; ++*this; return tmp; 375 } 376 }; 377 378 template<typename DenseMapT, typename KeyT> 379 class ValueMapConstIterator : 380 public std::iterator<std::forward_iterator_tag, 381 std::pair<KeyT, typename DenseMapT::mapped_type>, 382 ptrdiff_t> { 383 using BaseT = typename DenseMapT::const_iterator; 384 using ValueT = typename DenseMapT::mapped_type; 385 386 BaseT I; 387 388 public: 389 ValueMapConstIterator() : I() {} 390 ValueMapConstIterator(BaseT I) : I(I) {} 391 ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other) 392 : I(Other.base()) {} 393 394 BaseT base() const { return I; } 395 396 struct ValueTypeProxy { 397 const KeyT first; 398 const ValueT& second; 399 ValueTypeProxy *operator->() { return this; } 400 operator std::pair<KeyT, ValueT>() const { 401 return std::make_pair(first, second); 402 } 403 }; 404 405 ValueTypeProxy operator*() const { 406 ValueTypeProxy Result = {I->first.Unwrap(), I->second}; 407 return Result; 408 } 409 410 ValueTypeProxy operator->() const { 411 return operator*(); 412 } 413 414 bool operator==(const ValueMapConstIterator &RHS) const { 415 return I == RHS.I; 416 } 417 bool operator!=(const ValueMapConstIterator &RHS) const { 418 return I != RHS.I; 419 } 420 421 inline ValueMapConstIterator& operator++() { // Preincrement 422 ++I; 423 return *this; 424 } 425 ValueMapConstIterator operator++(int) { // Postincrement 426 ValueMapConstIterator tmp = *this; ++*this; return tmp; 427 } 428 }; 429 430 } // end namespace llvm 431 432 #endif // LLVM_IR_VALUEMAP_H 433