ValueMap.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  1. //===- ValueMap.h - Safe map from Values to data ----------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  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.
  16. //
  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.
  23. //
  24. //===----------------------------------------------------------------------===//
  25. #ifndef LLVM_IR_VALUEMAP_H
  26. #define LLVM_IR_VALUEMAP_H
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/IR/TrackingMDRef.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/Support/Mutex.h"
  31. #include "llvm/Support/UniqueLock.h"
  32. #include "llvm/Support/type_traits.h"
  33. #include <iterator>
  34. #include <memory>
  35. namespace llvm {
  36. template<typename KeyT, typename ValueT, typename Config>
  37. class ValueMapCallbackVH;
  38. template<typename DenseMapT, typename KeyT>
  39. class ValueMapIterator;
  40. template<typename DenseMapT, typename KeyT>
  41. class ValueMapConstIterator;
  42. /// This class defines the default behavior for configurable aspects of
  43. /// ValueMap<>. User Configs should inherit from this class to be as compatible
  44. /// as possible with future versions of ValueMap.
  45. template<typename KeyT, typename MutexT = sys::Mutex>
  46. struct ValueMapConfig {
  47. typedef MutexT mutex_type;
  48. /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
  49. /// false, the ValueMap will leave the original mapping in place.
  50. enum { FollowRAUW = true };
  51. // All methods will be called with a first argument of type ExtraData. The
  52. // default implementations in this class take a templated first argument so
  53. // that users' subclasses can use any type they want without having to
  54. // override all the defaults.
  55. struct ExtraData {};
  56. template<typename ExtraDataT>
  57. static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
  58. template<typename ExtraDataT>
  59. static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
  60. /// Returns a mutex that should be acquired around any changes to the map.
  61. /// This is only acquired from the CallbackVH (and held around calls to onRAUW
  62. /// and onDelete) and not inside other ValueMap methods. NULL means that no
  63. /// mutex is necessary.
  64. template<typename ExtraDataT>
  65. static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; }
  66. };
  67. /// See the file comment.
  68. template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT> >
  69. class ValueMap {
  70. friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
  71. typedef ValueMapCallbackVH<KeyT, ValueT, Config> ValueMapCVH;
  72. typedef DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH> > MapT;
  73. typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
  74. typedef typename Config::ExtraData ExtraData;
  75. MapT Map;
  76. std::unique_ptr<MDMapT> MDMap;
  77. ExtraData Data;
  78. ValueMap(const ValueMap&) = delete;
  79. ValueMap& operator=(const ValueMap&) = delete;
  80. public:
  81. typedef KeyT key_type;
  82. typedef ValueT mapped_type;
  83. typedef std::pair<KeyT, ValueT> value_type;
  84. typedef unsigned size_type;
  85. explicit ValueMap(unsigned NumInitBuckets = 64)
  86. : Map(NumInitBuckets), Data() {}
  87. explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
  88. : Map(NumInitBuckets), Data(Data) {}
  89. bool hasMD() const { return bool(MDMap); }
  90. MDMapT &MD() {
  91. if (!MDMap)
  92. MDMap.reset(new MDMapT);
  93. return *MDMap;
  94. }
  95. typedef ValueMapIterator<MapT, KeyT> iterator;
  96. typedef ValueMapConstIterator<MapT, KeyT> const_iterator;
  97. inline iterator begin() { return iterator(Map.begin()); }
  98. inline iterator end() { return iterator(Map.end()); }
  99. inline const_iterator begin() const { return const_iterator(Map.begin()); }
  100. inline const_iterator end() const { return const_iterator(Map.end()); }
  101. bool empty() const { return Map.empty(); }
  102. size_type size() const { return Map.size(); }
  103. /// Grow the map so that it has at least Size buckets. Does not shrink
  104. void resize(size_t Size) { Map.resize(Size); }
  105. void clear() {
  106. Map.clear();
  107. MDMap.reset();
  108. }
  109. /// Return 1 if the specified key is in the map, 0 otherwise.
  110. size_type count(const KeyT &Val) const {
  111. return Map.find_as(Val) == Map.end() ? 0 : 1;
  112. }
  113. iterator find(const KeyT &Val) {
  114. return iterator(Map.find_as(Val));
  115. }
  116. const_iterator find(const KeyT &Val) const {
  117. return const_iterator(Map.find_as(Val));
  118. }
  119. /// lookup - Return the entry for the specified key, or a default
  120. /// constructed value if no such entry exists.
  121. ValueT lookup(const KeyT &Val) const {
  122. typename MapT::const_iterator I = Map.find_as(Val);
  123. return I != Map.end() ? I->second : ValueT();
  124. }
  125. // Inserts key,value pair into the map if the key isn't already in the map.
  126. // If the key is already in the map, it returns false and doesn't update the
  127. // value.
  128. std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
  129. auto MapResult = Map.insert(std::make_pair(Wrap(KV.first), KV.second));
  130. return std::make_pair(iterator(MapResult.first), MapResult.second);
  131. }
  132. std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
  133. auto MapResult =
  134. Map.insert(std::make_pair(Wrap(KV.first), std::move(KV.second)));
  135. return std::make_pair(iterator(MapResult.first), MapResult.second);
  136. }
  137. /// insert - Range insertion of pairs.
  138. template<typename InputIt>
  139. void insert(InputIt I, InputIt E) {
  140. for (; I != E; ++I)
  141. insert(*I);
  142. }
  143. bool erase(const KeyT &Val) {
  144. typename MapT::iterator I = Map.find_as(Val);
  145. if (I == Map.end())
  146. return false;
  147. Map.erase(I);
  148. return true;
  149. }
  150. void erase(iterator I) {
  151. return Map.erase(I.base());
  152. }
  153. value_type& FindAndConstruct(const KeyT &Key) {
  154. return Map.FindAndConstruct(Wrap(Key));
  155. }
  156. ValueT &operator[](const KeyT &Key) {
  157. return Map[Wrap(Key)];
  158. }
  159. /// isPointerIntoBucketsArray - Return true if the specified pointer points
  160. /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
  161. /// value in the ValueMap).
  162. bool isPointerIntoBucketsArray(const void *Ptr) const {
  163. return Map.isPointerIntoBucketsArray(Ptr);
  164. }
  165. /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
  166. /// array. In conjunction with the previous method, this can be used to
  167. /// determine whether an insertion caused the ValueMap to reallocate.
  168. const void *getPointerIntoBucketsArray() const {
  169. return Map.getPointerIntoBucketsArray();
  170. }
  171. private:
  172. // Takes a key being looked up in the map and wraps it into a
  173. // ValueMapCallbackVH, the actual key type of the map. We use a helper
  174. // function because ValueMapCVH is constructed with a second parameter.
  175. ValueMapCVH Wrap(KeyT key) const {
  176. // The only way the resulting CallbackVH could try to modify *this (making
  177. // the const_cast incorrect) is if it gets inserted into the map. But then
  178. // this function must have been called from a non-const method, making the
  179. // const_cast ok.
  180. return ValueMapCVH(key, const_cast<ValueMap*>(this));
  181. }
  182. };
  183. // This CallbackVH updates its ValueMap when the contained Value changes,
  184. // according to the user's preferences expressed through the Config object.
  185. template<typename KeyT, typename ValueT, typename Config>
  186. class ValueMapCallbackVH : public CallbackVH {
  187. friend class ValueMap<KeyT, ValueT, Config>;
  188. friend struct DenseMapInfo<ValueMapCallbackVH>;
  189. typedef ValueMap<KeyT, ValueT, Config> ValueMapT;
  190. typedef typename std::remove_pointer<KeyT>::type KeySansPointerT;
  191. ValueMapT *Map;
  192. ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
  193. : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
  194. Map(Map) {}
  195. // Private constructor used to create empty/tombstone DenseMap keys.
  196. ValueMapCallbackVH(Value *V) : CallbackVH(V), Map(nullptr) {}
  197. public:
  198. KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
  199. void deleted() override {
  200. // Make a copy that won't get changed even when *this is destroyed.
  201. ValueMapCallbackVH Copy(*this);
  202. typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
  203. unique_lock<typename Config::mutex_type> Guard;
  204. if (M)
  205. Guard = unique_lock<typename Config::mutex_type>(*M);
  206. Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
  207. Copy.Map->Map.erase(Copy); // Definitely destroys *this.
  208. }
  209. void allUsesReplacedWith(Value *new_key) override {
  210. assert(isa<KeySansPointerT>(new_key) &&
  211. "Invalid RAUW on key of ValueMap<>");
  212. // Make a copy that won't get changed even when *this is destroyed.
  213. ValueMapCallbackVH Copy(*this);
  214. typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
  215. unique_lock<typename Config::mutex_type> Guard;
  216. if (M)
  217. Guard = unique_lock<typename Config::mutex_type>(*M);
  218. KeyT typed_new_key = cast<KeySansPointerT>(new_key);
  219. // Can destroy *this:
  220. Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
  221. if (Config::FollowRAUW) {
  222. typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
  223. // I could == Copy.Map->Map.end() if the onRAUW callback already
  224. // removed the old mapping.
  225. if (I != Copy.Map->Map.end()) {
  226. ValueT Target(std::move(I->second));
  227. Copy.Map->Map.erase(I); // Definitely destroys *this.
  228. Copy.Map->insert(std::make_pair(typed_new_key, std::move(Target)));
  229. }
  230. }
  231. }
  232. };
  233. template<typename KeyT, typename ValueT, typename Config>
  234. struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config> > {
  235. typedef ValueMapCallbackVH<KeyT, ValueT, Config> VH;
  236. static inline VH getEmptyKey() {
  237. return VH(DenseMapInfo<Value *>::getEmptyKey());
  238. }
  239. static inline VH getTombstoneKey() {
  240. return VH(DenseMapInfo<Value *>::getTombstoneKey());
  241. }
  242. static unsigned getHashValue(const VH &Val) {
  243. return DenseMapInfo<KeyT>::getHashValue(Val.Unwrap());
  244. }
  245. static unsigned getHashValue(const KeyT &Val) {
  246. return DenseMapInfo<KeyT>::getHashValue(Val);
  247. }
  248. static bool isEqual(const VH &LHS, const VH &RHS) {
  249. return LHS == RHS;
  250. }
  251. static bool isEqual(const KeyT &LHS, const VH &RHS) {
  252. return LHS == RHS.getValPtr();
  253. }
  254. };
  255. template<typename DenseMapT, typename KeyT>
  256. class ValueMapIterator :
  257. public std::iterator<std::forward_iterator_tag,
  258. std::pair<KeyT, typename DenseMapT::mapped_type>,
  259. ptrdiff_t> {
  260. typedef typename DenseMapT::iterator BaseT;
  261. typedef typename DenseMapT::mapped_type ValueT;
  262. BaseT I;
  263. public:
  264. ValueMapIterator() : I() {}
  265. ValueMapIterator(BaseT I) : I(I) {}
  266. BaseT base() const { return I; }
  267. struct ValueTypeProxy {
  268. const KeyT first;
  269. ValueT& second;
  270. ValueTypeProxy *operator->() { return this; }
  271. operator std::pair<KeyT, ValueT>() const {
  272. return std::make_pair(first, second);
  273. }
  274. };
  275. ValueTypeProxy operator*() const {
  276. ValueTypeProxy Result = {I->first.Unwrap(), I->second};
  277. return Result;
  278. }
  279. ValueTypeProxy operator->() const {
  280. return operator*();
  281. }
  282. bool operator==(const ValueMapIterator &RHS) const {
  283. return I == RHS.I;
  284. }
  285. bool operator!=(const ValueMapIterator &RHS) const {
  286. return I != RHS.I;
  287. }
  288. inline ValueMapIterator& operator++() { // Preincrement
  289. ++I;
  290. return *this;
  291. }
  292. ValueMapIterator operator++(int) { // Postincrement
  293. ValueMapIterator tmp = *this; ++*this; return tmp;
  294. }
  295. };
  296. template<typename DenseMapT, typename KeyT>
  297. class ValueMapConstIterator :
  298. public std::iterator<std::forward_iterator_tag,
  299. std::pair<KeyT, typename DenseMapT::mapped_type>,
  300. ptrdiff_t> {
  301. typedef typename DenseMapT::const_iterator BaseT;
  302. typedef typename DenseMapT::mapped_type ValueT;
  303. BaseT I;
  304. public:
  305. ValueMapConstIterator() : I() {}
  306. ValueMapConstIterator(BaseT I) : I(I) {}
  307. ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other)
  308. : I(Other.base()) {}
  309. BaseT base() const { return I; }
  310. struct ValueTypeProxy {
  311. const KeyT first;
  312. const ValueT& second;
  313. ValueTypeProxy *operator->() { return this; }
  314. operator std::pair<KeyT, ValueT>() const {
  315. return std::make_pair(first, second);
  316. }
  317. };
  318. ValueTypeProxy operator*() const {
  319. ValueTypeProxy Result = {I->first.Unwrap(), I->second};
  320. return Result;
  321. }
  322. ValueTypeProxy operator->() const {
  323. return operator*();
  324. }
  325. bool operator==(const ValueMapConstIterator &RHS) const {
  326. return I == RHS.I;
  327. }
  328. bool operator!=(const ValueMapConstIterator &RHS) const {
  329. return I != RHS.I;
  330. }
  331. inline ValueMapConstIterator& operator++() { // Preincrement
  332. ++I;
  333. return *this;
  334. }
  335. ValueMapConstIterator operator++(int) { // Postincrement
  336. ValueMapConstIterator tmp = *this; ++*this; return tmp;
  337. }
  338. };
  339. } // end namespace llvm
  340. #endif