ValueMap.h 14 KB

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