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