Metadata.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  1. //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- 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. /// @file
  11. /// This file contains the declarations for metadata subclasses.
  12. /// They represent the different flavors of metadata that live in LLVM.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_IR_METADATA_H
  16. #define LLVM_IR_METADATA_H
  17. #include "llvm/ADT/ArrayRef.h"
  18. #include "llvm/ADT/DenseMap.h"
  19. #include "llvm/ADT/ilist_node.h"
  20. #include "llvm/ADT/iterator_range.h"
  21. #include "llvm/IR/Constant.h"
  22. #include "llvm/IR/MetadataTracking.h"
  23. #include "llvm/IR/Value.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. #include <type_traits>
  26. namespace llvm {
  27. class LLVMContext;
  28. class Module;
  29. class ModuleSlotTracker;
  30. template<typename ValueSubClass, typename ItemParentClass>
  31. class SymbolTableListTraits;
  32. enum LLVMConstants : uint32_t {
  33. DEBUG_METADATA_VERSION = 3 // Current debug info version number.
  34. };
  35. /// \brief Root of the metadata hierarchy.
  36. ///
  37. /// This is a root class for typeless data in the IR.
  38. class Metadata {
  39. friend class ReplaceableMetadataImpl;
  40. /// \brief RTTI.
  41. const unsigned char SubclassID;
  42. protected:
  43. /// \brief Active type of storage.
  44. enum StorageType { Uniqued, Distinct, Temporary };
  45. /// \brief Storage flag for non-uniqued, otherwise unowned, metadata.
  46. unsigned Storage : 2;
  47. // TODO: expose remaining bits to subclasses.
  48. unsigned short SubclassData16;
  49. unsigned SubclassData32;
  50. public:
  51. enum MetadataKind {
  52. MDTupleKind,
  53. DILocationKind,
  54. GenericDINodeKind,
  55. DISubrangeKind,
  56. DIEnumeratorKind,
  57. DIBasicTypeKind,
  58. DIDerivedTypeKind,
  59. DICompositeTypeKind,
  60. DISubroutineTypeKind,
  61. DIFileKind,
  62. DICompileUnitKind,
  63. DISubprogramKind,
  64. DILexicalBlockKind,
  65. DILexicalBlockFileKind,
  66. DINamespaceKind,
  67. DIModuleKind,
  68. DITemplateTypeParameterKind,
  69. DITemplateValueParameterKind,
  70. DIGlobalVariableKind,
  71. DILocalVariableKind,
  72. DIExpressionKind,
  73. DIObjCPropertyKind,
  74. DIImportedEntityKind,
  75. ConstantAsMetadataKind,
  76. LocalAsMetadataKind,
  77. MDStringKind
  78. };
  79. protected:
  80. Metadata(unsigned ID, StorageType Storage)
  81. : SubclassID(ID), Storage(Storage), SubclassData16(0), SubclassData32(0) {
  82. }
  83. ~Metadata() = default;
  84. /// \brief Default handling of a changed operand, which asserts.
  85. ///
  86. /// If subclasses pass themselves in as owners to a tracking node reference,
  87. /// they must provide an implementation of this method.
  88. void handleChangedOperand(void *, Metadata *) {
  89. llvm_unreachable("Unimplemented in Metadata subclass");
  90. }
  91. public:
  92. unsigned getMetadataID() const { return SubclassID; }
  93. /// \brief User-friendly dump.
  94. ///
  95. /// If \c M is provided, metadata nodes will be numbered canonically;
  96. /// otherwise, pointer addresses are substituted.
  97. ///
  98. /// Note: this uses an explicit overload instead of default arguments so that
  99. /// the nullptr version is easy to call from a debugger.
  100. ///
  101. /// @{
  102. void dump() const;
  103. void dump(const Module *M) const;
  104. /// @}
  105. /// \brief Print.
  106. ///
  107. /// Prints definition of \c this.
  108. ///
  109. /// If \c M is provided, metadata nodes will be numbered canonically;
  110. /// otherwise, pointer addresses are substituted.
  111. /// @{
  112. void print(raw_ostream &OS, const Module *M = nullptr) const;
  113. void print(raw_ostream &OS, ModuleSlotTracker &MST,
  114. const Module *M = nullptr) const;
  115. /// @}
  116. /// \brief 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. #define HANDLE_METADATA(CLASS) class CLASS;
  129. #include "llvm/IR/Metadata.def"
  130. // Provide specializations of isa so that we don't need definitions of
  131. // subclasses to see if the metadata is a subclass.
  132. #define HANDLE_METADATA_LEAF(CLASS) \
  133. template <> struct isa_impl<CLASS, Metadata> { \
  134. static inline bool doit(const Metadata &MD) { \
  135. return MD.getMetadataID() == Metadata::CLASS##Kind; \
  136. } \
  137. };
  138. #include "llvm/IR/Metadata.def"
  139. inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
  140. MD.print(OS);
  141. return OS;
  142. }
  143. /// \brief Metadata wrapper in the Value hierarchy.
  144. ///
  145. /// A member of the \a Value hierarchy to represent a reference to metadata.
  146. /// This allows, e.g., instrinsics to have metadata as operands.
  147. ///
  148. /// Notably, this is the only thing in either hierarchy that is allowed to
  149. /// reference \a LocalAsMetadata.
  150. class MetadataAsValue : public Value {
  151. friend class ReplaceableMetadataImpl;
  152. friend class LLVMContextImpl;
  153. Metadata *MD;
  154. MetadataAsValue(Type *Ty, Metadata *MD);
  155. ~MetadataAsValue() override;
  156. /// \brief Drop use of metadata (during teardown).
  157. void dropUse() { MD = nullptr; }
  158. public:
  159. static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
  160. static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
  161. Metadata *getMetadata() const { return MD; }
  162. static bool classof(const Value *V) {
  163. return V->getValueID() == MetadataAsValueVal;
  164. }
  165. private:
  166. void handleChangedMetadata(Metadata *MD);
  167. void track();
  168. void untrack();
  169. };
  170. /// \brief Shared implementation of use-lists for replaceable metadata.
  171. ///
  172. /// Most metadata cannot be RAUW'ed. This is a shared implementation of
  173. /// use-lists and associated API for the two that support it (\a ValueAsMetadata
  174. /// and \a TempMDNode).
  175. class ReplaceableMetadataImpl {
  176. friend class MetadataTracking;
  177. public:
  178. typedef MetadataTracking::OwnerTy OwnerTy;
  179. private:
  180. LLVMContext &Context;
  181. uint64_t NextIndex;
  182. SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
  183. public:
  184. ReplaceableMetadataImpl(LLVMContext &Context)
  185. : Context(Context), NextIndex(0) {}
  186. ~ReplaceableMetadataImpl() {
  187. assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
  188. }
  189. LLVMContext &getContext() const { return Context; }
  190. /// \brief Replace all uses of this with MD.
  191. ///
  192. /// Replace all uses of this with \c MD, which is allowed to be null.
  193. void replaceAllUsesWith(Metadata *MD);
  194. /// \brief Resolve all uses of this.
  195. ///
  196. /// Resolve all uses of this, turning off RAUW permanently. If \c
  197. /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
  198. /// is resolved.
  199. void resolveAllUses(bool ResolveUsers = true);
  200. private:
  201. void addRef(void *Ref, OwnerTy Owner);
  202. void dropRef(void *Ref);
  203. void moveRef(void *Ref, void *New, const Metadata &MD);
  204. static ReplaceableMetadataImpl *get(Metadata &MD);
  205. };
  206. /// \brief Value wrapper in the Metadata hierarchy.
  207. ///
  208. /// This is a custom value handle that allows other metadata to refer to
  209. /// classes in the Value hierarchy.
  210. ///
  211. /// Because of full uniquing support, each value is only wrapped by a single \a
  212. /// ValueAsMetadata object, so the lookup maps are far more efficient than
  213. /// those using ValueHandleBase.
  214. class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
  215. friend class ReplaceableMetadataImpl;
  216. friend class LLVMContextImpl;
  217. Value *V;
  218. /// \brief Drop users without RAUW (during teardown).
  219. void dropUsers() {
  220. ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
  221. }
  222. protected:
  223. ValueAsMetadata(unsigned ID, Value *V)
  224. : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
  225. assert(V && "Expected valid value");
  226. }
  227. ~ValueAsMetadata() = default;
  228. public:
  229. static ValueAsMetadata *get(Value *V);
  230. static ConstantAsMetadata *getConstant(Value *C) {
  231. return cast<ConstantAsMetadata>(get(C));
  232. }
  233. static LocalAsMetadata *getLocal(Value *Local) {
  234. return cast<LocalAsMetadata>(get(Local));
  235. }
  236. static ValueAsMetadata *getIfExists(Value *V);
  237. static ConstantAsMetadata *getConstantIfExists(Value *C) {
  238. return cast_or_null<ConstantAsMetadata>(getIfExists(C));
  239. }
  240. static LocalAsMetadata *getLocalIfExists(Value *Local) {
  241. return cast_or_null<LocalAsMetadata>(getIfExists(Local));
  242. }
  243. Value *getValue() const { return V; }
  244. Type *getType() const { return V->getType(); }
  245. LLVMContext &getContext() const { return V->getContext(); }
  246. static void handleDeletion(Value *V);
  247. static void handleRAUW(Value *From, Value *To);
  248. protected:
  249. /// \brief Handle collisions after \a Value::replaceAllUsesWith().
  250. ///
  251. /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
  252. /// \a Value gets RAUW'ed and the target already exists, this is used to
  253. /// merge the two metadata nodes.
  254. void replaceAllUsesWith(Metadata *MD) {
  255. ReplaceableMetadataImpl::replaceAllUsesWith(MD);
  256. }
  257. public:
  258. static bool classof(const Metadata *MD) {
  259. return MD->getMetadataID() == LocalAsMetadataKind ||
  260. MD->getMetadataID() == ConstantAsMetadataKind;
  261. }
  262. };
  263. class ConstantAsMetadata : public ValueAsMetadata {
  264. friend class ValueAsMetadata;
  265. ConstantAsMetadata(Constant *C)
  266. : ValueAsMetadata(ConstantAsMetadataKind, C) {}
  267. public:
  268. static ConstantAsMetadata *get(Constant *C) {
  269. return ValueAsMetadata::getConstant(C);
  270. }
  271. static ConstantAsMetadata *getIfExists(Constant *C) {
  272. return ValueAsMetadata::getConstantIfExists(C);
  273. }
  274. Constant *getValue() const {
  275. return cast<Constant>(ValueAsMetadata::getValue());
  276. }
  277. static bool classof(const Metadata *MD) {
  278. return MD->getMetadataID() == ConstantAsMetadataKind;
  279. }
  280. };
  281. class LocalAsMetadata : public ValueAsMetadata {
  282. friend class ValueAsMetadata;
  283. LocalAsMetadata(Value *Local)
  284. : ValueAsMetadata(LocalAsMetadataKind, Local) {
  285. assert(!isa<Constant>(Local) && "Expected local value");
  286. }
  287. public:
  288. static LocalAsMetadata *get(Value *Local) {
  289. return ValueAsMetadata::getLocal(Local);
  290. }
  291. static LocalAsMetadata *getIfExists(Value *Local) {
  292. return ValueAsMetadata::getLocalIfExists(Local);
  293. }
  294. static bool classof(const Metadata *MD) {
  295. return MD->getMetadataID() == LocalAsMetadataKind;
  296. }
  297. };
  298. /// \brief Transitional API for extracting constants from Metadata.
  299. ///
  300. /// This namespace contains transitional functions for metadata that points to
  301. /// \a Constants.
  302. ///
  303. /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
  304. /// operands could refer to any \a Value. There's was a lot of code like this:
  305. ///
  306. /// \code
  307. /// MDNode *N = ...;
  308. /// auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
  309. /// \endcode
  310. ///
  311. /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
  312. /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
  313. /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
  314. /// cast in the \a Value hierarchy. Besides creating boiler-plate, this
  315. /// requires subtle control flow changes.
  316. ///
  317. /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
  318. /// so that metadata can refer to numbers without traversing a bridge to the \a
  319. /// Value hierarchy. In this final state, the code above would look like this:
  320. ///
  321. /// \code
  322. /// MDNode *N = ...;
  323. /// auto *MI = dyn_cast<MDInt>(N->getOperand(2));
  324. /// \endcode
  325. ///
  326. /// The API in this namespace supports the transition. \a MDInt doesn't exist
  327. /// yet, and even once it does, changing each metadata schema to use it is its
  328. /// own mini-project. In the meantime this API prevents us from introducing
  329. /// complex and bug-prone control flow that will disappear in the end. In
  330. /// particular, the above code looks like this:
  331. ///
  332. /// \code
  333. /// MDNode *N = ...;
  334. /// auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
  335. /// \endcode
  336. ///
  337. /// The full set of provided functions includes:
  338. ///
  339. /// mdconst::hasa <=> isa
  340. /// mdconst::extract <=> cast
  341. /// mdconst::extract_or_null <=> cast_or_null
  342. /// mdconst::dyn_extract <=> dyn_cast
  343. /// mdconst::dyn_extract_or_null <=> dyn_cast_or_null
  344. ///
  345. /// The target of the cast must be a subclass of \a Constant.
  346. namespace mdconst {
  347. namespace detail {
  348. template <class T> T &make();
  349. template <class T, class Result> struct HasDereference {
  350. typedef char Yes[1];
  351. typedef char No[2];
  352. template <size_t N> struct SFINAE {};
  353. template <class U, class V>
  354. static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
  355. template <class U, class V> static No &hasDereference(...);
  356. static const bool value =
  357. sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
  358. };
  359. template <class V, class M> struct IsValidPointer {
  360. static const bool value = std::is_base_of<Constant, V>::value &&
  361. HasDereference<M, const Metadata &>::value;
  362. };
  363. template <class V, class M> struct IsValidReference {
  364. static const bool value = std::is_base_of<Constant, V>::value &&
  365. std::is_convertible<M, const Metadata &>::value;
  366. };
  367. } // end namespace detail
  368. /// \brief Check whether Metadata has a Value.
  369. ///
  370. /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
  371. /// type \c X.
  372. template <class X, class Y>
  373. inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, bool>::type
  374. hasa(Y &&MD) {
  375. assert(MD && "Null pointer sent into hasa");
  376. if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
  377. return isa<X>(V->getValue());
  378. return false;
  379. }
  380. template <class X, class Y>
  381. inline
  382. typename std::enable_if<detail::IsValidReference<X, Y &>::value, bool>::type
  383. hasa(Y &MD) {
  384. return hasa(&MD);
  385. }
  386. /// \brief Extract a Value from Metadata.
  387. ///
  388. /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
  389. template <class X, class Y>
  390. inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
  391. extract(Y &&MD) {
  392. return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
  393. }
  394. template <class X, class Y>
  395. inline
  396. typename std::enable_if<detail::IsValidReference<X, Y &>::value, X *>::type
  397. extract(Y &MD) {
  398. return extract(&MD);
  399. }
  400. /// \brief Extract a Value from Metadata, allowing null.
  401. ///
  402. /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
  403. /// from \c MD, allowing \c MD to be null.
  404. template <class X, class Y>
  405. inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
  406. extract_or_null(Y &&MD) {
  407. if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
  408. return cast<X>(V->getValue());
  409. return nullptr;
  410. }
  411. /// \brief Extract a Value from Metadata, if any.
  412. ///
  413. /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
  414. /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
  415. /// Value it does contain is of the wrong subclass.
  416. template <class X, class Y>
  417. inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
  418. dyn_extract(Y &&MD) {
  419. if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
  420. return dyn_cast<X>(V->getValue());
  421. return nullptr;
  422. }
  423. /// \brief Extract a Value from Metadata, if any, allowing null.
  424. ///
  425. /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
  426. /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
  427. /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
  428. template <class X, class Y>
  429. inline typename std::enable_if<detail::IsValidPointer<X, Y>::value, X *>::type
  430. dyn_extract_or_null(Y &&MD) {
  431. if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
  432. return dyn_cast<X>(V->getValue());
  433. return nullptr;
  434. }
  435. } // end namespace mdconst
  436. //===----------------------------------------------------------------------===//
  437. /// \brief A single uniqued string.
  438. ///
  439. /// These are used to efficiently contain a byte sequence for metadata.
  440. /// MDString is always unnamed.
  441. class MDString : public Metadata {
  442. friend class StringMapEntry<MDString>;
  443. MDString(const MDString &) = delete;
  444. MDString &operator=(MDString &&) = delete;
  445. MDString &operator=(const MDString &) = delete;
  446. StringMapEntry<MDString> *Entry;
  447. MDString() : Metadata(MDStringKind, Uniqued), Entry(nullptr) {}
  448. MDString(MDString &&) : Metadata(MDStringKind, Uniqued) {}
  449. public:
  450. static MDString *get(LLVMContext &Context, StringRef Str);
  451. static MDString *get(LLVMContext &Context, const char *Str) {
  452. return get(Context, Str ? StringRef(Str) : StringRef());
  453. }
  454. StringRef getString() const;
  455. unsigned getLength() const { return (unsigned)getString().size(); }
  456. typedef StringRef::iterator iterator;
  457. /// \brief Pointer to the first byte of the string.
  458. iterator begin() const { return getString().begin(); }
  459. /// \brief Pointer to one byte past the end of the string.
  460. iterator end() const { return getString().end(); }
  461. const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
  462. const unsigned char *bytes_end() const { return getString().bytes_end(); }
  463. /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
  464. static bool classof(const Metadata *MD) {
  465. return MD->getMetadataID() == MDStringKind;
  466. }
  467. };
  468. /// \brief A collection of metadata nodes that might be associated with a
  469. /// memory access used by the alias-analysis infrastructure.
  470. struct AAMDNodes {
  471. explicit AAMDNodes(MDNode *T = nullptr, MDNode *S = nullptr,
  472. MDNode *N = nullptr)
  473. : TBAA(T), Scope(S), NoAlias(N) {}
  474. bool operator==(const AAMDNodes &A) const {
  475. return TBAA == A.TBAA && Scope == A.Scope && NoAlias == A.NoAlias;
  476. }
  477. bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
  478. explicit operator bool() const { return TBAA || Scope || NoAlias; }
  479. /// \brief The tag for type-based alias analysis.
  480. MDNode *TBAA;
  481. /// \brief The tag for alias scope specification (used with noalias).
  482. MDNode *Scope;
  483. /// \brief The tag specifying the noalias scope.
  484. MDNode *NoAlias;
  485. };
  486. // Specialize DenseMapInfo for AAMDNodes.
  487. template<>
  488. struct DenseMapInfo<AAMDNodes> {
  489. static inline AAMDNodes getEmptyKey() {
  490. return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(), 0, 0);
  491. }
  492. static inline AAMDNodes getTombstoneKey() {
  493. return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(), 0, 0);
  494. }
  495. static unsigned getHashValue(const AAMDNodes &Val) {
  496. return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
  497. DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
  498. DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
  499. }
  500. static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
  501. return LHS == RHS;
  502. }
  503. };
  504. /// \brief Tracking metadata reference owned by Metadata.
  505. ///
  506. /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
  507. /// of \a Metadata, which has the option of registering itself for callbacks to
  508. /// re-unique itself.
  509. ///
  510. /// In particular, this is used by \a MDNode.
  511. class MDOperand {
  512. MDOperand(MDOperand &&) = delete;
  513. MDOperand(const MDOperand &) = delete;
  514. MDOperand &operator=(MDOperand &&) = delete;
  515. MDOperand &operator=(const MDOperand &) = delete;
  516. Metadata *MD;
  517. public:
  518. MDOperand() : MD(nullptr) {}
  519. ~MDOperand() { untrack(); }
  520. Metadata *get() const { return MD; }
  521. operator Metadata *() const { return get(); }
  522. Metadata *operator->() const { return get(); }
  523. Metadata &operator*() const { return *get(); }
  524. void reset() {
  525. untrack();
  526. MD = nullptr;
  527. }
  528. void reset(Metadata *MD, Metadata *Owner) {
  529. untrack();
  530. this->MD = MD;
  531. track(Owner);
  532. }
  533. private:
  534. void track(Metadata *Owner) {
  535. if (MD) {
  536. if (Owner)
  537. MetadataTracking::track(this, *MD, *Owner);
  538. else
  539. MetadataTracking::track(MD);
  540. }
  541. }
  542. void untrack() {
  543. assert(static_cast<void *>(this) == &MD && "Expected same address");
  544. if (MD)
  545. MetadataTracking::untrack(MD);
  546. }
  547. };
  548. template <> struct simplify_type<MDOperand> {
  549. typedef Metadata *SimpleType;
  550. static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
  551. };
  552. template <> struct simplify_type<const MDOperand> {
  553. typedef Metadata *SimpleType;
  554. static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
  555. };
  556. /// \brief Pointer to the context, with optional RAUW support.
  557. ///
  558. /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
  559. /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
  560. class ContextAndReplaceableUses {
  561. PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
  562. ContextAndReplaceableUses() = delete;
  563. ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
  564. ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
  565. ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
  566. ContextAndReplaceableUses &
  567. operator=(const ContextAndReplaceableUses &) = delete;
  568. public:
  569. ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
  570. ContextAndReplaceableUses(
  571. std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
  572. : Ptr(ReplaceableUses.release()) {
  573. assert(getReplaceableUses() && "Expected non-null replaceable uses");
  574. }
  575. ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
  576. operator LLVMContext &() { return getContext(); }
  577. /// \brief Whether this contains RAUW support.
  578. bool hasReplaceableUses() const {
  579. return Ptr.is<ReplaceableMetadataImpl *>();
  580. }
  581. LLVMContext &getContext() const {
  582. if (hasReplaceableUses())
  583. return getReplaceableUses()->getContext();
  584. return *Ptr.get<LLVMContext *>();
  585. }
  586. ReplaceableMetadataImpl *getReplaceableUses() const {
  587. if (hasReplaceableUses())
  588. return Ptr.get<ReplaceableMetadataImpl *>();
  589. return nullptr;
  590. }
  591. /// \brief Assign RAUW support to this.
  592. ///
  593. /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
  594. /// not be null).
  595. void
  596. makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
  597. assert(ReplaceableUses && "Expected non-null replaceable uses");
  598. assert(&ReplaceableUses->getContext() == &getContext() &&
  599. "Expected same context");
  600. delete getReplaceableUses();
  601. Ptr = ReplaceableUses.release();
  602. }
  603. /// \brief Drop RAUW support.
  604. ///
  605. /// Cede ownership of RAUW support, returning it.
  606. std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
  607. assert(hasReplaceableUses() && "Expected to own replaceable uses");
  608. std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
  609. getReplaceableUses());
  610. Ptr = &ReplaceableUses->getContext();
  611. return ReplaceableUses;
  612. }
  613. };
  614. struct TempMDNodeDeleter {
  615. inline void operator()(MDNode *Node) const;
  616. };
  617. #define HANDLE_MDNODE_LEAF(CLASS) \
  618. typedef std::unique_ptr<CLASS, TempMDNodeDeleter> Temp##CLASS;
  619. #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
  620. #include "llvm/IR/Metadata.def"
  621. /// \brief Metadata node.
  622. ///
  623. /// Metadata nodes can be uniqued, like constants, or distinct. Temporary
  624. /// metadata nodes (with full support for RAUW) can be used to delay uniquing
  625. /// until forward references are known. The basic metadata node is an \a
  626. /// MDTuple.
  627. ///
  628. /// There is limited support for RAUW at construction time. At construction
  629. /// time, if any operand is a temporary node (or an unresolved uniqued node,
  630. /// which indicates a transitive temporary operand), the node itself will be
  631. /// unresolved. As soon as all operands become resolved, it will drop RAUW
  632. /// support permanently.
  633. ///
  634. /// If an unresolved node is part of a cycle, \a resolveCycles() needs
  635. /// to be called on some member of the cycle once all temporary nodes have been
  636. /// replaced.
  637. class MDNode : public Metadata {
  638. friend class ReplaceableMetadataImpl;
  639. friend class LLVMContextImpl;
  640. MDNode(const MDNode &) = delete;
  641. void operator=(const MDNode &) = delete;
  642. void *operator new(size_t) = delete;
  643. unsigned NumOperands;
  644. unsigned NumUnresolved;
  645. protected:
  646. ContextAndReplaceableUses Context;
  647. void *operator new(size_t Size, unsigned NumOps);
  648. void operator delete(void *Mem);
  649. /// \brief Required by std, but never called.
  650. void operator delete(void *Mem, unsigned) {
  651. //llvm_unreachable("Constructor throws?"); // HLSL Change - why, yes; yes it does (under OOM)
  652. MDNode::operator delete(Mem);
  653. }
  654. /// \brief Required by std, but never called.
  655. void operator delete(void *, unsigned, bool) {
  656. llvm_unreachable("Constructor throws?");
  657. }
  658. MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
  659. ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None);
  660. ~MDNode() = default;
  661. void dropAllReferences();
  662. MDOperand *mutable_begin() { return mutable_end() - NumOperands; }
  663. MDOperand *mutable_end() { return reinterpret_cast<MDOperand *>(this); }
  664. typedef iterator_range<MDOperand *> mutable_op_range;
  665. mutable_op_range mutable_operands() {
  666. return mutable_op_range(mutable_begin(), mutable_end());
  667. }
  668. public:
  669. static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
  670. static inline MDTuple *getIfExists(LLVMContext &Context,
  671. ArrayRef<Metadata *> MDs);
  672. static inline MDTuple *getDistinct(LLVMContext &Context,
  673. ArrayRef<Metadata *> MDs);
  674. static inline TempMDTuple getTemporary(LLVMContext &Context,
  675. ArrayRef<Metadata *> MDs);
  676. /// \brief Create a (temporary) clone of this.
  677. TempMDNode clone() const;
  678. /// \brief Deallocate a node created by getTemporary.
  679. ///
  680. /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
  681. /// references will be reset.
  682. static void deleteTemporary(MDNode *N);
  683. LLVMContext &getContext() const { return Context.getContext(); }
  684. /// \brief Replace a specific operand.
  685. void replaceOperandWith(unsigned I, Metadata *New);
  686. /// \brief Check if node is fully resolved.
  687. ///
  688. /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
  689. /// this always returns \c true.
  690. ///
  691. /// If \a isUniqued(), returns \c true if this has already dropped RAUW
  692. /// support (because all operands are resolved).
  693. ///
  694. /// As forward declarations are resolved, their containers should get
  695. /// resolved automatically. However, if this (or one of its operands) is
  696. /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
  697. bool isResolved() const { return !Context.hasReplaceableUses(); }
  698. bool isUniqued() const { return Storage == Uniqued; }
  699. bool isDistinct() const { return Storage == Distinct; }
  700. bool isTemporary() const { return Storage == Temporary; }
  701. /// \brief RAUW a temporary.
  702. ///
  703. /// \pre \a isTemporary() must be \c true.
  704. void replaceAllUsesWith(Metadata *MD) {
  705. assert(isTemporary() && "Expected temporary node");
  706. assert(!isResolved() && "Expected RAUW support");
  707. Context.getReplaceableUses()->replaceAllUsesWith(MD);
  708. }
  709. /// \brief Resolve cycles.
  710. ///
  711. /// Once all forward declarations have been resolved, force cycles to be
  712. /// resolved.
  713. ///
  714. /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
  715. void resolveCycles();
  716. /// \brief Replace a temporary node with a permanent one.
  717. ///
  718. /// Try to create a uniqued version of \c N -- in place, if possible -- and
  719. /// return it. If \c N cannot be uniqued, return a distinct node instead.
  720. template <class T>
  721. static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
  722. replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
  723. return cast<T>(N.release()->replaceWithPermanentImpl());
  724. }
  725. /// \brief Replace a temporary node with a uniqued one.
  726. ///
  727. /// Create a uniqued version of \c N -- in place, if possible -- and return
  728. /// it. Takes ownership of the temporary node.
  729. ///
  730. /// \pre N does not self-reference.
  731. template <class T>
  732. static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
  733. replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
  734. return cast<T>(N.release()->replaceWithUniquedImpl());
  735. }
  736. /// \brief Replace a temporary node with a distinct one.
  737. ///
  738. /// Create a distinct version of \c N -- in place, if possible -- and return
  739. /// it. Takes ownership of the temporary node.
  740. template <class T>
  741. static typename std::enable_if<std::is_base_of<MDNode, T>::value, T *>::type
  742. replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
  743. return cast<T>(N.release()->replaceWithDistinctImpl());
  744. }
  745. private:
  746. MDNode *replaceWithPermanentImpl();
  747. MDNode *replaceWithUniquedImpl();
  748. MDNode *replaceWithDistinctImpl();
  749. protected:
  750. /// \brief Set an operand.
  751. ///
  752. /// Sets the operand directly, without worrying about uniquing.
  753. void setOperand(unsigned I, Metadata *New);
  754. void storeDistinctInContext();
  755. template <class T, class StoreT>
  756. static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
  757. private:
  758. void handleChangedOperand(void *Ref, Metadata *New);
  759. void resolve();
  760. void resolveAfterOperandChange(Metadata *Old, Metadata *New);
  761. void decrementUnresolvedOperandCount();
  762. unsigned countUnresolvedOperands();
  763. /// \brief Mutate this to be "uniqued".
  764. ///
  765. /// Mutate this so that \a isUniqued().
  766. /// \pre \a isTemporary().
  767. /// \pre already added to uniquing set.
  768. void makeUniqued();
  769. /// \brief Mutate this to be "distinct".
  770. ///
  771. /// Mutate this so that \a isDistinct().
  772. /// \pre \a isTemporary().
  773. void makeDistinct();
  774. public: // HLSL Change - make deleteAsSubclass accessible
  775. void deleteAsSubclass();
  776. private:
  777. MDNode *uniquify();
  778. void eraseFromStore();
  779. template <class NodeTy> struct HasCachedHash;
  780. template <class NodeTy>
  781. static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
  782. N->recalculateHash();
  783. }
  784. template <class NodeTy>
  785. static void dispatchRecalculateHash(NodeTy *N, std::false_type) {}
  786. template <class NodeTy>
  787. static void dispatchResetHash(NodeTy *N, std::true_type) {
  788. N->setHash(0);
  789. }
  790. template <class NodeTy>
  791. static void dispatchResetHash(NodeTy *N, std::false_type) {}
  792. public:
  793. typedef const MDOperand *op_iterator;
  794. typedef iterator_range<op_iterator> op_range;
  795. op_iterator op_begin() const {
  796. return const_cast<MDNode *>(this)->mutable_begin();
  797. }
  798. op_iterator op_end() const {
  799. return const_cast<MDNode *>(this)->mutable_end();
  800. }
  801. op_range operands() const { return op_range(op_begin(), op_end()); }
  802. const MDOperand &getOperand(unsigned I) const {
  803. assert(I < NumOperands && "Out of range");
  804. return op_begin()[I];
  805. }
  806. /// \brief Return number of MDNode operands.
  807. unsigned getNumOperands() const { return NumOperands; }
  808. /// \brief Methods for support type inquiry through isa, cast, and dyn_cast:
  809. static bool classof(const Metadata *MD) {
  810. switch (MD->getMetadataID()) {
  811. default:
  812. return false;
  813. #define HANDLE_MDNODE_LEAF(CLASS) \
  814. case CLASS##Kind: \
  815. return true;
  816. #include "llvm/IR/Metadata.def"
  817. }
  818. }
  819. /// \brief Check whether MDNode is a vtable access.
  820. bool isTBAAVtableAccess() const;
  821. /// \brief Methods for metadata merging.
  822. static MDNode *concatenate(MDNode *A, MDNode *B);
  823. static MDNode *intersect(MDNode *A, MDNode *B);
  824. static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
  825. static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
  826. static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
  827. static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
  828. /// \brief Methods to print body of node, ie. without the '<addr> = ' prefix
  829. void printAsBody(raw_ostream &OS, const Module *M = nullptr) const; // HLSL Change
  830. void printAsBody(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr) const; // HLSL Change
  831. };
  832. /// \brief Tuple of metadata.
  833. ///
  834. /// This is the simple \a MDNode arbitrary tuple. Nodes are uniqued by
  835. /// default based on their operands.
  836. class MDTuple : public MDNode {
  837. friend class LLVMContextImpl;
  838. friend class MDNode;
  839. MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
  840. ArrayRef<Metadata *> Vals)
  841. : MDNode(C, MDTupleKind, Storage, Vals) {
  842. setHash(Hash);
  843. }
  844. ~MDTuple() { dropAllReferences(); }
  845. void setHash(unsigned Hash) { SubclassData32 = Hash; }
  846. void recalculateHash();
  847. static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
  848. StorageType Storage, bool ShouldCreate = true);
  849. TempMDTuple cloneImpl() const {
  850. return getTemporary(getContext(),
  851. SmallVector<Metadata *, 4>(op_begin(), op_end()));
  852. }
  853. public:
  854. /// \brief Get the hash, if any.
  855. unsigned getHash() const { return SubclassData32; }
  856. static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  857. return getImpl(Context, MDs, Uniqued);
  858. }
  859. static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  860. return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
  861. }
  862. /// \brief Return a distinct node.
  863. ///
  864. /// Return a distinct node -- i.e., a node that is not uniqued.
  865. static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  866. return getImpl(Context, MDs, Distinct);
  867. }
  868. /// \brief Return a temporary node.
  869. ///
  870. /// For use in constructing cyclic MDNode structures. A temporary MDNode is
  871. /// not uniqued, may be RAUW'd, and must be manually deleted with
  872. /// deleteTemporary.
  873. static TempMDTuple getTemporary(LLVMContext &Context,
  874. ArrayRef<Metadata *> MDs) {
  875. return TempMDTuple(getImpl(Context, MDs, Temporary));
  876. }
  877. /// \brief Return a (temporary) clone of this.
  878. TempMDTuple clone() const { return cloneImpl(); }
  879. static bool classof(const Metadata *MD) {
  880. return MD->getMetadataID() == MDTupleKind;
  881. }
  882. };
  883. MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  884. return MDTuple::get(Context, MDs);
  885. }
  886. MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  887. return MDTuple::getIfExists(Context, MDs);
  888. }
  889. MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
  890. return MDTuple::getDistinct(Context, MDs);
  891. }
  892. TempMDTuple MDNode::getTemporary(LLVMContext &Context,
  893. ArrayRef<Metadata *> MDs) {
  894. return MDTuple::getTemporary(Context, MDs);
  895. }
  896. void TempMDNodeDeleter::operator()(MDNode *Node) const {
  897. MDNode::deleteTemporary(Node);
  898. }
  899. /// \brief Typed iterator through MDNode operands.
  900. ///
  901. /// An iterator that transforms an \a MDNode::iterator into an iterator over a
  902. /// particular Metadata subclass.
  903. template <class T>
  904. class TypedMDOperandIterator
  905. : std::iterator<std::input_iterator_tag, T *, std::ptrdiff_t, void, T *> {
  906. MDNode::op_iterator I = nullptr;
  907. public:
  908. TypedMDOperandIterator() = default;
  909. explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
  910. T *operator*() const { return cast_or_null<T>(*I); }
  911. TypedMDOperandIterator &operator++() {
  912. ++I;
  913. return *this;
  914. }
  915. TypedMDOperandIterator operator++(int) {
  916. TypedMDOperandIterator Temp(*this);
  917. ++I;
  918. return Temp;
  919. }
  920. bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
  921. bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
  922. };
  923. /// \brief Typed, array-like tuple of metadata.
  924. ///
  925. /// This is a wrapper for \a MDTuple that makes it act like an array holding a
  926. /// particular type of metadata.
  927. template <class T> class MDTupleTypedArrayWrapper {
  928. const MDTuple *N = nullptr;
  929. public:
  930. MDTupleTypedArrayWrapper() = default;
  931. MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
  932. template <class U>
  933. MDTupleTypedArrayWrapper(
  934. const MDTupleTypedArrayWrapper<U> &Other,
  935. typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
  936. nullptr)
  937. : N(Other.get()) {}
  938. template <class U>
  939. explicit MDTupleTypedArrayWrapper(
  940. const MDTupleTypedArrayWrapper<U> &Other,
  941. typename std::enable_if<!std::is_convertible<U *, T *>::value>::type * =
  942. nullptr)
  943. : N(Other.get()) {}
  944. explicit operator bool() const { return get(); }
  945. explicit operator MDTuple *() const { return get(); }
  946. MDTuple *get() const { return const_cast<MDTuple *>(N); }
  947. MDTuple *operator->() const { return get(); }
  948. MDTuple &operator*() const { return *get(); }
  949. // FIXME: Fix callers and remove condition on N.
  950. unsigned size() const { return N ? N->getNumOperands() : 0u; }
  951. T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
  952. // FIXME: Fix callers and remove condition on N.
  953. typedef TypedMDOperandIterator<T> iterator;
  954. iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
  955. iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
  956. };
  957. #define HANDLE_METADATA(CLASS) \
  958. typedef MDTupleTypedArrayWrapper<CLASS> CLASS##Array;
  959. #include "llvm/IR/Metadata.def"
  960. // //
  961. ///////////////////////////////////////////////////////////////////////////////
  962. /// \brief A tuple of MDNodes.
  963. ///
  964. /// Despite its name, a NamedMDNode isn't itself an MDNode. NamedMDNodes belong
  965. /// to modules, have names, and contain lists of MDNodes.
  966. ///
  967. /// TODO: Inherit from Metadata.
  968. class NamedMDNode : public ilist_node<NamedMDNode> {
  969. friend class SymbolTableListTraits<NamedMDNode, Module>;
  970. friend struct ilist_traits<NamedMDNode>;
  971. friend class LLVMContextImpl;
  972. friend class Module;
  973. NamedMDNode(const NamedMDNode &) = delete;
  974. std::string Name;
  975. Module *Parent;
  976. void *Operands; // SmallVector<TrackingMDRef, 4>
  977. void setParent(Module *M) { Parent = M; }
  978. explicit NamedMDNode(const Twine &N);
  979. template<class T1, class T2>
  980. class op_iterator_impl :
  981. public std::iterator<std::bidirectional_iterator_tag, T2> {
  982. const NamedMDNode *Node;
  983. unsigned Idx;
  984. op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) { }
  985. friend class NamedMDNode;
  986. public:
  987. op_iterator_impl() : Node(nullptr), Idx(0) { }
  988. bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
  989. bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
  990. op_iterator_impl &operator++() {
  991. ++Idx;
  992. return *this;
  993. }
  994. op_iterator_impl operator++(int) {
  995. op_iterator_impl tmp(*this);
  996. operator++();
  997. return tmp;
  998. }
  999. op_iterator_impl &operator--() {
  1000. --Idx;
  1001. return *this;
  1002. }
  1003. op_iterator_impl operator--(int) {
  1004. op_iterator_impl tmp(*this);
  1005. operator--();
  1006. return tmp;
  1007. }
  1008. T1 operator*() const { return Node->getOperand(Idx); }
  1009. };
  1010. public:
  1011. /// \brief Drop all references and remove the node from parent module.
  1012. void eraseFromParent();
  1013. /// \brief Remove all uses and clear node vector.
  1014. void dropAllReferences();
  1015. ~NamedMDNode();
  1016. /// \brief Get the module that holds this named metadata collection.
  1017. inline Module *getParent() { return Parent; }
  1018. inline const Module *getParent() const { return Parent; }
  1019. MDNode *getOperand(unsigned i) const;
  1020. unsigned getNumOperands() const;
  1021. void addOperand(MDNode *M);
  1022. void setOperand(unsigned I, MDNode *New);
  1023. StringRef getName() const;
  1024. void print(raw_ostream &ROS) const;
  1025. void dump() const;
  1026. // ---------------------------------------------------------------------------
  1027. // Operand Iterator interface...
  1028. //
  1029. typedef op_iterator_impl<MDNode *, MDNode> op_iterator;
  1030. op_iterator op_begin() { return op_iterator(this, 0); }
  1031. op_iterator op_end() { return op_iterator(this, getNumOperands()); }
  1032. typedef op_iterator_impl<const MDNode *, MDNode> const_op_iterator;
  1033. const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
  1034. const_op_iterator op_end() const { return const_op_iterator(this, getNumOperands()); }
  1035. inline iterator_range<op_iterator> operands() {
  1036. return iterator_range<op_iterator>(op_begin(), op_end());
  1037. }
  1038. inline iterator_range<const_op_iterator> operands() const {
  1039. return iterator_range<const_op_iterator>(op_begin(), op_end());
  1040. }
  1041. };
  1042. } // end llvm namespace
  1043. #endif