Metadata.h 55 KB

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