Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:07

0001 //===- llvm/IR/Metadata.h - Metadata definitions ----------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 /// @file
0010 /// This file contains the declarations for metadata subclasses.
0011 /// They represent the different flavors of metadata that live in LLVM.
0012 //
0013 //===----------------------------------------------------------------------===//
0014 
0015 #ifndef LLVM_IR_METADATA_H
0016 #define LLVM_IR_METADATA_H
0017 
0018 #include "llvm/ADT/ArrayRef.h"
0019 #include "llvm/ADT/DenseMap.h"
0020 #include "llvm/ADT/DenseMapInfo.h"
0021 #include "llvm/ADT/PointerUnion.h"
0022 #include "llvm/ADT/SmallVector.h"
0023 #include "llvm/ADT/StringRef.h"
0024 #include "llvm/ADT/ilist_node.h"
0025 #include "llvm/ADT/iterator_range.h"
0026 #include "llvm/IR/Constant.h"
0027 #include "llvm/IR/LLVMContext.h"
0028 #include "llvm/IR/Value.h"
0029 #include "llvm/Support/CBindingWrapping.h"
0030 #include "llvm/Support/Casting.h"
0031 #include "llvm/Support/ErrorHandling.h"
0032 #include <cassert>
0033 #include <cstddef>
0034 #include <cstdint>
0035 #include <iterator>
0036 #include <memory>
0037 #include <string>
0038 #include <type_traits>
0039 #include <utility>
0040 
0041 namespace llvm {
0042 
0043 class Module;
0044 class ModuleSlotTracker;
0045 class raw_ostream;
0046 class DbgVariableRecord;
0047 template <typename T> class StringMapEntry;
0048 template <typename ValueTy> class StringMapEntryStorage;
0049 class Type;
0050 
0051 enum LLVMConstants : uint32_t {
0052   DEBUG_METADATA_VERSION = 3 // Current debug info version number.
0053 };
0054 
0055 /// Magic number in the value profile metadata showing a target has been
0056 /// promoted for the instruction and shouldn't be promoted again.
0057 const uint64_t NOMORE_ICP_MAGICNUM = -1;
0058 
0059 /// Root of the metadata hierarchy.
0060 ///
0061 /// This is a root class for typeless data in the IR.
0062 class Metadata {
0063   friend class ReplaceableMetadataImpl;
0064 
0065   /// RTTI.
0066   const unsigned char SubclassID;
0067 
0068 protected:
0069   /// Active type of storage.
0070   enum StorageType { Uniqued, Distinct, Temporary };
0071 
0072   /// Storage flag for non-uniqued, otherwise unowned, metadata.
0073   unsigned char Storage : 7;
0074 
0075   unsigned char SubclassData1 : 1;
0076   unsigned short SubclassData16 = 0;
0077   unsigned SubclassData32 = 0;
0078 
0079 public:
0080   enum MetadataKind {
0081 #define HANDLE_METADATA_LEAF(CLASS) CLASS##Kind,
0082 #include "llvm/IR/Metadata.def"
0083   };
0084 
0085 protected:
0086   Metadata(unsigned ID, StorageType Storage)
0087       : SubclassID(ID), Storage(Storage), SubclassData1(false) {
0088     static_assert(sizeof(*this) == 8, "Metadata fields poorly packed");
0089   }
0090 
0091   ~Metadata() = default;
0092 
0093   /// Default handling of a changed operand, which asserts.
0094   ///
0095   /// If subclasses pass themselves in as owners to a tracking node reference,
0096   /// they must provide an implementation of this method.
0097   void handleChangedOperand(void *, Metadata *) {
0098     llvm_unreachable("Unimplemented in Metadata subclass");
0099   }
0100 
0101 public:
0102   unsigned getMetadataID() const { return SubclassID; }
0103 
0104   /// User-friendly dump.
0105   ///
0106   /// If \c M is provided, metadata nodes will be numbered canonically;
0107   /// otherwise, pointer addresses are substituted.
0108   ///
0109   /// Note: this uses an explicit overload instead of default arguments so that
0110   /// the nullptr version is easy to call from a debugger.
0111   ///
0112   /// @{
0113   void dump() const;
0114   void dump(const Module *M) const;
0115   /// @}
0116 
0117   /// Print.
0118   ///
0119   /// Prints definition of \c this.
0120   ///
0121   /// If \c M is provided, metadata nodes will be numbered canonically;
0122   /// otherwise, pointer addresses are substituted.
0123   /// @{
0124   void print(raw_ostream &OS, const Module *M = nullptr,
0125              bool IsForDebug = false) const;
0126   void print(raw_ostream &OS, ModuleSlotTracker &MST, const Module *M = nullptr,
0127              bool IsForDebug = false) const;
0128   /// @}
0129 
0130   /// Print as operand.
0131   ///
0132   /// Prints reference of \c this.
0133   ///
0134   /// If \c M is provided, metadata nodes will be numbered canonically;
0135   /// otherwise, pointer addresses are substituted.
0136   /// @{
0137   void printAsOperand(raw_ostream &OS, const Module *M = nullptr) const;
0138   void printAsOperand(raw_ostream &OS, ModuleSlotTracker &MST,
0139                       const Module *M = nullptr) const;
0140   /// @}
0141 
0142   /// Metadata IDs that may generate poison.
0143   constexpr static const unsigned PoisonGeneratingIDs[] = {
0144       LLVMContext::MD_range, LLVMContext::MD_nonnull, LLVMContext::MD_align};
0145 };
0146 
0147 // Create wrappers for C Binding types (see CBindingWrapping.h).
0148 DEFINE_ISA_CONVERSION_FUNCTIONS(Metadata, LLVMMetadataRef)
0149 
0150 // Specialized opaque metadata conversions.
0151 inline Metadata **unwrap(LLVMMetadataRef *MDs) {
0152   return reinterpret_cast<Metadata**>(MDs);
0153 }
0154 
0155 #define HANDLE_METADATA(CLASS) class CLASS;
0156 #include "llvm/IR/Metadata.def"
0157 
0158 // Provide specializations of isa so that we don't need definitions of
0159 // subclasses to see if the metadata is a subclass.
0160 #define HANDLE_METADATA_LEAF(CLASS)                                            \
0161   template <> struct isa_impl<CLASS, Metadata> {                               \
0162     static inline bool doit(const Metadata &MD) {                              \
0163       return MD.getMetadataID() == Metadata::CLASS##Kind;                      \
0164     }                                                                          \
0165   };
0166 #include "llvm/IR/Metadata.def"
0167 
0168 inline raw_ostream &operator<<(raw_ostream &OS, const Metadata &MD) {
0169   MD.print(OS);
0170   return OS;
0171 }
0172 
0173 /// Metadata wrapper in the Value hierarchy.
0174 ///
0175 /// A member of the \a Value hierarchy to represent a reference to metadata.
0176 /// This allows, e.g., intrinsics to have metadata as operands.
0177 ///
0178 /// Notably, this is the only thing in either hierarchy that is allowed to
0179 /// reference \a LocalAsMetadata.
0180 class MetadataAsValue : public Value {
0181   friend class ReplaceableMetadataImpl;
0182   friend class LLVMContextImpl;
0183 
0184   Metadata *MD;
0185 
0186   MetadataAsValue(Type *Ty, Metadata *MD);
0187 
0188   /// Drop use of metadata (during teardown).
0189   void dropUse() { MD = nullptr; }
0190 
0191 public:
0192   ~MetadataAsValue();
0193 
0194   static MetadataAsValue *get(LLVMContext &Context, Metadata *MD);
0195   static MetadataAsValue *getIfExists(LLVMContext &Context, Metadata *MD);
0196 
0197   Metadata *getMetadata() const { return MD; }
0198 
0199   static bool classof(const Value *V) {
0200     return V->getValueID() == MetadataAsValueVal;
0201   }
0202 
0203 private:
0204   void handleChangedMetadata(Metadata *MD);
0205   void track();
0206   void untrack();
0207 };
0208 
0209 /// Base class for tracking ValueAsMetadata/DIArgLists with user lookups and
0210 /// Owner callbacks outside of ValueAsMetadata.
0211 ///
0212 /// Currently only inherited by DbgVariableRecord; if other classes need to use
0213 /// it, then a SubclassID will need to be added (either as a new field or by
0214 /// making DebugValue into a PointerIntUnion) to discriminate between the
0215 /// subclasses in lookup and callback handling.
0216 class DebugValueUser {
0217 protected:
0218   // Capacity to store 3 debug values.
0219   // TODO: Not all DebugValueUser instances need all 3 elements, if we
0220   // restructure the DbgVariableRecord class then we can template parameterize
0221   // this array size.
0222   std::array<Metadata *, 3> DebugValues;
0223 
0224   ArrayRef<Metadata *> getDebugValues() const { return DebugValues; }
0225 
0226 public:
0227   DbgVariableRecord *getUser();
0228   const DbgVariableRecord *getUser() const;
0229   /// To be called by ReplaceableMetadataImpl::replaceAllUsesWith, where `Old`
0230   /// is a pointer to one of the pointers in `DebugValues` (so should be type
0231   /// Metadata**), and `NewDebugValue` is the new Metadata* that is replacing
0232   /// *Old.
0233   /// For manually replacing elements of DebugValues,
0234   /// `resetDebugValue(Idx, NewDebugValue)` should be used instead.
0235   void handleChangedValue(void *Old, Metadata *NewDebugValue);
0236   DebugValueUser() = default;
0237   explicit DebugValueUser(std::array<Metadata *, 3> DebugValues)
0238       : DebugValues(DebugValues) {
0239     trackDebugValues();
0240   }
0241   DebugValueUser(DebugValueUser &&X) {
0242     DebugValues = X.DebugValues;
0243     retrackDebugValues(X);
0244   }
0245   DebugValueUser(const DebugValueUser &X) {
0246     DebugValues = X.DebugValues;
0247     trackDebugValues();
0248   }
0249 
0250   DebugValueUser &operator=(DebugValueUser &&X) {
0251     if (&X == this)
0252       return *this;
0253 
0254     untrackDebugValues();
0255     DebugValues = X.DebugValues;
0256     retrackDebugValues(X);
0257     return *this;
0258   }
0259 
0260   DebugValueUser &operator=(const DebugValueUser &X) {
0261     if (&X == this)
0262       return *this;
0263 
0264     untrackDebugValues();
0265     DebugValues = X.DebugValues;
0266     trackDebugValues();
0267     return *this;
0268   }
0269 
0270   ~DebugValueUser() { untrackDebugValues(); }
0271 
0272   void resetDebugValues() {
0273     untrackDebugValues();
0274     DebugValues.fill(nullptr);
0275   }
0276 
0277   void resetDebugValue(size_t Idx, Metadata *DebugValue) {
0278     assert(Idx < 3 && "Invalid debug value index.");
0279     untrackDebugValue(Idx);
0280     DebugValues[Idx] = DebugValue;
0281     trackDebugValue(Idx);
0282   }
0283 
0284   bool operator==(const DebugValueUser &X) const {
0285     return DebugValues == X.DebugValues;
0286   }
0287   bool operator!=(const DebugValueUser &X) const {
0288     return DebugValues != X.DebugValues;
0289   }
0290 
0291 private:
0292   void trackDebugValue(size_t Idx);
0293   void trackDebugValues();
0294 
0295   void untrackDebugValue(size_t Idx);
0296   void untrackDebugValues();
0297 
0298   void retrackDebugValues(DebugValueUser &X);
0299 };
0300 
0301 /// API for tracking metadata references through RAUW and deletion.
0302 ///
0303 /// Shared API for updating \a Metadata pointers in subclasses that support
0304 /// RAUW.
0305 ///
0306 /// This API is not meant to be used directly.  See \a TrackingMDRef for a
0307 /// user-friendly tracking reference.
0308 class MetadataTracking {
0309 public:
0310   /// Track the reference to metadata.
0311   ///
0312   /// Register \c MD with \c *MD, if the subclass supports tracking.  If \c *MD
0313   /// gets RAUW'ed, \c MD will be updated to the new address.  If \c *MD gets
0314   /// deleted, \c MD will be set to \c nullptr.
0315   ///
0316   /// If tracking isn't supported, \c *MD will not change.
0317   ///
0318   /// \return true iff tracking is supported by \c MD.
0319   static bool track(Metadata *&MD) {
0320     return track(&MD, *MD, static_cast<Metadata *>(nullptr));
0321   }
0322 
0323   /// Track the reference to metadata for \a Metadata.
0324   ///
0325   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
0326   /// tell it that its operand changed.  This could trigger \c Owner being
0327   /// re-uniqued.
0328   static bool track(void *Ref, Metadata &MD, Metadata &Owner) {
0329     return track(Ref, MD, &Owner);
0330   }
0331 
0332   /// Track the reference to metadata for \a MetadataAsValue.
0333   ///
0334   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
0335   /// tell it that its operand changed.  This could trigger \c Owner being
0336   /// re-uniqued.
0337   static bool track(void *Ref, Metadata &MD, MetadataAsValue &Owner) {
0338     return track(Ref, MD, &Owner);
0339   }
0340 
0341   /// Track the reference to metadata for \a DebugValueUser.
0342   ///
0343   /// As \a track(Metadata*&), but with support for calling back to \c Owner to
0344   /// tell it that its operand changed.  This could trigger \c Owner being
0345   /// re-uniqued.
0346   static bool track(void *Ref, Metadata &MD, DebugValueUser &Owner) {
0347     return track(Ref, MD, &Owner);
0348   }
0349 
0350   /// Stop tracking a reference to metadata.
0351   ///
0352   /// Stops \c *MD from tracking \c MD.
0353   static void untrack(Metadata *&MD) { untrack(&MD, *MD); }
0354   static void untrack(void *Ref, Metadata &MD);
0355 
0356   /// Move tracking from one reference to another.
0357   ///
0358   /// Semantically equivalent to \c untrack(MD) followed by \c track(New),
0359   /// except that ownership callbacks are maintained.
0360   ///
0361   /// Note: it is an error if \c *MD does not equal \c New.
0362   ///
0363   /// \return true iff tracking is supported by \c MD.
0364   static bool retrack(Metadata *&MD, Metadata *&New) {
0365     return retrack(&MD, *MD, &New);
0366   }
0367   static bool retrack(void *Ref, Metadata &MD, void *New);
0368 
0369   /// Check whether metadata is replaceable.
0370   static bool isReplaceable(const Metadata &MD);
0371 
0372   using OwnerTy = PointerUnion<MetadataAsValue *, Metadata *, DebugValueUser *>;
0373 
0374 private:
0375   /// Track a reference to metadata for an owner.
0376   ///
0377   /// Generalized version of tracking.
0378   static bool track(void *Ref, Metadata &MD, OwnerTy Owner);
0379 };
0380 
0381 /// Shared implementation of use-lists for replaceable metadata.
0382 ///
0383 /// Most metadata cannot be RAUW'ed.  This is a shared implementation of
0384 /// use-lists and associated API for the three that support it (
0385 /// \a ValueAsMetadata, \a TempMDNode, and \a DIArgList).
0386 class ReplaceableMetadataImpl {
0387   friend class MetadataTracking;
0388 
0389 public:
0390   using OwnerTy = MetadataTracking::OwnerTy;
0391 
0392 private:
0393   LLVMContext &Context;
0394   uint64_t NextIndex = 0;
0395   SmallDenseMap<void *, std::pair<OwnerTy, uint64_t>, 4> UseMap;
0396 
0397 public:
0398   ReplaceableMetadataImpl(LLVMContext &Context) : Context(Context) {}
0399 
0400   ~ReplaceableMetadataImpl() {
0401     assert(UseMap.empty() && "Cannot destroy in-use replaceable metadata");
0402   }
0403 
0404   LLVMContext &getContext() const { return Context; }
0405 
0406   /// Replace all uses of this with MD.
0407   ///
0408   /// Replace all uses of this with \c MD, which is allowed to be null.
0409   void replaceAllUsesWith(Metadata *MD);
0410    /// Replace all uses of the constant with Undef in debug info metadata
0411   static void SalvageDebugInfo(const Constant &C); 
0412   /// Returns the list of all DIArgList users of this.
0413   SmallVector<Metadata *> getAllArgListUsers();
0414   /// Returns the list of all DbgVariableRecord users of this.
0415   SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers();
0416 
0417   /// Resolve all uses of this.
0418   ///
0419   /// Resolve all uses of this, turning off RAUW permanently.  If \c
0420   /// ResolveUsers, call \a MDNode::resolve() on any users whose last operand
0421   /// is resolved.
0422   void resolveAllUses(bool ResolveUsers = true);
0423 
0424   unsigned getNumUses() const { return UseMap.size(); }
0425 
0426 private:
0427   void addRef(void *Ref, OwnerTy Owner);
0428   void dropRef(void *Ref);
0429   void moveRef(void *Ref, void *New, const Metadata &MD);
0430 
0431   /// Lazily construct RAUW support on MD.
0432   ///
0433   /// If this is an unresolved MDNode, RAUW support will be created on-demand.
0434   /// ValueAsMetadata always has RAUW support.
0435   static ReplaceableMetadataImpl *getOrCreate(Metadata &MD);
0436 
0437   /// Get RAUW support on MD, if it exists.
0438   static ReplaceableMetadataImpl *getIfExists(Metadata &MD);
0439 
0440   /// Check whether this node will support RAUW.
0441   ///
0442   /// Returns \c true unless getOrCreate() would return null.
0443   static bool isReplaceable(const Metadata &MD);
0444 };
0445 
0446 /// Value wrapper in the Metadata hierarchy.
0447 ///
0448 /// This is a custom value handle that allows other metadata to refer to
0449 /// classes in the Value hierarchy.
0450 ///
0451 /// Because of full uniquing support, each value is only wrapped by a single \a
0452 /// ValueAsMetadata object, so the lookup maps are far more efficient than
0453 /// those using ValueHandleBase.
0454 class ValueAsMetadata : public Metadata, ReplaceableMetadataImpl {
0455   friend class ReplaceableMetadataImpl;
0456   friend class LLVMContextImpl;
0457 
0458   Value *V;
0459 
0460   /// Drop users without RAUW (during teardown).
0461   void dropUsers() {
0462     ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
0463   }
0464 
0465 protected:
0466   ValueAsMetadata(unsigned ID, Value *V)
0467       : Metadata(ID, Uniqued), ReplaceableMetadataImpl(V->getContext()), V(V) {
0468     assert(V && "Expected valid value");
0469   }
0470 
0471   ~ValueAsMetadata() = default;
0472 
0473 public:
0474   static ValueAsMetadata *get(Value *V);
0475 
0476   static ConstantAsMetadata *getConstant(Value *C) {
0477     return cast<ConstantAsMetadata>(get(C));
0478   }
0479 
0480   static LocalAsMetadata *getLocal(Value *Local) {
0481     return cast<LocalAsMetadata>(get(Local));
0482   }
0483 
0484   static ValueAsMetadata *getIfExists(Value *V);
0485 
0486   static ConstantAsMetadata *getConstantIfExists(Value *C) {
0487     return cast_or_null<ConstantAsMetadata>(getIfExists(C));
0488   }
0489 
0490   static LocalAsMetadata *getLocalIfExists(Value *Local) {
0491     return cast_or_null<LocalAsMetadata>(getIfExists(Local));
0492   }
0493 
0494   Value *getValue() const { return V; }
0495   Type *getType() const { return V->getType(); }
0496   LLVMContext &getContext() const { return V->getContext(); }
0497 
0498   SmallVector<Metadata *> getAllArgListUsers() {
0499     return ReplaceableMetadataImpl::getAllArgListUsers();
0500   }
0501   SmallVector<DbgVariableRecord *> getAllDbgVariableRecordUsers() {
0502     return ReplaceableMetadataImpl::getAllDbgVariableRecordUsers();
0503   }
0504 
0505   static void handleDeletion(Value *V);
0506   static void handleRAUW(Value *From, Value *To);
0507 
0508 protected:
0509   /// Handle collisions after \a Value::replaceAllUsesWith().
0510   ///
0511   /// RAUW isn't supported directly for \a ValueAsMetadata, but if the wrapped
0512   /// \a Value gets RAUW'ed and the target already exists, this is used to
0513   /// merge the two metadata nodes.
0514   void replaceAllUsesWith(Metadata *MD) {
0515     ReplaceableMetadataImpl::replaceAllUsesWith(MD);
0516   }
0517 
0518 public:
0519   static bool classof(const Metadata *MD) {
0520     return MD->getMetadataID() == LocalAsMetadataKind ||
0521            MD->getMetadataID() == ConstantAsMetadataKind;
0522   }
0523 };
0524 
0525 class ConstantAsMetadata : public ValueAsMetadata {
0526   friend class ValueAsMetadata;
0527 
0528   ConstantAsMetadata(Constant *C)
0529       : ValueAsMetadata(ConstantAsMetadataKind, C) {}
0530 
0531 public:
0532   static ConstantAsMetadata *get(Constant *C) {
0533     return ValueAsMetadata::getConstant(C);
0534   }
0535 
0536   static ConstantAsMetadata *getIfExists(Constant *C) {
0537     return ValueAsMetadata::getConstantIfExists(C);
0538   }
0539 
0540   Constant *getValue() const {
0541     return cast<Constant>(ValueAsMetadata::getValue());
0542   }
0543 
0544   static bool classof(const Metadata *MD) {
0545     return MD->getMetadataID() == ConstantAsMetadataKind;
0546   }
0547 };
0548 
0549 class LocalAsMetadata : public ValueAsMetadata {
0550   friend class ValueAsMetadata;
0551 
0552   LocalAsMetadata(Value *Local)
0553       : ValueAsMetadata(LocalAsMetadataKind, Local) {
0554     assert(!isa<Constant>(Local) && "Expected local value");
0555   }
0556 
0557 public:
0558   static LocalAsMetadata *get(Value *Local) {
0559     return ValueAsMetadata::getLocal(Local);
0560   }
0561 
0562   static LocalAsMetadata *getIfExists(Value *Local) {
0563     return ValueAsMetadata::getLocalIfExists(Local);
0564   }
0565 
0566   static bool classof(const Metadata *MD) {
0567     return MD->getMetadataID() == LocalAsMetadataKind;
0568   }
0569 };
0570 
0571 /// Transitional API for extracting constants from Metadata.
0572 ///
0573 /// This namespace contains transitional functions for metadata that points to
0574 /// \a Constants.
0575 ///
0576 /// In prehistory -- when metadata was a subclass of \a Value -- \a MDNode
0577 /// operands could refer to any \a Value.  There's was a lot of code like this:
0578 ///
0579 /// \code
0580 ///     MDNode *N = ...;
0581 ///     auto *CI = dyn_cast<ConstantInt>(N->getOperand(2));
0582 /// \endcode
0583 ///
0584 /// Now that \a Value and \a Metadata are in separate hierarchies, maintaining
0585 /// the semantics for \a isa(), \a cast(), \a dyn_cast() (etc.) requires three
0586 /// steps: cast in the \a Metadata hierarchy, extraction of the \a Value, and
0587 /// cast in the \a Value hierarchy.  Besides creating boiler-plate, this
0588 /// requires subtle control flow changes.
0589 ///
0590 /// The end-goal is to create a new type of metadata, called (e.g.) \a MDInt,
0591 /// so that metadata can refer to numbers without traversing a bridge to the \a
0592 /// Value hierarchy.  In this final state, the code above would look like this:
0593 ///
0594 /// \code
0595 ///     MDNode *N = ...;
0596 ///     auto *MI = dyn_cast<MDInt>(N->getOperand(2));
0597 /// \endcode
0598 ///
0599 /// The API in this namespace supports the transition.  \a MDInt doesn't exist
0600 /// yet, and even once it does, changing each metadata schema to use it is its
0601 /// own mini-project.  In the meantime this API prevents us from introducing
0602 /// complex and bug-prone control flow that will disappear in the end.  In
0603 /// particular, the above code looks like this:
0604 ///
0605 /// \code
0606 ///     MDNode *N = ...;
0607 ///     auto *CI = mdconst::dyn_extract<ConstantInt>(N->getOperand(2));
0608 /// \endcode
0609 ///
0610 /// The full set of provided functions includes:
0611 ///
0612 ///   mdconst::hasa                <=> isa
0613 ///   mdconst::extract             <=> cast
0614 ///   mdconst::extract_or_null     <=> cast_or_null
0615 ///   mdconst::dyn_extract         <=> dyn_cast
0616 ///   mdconst::dyn_extract_or_null <=> dyn_cast_or_null
0617 ///
0618 /// The target of the cast must be a subclass of \a Constant.
0619 namespace mdconst {
0620 
0621 namespace detail {
0622 
0623 template <class T> T &make();
0624 template <class T, class Result> struct HasDereference {
0625   using Yes = char[1];
0626   using No = char[2];
0627   template <size_t N> struct SFINAE {};
0628 
0629   template <class U, class V>
0630   static Yes &hasDereference(SFINAE<sizeof(static_cast<V>(*make<U>()))> * = 0);
0631   template <class U, class V> static No &hasDereference(...);
0632 
0633   static const bool value =
0634       sizeof(hasDereference<T, Result>(nullptr)) == sizeof(Yes);
0635 };
0636 template <class V, class M> struct IsValidPointer {
0637   static const bool value = std::is_base_of<Constant, V>::value &&
0638                             HasDereference<M, const Metadata &>::value;
0639 };
0640 template <class V, class M> struct IsValidReference {
0641   static const bool value = std::is_base_of<Constant, V>::value &&
0642                             std::is_convertible<M, const Metadata &>::value;
0643 };
0644 
0645 } // end namespace detail
0646 
0647 /// Check whether Metadata has a Value.
0648 ///
0649 /// As an analogue to \a isa(), check whether \c MD has an \a Value inside of
0650 /// type \c X.
0651 template <class X, class Y>
0652 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, bool>
0653 hasa(Y &&MD) {
0654   assert(MD && "Null pointer sent into hasa");
0655   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
0656     return isa<X>(V->getValue());
0657   return false;
0658 }
0659 template <class X, class Y>
0660 inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, bool>
0661 hasa(Y &MD) {
0662   return hasa(&MD);
0663 }
0664 
0665 /// Extract a Value from Metadata.
0666 ///
0667 /// As an analogue to \a cast(), extract the \a Value subclass \c X from \c MD.
0668 template <class X, class Y>
0669 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
0670 extract(Y &&MD) {
0671   return cast<X>(cast<ConstantAsMetadata>(MD)->getValue());
0672 }
0673 template <class X, class Y>
0674 inline std::enable_if_t<detail::IsValidReference<X, Y &>::value, X *>
0675 extract(Y &MD) {
0676   return extract(&MD);
0677 }
0678 
0679 /// Extract a Value from Metadata, allowing null.
0680 ///
0681 /// As an analogue to \a cast_or_null(), extract the \a Value subclass \c X
0682 /// from \c MD, allowing \c MD to be null.
0683 template <class X, class Y>
0684 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
0685 extract_or_null(Y &&MD) {
0686   if (auto *V = cast_or_null<ConstantAsMetadata>(MD))
0687     return cast<X>(V->getValue());
0688   return nullptr;
0689 }
0690 
0691 /// Extract a Value from Metadata, if any.
0692 ///
0693 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
0694 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
0695 /// Value it does contain is of the wrong subclass.
0696 template <class X, class Y>
0697 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
0698 dyn_extract(Y &&MD) {
0699   if (auto *V = dyn_cast<ConstantAsMetadata>(MD))
0700     return dyn_cast<X>(V->getValue());
0701   return nullptr;
0702 }
0703 
0704 /// Extract a Value from Metadata, if any, allowing null.
0705 ///
0706 /// As an analogue to \a dyn_cast_or_null(), extract the \a Value subclass \c X
0707 /// from \c MD, return null if \c MD doesn't contain a \a Value or if the \a
0708 /// Value it does contain is of the wrong subclass, allowing \c MD to be null.
0709 template <class X, class Y>
0710 inline std::enable_if_t<detail::IsValidPointer<X, Y>::value, X *>
0711 dyn_extract_or_null(Y &&MD) {
0712   if (auto *V = dyn_cast_or_null<ConstantAsMetadata>(MD))
0713     return dyn_cast<X>(V->getValue());
0714   return nullptr;
0715 }
0716 
0717 } // end namespace mdconst
0718 
0719 //===----------------------------------------------------------------------===//
0720 /// A single uniqued string.
0721 ///
0722 /// These are used to efficiently contain a byte sequence for metadata.
0723 /// MDString is always unnamed.
0724 class MDString : public Metadata {
0725   friend class StringMapEntryStorage<MDString>;
0726 
0727   StringMapEntry<MDString> *Entry = nullptr;
0728 
0729   MDString() : Metadata(MDStringKind, Uniqued) {}
0730 
0731 public:
0732   MDString(const MDString &) = delete;
0733   MDString &operator=(MDString &&) = delete;
0734   MDString &operator=(const MDString &) = delete;
0735 
0736   static MDString *get(LLVMContext &Context, StringRef Str);
0737   static MDString *get(LLVMContext &Context, const char *Str) {
0738     return get(Context, Str ? StringRef(Str) : StringRef());
0739   }
0740 
0741   StringRef getString() const;
0742 
0743   unsigned getLength() const { return (unsigned)getString().size(); }
0744 
0745   using iterator = StringRef::iterator;
0746 
0747   /// Pointer to the first byte of the string.
0748   iterator begin() const { return getString().begin(); }
0749 
0750   /// Pointer to one byte past the end of the string.
0751   iterator end() const { return getString().end(); }
0752 
0753   const unsigned char *bytes_begin() const { return getString().bytes_begin(); }
0754   const unsigned char *bytes_end() const { return getString().bytes_end(); }
0755 
0756   /// Methods for support type inquiry through isa, cast, and dyn_cast.
0757   static bool classof(const Metadata *MD) {
0758     return MD->getMetadataID() == MDStringKind;
0759   }
0760 };
0761 
0762 /// A collection of metadata nodes that might be associated with a
0763 /// memory access used by the alias-analysis infrastructure.
0764 struct AAMDNodes {
0765   explicit AAMDNodes() = default;
0766   explicit AAMDNodes(MDNode *T, MDNode *TS, MDNode *S, MDNode *N)
0767       : TBAA(T), TBAAStruct(TS), Scope(S), NoAlias(N) {}
0768 
0769   bool operator==(const AAMDNodes &A) const {
0770     return TBAA == A.TBAA && TBAAStruct == A.TBAAStruct && Scope == A.Scope &&
0771            NoAlias == A.NoAlias;
0772   }
0773 
0774   bool operator!=(const AAMDNodes &A) const { return !(*this == A); }
0775 
0776   explicit operator bool() const {
0777     return TBAA || TBAAStruct || Scope || NoAlias;
0778   }
0779 
0780   /// The tag for type-based alias analysis.
0781   MDNode *TBAA = nullptr;
0782 
0783   /// The tag for type-based alias analysis (tbaa struct).
0784   MDNode *TBAAStruct = nullptr;
0785 
0786   /// The tag for alias scope specification (used with noalias).
0787   MDNode *Scope = nullptr;
0788 
0789   /// The tag specifying the noalias scope.
0790   MDNode *NoAlias = nullptr;
0791 
0792   // Shift tbaa Metadata node to start off bytes later
0793   static MDNode *shiftTBAA(MDNode *M, size_t off);
0794 
0795   // Shift tbaa.struct Metadata node to start off bytes later
0796   static MDNode *shiftTBAAStruct(MDNode *M, size_t off);
0797 
0798   // Extend tbaa Metadata node to apply to a series of bytes of length len.
0799   // A size of -1 denotes an unknown size.
0800   static MDNode *extendToTBAA(MDNode *TBAA, ssize_t len);
0801 
0802   /// Given two sets of AAMDNodes that apply to the same pointer,
0803   /// give the best AAMDNodes that are compatible with both (i.e. a set of
0804   /// nodes whose allowable aliasing conclusions are a subset of those
0805   /// allowable by both of the inputs). However, for efficiency
0806   /// reasons, do not create any new MDNodes.
0807   AAMDNodes intersect(const AAMDNodes &Other) const {
0808     AAMDNodes Result;
0809     Result.TBAA = Other.TBAA == TBAA ? TBAA : nullptr;
0810     Result.TBAAStruct = Other.TBAAStruct == TBAAStruct ? TBAAStruct : nullptr;
0811     Result.Scope = Other.Scope == Scope ? Scope : nullptr;
0812     Result.NoAlias = Other.NoAlias == NoAlias ? NoAlias : nullptr;
0813     return Result;
0814   }
0815 
0816   /// Create a new AAMDNode that describes this AAMDNode after applying a
0817   /// constant offset to the start of the pointer.
0818   AAMDNodes shift(size_t Offset) const {
0819     AAMDNodes Result;
0820     Result.TBAA = TBAA ? shiftTBAA(TBAA, Offset) : nullptr;
0821     Result.TBAAStruct =
0822         TBAAStruct ? shiftTBAAStruct(TBAAStruct, Offset) : nullptr;
0823     Result.Scope = Scope;
0824     Result.NoAlias = NoAlias;
0825     return Result;
0826   }
0827 
0828   /// Create a new AAMDNode that describes this AAMDNode after extending it to
0829   /// apply to a series of bytes of length Len. A size of -1 denotes an unknown
0830   /// size.
0831   AAMDNodes extendTo(ssize_t Len) const {
0832     AAMDNodes Result;
0833     Result.TBAA = TBAA ? extendToTBAA(TBAA, Len) : nullptr;
0834     // tbaa.struct contains (offset, size, type) triples. Extending the length
0835     // of the tbaa.struct doesn't require changing this (though more information
0836     // could be provided by adding more triples at subsequent lengths).
0837     Result.TBAAStruct = TBAAStruct;
0838     Result.Scope = Scope;
0839     Result.NoAlias = NoAlias;
0840     return Result;
0841   }
0842 
0843   /// Given two sets of AAMDNodes applying to potentially different locations,
0844   /// determine the best AAMDNodes that apply to both.
0845   AAMDNodes merge(const AAMDNodes &Other) const;
0846 
0847   /// Determine the best AAMDNodes after concatenating two different locations
0848   /// together. Different from `merge`, where different locations should
0849   /// overlap each other, `concat` puts non-overlapping locations together.
0850   AAMDNodes concat(const AAMDNodes &Other) const;
0851 
0852   /// Create a new AAMDNode for accessing \p AccessSize bytes of this AAMDNode.
0853   /// If this AAMDNode has !tbaa.struct and \p AccessSize matches the size of
0854   /// the field at offset 0, get the TBAA tag describing the accessed field.
0855   /// If such an AAMDNode already embeds !tbaa, the existing one is retrieved.
0856   /// Finally, !tbaa.struct is zeroed out.
0857   AAMDNodes adjustForAccess(unsigned AccessSize);
0858   AAMDNodes adjustForAccess(size_t Offset, Type *AccessTy,
0859                             const DataLayout &DL);
0860   AAMDNodes adjustForAccess(size_t Offset, unsigned AccessSize);
0861 };
0862 
0863 // Specialize DenseMapInfo for AAMDNodes.
0864 template<>
0865 struct DenseMapInfo<AAMDNodes> {
0866   static inline AAMDNodes getEmptyKey() {
0867     return AAMDNodes(DenseMapInfo<MDNode *>::getEmptyKey(),
0868                      nullptr, nullptr, nullptr);
0869   }
0870 
0871   static inline AAMDNodes getTombstoneKey() {
0872     return AAMDNodes(DenseMapInfo<MDNode *>::getTombstoneKey(),
0873                      nullptr, nullptr, nullptr);
0874   }
0875 
0876   static unsigned getHashValue(const AAMDNodes &Val) {
0877     return DenseMapInfo<MDNode *>::getHashValue(Val.TBAA) ^
0878            DenseMapInfo<MDNode *>::getHashValue(Val.TBAAStruct) ^
0879            DenseMapInfo<MDNode *>::getHashValue(Val.Scope) ^
0880            DenseMapInfo<MDNode *>::getHashValue(Val.NoAlias);
0881   }
0882 
0883   static bool isEqual(const AAMDNodes &LHS, const AAMDNodes &RHS) {
0884     return LHS == RHS;
0885   }
0886 };
0887 
0888 /// Tracking metadata reference owned by Metadata.
0889 ///
0890 /// Similar to \a TrackingMDRef, but it's expected to be owned by an instance
0891 /// of \a Metadata, which has the option of registering itself for callbacks to
0892 /// re-unique itself.
0893 ///
0894 /// In particular, this is used by \a MDNode.
0895 class MDOperand {
0896   Metadata *MD = nullptr;
0897 
0898 public:
0899   MDOperand() = default;
0900   MDOperand(const MDOperand &) = delete;
0901   MDOperand(MDOperand &&Op) {
0902     MD = Op.MD;
0903     if (MD)
0904       (void)MetadataTracking::retrack(Op.MD, MD);
0905     Op.MD = nullptr;
0906   }
0907   MDOperand &operator=(const MDOperand &) = delete;
0908   MDOperand &operator=(MDOperand &&Op) {
0909     MD = Op.MD;
0910     if (MD)
0911       (void)MetadataTracking::retrack(Op.MD, MD);
0912     Op.MD = nullptr;
0913     return *this;
0914   }
0915 
0916   // Check if MDOperand is of type MDString and equals `Str`.
0917   bool equalsStr(StringRef Str) const {
0918     return isa<MDString>(this->get()) &&
0919            cast<MDString>(this->get())->getString() == Str;
0920   }
0921 
0922   ~MDOperand() { untrack(); }
0923 
0924   Metadata *get() const { return MD; }
0925   operator Metadata *() const { return get(); }
0926   Metadata *operator->() const { return get(); }
0927   Metadata &operator*() const { return *get(); }
0928 
0929   void reset() {
0930     untrack();
0931     MD = nullptr;
0932   }
0933   void reset(Metadata *MD, Metadata *Owner) {
0934     untrack();
0935     this->MD = MD;
0936     track(Owner);
0937   }
0938 
0939 private:
0940   void track(Metadata *Owner) {
0941     if (MD) {
0942       if (Owner)
0943         MetadataTracking::track(this, *MD, *Owner);
0944       else
0945         MetadataTracking::track(MD);
0946     }
0947   }
0948 
0949   void untrack() {
0950     assert(static_cast<void *>(this) == &MD && "Expected same address");
0951     if (MD)
0952       MetadataTracking::untrack(MD);
0953   }
0954 };
0955 
0956 template <> struct simplify_type<MDOperand> {
0957   using SimpleType = Metadata *;
0958 
0959   static SimpleType getSimplifiedValue(MDOperand &MD) { return MD.get(); }
0960 };
0961 
0962 template <> struct simplify_type<const MDOperand> {
0963   using SimpleType = Metadata *;
0964 
0965   static SimpleType getSimplifiedValue(const MDOperand &MD) { return MD.get(); }
0966 };
0967 
0968 /// Pointer to the context, with optional RAUW support.
0969 ///
0970 /// Either a raw (non-null) pointer to the \a LLVMContext, or an owned pointer
0971 /// to \a ReplaceableMetadataImpl (which has a reference to \a LLVMContext).
0972 class ContextAndReplaceableUses {
0973   PointerUnion<LLVMContext *, ReplaceableMetadataImpl *> Ptr;
0974 
0975 public:
0976   ContextAndReplaceableUses(LLVMContext &Context) : Ptr(&Context) {}
0977   ContextAndReplaceableUses(
0978       std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses)
0979       : Ptr(ReplaceableUses.release()) {
0980     assert(getReplaceableUses() && "Expected non-null replaceable uses");
0981   }
0982   ContextAndReplaceableUses() = delete;
0983   ContextAndReplaceableUses(ContextAndReplaceableUses &&) = delete;
0984   ContextAndReplaceableUses(const ContextAndReplaceableUses &) = delete;
0985   ContextAndReplaceableUses &operator=(ContextAndReplaceableUses &&) = delete;
0986   ContextAndReplaceableUses &
0987   operator=(const ContextAndReplaceableUses &) = delete;
0988   ~ContextAndReplaceableUses() { delete getReplaceableUses(); }
0989 
0990   operator LLVMContext &() { return getContext(); }
0991 
0992   /// Whether this contains RAUW support.
0993   bool hasReplaceableUses() const {
0994     return isa<ReplaceableMetadataImpl *>(Ptr);
0995   }
0996 
0997   LLVMContext &getContext() const {
0998     if (hasReplaceableUses())
0999       return getReplaceableUses()->getContext();
1000     return *cast<LLVMContext *>(Ptr);
1001   }
1002 
1003   ReplaceableMetadataImpl *getReplaceableUses() const {
1004     if (hasReplaceableUses())
1005       return cast<ReplaceableMetadataImpl *>(Ptr);
1006     return nullptr;
1007   }
1008 
1009   /// Ensure that this has RAUW support, and then return it.
1010   ReplaceableMetadataImpl *getOrCreateReplaceableUses() {
1011     if (!hasReplaceableUses())
1012       makeReplaceable(std::make_unique<ReplaceableMetadataImpl>(getContext()));
1013     return getReplaceableUses();
1014   }
1015 
1016   /// Assign RAUW support to this.
1017   ///
1018   /// Make this replaceable, taking ownership of \c ReplaceableUses (which must
1019   /// not be null).
1020   void
1021   makeReplaceable(std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses) {
1022     assert(ReplaceableUses && "Expected non-null replaceable uses");
1023     assert(&ReplaceableUses->getContext() == &getContext() &&
1024            "Expected same context");
1025     delete getReplaceableUses();
1026     Ptr = ReplaceableUses.release();
1027   }
1028 
1029   /// Drop RAUW support.
1030   ///
1031   /// Cede ownership of RAUW support, returning it.
1032   std::unique_ptr<ReplaceableMetadataImpl> takeReplaceableUses() {
1033     assert(hasReplaceableUses() && "Expected to own replaceable uses");
1034     std::unique_ptr<ReplaceableMetadataImpl> ReplaceableUses(
1035         getReplaceableUses());
1036     Ptr = &ReplaceableUses->getContext();
1037     return ReplaceableUses;
1038   }
1039 };
1040 
1041 struct TempMDNodeDeleter {
1042   inline void operator()(MDNode *Node) const;
1043 };
1044 
1045 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1046   using Temp##CLASS = std::unique_ptr<CLASS, TempMDNodeDeleter>;
1047 #define HANDLE_MDNODE_BRANCH(CLASS) HANDLE_MDNODE_LEAF(CLASS)
1048 #include "llvm/IR/Metadata.def"
1049 
1050 /// Metadata node.
1051 ///
1052 /// Metadata nodes can be uniqued, like constants, or distinct.  Temporary
1053 /// metadata nodes (with full support for RAUW) can be used to delay uniquing
1054 /// until forward references are known.  The basic metadata node is an \a
1055 /// MDTuple.
1056 ///
1057 /// There is limited support for RAUW at construction time.  At construction
1058 /// time, if any operand is a temporary node (or an unresolved uniqued node,
1059 /// which indicates a transitive temporary operand), the node itself will be
1060 /// unresolved.  As soon as all operands become resolved, it will drop RAUW
1061 /// support permanently.
1062 ///
1063 /// If an unresolved node is part of a cycle, \a resolveCycles() needs
1064 /// to be called on some member of the cycle once all temporary nodes have been
1065 /// replaced.
1066 ///
1067 /// MDNodes can be large or small, as well as resizable or non-resizable.
1068 /// Large MDNodes' operands are allocated in a separate storage vector,
1069 /// whereas small MDNodes' operands are co-allocated. Distinct and temporary
1070 /// MDnodes are resizable, but only MDTuples support this capability.
1071 ///
1072 /// Clients can add operands to resizable MDNodes using push_back().
1073 class MDNode : public Metadata {
1074   friend class ReplaceableMetadataImpl;
1075   friend class LLVMContextImpl;
1076   friend class DIAssignID;
1077 
1078   /// The header that is coallocated with an MDNode along with its "small"
1079   /// operands. It is located immediately before the main body of the node.
1080   /// The operands are in turn located immediately before the header.
1081   /// For resizable MDNodes, the space for the storage vector is also allocated
1082   /// immediately before the header, overlapping with the operands.
1083   /// Explicity set alignment because bitfields by default have an
1084   /// alignment of 1 on z/OS.
1085   struct alignas(alignof(size_t)) Header {
1086     bool IsResizable : 1;
1087     bool IsLarge : 1;
1088     size_t SmallSize : 4;
1089     size_t SmallNumOps : 4;
1090     size_t : sizeof(size_t) * CHAR_BIT - 10;
1091 
1092     unsigned NumUnresolved = 0;
1093     using LargeStorageVector = SmallVector<MDOperand, 0>;
1094 
1095     static constexpr size_t NumOpsFitInVector =
1096         sizeof(LargeStorageVector) / sizeof(MDOperand);
1097     static_assert(
1098         NumOpsFitInVector * sizeof(MDOperand) == sizeof(LargeStorageVector),
1099         "sizeof(LargeStorageVector) must be a multiple of sizeof(MDOperand)");
1100 
1101     static constexpr size_t MaxSmallSize = 15;
1102 
1103     static constexpr size_t getOpSize(unsigned NumOps) {
1104       return sizeof(MDOperand) * NumOps;
1105     }
1106     /// Returns the number of operands the node has space for based on its
1107     /// allocation characteristics.
1108     static size_t getSmallSize(size_t NumOps, bool IsResizable, bool IsLarge) {
1109       return IsLarge ? NumOpsFitInVector
1110                      : std::max(NumOps, NumOpsFitInVector * IsResizable);
1111     }
1112     /// Returns the number of bytes allocated for operands and header.
1113     static size_t getAllocSize(StorageType Storage, size_t NumOps) {
1114       return getOpSize(
1115                  getSmallSize(NumOps, isResizable(Storage), isLarge(NumOps))) +
1116              sizeof(Header);
1117     }
1118 
1119     /// Only temporary and distinct nodes are resizable.
1120     static bool isResizable(StorageType Storage) { return Storage != Uniqued; }
1121     static bool isLarge(size_t NumOps) { return NumOps > MaxSmallSize; }
1122 
1123     size_t getAllocSize() const {
1124       return getOpSize(SmallSize) + sizeof(Header);
1125     }
1126     void *getAllocation() {
1127       return reinterpret_cast<char *>(this + 1) -
1128              alignTo(getAllocSize(), alignof(uint64_t));
1129     }
1130 
1131     void *getLargePtr() const {
1132       static_assert(alignof(LargeStorageVector) <= alignof(Header),
1133                     "LargeStorageVector too strongly aligned");
1134       return reinterpret_cast<char *>(const_cast<Header *>(this)) -
1135              sizeof(LargeStorageVector);
1136     }
1137 
1138     void *getSmallPtr();
1139 
1140     LargeStorageVector &getLarge() {
1141       assert(IsLarge);
1142       return *reinterpret_cast<LargeStorageVector *>(getLargePtr());
1143     }
1144 
1145     const LargeStorageVector &getLarge() const {
1146       assert(IsLarge);
1147       return *reinterpret_cast<const LargeStorageVector *>(getLargePtr());
1148     }
1149 
1150     void resizeSmall(size_t NumOps);
1151     void resizeSmallToLarge(size_t NumOps);
1152     void resize(size_t NumOps);
1153 
1154     explicit Header(size_t NumOps, StorageType Storage);
1155     ~Header();
1156 
1157     MutableArrayRef<MDOperand> operands() {
1158       if (IsLarge)
1159         return getLarge();
1160       return MutableArrayRef(
1161           reinterpret_cast<MDOperand *>(this) - SmallSize, SmallNumOps);
1162     }
1163 
1164     ArrayRef<MDOperand> operands() const {
1165       if (IsLarge)
1166         return getLarge();
1167       return ArrayRef(reinterpret_cast<const MDOperand *>(this) - SmallSize,
1168                       SmallNumOps);
1169     }
1170 
1171     unsigned getNumOperands() const {
1172       if (!IsLarge)
1173         return SmallNumOps;
1174       return getLarge().size();
1175     }
1176   };
1177 
1178   Header &getHeader() { return *(reinterpret_cast<Header *>(this) - 1); }
1179 
1180   const Header &getHeader() const {
1181     return *(reinterpret_cast<const Header *>(this) - 1);
1182   }
1183 
1184   ContextAndReplaceableUses Context;
1185 
1186 protected:
1187   MDNode(LLVMContext &Context, unsigned ID, StorageType Storage,
1188          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = {});
1189   ~MDNode() = default;
1190 
1191   void *operator new(size_t Size, size_t NumOps, StorageType Storage);
1192   void operator delete(void *Mem);
1193 
1194   /// Required by std, but never called.
1195   void operator delete(void *, unsigned) {
1196     llvm_unreachable("Constructor throws?");
1197   }
1198 
1199   /// Required by std, but never called.
1200   void operator delete(void *, unsigned, bool) {
1201     llvm_unreachable("Constructor throws?");
1202   }
1203 
1204   void dropAllReferences();
1205 
1206   MDOperand *mutable_begin() { return getHeader().operands().begin(); }
1207   MDOperand *mutable_end() { return getHeader().operands().end(); }
1208 
1209   using mutable_op_range = iterator_range<MDOperand *>;
1210 
1211   mutable_op_range mutable_operands() {
1212     return mutable_op_range(mutable_begin(), mutable_end());
1213   }
1214 
1215 public:
1216   MDNode(const MDNode &) = delete;
1217   void operator=(const MDNode &) = delete;
1218   void *operator new(size_t) = delete;
1219 
1220   static inline MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs);
1221   static inline MDTuple *getIfExists(LLVMContext &Context,
1222                                      ArrayRef<Metadata *> MDs);
1223   static inline MDTuple *getDistinct(LLVMContext &Context,
1224                                      ArrayRef<Metadata *> MDs);
1225   static inline TempMDTuple getTemporary(LLVMContext &Context,
1226                                          ArrayRef<Metadata *> MDs);
1227 
1228   /// Create a (temporary) clone of this.
1229   TempMDNode clone() const;
1230 
1231   /// Deallocate a node created by getTemporary.
1232   ///
1233   /// Calls \c replaceAllUsesWith(nullptr) before deleting, so any remaining
1234   /// references will be reset.
1235   static void deleteTemporary(MDNode *N);
1236 
1237   LLVMContext &getContext() const { return Context.getContext(); }
1238 
1239   /// Replace a specific operand.
1240   void replaceOperandWith(unsigned I, Metadata *New);
1241 
1242   /// Check if node is fully resolved.
1243   ///
1244   /// If \a isTemporary(), this always returns \c false; if \a isDistinct(),
1245   /// this always returns \c true.
1246   ///
1247   /// If \a isUniqued(), returns \c true if this has already dropped RAUW
1248   /// support (because all operands are resolved).
1249   ///
1250   /// As forward declarations are resolved, their containers should get
1251   /// resolved automatically.  However, if this (or one of its operands) is
1252   /// involved in a cycle, \a resolveCycles() needs to be called explicitly.
1253   bool isResolved() const { return !isTemporary() && !getNumUnresolved(); }
1254 
1255   bool isUniqued() const { return Storage == Uniqued; }
1256   bool isDistinct() const { return Storage == Distinct; }
1257   bool isTemporary() const { return Storage == Temporary; }
1258 
1259   bool isReplaceable() const { return isTemporary() || isAlwaysReplaceable(); }
1260   bool isAlwaysReplaceable() const { return getMetadataID() == DIAssignIDKind; }
1261 
1262   unsigned getNumTemporaryUses() const {
1263     assert(isTemporary() && "Only for temporaries");
1264     return Context.getReplaceableUses()->getNumUses();
1265   }
1266 
1267   /// RAUW a temporary.
1268   ///
1269   /// \pre \a isTemporary() must be \c true.
1270   void replaceAllUsesWith(Metadata *MD) {
1271     assert(isReplaceable() && "Expected temporary/replaceable node");
1272     if (Context.hasReplaceableUses())
1273       Context.getReplaceableUses()->replaceAllUsesWith(MD);
1274   }
1275 
1276   /// Resolve cycles.
1277   ///
1278   /// Once all forward declarations have been resolved, force cycles to be
1279   /// resolved.
1280   ///
1281   /// \pre No operands (or operands' operands, etc.) have \a isTemporary().
1282   void resolveCycles();
1283 
1284   /// Resolve a unique, unresolved node.
1285   void resolve();
1286 
1287   /// Replace a temporary node with a permanent one.
1288   ///
1289   /// Try to create a uniqued version of \c N -- in place, if possible -- and
1290   /// return it.  If \c N cannot be uniqued, return a distinct node instead.
1291   template <class T>
1292   static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1293   replaceWithPermanent(std::unique_ptr<T, TempMDNodeDeleter> N) {
1294     return cast<T>(N.release()->replaceWithPermanentImpl());
1295   }
1296 
1297   /// Replace a temporary node with a uniqued one.
1298   ///
1299   /// Create a uniqued version of \c N -- in place, if possible -- and return
1300   /// it.  Takes ownership of the temporary node.
1301   ///
1302   /// \pre N does not self-reference.
1303   template <class T>
1304   static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1305   replaceWithUniqued(std::unique_ptr<T, TempMDNodeDeleter> N) {
1306     return cast<T>(N.release()->replaceWithUniquedImpl());
1307   }
1308 
1309   /// Replace a temporary node with a distinct one.
1310   ///
1311   /// Create a distinct version of \c N -- in place, if possible -- and return
1312   /// it.  Takes ownership of the temporary node.
1313   template <class T>
1314   static std::enable_if_t<std::is_base_of<MDNode, T>::value, T *>
1315   replaceWithDistinct(std::unique_ptr<T, TempMDNodeDeleter> N) {
1316     return cast<T>(N.release()->replaceWithDistinctImpl());
1317   }
1318 
1319   /// Print in tree shape.
1320   ///
1321   /// Prints definition of \c this in tree shape.
1322   ///
1323   /// If \c M is provided, metadata nodes will be numbered canonically;
1324   /// otherwise, pointer addresses are substituted.
1325   /// @{
1326   void printTree(raw_ostream &OS, const Module *M = nullptr) const;
1327   void printTree(raw_ostream &OS, ModuleSlotTracker &MST,
1328                  const Module *M = nullptr) const;
1329   /// @}
1330 
1331   /// User-friendly dump in tree shape.
1332   ///
1333   /// If \c M is provided, metadata nodes will be numbered canonically;
1334   /// otherwise, pointer addresses are substituted.
1335   ///
1336   /// Note: this uses an explicit overload instead of default arguments so that
1337   /// the nullptr version is easy to call from a debugger.
1338   ///
1339   /// @{
1340   void dumpTree() const;
1341   void dumpTree(const Module *M) const;
1342   /// @}
1343 
1344 private:
1345   MDNode *replaceWithPermanentImpl();
1346   MDNode *replaceWithUniquedImpl();
1347   MDNode *replaceWithDistinctImpl();
1348 
1349 protected:
1350   /// Set an operand.
1351   ///
1352   /// Sets the operand directly, without worrying about uniquing.
1353   void setOperand(unsigned I, Metadata *New);
1354 
1355   unsigned getNumUnresolved() const { return getHeader().NumUnresolved; }
1356 
1357   void setNumUnresolved(unsigned N) { getHeader().NumUnresolved = N; }
1358   void storeDistinctInContext();
1359   template <class T, class StoreT>
1360   static T *storeImpl(T *N, StorageType Storage, StoreT &Store);
1361   template <class T> static T *storeImpl(T *N, StorageType Storage);
1362 
1363   /// Resize the node to hold \a NumOps operands.
1364   ///
1365   /// \pre \a isTemporary() or \a isDistinct()
1366   /// \pre MetadataID == MDTupleKind
1367   void resize(size_t NumOps) {
1368     assert(!isUniqued() && "Resizing is not supported for uniqued nodes");
1369     assert(getMetadataID() == MDTupleKind &&
1370            "Resizing is not supported for this node kind");
1371     getHeader().resize(NumOps);
1372   }
1373 
1374 private:
1375   void handleChangedOperand(void *Ref, Metadata *New);
1376 
1377   /// Drop RAUW support, if any.
1378   void dropReplaceableUses();
1379 
1380   void resolveAfterOperandChange(Metadata *Old, Metadata *New);
1381   void decrementUnresolvedOperandCount();
1382   void countUnresolvedOperands();
1383 
1384   /// Mutate this to be "uniqued".
1385   ///
1386   /// Mutate this so that \a isUniqued().
1387   /// \pre \a isTemporary().
1388   /// \pre already added to uniquing set.
1389   void makeUniqued();
1390 
1391   /// Mutate this to be "distinct".
1392   ///
1393   /// Mutate this so that \a isDistinct().
1394   /// \pre \a isTemporary().
1395   void makeDistinct();
1396 
1397   void deleteAsSubclass();
1398   MDNode *uniquify();
1399   void eraseFromStore();
1400 
1401   template <class NodeTy> struct HasCachedHash;
1402   template <class NodeTy>
1403   static void dispatchRecalculateHash(NodeTy *N, std::true_type) {
1404     N->recalculateHash();
1405   }
1406   template <class NodeTy>
1407   static void dispatchRecalculateHash(NodeTy *, std::false_type) {}
1408   template <class NodeTy>
1409   static void dispatchResetHash(NodeTy *N, std::true_type) {
1410     N->setHash(0);
1411   }
1412   template <class NodeTy>
1413   static void dispatchResetHash(NodeTy *, std::false_type) {}
1414 
1415   /// Merge branch weights from two direct callsites.
1416   static MDNode *mergeDirectCallProfMetadata(MDNode *A, MDNode *B,
1417                                              const Instruction *AInstr,
1418                                              const Instruction *BInstr);
1419 
1420 public:
1421   using op_iterator = const MDOperand *;
1422   using op_range = iterator_range<op_iterator>;
1423 
1424   op_iterator op_begin() const {
1425     return const_cast<MDNode *>(this)->mutable_begin();
1426   }
1427 
1428   op_iterator op_end() const {
1429     return const_cast<MDNode *>(this)->mutable_end();
1430   }
1431 
1432   ArrayRef<MDOperand> operands() const { return getHeader().operands(); }
1433 
1434   const MDOperand &getOperand(unsigned I) const {
1435     assert(I < getNumOperands() && "Out of range");
1436     return getHeader().operands()[I];
1437   }
1438 
1439   /// Return number of MDNode operands.
1440   unsigned getNumOperands() const { return getHeader().getNumOperands(); }
1441 
1442   /// Methods for support type inquiry through isa, cast, and dyn_cast:
1443   static bool classof(const Metadata *MD) {
1444     switch (MD->getMetadataID()) {
1445     default:
1446       return false;
1447 #define HANDLE_MDNODE_LEAF(CLASS)                                              \
1448   case CLASS##Kind:                                                            \
1449     return true;
1450 #include "llvm/IR/Metadata.def"
1451     }
1452   }
1453 
1454   /// Check whether MDNode is a vtable access.
1455   bool isTBAAVtableAccess() const;
1456 
1457   /// Methods for metadata merging.
1458   static MDNode *concatenate(MDNode *A, MDNode *B);
1459   static MDNode *intersect(MDNode *A, MDNode *B);
1460   static MDNode *getMostGenericTBAA(MDNode *A, MDNode *B);
1461   static MDNode *getMostGenericFPMath(MDNode *A, MDNode *B);
1462   static MDNode *getMostGenericRange(MDNode *A, MDNode *B);
1463   static MDNode *getMostGenericNoaliasAddrspace(MDNode *A, MDNode *B);
1464   static MDNode *getMostGenericAliasScope(MDNode *A, MDNode *B);
1465   static MDNode *getMostGenericAlignmentOrDereferenceable(MDNode *A, MDNode *B);
1466   /// Merge !prof metadata from two instructions.
1467   /// Currently only implemented with direct callsites with branch weights.
1468   static MDNode *getMergedProfMetadata(MDNode *A, MDNode *B,
1469                                        const Instruction *AInstr,
1470                                        const Instruction *BInstr);
1471   static MDNode *getMergedMemProfMetadata(MDNode *A, MDNode *B);
1472   static MDNode *getMergedCallsiteMetadata(MDNode *A, MDNode *B);
1473 };
1474 
1475 /// Tuple of metadata.
1476 ///
1477 /// This is the simple \a MDNode arbitrary tuple.  Nodes are uniqued by
1478 /// default based on their operands.
1479 class MDTuple : public MDNode {
1480   friend class LLVMContextImpl;
1481   friend class MDNode;
1482 
1483   MDTuple(LLVMContext &C, StorageType Storage, unsigned Hash,
1484           ArrayRef<Metadata *> Vals)
1485       : MDNode(C, MDTupleKind, Storage, Vals) {
1486     setHash(Hash);
1487   }
1488 
1489   ~MDTuple() { dropAllReferences(); }
1490 
1491   void setHash(unsigned Hash) { SubclassData32 = Hash; }
1492   void recalculateHash();
1493 
1494   static MDTuple *getImpl(LLVMContext &Context, ArrayRef<Metadata *> MDs,
1495                           StorageType Storage, bool ShouldCreate = true);
1496 
1497   TempMDTuple cloneImpl() const {
1498     ArrayRef<MDOperand> Operands = operands();
1499     return getTemporary(getContext(), SmallVector<Metadata *, 4>(Operands));
1500   }
1501 
1502 public:
1503   /// Get the hash, if any.
1504   unsigned getHash() const { return SubclassData32; }
1505 
1506   static MDTuple *get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1507     return getImpl(Context, MDs, Uniqued);
1508   }
1509 
1510   static MDTuple *getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1511     return getImpl(Context, MDs, Uniqued, /* ShouldCreate */ false);
1512   }
1513 
1514   /// Return a distinct node.
1515   ///
1516   /// Return a distinct node -- i.e., a node that is not uniqued.
1517   static MDTuple *getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1518     return getImpl(Context, MDs, Distinct);
1519   }
1520 
1521   /// Return a temporary node.
1522   ///
1523   /// For use in constructing cyclic MDNode structures. A temporary MDNode is
1524   /// not uniqued, may be RAUW'd, and must be manually deleted with
1525   /// deleteTemporary.
1526   static TempMDTuple getTemporary(LLVMContext &Context,
1527                                   ArrayRef<Metadata *> MDs) {
1528     return TempMDTuple(getImpl(Context, MDs, Temporary));
1529   }
1530 
1531   /// Return a (temporary) clone of this.
1532   TempMDTuple clone() const { return cloneImpl(); }
1533 
1534   /// Append an element to the tuple. This will resize the node.
1535   void push_back(Metadata *MD) {
1536     size_t NumOps = getNumOperands();
1537     resize(NumOps + 1);
1538     setOperand(NumOps, MD);
1539   }
1540 
1541   /// Shrink the operands by 1.
1542   void pop_back() { resize(getNumOperands() - 1); }
1543 
1544   static bool classof(const Metadata *MD) {
1545     return MD->getMetadataID() == MDTupleKind;
1546   }
1547 };
1548 
1549 MDTuple *MDNode::get(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1550   return MDTuple::get(Context, MDs);
1551 }
1552 
1553 MDTuple *MDNode::getIfExists(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1554   return MDTuple::getIfExists(Context, MDs);
1555 }
1556 
1557 MDTuple *MDNode::getDistinct(LLVMContext &Context, ArrayRef<Metadata *> MDs) {
1558   return MDTuple::getDistinct(Context, MDs);
1559 }
1560 
1561 TempMDTuple MDNode::getTemporary(LLVMContext &Context,
1562                                  ArrayRef<Metadata *> MDs) {
1563   return MDTuple::getTemporary(Context, MDs);
1564 }
1565 
1566 void TempMDNodeDeleter::operator()(MDNode *Node) const {
1567   MDNode::deleteTemporary(Node);
1568 }
1569 
1570 /// This is a simple wrapper around an MDNode which provides a higher-level
1571 /// interface by hiding the details of how alias analysis information is encoded
1572 /// in its operands.
1573 class AliasScopeNode {
1574   const MDNode *Node = nullptr;
1575 
1576 public:
1577   AliasScopeNode() = default;
1578   explicit AliasScopeNode(const MDNode *N) : Node(N) {}
1579 
1580   /// Get the MDNode for this AliasScopeNode.
1581   const MDNode *getNode() const { return Node; }
1582 
1583   /// Get the MDNode for this AliasScopeNode's domain.
1584   const MDNode *getDomain() const {
1585     if (Node->getNumOperands() < 2)
1586       return nullptr;
1587     return dyn_cast_or_null<MDNode>(Node->getOperand(1));
1588   }
1589   StringRef getName() const {
1590     if (Node->getNumOperands() > 2)
1591       if (MDString *N = dyn_cast_or_null<MDString>(Node->getOperand(2)))
1592         return N->getString();
1593     return StringRef();
1594   }
1595 };
1596 
1597 /// Typed iterator through MDNode operands.
1598 ///
1599 /// An iterator that transforms an \a MDNode::iterator into an iterator over a
1600 /// particular Metadata subclass.
1601 template <class T> class TypedMDOperandIterator {
1602   MDNode::op_iterator I = nullptr;
1603 
1604 public:
1605   using iterator_category = std::input_iterator_tag;
1606   using value_type = T *;
1607   using difference_type = std::ptrdiff_t;
1608   using pointer = void;
1609   using reference = T *;
1610 
1611   TypedMDOperandIterator() = default;
1612   explicit TypedMDOperandIterator(MDNode::op_iterator I) : I(I) {}
1613 
1614   T *operator*() const { return cast_or_null<T>(*I); }
1615 
1616   TypedMDOperandIterator &operator++() {
1617     ++I;
1618     return *this;
1619   }
1620 
1621   TypedMDOperandIterator operator++(int) {
1622     TypedMDOperandIterator Temp(*this);
1623     ++I;
1624     return Temp;
1625   }
1626 
1627   bool operator==(const TypedMDOperandIterator &X) const { return I == X.I; }
1628   bool operator!=(const TypedMDOperandIterator &X) const { return I != X.I; }
1629 };
1630 
1631 /// Typed, array-like tuple of metadata.
1632 ///
1633 /// This is a wrapper for \a MDTuple that makes it act like an array holding a
1634 /// particular type of metadata.
1635 template <class T> class MDTupleTypedArrayWrapper {
1636   const MDTuple *N = nullptr;
1637 
1638 public:
1639   MDTupleTypedArrayWrapper() = default;
1640   MDTupleTypedArrayWrapper(const MDTuple *N) : N(N) {}
1641 
1642   template <class U>
1643   MDTupleTypedArrayWrapper(
1644       const MDTupleTypedArrayWrapper<U> &Other,
1645       std::enable_if_t<std::is_convertible<U *, T *>::value> * = nullptr)
1646       : N(Other.get()) {}
1647 
1648   template <class U>
1649   explicit MDTupleTypedArrayWrapper(
1650       const MDTupleTypedArrayWrapper<U> &Other,
1651       std::enable_if_t<!std::is_convertible<U *, T *>::value> * = nullptr)
1652       : N(Other.get()) {}
1653 
1654   explicit operator bool() const { return get(); }
1655   explicit operator MDTuple *() const { return get(); }
1656 
1657   MDTuple *get() const { return const_cast<MDTuple *>(N); }
1658   MDTuple *operator->() const { return get(); }
1659   MDTuple &operator*() const { return *get(); }
1660 
1661   // FIXME: Fix callers and remove condition on N.
1662   unsigned size() const { return N ? N->getNumOperands() : 0u; }
1663   bool empty() const { return N ? N->getNumOperands() == 0 : true; }
1664   T *operator[](unsigned I) const { return cast_or_null<T>(N->getOperand(I)); }
1665 
1666   // FIXME: Fix callers and remove condition on N.
1667   using iterator = TypedMDOperandIterator<T>;
1668 
1669   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
1670   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
1671 };
1672 
1673 #define HANDLE_METADATA(CLASS)                                                 \
1674   using CLASS##Array = MDTupleTypedArrayWrapper<CLASS>;
1675 #include "llvm/IR/Metadata.def"
1676 
1677 /// Placeholder metadata for operands of distinct MDNodes.
1678 ///
1679 /// This is a lightweight placeholder for an operand of a distinct node.  It's
1680 /// purpose is to help track forward references when creating a distinct node.
1681 /// This allows distinct nodes involved in a cycle to be constructed before
1682 /// their operands without requiring a heavyweight temporary node with
1683 /// full-blown RAUW support.
1684 ///
1685 /// Each placeholder supports only a single MDNode user.  Clients should pass
1686 /// an ID, retrieved via \a getID(), to indicate the "real" operand that this
1687 /// should be replaced with.
1688 ///
1689 /// While it would be possible to implement move operators, they would be
1690 /// fairly expensive.  Leave them unimplemented to discourage their use
1691 /// (clients can use std::deque, std::list, BumpPtrAllocator, etc.).
1692 class DistinctMDOperandPlaceholder : public Metadata {
1693   friend class MetadataTracking;
1694 
1695   Metadata **Use = nullptr;
1696 
1697 public:
1698   explicit DistinctMDOperandPlaceholder(unsigned ID)
1699       : Metadata(DistinctMDOperandPlaceholderKind, Distinct) {
1700     SubclassData32 = ID;
1701   }
1702 
1703   DistinctMDOperandPlaceholder() = delete;
1704   DistinctMDOperandPlaceholder(DistinctMDOperandPlaceholder &&) = delete;
1705   DistinctMDOperandPlaceholder(const DistinctMDOperandPlaceholder &) = delete;
1706 
1707   ~DistinctMDOperandPlaceholder() {
1708     if (Use)
1709       *Use = nullptr;
1710   }
1711 
1712   unsigned getID() const { return SubclassData32; }
1713 
1714   /// Replace the use of this with MD.
1715   void replaceUseWith(Metadata *MD) {
1716     if (!Use)
1717       return;
1718     *Use = MD;
1719 
1720     if (*Use)
1721       MetadataTracking::track(*Use);
1722 
1723     Metadata *T = cast<Metadata>(this);
1724     MetadataTracking::untrack(T);
1725     assert(!Use && "Use is still being tracked despite being untracked!");
1726   }
1727 };
1728 
1729 //===----------------------------------------------------------------------===//
1730 /// A tuple of MDNodes.
1731 ///
1732 /// Despite its name, a NamedMDNode isn't itself an MDNode.
1733 ///
1734 /// NamedMDNodes are named module-level entities that contain lists of MDNodes.
1735 ///
1736 /// It is illegal for a NamedMDNode to appear as an operand of an MDNode.
1737 class NamedMDNode : public ilist_node<NamedMDNode> {
1738   friend class LLVMContextImpl;
1739   friend class Module;
1740 
1741   std::string Name;
1742   Module *Parent = nullptr;
1743   void *Operands; // SmallVector<TrackingMDRef, 4>
1744 
1745   void setParent(Module *M) { Parent = M; }
1746 
1747   explicit NamedMDNode(const Twine &N);
1748 
1749   template <class T1> class op_iterator_impl {
1750     friend class NamedMDNode;
1751 
1752     const NamedMDNode *Node = nullptr;
1753     unsigned Idx = 0;
1754 
1755     op_iterator_impl(const NamedMDNode *N, unsigned i) : Node(N), Idx(i) {}
1756 
1757   public:
1758     using iterator_category = std::bidirectional_iterator_tag;
1759     using value_type = T1;
1760     using difference_type = std::ptrdiff_t;
1761     using pointer = value_type *;
1762     using reference = value_type;
1763 
1764     op_iterator_impl() = default;
1765 
1766     bool operator==(const op_iterator_impl &o) const { return Idx == o.Idx; }
1767     bool operator!=(const op_iterator_impl &o) const { return Idx != o.Idx; }
1768 
1769     op_iterator_impl &operator++() {
1770       ++Idx;
1771       return *this;
1772     }
1773 
1774     op_iterator_impl operator++(int) {
1775       op_iterator_impl tmp(*this);
1776       operator++();
1777       return tmp;
1778     }
1779 
1780     op_iterator_impl &operator--() {
1781       --Idx;
1782       return *this;
1783     }
1784 
1785     op_iterator_impl operator--(int) {
1786       op_iterator_impl tmp(*this);
1787       operator--();
1788       return tmp;
1789     }
1790 
1791     T1 operator*() const { return Node->getOperand(Idx); }
1792   };
1793 
1794 public:
1795   NamedMDNode(const NamedMDNode &) = delete;
1796   ~NamedMDNode();
1797 
1798   /// Drop all references and remove the node from parent module.
1799   void eraseFromParent();
1800 
1801   /// Remove all uses and clear node vector.
1802   void dropAllReferences() { clearOperands(); }
1803   /// Drop all references to this node's operands.
1804   void clearOperands();
1805 
1806   /// Get the module that holds this named metadata collection.
1807   inline Module *getParent() { return Parent; }
1808   inline const Module *getParent() const { return Parent; }
1809 
1810   MDNode *getOperand(unsigned i) const;
1811   unsigned getNumOperands() const;
1812   void addOperand(MDNode *M);
1813   void setOperand(unsigned I, MDNode *New);
1814   StringRef getName() const;
1815   void print(raw_ostream &ROS, bool IsForDebug = false) const;
1816   void print(raw_ostream &ROS, ModuleSlotTracker &MST,
1817              bool IsForDebug = false) const;
1818   void dump() const;
1819 
1820   // ---------------------------------------------------------------------------
1821   // Operand Iterator interface...
1822   //
1823   using op_iterator = op_iterator_impl<MDNode *>;
1824 
1825   op_iterator op_begin() { return op_iterator(this, 0); }
1826   op_iterator op_end()   { return op_iterator(this, getNumOperands()); }
1827 
1828   using const_op_iterator = op_iterator_impl<const MDNode *>;
1829 
1830   const_op_iterator op_begin() const { return const_op_iterator(this, 0); }
1831   const_op_iterator op_end()   const { return const_op_iterator(this, getNumOperands()); }
1832 
1833   inline iterator_range<op_iterator>  operands() {
1834     return make_range(op_begin(), op_end());
1835   }
1836   inline iterator_range<const_op_iterator> operands() const {
1837     return make_range(op_begin(), op_end());
1838   }
1839 };
1840 
1841 // Create wrappers for C Binding types (see CBindingWrapping.h).
1842 DEFINE_ISA_CONVERSION_FUNCTIONS(NamedMDNode, LLVMNamedMDNodeRef)
1843 
1844 } // end namespace llvm
1845 
1846 #endif // LLVM_IR_METADATA_H