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