Metadata.h 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- 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. /// @file
  15. /// This file contains the declarations for metadata subclasses.
  16. /// They represent the different flavors of metadata that live in LLVM.
  17. //
  18. //===----------------------------------------------------------------------===//
  19. #ifndef LLVM_IR_METADATA_H
  20. #define LLVM_IR_METADATA_H
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/DenseMap.h"
  23. #include "llvm/ADT/DenseMapInfo.h"
  24. #include "llvm/ADT/None.h"
  25. #include "llvm/ADT/PointerUnion.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/StringRef.h"
  28. #include "llvm/ADT/ilist_node.h"
  29. #include "llvm/ADT/iterator_range.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/LLVMContext.h"
  32. #include "llvm/IR/Value.h"
  33. #include "llvm/Support/CBindingWrapping.h"
  34. #include "llvm/Support/Casting.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include <cassert>
  37. #include <cstddef>
  38. #include <cstdint>
  39. #include <iterator>
  40. #include <memory>
  41. #include <string>
  42. #include <type_traits>
  43. #include <utility>
  44. namespace llvm {
  45. class Module;
  46. class ModuleSlotTracker;
  47. class raw_ostream;
  48. template <typename T> class StringMapEntry;
  49. template <typename ValueTy> class StringMapEntryStorage;
  50. class Type;
  51. enum LLVMConstants : uint32_t {
  52. DEBUG_METADATA_VERSION = 3 // Current debug info version number.
  53. };
  54. /// Magic number in the value profile metadata showing a target has been
  55. /// promoted for the instruction and shouldn't be promoted again.
  56. const uint64_t NOMORE_ICP_MAGICNUM = -1;
  57. /// Root of the metadata hierarchy.
  58. ///
  59. /// This is a root class for typeless data in the IR.
  60. class Metadata {
  61. friend class ReplaceableMetadataImpl;
  62. /// RTTI.
  63. const unsigned char SubclassID;
  64. protected:
  65. /// Active type of storage.
  66. enum StorageType { Uniqued, Distinct, Temporary };
  67. /// Storage flag for non-uniqued, otherwise unowned, metadata.
  68. unsigned char Storage : 7;
  69. unsigned char SubclassData1 : 1;
  70. unsigned short SubclassData16 = 0;
  71. unsigned SubclassData32 = 0;
  72. public:
  73. enum MetadataKind {
  74. #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
  75. #include "llvm/IR/Metadata.def"
  76. };
  77. protected:
  78. Metadata(unsigned ID, StorageType Storage)
  79. : SubclassID(ID), Storage(Storage), SubclassData1(false) {
  80. static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
  81. }
  82. ~Metadata() = default;
  83. /// Default handling of a changed operand, which asserts.
  84. ///
  85. /// If subclasses pass themselves in as owners to a tracking node reference,
  86. /// they must provide an implementation of this method.
  87. void handleChangedOperand(void *, Metadata *) {
  88. llvm_unreachable("Unimplemented in Metadata subclass");
  89. }
  90. public:
  91. unsigned getMetadataID() const { return SubclassID; }
  92. /// User-friendly dump.
  93. ///
  94. /// If \c M is provided, metadata nodes will be numbered canonically;
  95. /// otherwise, pointer addresses are substituted.
  96. ///
  97. /// Note: this uses an explicit overload instead of default arguments so that
  98. /// the nullptr version is easy to call from a debugger.
  99. ///
  100. /// @{
  101. void dump() const;
  102. void dump(const Module *M) const;
  103. /// @}
  104. /// Print.
  105. ///
  106. /// Prints definition of \c this.
  107. ///
  108. /// If \c M is provided, metadata nodes will be numbered canonically;
  109. /// otherwise, pointer addresses are substituted.
  110. /// @{
  111. void print(raw_ostream &OS, const Module *M = nullptr,
  112. bool IsForDebug = false) const;
  113. void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
  114. bool IsForDebug = false) const;
  115. /// @}
  116. /// Print as operand.
  117. ///
  118. /// Prints reference of \c this.
  119. ///
  120. /// If \c M is provided, metadata nodes will be numbered canonically;
  121. /// otherwise, pointer addresses are substituted.
  122. /// @{
  123. void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
  124. void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
  125. const Module *M = nullptr) const;
  126. /// @}
  127. };
  128. // Create wrappers for C Binding types (see CBindingWrapping.h).
  129. DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
  130. // Specialized opaque metadata conversions.
  131. inline Metadata **unwrap(LLVMMetadataRef *MDs) {
  132. return reinterpret_cast<Metadata**>(MDs);
  133. }
  134. #define HANDLE_METADATA(CLASS) class CLASS;
  135. #include "llvm/IR/Metadata.def"
  136. // Provide specializations of isa so that we don't need definitions of
  137. // subclasses to see if the metadata is a subclass.
  138. #define HANDLE_METADATA_LEAF(CLASS) \
  139. template <> struct isa_impl<CLASS, Metadata> { \
  140. static inline bool doit(const Metadata &MD) { \
  141. return MD.getMetadataID() == Metadata::CLASS##Kind; \
  142. } \
  143. };
  144. #include "llvm/IR/Metadata.def"
  145. inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
  146. MD.print(OS);
  147. return OS;
  148. }
  149. /// Metadata wrapper in the Value hierarchy.
  150. ///
  151. /// A member of the \a Value hierarchy to represent a reference to metadata.
  152. /// This allows, e.g., instrinsics to have metadata as operands.
  153. ///
  154. /// Notably, this is the only thing in either hierarchy that is allowed to
  155. /// reference \a LocalAsMetadata.
  156. class MetadataAsValue : public Value {
  157. friend class ReplaceableMetadataImpl;
  158. friend class LLVMContextImpl;
  159. Metadata *MD;
  160. MetadataAsValue(Type *Ty, Metadata *MD);
  161. /// Drop use of metadata (during teardown).
  162. void dropUse() { MD = nullptr; }
  163. public:
  164. ~MetadataAsValue();
  165. static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
  166. static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
  167. Metadata *getMetadata() const { return MD; }
  168. static bool classof(const Value *V) {
  169. return V->getValueID() == MetadataAsValueVal;
  170. }
  171. private:
  172. void handleChangedMetadata(Metadata *MD);
  173. void track();
  174. void untrack();
  175. };
  176. /// API for tracking metadata references through RAUW and deletion.
  177. ///
  178. /// Shared API for updating \a Metadata pointers in subclasses that support
  179. /// RAUW.
  180. ///
  181. /// This API is not meant to be used directly. See \a TrackingMDRef for a
  182. /// user-friendly tracking reference.
  183. class MetadataTracking {
  184. public:
  185. /// Track the reference to metadata.
  186. ///
  187. /// Register \c MD with \c *MD, if the subclass supports tracking. If \c *MD
  188. /// gets RAUW'ed, \c MD will be updated to the new address. If \c *MD gets
  189. /// deleted, \c MD will be set to \c nullptr.
  190. ///
  191. /// If tracking isn't supported, \c *MD will not change.
  192. ///
  193. /// \return true iff tracking is supported by \c MD.
  194. static bool track(Metadata *&MD) {
  195. return track(&MD, *MD, static_cast<Metadata *>(nullptr));
  196. }
  197. /// Track the reference to metadata for \a Metadata.
  198. ///
  199. /// As \a track(Metadata*&), but with support for calling back to \c Owner to
  200. /// tell it that its operand changed. This could trigger \c Owner being
  201. /// re-uniqued.
  202. static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
  203. return track(Ref, MD, &Owner);
  204. }
  205. /// Track the reference to metadata for \a MetadataAsValue.
  206. ///
  207. /// As \a track(Metadata*&), but with support for calling back to \c Owner to
  208. /// tell it that its operand changed. This could trigger \c Owner being
  209. /// re-uniqued.
  210. static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
  211. return track(Ref, MD, &Owner);
  212. }
  213. /// Stop tracking a reference to metadata.
  214. ///
  215. /// Stops \c *MD from tracking \c MD.
  216. static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
  217. static void untrack(void *Ref, Metadata &MD);
  218. /// Move tracking from one reference to another.
  219. ///
  220. /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
  221. /// except that ownership callbacks are maintained.
  222. ///
  223. /// Note: it is an error if \c *MD does not equal \c New.
  224. ///
  225. /// \return true iff tracking is supported by \c MD.
  226. static bool retrack(Metadata *&MD, Metadata *&New) {
  227. return retrack(&MD, *MD, &New);
  228. }
  229. static bool retrack(void *Ref, Metadata &MD, void *New);
  230. /// Check whether metadata is replaceable.
  231. static bool isReplaceable(const Metadata &MD);
  232. using OwnerTy = PointerUnion<MetadataAsValue *, Metadata *>;
  233. private:
  234. /// Track a reference to metadata for an owner.
  235. ///
  236. /// Generalized version of tracking.
  237. static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
  238. };
  239. /// Shared implementation of use-lists for replaceable metadata.
  240. ///
  241. /// Most metadata cannot be RAUW'ed. This is a shared implementation of
  242. /// use-lists and associated API for the two that support it (\a ValueAsMetadata
  243. /// and \a TempMDNode).
  244. class ReplaceableMetadataImpl {
  245. friend class MetadataTracking;
  246. public:
  247. using OwnerTy = MetadataTracking::OwnerTy;
  248. private:
  249. LLVMContext &Context;
  250. uint64_t NextIndex = 0;
  251. SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
  252. public:
  253. ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
  254. ~ReplaceableMetadataImpl() {
  255. assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
  256. }
  257. LLVMContext &getContext() const { return Context; }
  258. /// Replace all uses of this with MD.
  259. ///
  260. /// Replace all uses of this with \c MD, which is allowed to be null.
  261. void replaceAllUsesWith(Metadata *MD);
  262. /// Returns the list of all DIArgList users of this.
  263. SmallVector<Metadata *> getAllArgListUsers();
  264. /// Resolve all uses of this.
  265. ///
  266. /// Resolve all uses of this, turning off RAUW permanently. If \c
  267. /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
  268. /// is resolved.
  269. void resolveAllUses(bool ResolveUsers = true);
  270. private:
  271. void addRef(void *Ref, OwnerTy Owner);
  272. void dropRef(void *Ref);
  273. void moveRef(void *Ref, void *New, const Metadata &MD);
  274. /// Lazily construct RAUW support on MD.
  275. ///
  276. /// If this is an unresolved MDNode, RAUW support will be created on-demand.
  277. /// ValueAsMetadata always has RAUW support.
  278. static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
  279. /// Get RAUW support on MD, if it exists.
  280. static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
  281. /// Check whether this node will support RAUW.
  282. ///
  283. /// Returns \c true unless getOrCreate() would return null.
  284. static bool isReplaceable(const Metadata &MD);
  285. };
  286. /// Value wrapper in the Metadata hierarchy.
  287. ///
  288. /// This is a custom value handle that allows other metadata to refer to
  289. /// classes in the Value hierarchy.
  290. ///
  291. /// Because of full uniquing support, each value is only wrapped by a single \a
  292. /// ValueAsMetadata object, so the lookup maps are far more efficient than
  293. /// those using ValueHandleBase.
  294. class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
  295. friend class ReplaceableMetadataImpl;
  296. friend class LLVMContextImpl;
  297. Value *V;
  298. /// Drop users without RAUW (during teardown).
  299. void dropUsers() {
  300. ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
  301. }
  302. protected:
  303. ValueAsMetadata(unsigned ID, Value *V)
  304. : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
  305. assert(V && "Expected valid value");
  306. }
  307. ~ValueAsMetadata() = default;
  308. public:
  309. static ValueAsMetadata *get(Value *V);
  310. static ConstantAsMetadata *getConstant(Value *C) {
  311. return cast<ConstantAsMetadata>(get(C));
  312. }
  313. static LocalAsMetadata *getLocal(Value *Local) {
  314. return cast<LocalAsMetadata>(get(Local));
  315. }
  316. static ValueAsMetadata *getIfExists(Value *V);
  317. static ConstantAsMetadata *getConstantIfExists(Value *C) {
  318. return cast_or_null<ConstantAsMetadata>(getIfExists(C));
  319. }
  320. static LocalAsMetadata *getLocalIfExists(Value *Local) {
  321. return cast_or_null<LocalAsMetadata>(getIfExists(Local));
  322. }
  323. Value *getValue() const { return V; }
  324. Type *getType() const { return V->getType(); }
  325. LLVMContext &getContext() const { return V->getContext(); }
  326. SmallVector<Metadata *> getAllArgListUsers() {
  327. return ReplaceableMetadataImpl::getAllArgListUsers();
  328. }
  329. static void handleDeletion(Value *V);
  330. static void handleRAUW(Value *From, Value *To);
  331. protected:
  332. /// Handle collisions after \a Value::replaceAllUsesWith().
  333. ///
  334. /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
  335. /// \a Value gets RAUW'ed and the target already exists, this is used to
  336. /// merge the two metadata nodes.
  337. void replaceAllUsesWith(Metadata *MD) {
  338. ReplaceableMetadataImpl::replaceAllUsesWith(MD);
  339. }
  340. public:
  341. static bool classof(const Metadata *MD) {
  342. return MD->getMetadataID() == LocalAsMetadataKind ||
  343. MD->getMetadataID() == ConstantAsMetadataKind;
  344. }
  345. };
  346. class ConstantAsMetadata : public ValueAsMetadata {
  347. friend class ValueAsMetadata;
  348. ConstantAsMetadata(Constant *C)
  349. : ValueAsMetadata(ConstantAsMetadataKind, C) {}
  350. public:
  351. static ConstantAsMetadata *get(Constant *C) {
  352. return ValueAsMetadata::getConstant(C);
  353. }
  354. static ConstantAsMetadata *getIfExists(Constant *C) {
  355. return ValueAsMetadata::getConstantIfExists(C);
  356. }
  357. Constant *getValue() const {
  358. return cast<Constant>(ValueAsMetadata::getValue());
  359. }
  360. static bool classof(const Metadata *MD) {
  361. return MD->getMetadataID() == ConstantAsMetadataKind;
  362. }
  363. };
  364. class LocalAsMetadata : public ValueAsMetadata {
  365. friend class ValueAsMetadata;
  366. LocalAsMetadata(Value *Local)
  367. : ValueAsMetadata(LocalAsMetadataKind, Local) {
  368. assert(!isa<Constant>(Local) && "Expected local value");
  369. }
  370. public:
  371. static LocalAsMetadata *get(Value *Local) {
  372. return ValueAsMetadata::getLocal(Local);
  373. }
  374. static LocalAsMetadata *getIfExists(Value *Local) {
  375. return ValueAsMetadata::getLocalIfExists(Local);
  376. }
  377. static bool classof(const Metadata *MD) {
  378. return MD->getMetadataID() == LocalAsMetadataKind;
  379. }
  380. };
  381. /// Transitional API for extracting constants from Metadata.
  382. ///
  383. /// This namespace contains transitional functions for metadata that points to
  384. /// \a Constants.
  385. ///
  386. /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
  387. /// operands could refer to any \a Value. There's was a lot of code like this:
  388. ///
  389. /// \code
  390. /// MDNode *N = ...;
  391. /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
  392. /// \endcode
  393. ///
  394. /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
  395. /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
  396. /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
  397. /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
  398. /// requires subtle control flow changes.
  399. ///
  400. /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
  401. /// so that metadata can refer to numbers without traversing a bridge to the \a
  402. /// Value hierarchy. In this final state, the code above would look like this:
  403. ///
  404. /// \code
  405. /// MDNode *N = ...;
  406. /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
  407. /// \endcode
  408. ///
  409. /// The API in this namespace supports the transition. \a MDInt doesn't exist
  410. /// yet, and even once it does, changing each metadata schema to use it is its
  411. /// own mini-project. In the meantime this API prevents us from introducing
  412. /// complex and bug-prone control flow that will disappear in the end. In
  413. /// particular, the above code looks like this:
  414. ///
  415. /// \code
  416. /// MDNode *N = ...;
  417. /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
  418. /// \endcode
  419. ///
  420. /// The full set of provided functions includes:
  421. ///
  422. /// mdconst::hasa <=> isa
  423. /// mdconst::extract <=> cast
  424. /// mdconst::extract_or_null <=> cast_or_null
  425. /// mdconst::dyn_extract <=> dyn_cast
  426. /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
  427. ///
  428. /// The target of the cast must be a subclass of \a Constant.
  429. namespace mdconst {
  430. namespace detail {
  431. template <class T> T &make();
  432. template <class T, class Result> struct HasDereference {
  433. using Yes = char[1];
  434. using No = char[2];
  435. template <size_t N> struct SFINAE {};
  436. template <class U, class V>
  437. static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
  438. template <class U, class V> static No &hasDereference(...);
  439. static const bool value =
  440. sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
  441. };
  442. template <class V, class M> struct IsValidPointer {
  443. static const bool value = std::is_base_of<Constant, V>::value &&
  444. HasDereference<M, const Metadata &>::value;
  445. };
  446. template <class V, class M> struct IsValidReference {
  447. static const bool value = std::is_base_of<Constant, V>::value &&
  448. std::is_convertible<M, const Metadata &>::value;
  449. };
  450. } // end namespace detail
  451. /// Check whether Metadata has a Value.
  452. ///
  453. /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
  454. /// type \c X.
  455. template <class X, class Y>
  456. inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
  457. hasa(Y &&MD) {
  458. assert(MD && "Null pointer sent into hasa");
  459. if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
  460. return isa<X>(V->getValue());
  461. return false;
  462. }
  463. template <class X, class Y>
  464. inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
  465. hasa(Y &MD) {
  466. return hasa(&MD);
  467. }
  468. /// Extract a Value from Metadata.
  469. ///
  470. /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
  471. template <class X, class Y>
  472. inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
  473. extract(Y &&MD) {
  474. return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
  475. }
  476. template <class X, class Y>
  477. inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
  478. extract(Y &MD) {
  479. return extract(&MD);
  480. }
  481. /// Extract a Value from Metadata, allowing null.
  482. ///
  483. /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
  484. /// from \c MD, allowing \c MD to be null.
  485. template <class X, class Y>
  486. inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
  487. extract_or_null(Y &&MD) {
  488. if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
  489. return cast<X>(V->getValue());
  490. return nullptr;
  491. }
  492. /// Extract a Value from Metadata, if any.
  493. ///
  494. /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
  495. /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
  496. /// Value it does contain is of the wrong subclass.
  497. template <class X, class Y>
  498. inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
  499. dyn_extract(Y &&MD) {
  500. if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
  501. return dyn_cast<X>(V->getValue());
  502. return nullptr;
  503. }
  504. /// Extract a Value from Metadata, if any, allowing null.
  505. ///
  506. /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
  507. /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
  508. /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
  509. template <class X, class Y>
  510. inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
  511. dyn_extract_or_null(Y &&MD) {
  512. if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
  513. return dyn_cast<X>(V->getValue());
  514. return nullptr;
  515. }
  516. } // end namespace mdconst
  517. //===----------------------------------------------------------------------===//
  518. /// A single uniqued string.
  519. ///
  520. /// These are used to efficiently contain a byte sequence for metadata.
  521. /// MDString is always unnamed.
  522. class MDString : public Metadata {
  523. friend class StringMapEntryStorage<MDString>;
  524. StringMapEntry<MDString> *Entry = nullptr;
  525. MDString() : Metadata(MDStringKind, Uniqued) {}
  526. public:
  527. MDString(const MDString &) = delete;
  528. MDString &operator=(MDString &&) = delete;
  529. MDString &operator=(const MDString &) = delete;
  530. static MDString *get(LLVMContext &Context, StringRef Str);
  531. static MDString *get(LLVMContext &Context, const char *Str) {
  532. return get(Context, Str ? StringRef(Str) : StringRef());
  533. }
  534. StringRef getString() const;
  535. unsigned getLength() const { return (unsigned)getString().size(); }
  536. using iterator = StringRef::iterator;
  537. /// Pointer to the first byte of the string.
  538. iterator begin() const { return getString().begin(); }
  539. /// Pointer to one byte past the end of the string.
  540. iterator end() const { return getString().end(); }
  541. const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
  542. const unsigned char *bytes_end() const { return getString().bytes_end(); }
  543. /// Methods for support type inquiry through isa, cast, and dyn_cast.
  544. static bool classof(const Metadata *MD) {
  545. return MD->getMetadataID() == MDStringKind;
  546. }
  547. };
  548. /// A collection of metadata nodes that might be associated with a
  549. /// memory access used by the alias-analysis infrastructure.
  550. struct AAMDNodes {
  551. explicit AAMDNodes() = default;
  552. explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N)
  553. : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N) {}
  554. bool operator==(const AAMDNodes &A) const {
  555. return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
  556. NoAlias == A.NoAlias;
  557. }
  558. bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
  559. explicit operator bool() const {
  560. return TBAA || TBAAStruct || Scope || NoAlias;
  561. }
  562. /// The tag for type-based alias analysis.
  563. MDNode *TBAA = nullptr;
  564. /// The tag for type-based alias analysis (tbaa struct).
  565. MDNode *TBAAStruct = nullptr;
  566. /// The tag for alias scope specification (used with noalias).
  567. MDNode *Scope = nullptr;
  568. /// The tag specifying the noalias scope.
  569. MDNode *NoAlias = nullptr;
  570. // Shift tbaa Metadata node to start off bytes later
  571. static MDNode *shiftTBAA(MDNode *M, size_t off);
  572. // Shift tbaa.struct Metadata node to start off bytes later
  573. static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
  574. // Extend tbaa Metadata node to apply to a series of bytes of length len.
  575. // A size of -1 denotes an unknown size.
  576. static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
  577. /// Given two sets of AAMDNodes that apply to the same pointer,
  578. /// give the best AAMDNodes that are compatible with both (i.e. a set of
  579. /// nodes whose allowable aliasing conclusions are a subset of those
  580. /// allowable by both of the inputs). However, for efficiency
  581. /// reasons, do not create any new MDNodes.
  582. AAMDNodes intersect(const AAMDNodes &Other) const {
  583. AAMDNodes Result;
  584. Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
  585. Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
  586. Result.Scope = Other.Scope == Scope ? Scope : nullptr;
  587. Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
  588. return Result;
  589. }
  590. /// Create a new AAMDNode that describes this AAMDNode after applying a
  591. /// constant offset to the start of the pointer.
  592. AAMDNodes shift(size_t Offset) const {
  593. AAMDNodes Result;
  594. Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
  595. Result.TBAAStruct =
  596. TBAAStruct ? shiftTBAAStruct(TBAAStruct, Offset) : nullptr;
  597. Result.Scope = Scope;
  598. Result.NoAlias = NoAlias;
  599. return Result;
  600. }
  601. /// Create a new AAMDNode that describes this AAMDNode after extending it to
  602. /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
  603. /// size.
  604. AAMDNodes extendTo(ssize_t Len) const {
  605. AAMDNodes Result;
  606. Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
  607. // tbaa.struct contains (offset, size, type) triples. Extending the length
  608. // of the tbaa.struct doesn't require changing this (though more information
  609. // could be provided by adding more triples at subsequent lengths).
  610. Result.TBAAStruct = TBAAStruct;
  611. Result.Scope = Scope;
  612. Result.NoAlias = NoAlias;
  613. return Result;
  614. }
  615. /// Given two sets of AAMDNodes applying to potentially different locations,
  616. /// determine the best AAMDNodes that apply to both.
  617. AAMDNodes merge(const AAMDNodes &Other) const;
  618. /// Determine the best AAMDNodes after concatenating two different locations
  619. /// together. Different from `merge`, where different locations should
  620. /// overlap each other, `concat` puts non-overlapping locations together.
  621. AAMDNodes concat(const AAMDNodes &Other) const;
  622. };
  623. // Specialize DenseMapInfo for AAMDNodes.
  624. template<>
  625. struct DenseMapInfo<AAMDNodes> {
  626. static inline AAMDNodes getEmptyKey() {
  627. return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
  628. nullptr, nullptr, nullptr);
  629. }
  630. static inline AAMDNodes getTombstoneKey() {
  631. return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
  632. nullptr, nullptr, nullptr);
  633. }
  634. static unsigned getHashValue(const AAMDNodes &Val) {
  635. return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
  636. DenseMapInfo<MDNode *>::getHashValue(Val.TBAAStruct) ^
  637. DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
  638. DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
  639. }
  640. static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
  641. return LHS == RHS;
  642. }
  643. };
  644. /// Tracking metadata reference owned by Metadata.
  645. ///
  646. /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
  647. /// of \a Metadata, which has the option of registering itself for callbacks to
  648. /// re-unique itself.
  649. ///
  650. /// In particular, this is used by \a MDNode.
  651. class MDOperand {
  652. Metadata *MD = nullptr;
  653. public:
  654. MDOperand() = default;
  655. MDOperand(MDOperand &&) = delete;
  656. MDOperand(const MDOperand &) = delete;
  657. MDOperand &operator=(MDOperand &&) = delete;
  658. MDOperand &operator=(const MDOperand &) = delete;
  659. ~MDOperand() { untrack(); }
  660. Metadata *get() const { return MD; }
  661. operator Metadata *() const { return get(); }
  662. Metadata *operator->() const { return get(); }
  663. Metadata &operator*() const { return *get(); }
  664. void reset() {
  665. untrack();
  666. MD = nullptr;
  667. }
  668. void reset(Metadata *MD, Metadata *Owner) {
  669. untrack();
  670. this->MD = MD;
  671. track(Owner);
  672. }
  673. private:
  674. void track(Metadata *Owner) {
  675. if (MD) {
  676. if (Owner)
  677. MetadataTracking::track(this, *MD, *Owner);
  678. else
  679. MetadataTracking::track(MD);
  680. }
  681. }
  682. void untrack() {
  683. assert(static_cast<void *>(this) == &MD && "Expected same address");
  684. if (MD)
  685. MetadataTracking::untrack(MD);
  686. }
  687. };
  688. template <> struct simplify_type<MDOperand> {
  689. using SimpleType = Metadata *;
  690. static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
  691. };
  692. template <> struct simplify_type<const MDOperand> {
  693. using SimpleType = Metadata *;
  694. static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
  695. };
  696. /// Pointer to the context, with optional RAUW support.
  697. ///
  698. /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
  699. /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
  700. class ContextAndReplaceableUses {
  701. PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
  702. public:
  703. ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
  704. ContextAndReplaceableUses(
  705. std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
  706. : Ptr(ReplaceableUses.release()) {
  707. assert(getReplaceableUses() && "Expected non-null replaceable uses");
  708. }
  709. ContextAndReplaceableUses() = delete;
  710. ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
  711. ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
  712. ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
  713. ContextAndReplaceableUses &
  714. operator=(const ContextAndReplaceableUses &) = delete;
  715. ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
  716. operator LLVMContext &() { return getContext(); }
  717. /// Whether this contains RAUW support.
  718. bool hasReplaceableUses() const {
  719. return Ptr.is<ReplaceableMetadataImpl *>();
  720. }
  721. LLVMContext &getContext() const {
  722. if (hasReplaceableUses())
  723. return getReplaceableUses()->getContext();
  724. return *Ptr.get<LLVMContext *>();
  725. }
  726. ReplaceableMetadataImpl *getReplaceableUses() const {
  727. if (hasReplaceableUses())
  728. return Ptr.get<ReplaceableMetadataImpl *>();
  729. return nullptr;
  730. }
  731. /// Ensure that this has RAUW support, and then return it.
  732. ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
  733. if (!hasReplaceableUses())
  734. makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
  735. return getReplaceableUses();
  736. }
  737. /// Assign RAUW support to this.
  738. ///
  739. /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
  740. /// not be null).
  741. void
  742. makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
  743. assert(ReplaceableUses && "Expected non-null replaceable uses");
  744. assert(&ReplaceableUses->getContext() == &getContext() &&
  745. "Expected same context");
  746. delete getReplaceableUses();
  747. Ptr = ReplaceableUses.release();
  748. }
  749. /// Drop RAUW support.
  750. ///
  751. /// Cede ownership of RAUW support, returning it.
  752. std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
  753. assert(hasReplaceableUses() && "Expected to own replaceable uses");
  754. std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
  755. getReplaceableUses());
  756. Ptr = &ReplaceableUses->getContext();
  757. return ReplaceableUses;
  758. }
  759. };
  760. struct TempMDNodeDeleter {
  761. inline void operator()(MDNode *Node) const;
  762. };
  763. #define HANDLE_MDNODE_LEAF(CLASS) \
  764. using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
  765. #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
  766. #include "llvm/IR/Metadata.def"
  767. /// Metadata node.
  768. ///
  769. /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
  770. /// metadata nodes (with full support for RAUW) can be used to delay uniquing
  771. /// until forward references are known. The basic metadata node is an \a
  772. /// MDTuple.
  773. ///
  774. /// There is limited support for RAUW at construction time. At construction
  775. /// time, if any operand is a temporary node (or an unresolved uniqued node,
  776. /// which indicates a transitive temporary operand), the node itself will be
  777. /// unresolved. As soon as all operands become resolved, it will drop RAUW
  778. /// support permanently.
  779. ///
  780. /// If an unresolved node is part of a cycle, \a resolveCycles() needs
  781. /// to be called on some member of the cycle once all temporary nodes have been
  782. /// replaced.
  783. class MDNode : public Metadata {
  784. friend class ReplaceableMetadataImpl;
  785. friend class LLVMContextImpl;
  786. friend class DIArgList;
  787. unsigned NumOperands;
  788. unsigned NumUnresolved;
  789. ContextAndReplaceableUses Context;
  790. protected:
  791. MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  792. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
  793. ~MDNode() = default;
  794. void *operator new(size_t Size, unsigned NumOps);
  795. void operator delete(void *Mem);
  796. /// Required by std, but never called.
  797. void operator delete(void *, unsigned) {
  798. llvm_unreachable("Constructor throws?");
  799. }
  800. /// Required by std, but never called.
  801. void operator delete(void *, unsigned, bool) {
  802. llvm_unreachable("Constructor throws?");
  803. }
  804. void dropAllReferences();
  805. MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
  806. MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
  807. using mutable_op_range = iterator_range<MDOperand *>;
  808. mutable_op_range mutable_operands() {
  809. return mutable_op_range(mutable_begin(), mutable_end());
  810. }
  811. public:
  812. MDNode(const MDNode &) = delete;
  813. void operator=(const MDNode &) = delete;
  814. void *operator new(size_t) = delete;
  815. static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
  816. static inline MDTuple *getIfExists(LLVMContext &Context,
  817. ArrayRef<Metadata *> MDs);
  818. static inline MDTuple *getDistinct(LLVMContext &Context,
  819. ArrayRef<Metadata *> MDs);
  820. static inline TempMDTuple getTemporary(LLVMContext &Context,
  821. ArrayRef<Metadata *> MDs);
  822. /// Create a (temporary) clone of this.
  823. TempMDNode clone() const;
  824. /// Deallocate a node created by getTemporary.
  825. ///
  826. /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
  827. /// references will be reset.
  828. static void deleteTemporary(MDNode *N);
  829. LLVMContext &getContext() const { return Context.getContext(); }
  830. /// Replace a specific operand.
  831. void replaceOperandWith(unsigned I, Metadata *New);
  832. /// Check if node is fully resolved.
  833. ///
  834. /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
  835. /// this always returns \c true.
  836. ///
  837. /// If \a isUniqued(), returns \c true if this has already dropped RAUW
  838. /// support (because all operands are resolved).
  839. ///
  840. /// As forward declarations are resolved, their containers should get
  841. /// resolved automatically. However, if this (or one of its operands) is
  842. /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
  843. bool isResolved() const { return !isTemporary() && !NumUnresolved; }
  844. bool isUniqued() const { return Storage == Uniqued; }
  845. bool isDistinct() const { return Storage == Distinct; }
  846. bool isTemporary() const { return Storage == Temporary; }
  847. /// RAUW a temporary.
  848. ///
  849. /// \pre \a isTemporary() must be \c true.
  850. void replaceAllUsesWith(Metadata *MD) {
  851. assert(isTemporary() && "Expected temporary node");
  852. if (Context.hasReplaceableUses())
  853. Context.getReplaceableUses()->replaceAllUsesWith(MD);
  854. }
  855. /// Resolve cycles.
  856. ///
  857. /// Once all forward declarations have been resolved, force cycles to be
  858. /// resolved.
  859. ///
  860. /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
  861. void resolveCycles();
  862. /// Resolve a unique, unresolved node.
  863. void resolve();
  864. /// Replace a temporary node with a permanent one.
  865. ///
  866. /// Try to create a uniqued version of \c N -- in place, if possible -- and
  867. /// return it. If \c N cannot be uniqued, return a distinct node instead.
  868. template <class T>
  869. static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
  870. replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
  871. return cast<T>(N.release()->replaceWithPermanentImpl());
  872. }
  873. /// Replace a temporary node with a uniqued one.
  874. ///
  875. /// Create a uniqued version of \c N -- in place, if possible -- and return
  876. /// it. Takes ownership of the temporary node.
  877. ///
  878. /// \pre N does not self-reference.
  879. template <class T>
  880. static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
  881. replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
  882. return cast<T>(N.release()->replaceWithUniquedImpl());
  883. }
  884. /// Replace a temporary node with a distinct one.
  885. ///
  886. /// Create a distinct version of \c N -- in place, if possible -- and return
  887. /// it. Takes ownership of the temporary node.
  888. template <class T>
  889. static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
  890. replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
  891. return cast<T>(N.release()->replaceWithDistinctImpl());
  892. }
  893. /// Print in tree shape.
  894. ///
  895. /// Prints definition of \c this in tree shape.
  896. ///
  897. /// If \c M is provided, metadata nodes will be numbered canonically;
  898. /// otherwise, pointer addresses are substituted.
  899. /// @{
  900. void printTree(raw_ostream &OS, const Module *M = nullptr) const;
  901. void printTree(raw_ostream &OS, ModuleSlotTracker &MST,
  902. const Module *M = nullptr) const;
  903. /// @}
  904. /// User-friendly dump in tree shape.
  905. ///
  906. /// If \c M is provided, metadata nodes will be numbered canonically;
  907. /// otherwise, pointer addresses are substituted.
  908. ///
  909. /// Note: this uses an explicit overload instead of default arguments so that
  910. /// the nullptr version is easy to call from a debugger.
  911. ///
  912. /// @{
  913. void dumpTree() const;
  914. void dumpTree(const Module *M) const;
  915. /// @}
  916. private:
  917. MDNode *replaceWithPermanentImpl();
  918. MDNode *replaceWithUniquedImpl();
  919. MDNode *replaceWithDistinctImpl();
  920. protected:
  921. /// Set an operand.
  922. ///
  923. /// Sets the operand directly, without worrying about uniquing.
  924. void setOperand(unsigned I, Metadata *New);
  925. void storeDistinctInContext();
  926. template <class T, class StoreT>
  927. static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
  928. template <class T> static T *storeImpl(T *N, StorageType Storage);
  929. private:
  930. void handleChangedOperand(void *Ref, Metadata *New);
  931. /// Drop RAUW support, if any.
  932. void dropReplaceableUses();
  933. void resolveAfterOperandChange(Metadata *Old, Metadata *New);
  934. void decrementUnresolvedOperandCount();
  935. void countUnresolvedOperands();
  936. /// Mutate this to be "uniqued".
  937. ///
  938. /// Mutate this so that \a isUniqued().
  939. /// \pre \a isTemporary().
  940. /// \pre already added to uniquing set.
  941. void makeUniqued();
  942. /// Mutate this to be "distinct".
  943. ///
  944. /// Mutate this so that \a isDistinct().
  945. /// \pre \a isTemporary().
  946. void makeDistinct();
  947. void deleteAsSubclass();
  948. MDNode *uniquify();
  949. void eraseFromStore();
  950. template <class NodeTy> struct HasCachedHash;
  951. template <class NodeTy>
  952. static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
  953. N->recalculateHash();
  954. }
  955. template <class NodeTy>
  956. static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
  957. template <class NodeTy>
  958. static void dispatchResetHash(NodeTy *N, std::true_type) {
  959. N->setHash(0);
  960. }
  961. template <class NodeTy>
  962. static void dispatchResetHash(NodeTy *, std::false_type) {}
  963. public:
  964. using op_iterator = const MDOperand *;
  965. using op_range = iterator_range<op_iterator>;
  966. op_iterator op_begin() const {
  967. return const_cast<MDNode *>(this)->mutable_begin();
  968. }
  969. op_iterator op_end() const {
  970. return const_cast<MDNode *>(this)->mutable_end();
  971. }
  972. op_range operands() const { return op_range(op_begin(), op_end()); }
  973. const MDOperand &getOperand(unsigned I) const {
  974. assert(I < NumOperands && "Out of range");
  975. return op_begin()[I];
  976. }
  977. /// Return number of MDNode operands.
  978. unsigned getNumOperands() const { return NumOperands; }
  979. /// Methods for support type inquiry through isa, cast, and dyn_cast:
  980. static bool classof(const Metadata *MD) {
  981. switch (MD->getMetadataID()) {
  982. default:
  983. return false;
  984. #define HANDLE_MDNODE_LEAF(CLASS) \
  985. case CLASS##Kind: \
  986. return true;
  987. #include "llvm/IR/Metadata.def"
  988. }
  989. }
  990. /// Check whether MDNode is a vtable access.
  991. bool isTBAAVtableAccess() const;
  992. /// Methods for metadata merging.
  993. static MDNode *concatenate(MDNode *A, MDNode *B);
  994. static MDNode *intersect(MDNode *A, MDNode *B);
  995. static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
  996. static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
  997. static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
  998. static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
  999. static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
  1000. };
  1001. /// Tuple of metadata.
  1002. ///
  1003. /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
  1004. /// default based on their operands.
  1005. class MDTuple : public MDNode {
  1006. friend class LLVMContextImpl;
  1007. friend class MDNode;
  1008. MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
  1009. ArrayRef<Metadata *> Vals)
  1010. : MDNode(C, MDTupleKind, Storage, Vals) {
  1011. setHash(Hash);
  1012. }
  1013. ~MDTuple() { dropAllReferences(); }
  1014. void setHash(unsigned Hash) { SubclassData32 = Hash; }
  1015. void recalculateHash();
  1016. static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  1017. StorageType Storage, bool ShouldCreate = true);
  1018. TempMDTuple cloneImpl() const {
  1019. return getTemporary(getContext(), SmallVector<Metadata *, 4>(operands()));
  1020. }
  1021. public:
  1022. /// Get the hash, if any.
  1023. unsigned getHash() const { return SubclassData32; }
  1024. static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1025. return getImpl(Context, MDs, Uniqued);
  1026. }
  1027. static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1028. return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
  1029. }
  1030. /// Return a distinct node.
  1031. ///
  1032. /// Return a distinct node -- i.e., a node that is not uniqued.
  1033. static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1034. return getImpl(Context, MDs, Distinct);
  1035. }
  1036. /// Return a temporary node.
  1037. ///
  1038. /// For use in constructing cyclic MDNode structures. A temporary MDNode is
  1039. /// not uniqued, may be RAUW'd, and must be manually deleted with
  1040. /// deleteTemporary.
  1041. static TempMDTuple getTemporary(LLVMContext &Context,
  1042. ArrayRef<Metadata *> MDs) {
  1043. return TempMDTuple(getImpl(Context, MDs, Temporary));
  1044. }
  1045. /// Return a (temporary) clone of this.
  1046. TempMDTuple clone() const { return cloneImpl(); }
  1047. static bool classof(const Metadata *MD) {
  1048. return MD->getMetadataID() == MDTupleKind;
  1049. }
  1050. };
  1051. MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1052. return MDTuple::get(Context, MDs);
  1053. }
  1054. MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1055. return MDTuple::getIfExists(Context, MDs);
  1056. }
  1057. MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  1058. return MDTuple::getDistinct(Context, MDs);
  1059. }
  1060. TempMDTuple MDNode::getTemporary(LLVMContext &Context,
  1061. ArrayRef<Metadata *> MDs) {
  1062. return MDTuple::getTemporary(Context, MDs);
  1063. }
  1064. void TempMDNodeDeleter::operator()(MDNode *Node) const {
  1065. MDNode::deleteTemporary(Node);
  1066. }
  1067. /// This is a simple wrapper around an MDNode which provides a higher-level
  1068. /// interface by hiding the details of how alias analysis information is encoded
  1069. /// in its operands.
  1070. class AliasScopeNode {
  1071. const MDNode *Node = nullptr;
  1072. public:
  1073. AliasScopeNode() = default;
  1074. explicit AliasScopeNode(const MDNode *N) : Node(N) {}
  1075. /// Get the MDNode for this AliasScopeNode.
  1076. const MDNode *getNode() const { return Node; }
  1077. /// Get the MDNode for this AliasScopeNode's domain.
  1078. const MDNode *getDomain() const {
  1079. if (Node->getNumOperands() < 2)
  1080. return nullptr;
  1081. return dyn_cast_or_null<MDNode>(Node->getOperand(1));
  1082. }
  1083. StringRef getName() const {
  1084. if (Node->getNumOperands() > 2)
  1085. if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
  1086. return N->getString();
  1087. return StringRef();
  1088. }
  1089. };
  1090. /// Typed iterator through MDNode operands.
  1091. ///
  1092. /// An iterator that transforms an \a MDNode::iterator into an iterator over a
  1093. /// particular Metadata subclass.
  1094. template <class T> class TypedMDOperandIterator {
  1095. MDNode::op_iterator I = nullptr;
  1096. public:
  1097. using iterator_category = std::input_iterator_tag;
  1098. using value_type = T *;
  1099. using difference_type = std::ptrdiff_t;
  1100. using pointer = void;
  1101. using reference = T *;
  1102. TypedMDOperandIterator() = default;
  1103. explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
  1104. T *operator*() const { return cast_or_null<T>(*I); }
  1105. TypedMDOperandIterator &operator++() {
  1106. ++I;
  1107. return *this;
  1108. }
  1109. TypedMDOperandIterator operator++(int) {
  1110. TypedMDOperandIterator Temp(*this);
  1111. ++I;
  1112. return Temp;
  1113. }
  1114. bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
  1115. bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
  1116. };
  1117. /// Typed, array-like tuple of metadata.
  1118. ///
  1119. /// This is a wrapper for \a MDTuple that makes it act like an array holding a
  1120. /// particular type of metadata.
  1121. template <class T> class MDTupleTypedArrayWrapper {
  1122. const MDTuple *N = nullptr;
  1123. public:
  1124. MDTupleTypedArrayWrapper() = default;
  1125. MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
  1126. template <class U>
  1127. MDTupleTypedArrayWrapper(
  1128. const MDTupleTypedArrayWrapper<U> &Other,
  1129. std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
  1130. : N(Other.get()) {}
  1131. template <class U>
  1132. explicit MDTupleTypedArrayWrapper(
  1133. const MDTupleTypedArrayWrapper<U> &Other,
  1134. std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
  1135. : N(Other.get()) {}
  1136. explicit operator bool() const { return get(); }
  1137. explicit operator MDTuple *() const { return get(); }
  1138. MDTuple *get() const { return const_cast<MDTuple *>(N); }
  1139. MDTuple *operator->() const { return get(); }
  1140. MDTuple &operator*() const { return *get(); }
  1141. // FIXME: Fix callers and remove condition on N.
  1142. unsigned size() const { return N ? N->getNumOperands() : 0u; }
  1143. bool empty() const { return N ? N->getNumOperands() == 0 : true; }
  1144. T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
  1145. // FIXME: Fix callers and remove condition on N.
  1146. using iterator = TypedMDOperandIterator<T>;
  1147. iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
  1148. iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
  1149. };
  1150. #define HANDLE_METADATA(CLASS) \
  1151. using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
  1152. #include "llvm/IR/Metadata.def"
  1153. /// Placeholder metadata for operands of distinct MDNodes.
  1154. ///
  1155. /// This is a lightweight placeholder for an operand of a distinct node. It's
  1156. /// purpose is to help track forward references when creating a distinct node.
  1157. /// This allows distinct nodes involved in a cycle to be constructed before
  1158. /// their operands without requiring a heavyweight temporary node with
  1159. /// full-blown RAUW support.
  1160. ///
  1161. /// Each placeholder supports only a single MDNode user. Clients should pass
  1162. /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
  1163. /// should be replaced with.
  1164. ///
  1165. /// While it would be possible to implement move operators, they would be
  1166. /// fairly expensive. Leave them unimplemented to discourage their use
  1167. /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
  1168. class DistinctMDOperandPlaceholder : public Metadata {
  1169. friend class MetadataTracking;
  1170. Metadata **Use = nullptr;
  1171. public:
  1172. explicit DistinctMDOperandPlaceholder(unsigned ID)
  1173. : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
  1174. SubclassData32 = ID;
  1175. }
  1176. DistinctMDOperandPlaceholder() = delete;
  1177. DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
  1178. DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
  1179. ~DistinctMDOperandPlaceholder() {
  1180. if (Use)
  1181. *Use = nullptr;
  1182. }
  1183. unsigned getID() const { return SubclassData32; }
  1184. /// Replace the use of this with MD.
  1185. void replaceUseWith(Metadata *MD) {
  1186. if (!Use)
  1187. return;
  1188. *Use = MD;
  1189. if (*Use)
  1190. MetadataTracking::track(*Use);
  1191. Metadata *T = cast<Metadata>(this);
  1192. MetadataTracking::untrack(T);
  1193. assert(!Use && "Use is still being tracked despite being untracked!");
  1194. }
  1195. };
  1196. //===----------------------------------------------------------------------===//
  1197. /// A tuple of MDNodes.
  1198. ///
  1199. /// Despite its name, a NamedMDNode isn't itself an MDNode.
  1200. ///
  1201. /// NamedMDNodes are named module-level entities that contain lists of MDNodes.
  1202. ///
  1203. /// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
  1204. class NamedMDNode : public ilist_node<NamedMDNode> {
  1205. friend class LLVMContextImpl;
  1206. friend class Module;
  1207. std::string Name;
  1208. Module *Parent = nullptr;
  1209. void *Operands; // SmallVector<TrackingMDRef, 4>
  1210. void setParent(Module *M) { Parent = M; }
  1211. explicit NamedMDNode(const Twine &N);
  1212. template <class T1, class T2> class op_iterator_impl {
  1213. friend class NamedMDNode;
  1214. const NamedMDNode *Node = nullptr;
  1215. unsigned Idx = 0;
  1216. op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
  1217. public:
  1218. using iterator_category = std::bidirectional_iterator_tag;
  1219. using value_type = T2;
  1220. using difference_type = std::ptrdiff_t;
  1221. using pointer = value_type *;
  1222. using reference = value_type &;
  1223. op_iterator_impl() = default;
  1224. bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
  1225. bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
  1226. op_iterator_impl &operator++() {
  1227. ++Idx;
  1228. return *this;
  1229. }
  1230. op_iterator_impl operator++(int) {
  1231. op_iterator_impl tmp(*this);
  1232. operator++();
  1233. return tmp;
  1234. }
  1235. op_iterator_impl &operator--() {
  1236. --Idx;
  1237. return *this;
  1238. }
  1239. op_iterator_impl operator--(int) {
  1240. op_iterator_impl tmp(*this);
  1241. operator--();
  1242. return tmp;
  1243. }
  1244. T1 operator*() const { return Node->getOperand(Idx); }
  1245. };
  1246. public:
  1247. NamedMDNode(const NamedMDNode &) = delete;
  1248. ~NamedMDNode();
  1249. /// Drop all references and remove the node from parent module.
  1250. void eraseFromParent();
  1251. /// Remove all uses and clear node vector.
  1252. void dropAllReferences() { clearOperands(); }
  1253. /// Drop all references to this node's operands.
  1254. void clearOperands();
  1255. /// Get the module that holds this named metadata collection.
  1256. inline Module *getParent() { return Parent; }
  1257. inline const Module *getParent() const { return Parent; }
  1258. MDNode *getOperand(unsigned i) const;
  1259. unsigned getNumOperands() const;
  1260. void addOperand(MDNode *M);
  1261. void setOperand(unsigned I, MDNode *New);
  1262. StringRef getName() const;
  1263. void print(raw_ostream &ROS, bool IsForDebug = false) const;
  1264. void print(raw_ostream &ROS, ModuleSlotTracker &MST,
  1265. bool IsForDebug = false) const;
  1266. void dump() const;
  1267. // ---------------------------------------------------------------------------
  1268. // Operand Iterator interface...
  1269. //
  1270. using op_iterator = op_iterator_impl<MDNode *, MDNode>;
  1271. op_iterator op_begin() { return op_iterator(this, 0); }
  1272. op_iterator op_end() { return op_iterator(this, getNumOperands()); }
  1273. using const_op_iterator = op_iterator_impl<const MDNode *, MDNode>;
  1274. const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
  1275. const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
  1276. inline iterator_range<op_iterator> operands() {
  1277. return make_range(op_begin(), op_end());
  1278. }
  1279. inline iterator_range<const_op_iterator> operands() const {
  1280. return make_range(op_begin(), op_end());
  1281. }
  1282. };
  1283. // Create wrappers for C Binding types (see CBindingWrapping.h).
  1284. DEFINE_ISA_CONVERSION_FUNCTIONS(NamedMDNode, LLVMNamedMDNodeRef)
  1285. } // end namespace llvm
  1286. #endif // LLVM_IR_METADATA_H
  1287. #ifdef __GNUC__
  1288. #pragma GCC diagnostic pop
  1289. #endif