Home | History | Annotate | Download | only in IR
      1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- 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 // Declarations for metadata specific to debug info.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
     15 #define LLVM_IR_DEBUGINFOMETADATA_H
     16 
     17 #include "llvm/ADT/ArrayRef.h"
     18 #include "llvm/ADT/BitmaskEnum.h"
     19 #include "llvm/ADT/None.h"
     20 #include "llvm/ADT/SmallVector.h"
     21 #include "llvm/ADT/StringRef.h"
     22 #include "llvm/IR/Metadata.h"
     23 #include "llvm/Support/Casting.h"
     24 #include "llvm/Support/Dwarf.h"
     25 #include <cassert>
     26 #include <climits>
     27 #include <cstddef>
     28 #include <cstdint>
     29 #include <iterator>
     30 #include <type_traits>
     31 #include <vector>
     32 
     33 // Helper macros for defining get() overrides.
     34 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
     35 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
     36 #define DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)              \
     37   static CLASS *getDistinct(LLVMContext &Context,                              \
     38                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
     39     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
     40   }                                                                            \
     41   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
     42                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
     43     return Temp##CLASS(                                                        \
     44         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
     45   }
     46 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
     47   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
     48     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
     49   }                                                                            \
     50   static CLASS *getIfExists(LLVMContext &Context,                              \
     51                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
     52     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
     53                    /* ShouldCreate */ false);                                  \
     54   }                                                                            \
     55   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)
     56 
     57 namespace llvm {
     58 
     59 template <typename T> class Optional;
     60 
     61 /// Holds a subclass of DINode.
     62 ///
     63 /// FIXME: This class doesn't currently make much sense.  Previously it was a
     64 /// union beteen MDString (for ODR-uniqued types) and things like DIType.  To
     65 /// support CodeView work, it wasn't deleted outright when MDString-based type
     66 /// references were deleted; we'll soon need a similar concept for CodeView
     67 /// DITypeIndex.
     68 template <class T> class TypedDINodeRef {
     69   const Metadata *MD = nullptr;
     70 
     71 public:
     72   TypedDINodeRef() = default;
     73   TypedDINodeRef(std::nullptr_t) {}
     74   TypedDINodeRef(const T *MD) : MD(MD) {}
     75 
     76   explicit TypedDINodeRef(const Metadata *MD) : MD(MD) {
     77     assert((!MD || isa<T>(MD)) && "Expected valid type ref");
     78   }
     79 
     80   template <class U>
     81   TypedDINodeRef(
     82       const TypedDINodeRef<U> &X,
     83       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
     84           nullptr)
     85       : MD(X) {}
     86 
     87   operator Metadata *() const { return const_cast<Metadata *>(MD); }
     88 
     89   T *resolve() const { return const_cast<T *>(cast_or_null<T>(MD)); }
     90 
     91   bool operator==(const TypedDINodeRef<T> &X) const { return MD == X.MD; }
     92   bool operator!=(const TypedDINodeRef<T> &X) const { return MD != X.MD; }
     93 };
     94 
     95 typedef TypedDINodeRef<DINode> DINodeRef;
     96 typedef TypedDINodeRef<DIScope> DIScopeRef;
     97 typedef TypedDINodeRef<DIType> DITypeRef;
     98 
     99 class DITypeRefArray {
    100   const MDTuple *N = nullptr;
    101 
    102 public:
    103   DITypeRefArray() = default;
    104   DITypeRefArray(const MDTuple *N) : N(N) {}
    105 
    106   explicit operator bool() const { return get(); }
    107   explicit operator MDTuple *() const { return get(); }
    108 
    109   MDTuple *get() const { return const_cast<MDTuple *>(N); }
    110   MDTuple *operator->() const { return get(); }
    111   MDTuple &operator*() const { return *get(); }
    112 
    113   // FIXME: Fix callers and remove condition on N.
    114   unsigned size() const { return N ? N->getNumOperands() : 0u; }
    115   DITypeRef operator[](unsigned I) const { return DITypeRef(N->getOperand(I)); }
    116 
    117   class iterator : std::iterator<std::input_iterator_tag, DITypeRef,
    118                                  std::ptrdiff_t, void, DITypeRef> {
    119     MDNode::op_iterator I = nullptr;
    120 
    121   public:
    122     iterator() = default;
    123     explicit iterator(MDNode::op_iterator I) : I(I) {}
    124 
    125     DITypeRef operator*() const { return DITypeRef(*I); }
    126 
    127     iterator &operator++() {
    128       ++I;
    129       return *this;
    130     }
    131 
    132     iterator operator++(int) {
    133       iterator Temp(*this);
    134       ++I;
    135       return Temp;
    136     }
    137 
    138     bool operator==(const iterator &X) const { return I == X.I; }
    139     bool operator!=(const iterator &X) const { return I != X.I; }
    140   };
    141 
    142   // FIXME: Fix callers and remove condition on N.
    143   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
    144   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
    145 };
    146 
    147 /// Tagged DWARF-like metadata node.
    148 ///
    149 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
    150 /// defined in llvm/Support/Dwarf.h).  Called \a DINode because it's
    151 /// potentially used for non-DWARF output.
    152 class DINode : public MDNode {
    153   friend class LLVMContextImpl;
    154   friend class MDNode;
    155 
    156 protected:
    157   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    158          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
    159       : MDNode(C, ID, Storage, Ops1, Ops2) {
    160     assert(Tag < 1u << 16);
    161     SubclassData16 = Tag;
    162   }
    163   ~DINode() = default;
    164 
    165   template <class Ty> Ty *getOperandAs(unsigned I) const {
    166     return cast_or_null<Ty>(getOperand(I));
    167   }
    168 
    169   StringRef getStringOperand(unsigned I) const {
    170     if (auto *S = getOperandAs<MDString>(I))
    171       return S->getString();
    172     return StringRef();
    173   }
    174 
    175   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
    176     if (S.empty())
    177       return nullptr;
    178     return MDString::get(Context, S);
    179   }
    180 
    181   /// Allow subclasses to mutate the tag.
    182   void setTag(unsigned Tag) { SubclassData16 = Tag; }
    183 
    184 public:
    185   unsigned getTag() const { return SubclassData16; }
    186 
    187   /// Debug info flags.
    188   ///
    189   /// The three accessibility flags are mutually exclusive and rolled together
    190   /// in the first two bits.
    191   enum DIFlags : uint32_t {
    192 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
    193 #define DI_FLAG_LARGEST_NEEDED
    194 #include "llvm/IR/DebugInfoFlags.def"
    195     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
    196     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
    197                          FlagVirtualInheritance,
    198     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
    199   };
    200 
    201   static DIFlags getFlag(StringRef Flag);
    202   static StringRef getFlagString(DIFlags Flag);
    203 
    204   /// Split up a flags bitfield.
    205   ///
    206   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
    207   /// any remaining (unrecognized) bits.
    208   static DIFlags splitFlags(DIFlags Flags,
    209                             SmallVectorImpl<DIFlags> &SplitFlags);
    210 
    211   static bool classof(const Metadata *MD) {
    212     switch (MD->getMetadataID()) {
    213     default:
    214       return false;
    215     case GenericDINodeKind:
    216     case DISubrangeKind:
    217     case DIEnumeratorKind:
    218     case DIBasicTypeKind:
    219     case DIDerivedTypeKind:
    220     case DICompositeTypeKind:
    221     case DISubroutineTypeKind:
    222     case DIFileKind:
    223     case DICompileUnitKind:
    224     case DISubprogramKind:
    225     case DILexicalBlockKind:
    226     case DILexicalBlockFileKind:
    227     case DINamespaceKind:
    228     case DITemplateTypeParameterKind:
    229     case DITemplateValueParameterKind:
    230     case DIGlobalVariableKind:
    231     case DILocalVariableKind:
    232     case DIObjCPropertyKind:
    233     case DIImportedEntityKind:
    234     case DIModuleKind:
    235       return true;
    236     }
    237   }
    238 };
    239 
    240 template <class T> struct simplify_type<const TypedDINodeRef<T>> {
    241   typedef Metadata *SimpleType;
    242   static SimpleType getSimplifiedValue(const TypedDINodeRef<T> &MD) {
    243     return MD;
    244   }
    245 };
    246 
    247 template <class T>
    248 struct simplify_type<TypedDINodeRef<T>>
    249     : simplify_type<const TypedDINodeRef<T>> {};
    250 
    251 /// Generic tagged DWARF-like metadata node.
    252 ///
    253 /// An un-specialized DWARF-like metadata node.  The first operand is a
    254 /// (possibly empty) null-separated \a MDString header that contains arbitrary
    255 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
    256 /// to other metadata.
    257 class GenericDINode : public DINode {
    258   friend class LLVMContextImpl;
    259   friend class MDNode;
    260 
    261   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
    262                 unsigned Tag, ArrayRef<Metadata *> Ops1,
    263                 ArrayRef<Metadata *> Ops2)
    264       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
    265     setHash(Hash);
    266   }
    267   ~GenericDINode() { dropAllReferences(); }
    268 
    269   void setHash(unsigned Hash) { SubclassData32 = Hash; }
    270   void recalculateHash();
    271 
    272   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
    273                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
    274                                 StorageType Storage, bool ShouldCreate = true) {
    275     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
    276                    DwarfOps, Storage, ShouldCreate);
    277   }
    278 
    279   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
    280                                 MDString *Header, ArrayRef<Metadata *> DwarfOps,
    281                                 StorageType Storage, bool ShouldCreate = true);
    282 
    283   TempGenericDINode cloneImpl() const {
    284     return getTemporary(
    285         getContext(), getTag(), getHeader(),
    286         SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
    287   }
    288 
    289 public:
    290   unsigned getHash() const { return SubclassData32; }
    291 
    292   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, StringRef Header,
    293                                     ArrayRef<Metadata *> DwarfOps),
    294                     (Tag, Header, DwarfOps))
    295   DEFINE_MDNODE_GET(GenericDINode, (unsigned Tag, MDString *Header,
    296                                     ArrayRef<Metadata *> DwarfOps),
    297                     (Tag, Header, DwarfOps))
    298 
    299   /// Return a (temporary) clone of this.
    300   TempGenericDINode clone() const { return cloneImpl(); }
    301 
    302   unsigned getTag() const { return SubclassData16; }
    303   StringRef getHeader() const { return getStringOperand(0); }
    304   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
    305 
    306   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
    307   op_iterator dwarf_op_end() const { return op_end(); }
    308   op_range dwarf_operands() const {
    309     return op_range(dwarf_op_begin(), dwarf_op_end());
    310   }
    311 
    312   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
    313   const MDOperand &getDwarfOperand(unsigned I) const {
    314     return getOperand(I + 1);
    315   }
    316   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
    317     replaceOperandWith(I + 1, New);
    318   }
    319 
    320   static bool classof(const Metadata *MD) {
    321     return MD->getMetadataID() == GenericDINodeKind;
    322   }
    323 };
    324 
    325 /// Array subrange.
    326 ///
    327 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
    328 /// type.
    329 class DISubrange : public DINode {
    330   friend class LLVMContextImpl;
    331   friend class MDNode;
    332 
    333   int64_t Count;
    334   int64_t LowerBound;
    335 
    336   DISubrange(LLVMContext &C, StorageType Storage, int64_t Count,
    337              int64_t LowerBound)
    338       : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, None),
    339         Count(Count), LowerBound(LowerBound) {}
    340   ~DISubrange() = default;
    341 
    342   static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
    343                              int64_t LowerBound, StorageType Storage,
    344                              bool ShouldCreate = true);
    345 
    346   TempDISubrange cloneImpl() const {
    347     return getTemporary(getContext(), getCount(), getLowerBound());
    348   }
    349 
    350 public:
    351   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
    352                     (Count, LowerBound))
    353 
    354   TempDISubrange clone() const { return cloneImpl(); }
    355 
    356   int64_t getLowerBound() const { return LowerBound; }
    357   int64_t getCount() const { return Count; }
    358 
    359   static bool classof(const Metadata *MD) {
    360     return MD->getMetadataID() == DISubrangeKind;
    361   }
    362 };
    363 
    364 /// Enumeration value.
    365 ///
    366 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
    367 /// longer creates a type cycle.
    368 class DIEnumerator : public DINode {
    369   friend class LLVMContextImpl;
    370   friend class MDNode;
    371 
    372   int64_t Value;
    373 
    374   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
    375                ArrayRef<Metadata *> Ops)
    376       : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
    377         Value(Value) {}
    378   ~DIEnumerator() = default;
    379 
    380   static DIEnumerator *getImpl(LLVMContext &Context, int64_t Value,
    381                                StringRef Name, StorageType Storage,
    382                                bool ShouldCreate = true) {
    383     return getImpl(Context, Value, getCanonicalMDString(Context, Name), Storage,
    384                    ShouldCreate);
    385   }
    386   static DIEnumerator *getImpl(LLVMContext &Context, int64_t Value,
    387                                MDString *Name, StorageType Storage,
    388                                bool ShouldCreate = true);
    389 
    390   TempDIEnumerator cloneImpl() const {
    391     return getTemporary(getContext(), getValue(), getName());
    392   }
    393 
    394 public:
    395   DEFINE_MDNODE_GET(DIEnumerator, (int64_t Value, StringRef Name),
    396                     (Value, Name))
    397   DEFINE_MDNODE_GET(DIEnumerator, (int64_t Value, MDString *Name),
    398                     (Value, Name))
    399 
    400   TempDIEnumerator clone() const { return cloneImpl(); }
    401 
    402   int64_t getValue() const { return Value; }
    403   StringRef getName() const { return getStringOperand(0); }
    404 
    405   MDString *getRawName() const { return getOperandAs<MDString>(0); }
    406 
    407   static bool classof(const Metadata *MD) {
    408     return MD->getMetadataID() == DIEnumeratorKind;
    409   }
    410 };
    411 
    412 /// Base class for scope-like contexts.
    413 ///
    414 /// Base class for lexical scopes and types (which are also declaration
    415 /// contexts).
    416 ///
    417 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
    418 class DIScope : public DINode {
    419 protected:
    420   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    421           ArrayRef<Metadata *> Ops)
    422       : DINode(C, ID, Storage, Tag, Ops) {}
    423   ~DIScope() = default;
    424 
    425 public:
    426   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
    427 
    428   inline StringRef getFilename() const;
    429   inline StringRef getDirectory() const;
    430 
    431   StringRef getName() const;
    432   DIScopeRef getScope() const;
    433 
    434   /// Return the raw underlying file.
    435   ///
    436   /// An \a DIFile is an \a DIScope, but it doesn't point at a separate file
    437   /// (it\em is the file).  If \c this is an \a DIFile, we need to return \c
    438   /// this.  Otherwise, return the first operand, which is where all other
    439   /// subclasses store their file pointer.
    440   Metadata *getRawFile() const {
    441     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
    442                              : static_cast<Metadata *>(getOperand(0));
    443   }
    444 
    445   static bool classof(const Metadata *MD) {
    446     switch (MD->getMetadataID()) {
    447     default:
    448       return false;
    449     case DIBasicTypeKind:
    450     case DIDerivedTypeKind:
    451     case DICompositeTypeKind:
    452     case DISubroutineTypeKind:
    453     case DIFileKind:
    454     case DICompileUnitKind:
    455     case DISubprogramKind:
    456     case DILexicalBlockKind:
    457     case DILexicalBlockFileKind:
    458     case DINamespaceKind:
    459     case DIModuleKind:
    460       return true;
    461     }
    462   }
    463 };
    464 
    465 /// File.
    466 ///
    467 /// TODO: Merge with directory/file node (including users).
    468 /// TODO: Canonicalize paths on creation.
    469 class DIFile : public DIScope {
    470   friend class LLVMContextImpl;
    471   friend class MDNode;
    472 
    473 public:
    474   enum ChecksumKind {
    475     CSK_None,
    476     CSK_MD5,
    477     CSK_SHA1,
    478     CSK_Last = CSK_SHA1 // Should be last enumeration.
    479   };
    480 
    481 private:
    482   ChecksumKind CSKind;
    483 
    484   DIFile(LLVMContext &C, StorageType Storage, ChecksumKind CSK,
    485          ArrayRef<Metadata *> Ops)
    486       : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
    487         CSKind(CSK) {}
    488   ~DIFile() = default;
    489 
    490   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
    491                          StringRef Directory, ChecksumKind CSK, StringRef CS,
    492                          StorageType Storage, bool ShouldCreate = true) {
    493     return getImpl(Context, getCanonicalMDString(Context, Filename),
    494                    getCanonicalMDString(Context, Directory), CSK,
    495                    getCanonicalMDString(Context, CS), Storage, ShouldCreate);
    496   }
    497   static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
    498                          MDString *Directory, ChecksumKind CSK, MDString *CS,
    499                          StorageType Storage, bool ShouldCreate = true);
    500 
    501   TempDIFile cloneImpl() const {
    502     return getTemporary(getContext(), getFilename(), getDirectory(),
    503                         getChecksumKind(), getChecksum());
    504   }
    505 
    506 public:
    507   DEFINE_MDNODE_GET(DIFile, (StringRef Filename, StringRef Directory,
    508                              ChecksumKind CSK = CSK_None,
    509                              StringRef CS = StringRef()),
    510                     (Filename, Directory, CSK, CS))
    511   DEFINE_MDNODE_GET(DIFile, (MDString *Filename, MDString *Directory,
    512                              ChecksumKind CSK = CSK_None,
    513                              MDString *CS = nullptr),
    514                     (Filename, Directory, CSK, CS))
    515 
    516   TempDIFile clone() const { return cloneImpl(); }
    517 
    518   StringRef getFilename() const { return getStringOperand(0); }
    519   StringRef getDirectory() const { return getStringOperand(1); }
    520   StringRef getChecksum() const { return getStringOperand(2); }
    521   ChecksumKind getChecksumKind() const { return CSKind; }
    522   StringRef getChecksumKindAsString() const;
    523 
    524   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
    525   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
    526   MDString *getRawChecksum() const { return getOperandAs<MDString>(2); }
    527 
    528   static ChecksumKind getChecksumKind(StringRef CSKindStr);
    529 
    530   static bool classof(const Metadata *MD) {
    531     return MD->getMetadataID() == DIFileKind;
    532   }
    533 };
    534 
    535 StringRef DIScope::getFilename() const {
    536   if (auto *F = getFile())
    537     return F->getFilename();
    538   return "";
    539 }
    540 
    541 StringRef DIScope::getDirectory() const {
    542   if (auto *F = getFile())
    543     return F->getDirectory();
    544   return "";
    545 }
    546 
    547 /// Base class for types.
    548 ///
    549 /// TODO: Remove the hardcoded name and context, since many types don't use
    550 /// them.
    551 /// TODO: Split up flags.
    552 class DIType : public DIScope {
    553   unsigned Line;
    554   DIFlags Flags;
    555   uint64_t SizeInBits;
    556   uint64_t OffsetInBits;
    557   uint32_t AlignInBits;
    558 
    559 protected:
    560   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
    561          unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    562          uint64_t OffsetInBits, DIFlags Flags, ArrayRef<Metadata *> Ops)
    563       : DIScope(C, ID, Storage, Tag, Ops) {
    564     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
    565   }
    566   ~DIType() = default;
    567 
    568   void init(unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    569             uint64_t OffsetInBits, DIFlags Flags) {
    570     this->Line = Line;
    571     this->Flags = Flags;
    572     this->SizeInBits = SizeInBits;
    573     this->AlignInBits = AlignInBits;
    574     this->OffsetInBits = OffsetInBits;
    575   }
    576 
    577   /// Change fields in place.
    578   void mutate(unsigned Tag, unsigned Line, uint64_t SizeInBits,
    579               uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags) {
    580     assert(isDistinct() && "Only distinct nodes can mutate");
    581     setTag(Tag);
    582     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
    583   }
    584 
    585 public:
    586   TempDIType clone() const {
    587     return TempDIType(cast<DIType>(MDNode::clone().release()));
    588   }
    589 
    590   unsigned getLine() const { return Line; }
    591   uint64_t getSizeInBits() const { return SizeInBits; }
    592   uint32_t getAlignInBits() const { return AlignInBits; }
    593   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
    594   uint64_t getOffsetInBits() const { return OffsetInBits; }
    595   DIFlags getFlags() const { return Flags; }
    596 
    597   DIScopeRef getScope() const { return DIScopeRef(getRawScope()); }
    598   StringRef getName() const { return getStringOperand(2); }
    599 
    600 
    601   Metadata *getRawScope() const { return getOperand(1); }
    602   MDString *getRawName() const { return getOperandAs<MDString>(2); }
    603 
    604   void setFlags(DIFlags NewFlags) {
    605     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
    606     Flags = NewFlags;
    607   }
    608 
    609   bool isPrivate() const {
    610     return (getFlags() & FlagAccessibility) == FlagPrivate;
    611   }
    612   bool isProtected() const {
    613     return (getFlags() & FlagAccessibility) == FlagProtected;
    614   }
    615   bool isPublic() const {
    616     return (getFlags() & FlagAccessibility) == FlagPublic;
    617   }
    618   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
    619   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
    620   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
    621   bool isVirtual() const { return getFlags() & FlagVirtual; }
    622   bool isArtificial() const { return getFlags() & FlagArtificial; }
    623   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
    624   bool isObjcClassComplete() const {
    625     return getFlags() & FlagObjcClassComplete;
    626   }
    627   bool isVector() const { return getFlags() & FlagVector; }
    628   bool isBitField() const { return getFlags() & FlagBitField; }
    629   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
    630   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
    631   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
    632 
    633   static bool classof(const Metadata *MD) {
    634     switch (MD->getMetadataID()) {
    635     default:
    636       return false;
    637     case DIBasicTypeKind:
    638     case DIDerivedTypeKind:
    639     case DICompositeTypeKind:
    640     case DISubroutineTypeKind:
    641       return true;
    642     }
    643   }
    644 };
    645 
    646 /// Basic type, like 'int' or 'float'.
    647 ///
    648 /// TODO: Split out DW_TAG_unspecified_type.
    649 /// TODO: Drop unused accessors.
    650 class DIBasicType : public DIType {
    651   friend class LLVMContextImpl;
    652   friend class MDNode;
    653 
    654   unsigned Encoding;
    655 
    656   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
    657               uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
    658               ArrayRef<Metadata *> Ops)
    659       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
    660                FlagZero, Ops),
    661         Encoding(Encoding) {}
    662   ~DIBasicType() = default;
    663 
    664   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
    665                               StringRef Name, uint64_t SizeInBits,
    666                               uint32_t AlignInBits, unsigned Encoding,
    667                               StorageType Storage, bool ShouldCreate = true) {
    668     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
    669                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
    670   }
    671   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
    672                               MDString *Name, uint64_t SizeInBits,
    673                               uint32_t AlignInBits, unsigned Encoding,
    674                               StorageType Storage, bool ShouldCreate = true);
    675 
    676   TempDIBasicType cloneImpl() const {
    677     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
    678                         getAlignInBits(), getEncoding());
    679   }
    680 
    681 public:
    682   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
    683                     (Tag, Name, 0, 0, 0))
    684   DEFINE_MDNODE_GET(DIBasicType,
    685                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
    686                      uint32_t AlignInBits, unsigned Encoding),
    687                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
    688   DEFINE_MDNODE_GET(DIBasicType,
    689                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
    690                      uint32_t AlignInBits, unsigned Encoding),
    691                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
    692 
    693   TempDIBasicType clone() const { return cloneImpl(); }
    694 
    695   unsigned getEncoding() const { return Encoding; }
    696 
    697   static bool classof(const Metadata *MD) {
    698     return MD->getMetadataID() == DIBasicTypeKind;
    699   }
    700 };
    701 
    702 /// Derived types.
    703 ///
    704 /// This includes qualified types, pointers, references, friends, typedefs, and
    705 /// class members.
    706 ///
    707 /// TODO: Split out members (inheritance, fields, methods, etc.).
    708 class DIDerivedType : public DIType {
    709   friend class LLVMContextImpl;
    710   friend class MDNode;
    711 
    712   /// \brief The DWARF address space of the memory pointed to or referenced by a
    713   /// pointer or reference type respectively.
    714   Optional<unsigned> DWARFAddressSpace;
    715 
    716   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
    717                 unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
    718                 uint64_t OffsetInBits, Optional<unsigned> DWARFAddressSpace,
    719                 DIFlags Flags, ArrayRef<Metadata *> Ops)
    720       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
    721                AlignInBits, OffsetInBits, Flags, Ops),
    722         DWARFAddressSpace(DWARFAddressSpace) {}
    723   ~DIDerivedType() = default;
    724 
    725   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
    726                                 StringRef Name, DIFile *File, unsigned Line,
    727                                 DIScopeRef Scope, DITypeRef BaseType,
    728                                 uint64_t SizeInBits, uint32_t AlignInBits,
    729                                 uint64_t OffsetInBits,
    730                                 Optional<unsigned> DWARFAddressSpace,
    731                                 DIFlags Flags, Metadata *ExtraData,
    732                                 StorageType Storage, bool ShouldCreate = true) {
    733     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
    734                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
    735                    DWARFAddressSpace, Flags, ExtraData, Storage, ShouldCreate);
    736   }
    737   static DIDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
    738                                 MDString *Name, Metadata *File, unsigned Line,
    739                                 Metadata *Scope, Metadata *BaseType,
    740                                 uint64_t SizeInBits, uint32_t AlignInBits,
    741                                 uint64_t OffsetInBits,
    742                                 Optional<unsigned> DWARFAddressSpace,
    743                                 DIFlags Flags, Metadata *ExtraData,
    744                                 StorageType Storage, bool ShouldCreate = true);
    745 
    746   TempDIDerivedType cloneImpl() const {
    747     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
    748                         getScope(), getBaseType(), getSizeInBits(),
    749                         getAlignInBits(), getOffsetInBits(),
    750                         getDWARFAddressSpace(), getFlags(), getExtraData());
    751   }
    752 
    753 public:
    754   DEFINE_MDNODE_GET(DIDerivedType,
    755                     (unsigned Tag, MDString *Name, Metadata *File,
    756                      unsigned Line, Metadata *Scope, Metadata *BaseType,
    757                      uint64_t SizeInBits, uint32_t AlignInBits,
    758                      uint64_t OffsetInBits,
    759                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
    760                      Metadata *ExtraData = nullptr),
    761                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    762                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
    763                      ExtraData))
    764   DEFINE_MDNODE_GET(DIDerivedType,
    765                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
    766                      DIScopeRef Scope, DITypeRef BaseType, uint64_t SizeInBits,
    767                      uint32_t AlignInBits, uint64_t OffsetInBits,
    768                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
    769                      Metadata *ExtraData = nullptr),
    770                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    771                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
    772                      ExtraData))
    773 
    774   TempDIDerivedType clone() const { return cloneImpl(); }
    775 
    776   /// Get the base type this is derived from.
    777   DITypeRef getBaseType() const { return DITypeRef(getRawBaseType()); }
    778   Metadata *getRawBaseType() const { return getOperand(3); }
    779 
    780   /// \returns The DWARF address space of the memory pointed to or referenced by
    781   /// a pointer or reference type respectively.
    782   Optional<unsigned> getDWARFAddressSpace() const { return DWARFAddressSpace; }
    783 
    784   /// Get extra data associated with this derived type.
    785   ///
    786   /// Class type for pointer-to-members, objective-c property node for ivars,
    787   /// or global constant wrapper for static members.
    788   ///
    789   /// TODO: Separate out types that need this extra operand: pointer-to-member
    790   /// types and member fields (static members and ivars).
    791   Metadata *getExtraData() const { return getRawExtraData(); }
    792   Metadata *getRawExtraData() const { return getOperand(4); }
    793 
    794   /// Get casted version of extra data.
    795   /// @{
    796   DITypeRef getClassType() const {
    797     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
    798     return DITypeRef(getExtraData());
    799   }
    800   DIObjCProperty *getObjCProperty() const {
    801     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
    802   }
    803   Constant *getStorageOffsetInBits() const {
    804     assert(getTag() == dwarf::DW_TAG_member && isBitField());
    805     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
    806       return C->getValue();
    807     return nullptr;
    808   }
    809   Constant *getConstant() const {
    810     assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
    811     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
    812       return C->getValue();
    813     return nullptr;
    814   }
    815   /// @}
    816 
    817   static bool classof(const Metadata *MD) {
    818     return MD->getMetadataID() == DIDerivedTypeKind;
    819   }
    820 };
    821 
    822 /// Composite types.
    823 ///
    824 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
    825 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
    826 class DICompositeType : public DIType {
    827   friend class LLVMContextImpl;
    828   friend class MDNode;
    829 
    830   unsigned RuntimeLang;
    831 
    832   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
    833                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
    834                   uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
    835                   ArrayRef<Metadata *> Ops)
    836       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
    837                AlignInBits, OffsetInBits, Flags, Ops),
    838         RuntimeLang(RuntimeLang) {}
    839   ~DICompositeType() = default;
    840 
    841   /// Change fields in place.
    842   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
    843               uint64_t SizeInBits, uint32_t AlignInBits,
    844               uint64_t OffsetInBits, DIFlags Flags) {
    845     assert(isDistinct() && "Only distinct nodes can mutate");
    846     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
    847     this->RuntimeLang = RuntimeLang;
    848     DIType::mutate(Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
    849   }
    850 
    851   static DICompositeType *
    852   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
    853           unsigned Line, DIScopeRef Scope, DITypeRef BaseType,
    854           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
    855           DIFlags Flags, DINodeArray Elements, unsigned RuntimeLang,
    856           DITypeRef VTableHolder, DITemplateParameterArray TemplateParams,
    857           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
    858     return getImpl(
    859         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
    860         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
    861         RuntimeLang, VTableHolder, TemplateParams.get(),
    862         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
    863   }
    864   static DICompositeType *
    865   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
    866           unsigned Line, Metadata *Scope, Metadata *BaseType,
    867           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
    868           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
    869           Metadata *VTableHolder, Metadata *TemplateParams,
    870           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
    871 
    872   TempDICompositeType cloneImpl() const {
    873     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
    874                         getScope(), getBaseType(), getSizeInBits(),
    875                         getAlignInBits(), getOffsetInBits(), getFlags(),
    876                         getElements(), getRuntimeLang(), getVTableHolder(),
    877                         getTemplateParams(), getIdentifier());
    878   }
    879 
    880 public:
    881   DEFINE_MDNODE_GET(DICompositeType,
    882                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
    883                      DIScopeRef Scope, DITypeRef BaseType, uint64_t SizeInBits,
    884                      uint32_t AlignInBits, uint64_t OffsetInBits,
    885                      DIFlags Flags, DINodeArray Elements, unsigned RuntimeLang,
    886                      DITypeRef VTableHolder,
    887                      DITemplateParameterArray TemplateParams = nullptr,
    888                      StringRef Identifier = ""),
    889                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    890                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
    891                      VTableHolder, TemplateParams, Identifier))
    892   DEFINE_MDNODE_GET(DICompositeType,
    893                     (unsigned Tag, MDString *Name, Metadata *File,
    894                      unsigned Line, Metadata *Scope, Metadata *BaseType,
    895                      uint64_t SizeInBits, uint32_t AlignInBits,
    896                      uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
    897                      unsigned RuntimeLang, Metadata *VTableHolder,
    898                      Metadata *TemplateParams = nullptr,
    899                      MDString *Identifier = nullptr),
    900                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
    901                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
    902                      VTableHolder, TemplateParams, Identifier))
    903 
    904   TempDICompositeType clone() const { return cloneImpl(); }
    905 
    906   /// Get a DICompositeType with the given ODR identifier.
    907   ///
    908   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
    909   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
    910   /// a new node.
    911   ///
    912   /// Else, returns \c nullptr.
    913   static DICompositeType *
    914   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
    915              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
    916              Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
    917              uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
    918              unsigned RuntimeLang, Metadata *VTableHolder,
    919              Metadata *TemplateParams);
    920   static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
    921                                              MDString &Identifier);
    922 
    923   /// Build a DICompositeType with the given ODR identifier.
    924   ///
    925   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
    926   /// it doesn't exist, creates a new one.  If it does exist and \a
    927   /// isForwardDecl(), and the new arguments would be a definition, mutates the
    928   /// the type in place.  In either case, returns the type.
    929   ///
    930   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
    931   /// nullptr.
    932   static DICompositeType *
    933   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
    934                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
    935                Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
    936                uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
    937                unsigned RuntimeLang, Metadata *VTableHolder,
    938                Metadata *TemplateParams);
    939 
    940   DITypeRef getBaseType() const { return DITypeRef(getRawBaseType()); }
    941   DINodeArray getElements() const {
    942     return cast_or_null<MDTuple>(getRawElements());
    943   }
    944   DITypeRef getVTableHolder() const { return DITypeRef(getRawVTableHolder()); }
    945   DITemplateParameterArray getTemplateParams() const {
    946     return cast_or_null<MDTuple>(getRawTemplateParams());
    947   }
    948   StringRef getIdentifier() const { return getStringOperand(7); }
    949   unsigned getRuntimeLang() const { return RuntimeLang; }
    950 
    951   Metadata *getRawBaseType() const { return getOperand(3); }
    952   Metadata *getRawElements() const { return getOperand(4); }
    953   Metadata *getRawVTableHolder() const { return getOperand(5); }
    954   Metadata *getRawTemplateParams() const { return getOperand(6); }
    955   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
    956 
    957   /// Replace operands.
    958   ///
    959   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
    960   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
    961   /// of its movement if necessary.
    962   /// @{
    963   void replaceElements(DINodeArray Elements) {
    964 #ifndef NDEBUG
    965     for (DINode *Op : getElements())
    966       assert(is_contained(Elements->operands(), Op) &&
    967              "Lost a member during member list replacement");
    968 #endif
    969     replaceOperandWith(4, Elements.get());
    970   }
    971   void replaceVTableHolder(DITypeRef VTableHolder) {
    972     replaceOperandWith(5, VTableHolder);
    973   }
    974   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
    975     replaceOperandWith(6, TemplateParams.get());
    976   }
    977   /// @}
    978 
    979   static bool classof(const Metadata *MD) {
    980     return MD->getMetadataID() == DICompositeTypeKind;
    981   }
    982 };
    983 
    984 /// Type array for a subprogram.
    985 ///
    986 /// TODO: Fold the array of types in directly as operands.
    987 class DISubroutineType : public DIType {
    988   friend class LLVMContextImpl;
    989   friend class MDNode;
    990 
    991   /// The calling convention used with DW_AT_calling_convention. Actually of
    992   /// type dwarf::CallingConvention.
    993   uint8_t CC;
    994 
    995   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
    996                    uint8_t CC, ArrayRef<Metadata *> Ops)
    997       : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type,
    998                0, 0, 0, 0, Flags, Ops),
    999         CC(CC) {}
   1000   ~DISubroutineType() = default;
   1001 
   1002   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
   1003                                    uint8_t CC, DITypeRefArray TypeArray,
   1004                                    StorageType Storage,
   1005                                    bool ShouldCreate = true) {
   1006     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
   1007   }
   1008   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
   1009                                    uint8_t CC, Metadata *TypeArray,
   1010                                    StorageType Storage,
   1011                                    bool ShouldCreate = true);
   1012 
   1013   TempDISubroutineType cloneImpl() const {
   1014     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
   1015   }
   1016 
   1017 public:
   1018   DEFINE_MDNODE_GET(DISubroutineType,
   1019                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
   1020                     (Flags, CC, TypeArray))
   1021   DEFINE_MDNODE_GET(DISubroutineType,
   1022                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
   1023                     (Flags, CC, TypeArray))
   1024 
   1025   TempDISubroutineType clone() const { return cloneImpl(); }
   1026 
   1027   uint8_t getCC() const { return CC; }
   1028 
   1029   DITypeRefArray getTypeArray() const {
   1030     return cast_or_null<MDTuple>(getRawTypeArray());
   1031   }
   1032   Metadata *getRawTypeArray() const { return getOperand(3); }
   1033 
   1034   static bool classof(const Metadata *MD) {
   1035     return MD->getMetadataID() == DISubroutineTypeKind;
   1036   }
   1037 };
   1038 
   1039 /// Compile unit.
   1040 class DICompileUnit : public DIScope {
   1041   friend class LLVMContextImpl;
   1042   friend class MDNode;
   1043 
   1044 public:
   1045   enum DebugEmissionKind : unsigned {
   1046     NoDebug = 0,
   1047     FullDebug,
   1048     LineTablesOnly,
   1049     LastEmissionKind = LineTablesOnly
   1050   };
   1051 
   1052   static Optional<DebugEmissionKind> getEmissionKind(StringRef Str);
   1053   static const char *EmissionKindString(DebugEmissionKind EK);
   1054 
   1055 private:
   1056   unsigned SourceLanguage;
   1057   bool IsOptimized;
   1058   unsigned RuntimeVersion;
   1059   unsigned EmissionKind;
   1060   uint64_t DWOId;
   1061   bool SplitDebugInlining;
   1062   bool DebugInfoForProfiling;
   1063 
   1064   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
   1065                 bool IsOptimized, unsigned RuntimeVersion,
   1066                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
   1067                 bool DebugInfoForProfiling, ArrayRef<Metadata *> Ops)
   1068       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
   1069         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
   1070         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
   1071         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining),
   1072         DebugInfoForProfiling(DebugInfoForProfiling) {
   1073     assert(Storage != Uniqued);
   1074   }
   1075   ~DICompileUnit() = default;
   1076 
   1077   static DICompileUnit *
   1078   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
   1079           StringRef Producer, bool IsOptimized, StringRef Flags,
   1080           unsigned RuntimeVersion, StringRef SplitDebugFilename,
   1081           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
   1082           DIScopeArray RetainedTypes,
   1083           DIGlobalVariableExpressionArray GlobalVariables,
   1084           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
   1085           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
   1086           StorageType Storage, bool ShouldCreate = true) {
   1087     return getImpl(Context, SourceLanguage, File,
   1088                    getCanonicalMDString(Context, Producer), IsOptimized,
   1089                    getCanonicalMDString(Context, Flags), RuntimeVersion,
   1090                    getCanonicalMDString(Context, SplitDebugFilename),
   1091                    EmissionKind, EnumTypes.get(), RetainedTypes.get(),
   1092                    GlobalVariables.get(), ImportedEntities.get(), Macros.get(),
   1093                    DWOId, SplitDebugInlining, DebugInfoForProfiling, Storage,
   1094                    ShouldCreate);
   1095   }
   1096   static DICompileUnit *
   1097   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
   1098           MDString *Producer, bool IsOptimized, MDString *Flags,
   1099           unsigned RuntimeVersion, MDString *SplitDebugFilename,
   1100           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
   1101           Metadata *GlobalVariables, Metadata *ImportedEntities,
   1102           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
   1103           bool DebugInfoForProfiling, StorageType Storage,
   1104           bool ShouldCreate = true);
   1105 
   1106   TempDICompileUnit cloneImpl() const {
   1107     return getTemporary(getContext(), getSourceLanguage(), getFile(),
   1108                         getProducer(), isOptimized(), getFlags(),
   1109                         getRuntimeVersion(), getSplitDebugFilename(),
   1110                         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
   1111                         getGlobalVariables(), getImportedEntities(),
   1112                         getMacros(), DWOId, getSplitDebugInlining(),
   1113                         getDebugInfoForProfiling());
   1114   }
   1115 
   1116 public:
   1117   static void get() = delete;
   1118   static void getIfExists() = delete;
   1119 
   1120   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
   1121       DICompileUnit,
   1122       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
   1123        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
   1124        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
   1125        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
   1126        DIGlobalVariableExpressionArray GlobalVariables,
   1127        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
   1128        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling),
   1129       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
   1130        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
   1131        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
   1132        DebugInfoForProfiling))
   1133   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
   1134       DICompileUnit,
   1135       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
   1136        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
   1137        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
   1138        Metadata *RetainedTypes, Metadata *GlobalVariables,
   1139        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
   1140        bool SplitDebugInlining, bool DebugInfoForProfiling),
   1141       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
   1142        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
   1143        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
   1144        DebugInfoForProfiling))
   1145 
   1146   TempDICompileUnit clone() const { return cloneImpl(); }
   1147 
   1148   unsigned getSourceLanguage() const { return SourceLanguage; }
   1149   bool isOptimized() const { return IsOptimized; }
   1150   unsigned getRuntimeVersion() const { return RuntimeVersion; }
   1151   DebugEmissionKind getEmissionKind() const {
   1152     return (DebugEmissionKind)EmissionKind;
   1153   }
   1154   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
   1155   StringRef getProducer() const { return getStringOperand(1); }
   1156   StringRef getFlags() const { return getStringOperand(2); }
   1157   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
   1158   DICompositeTypeArray getEnumTypes() const {
   1159     return cast_or_null<MDTuple>(getRawEnumTypes());
   1160   }
   1161   DIScopeArray getRetainedTypes() const {
   1162     return cast_or_null<MDTuple>(getRawRetainedTypes());
   1163   }
   1164   DIGlobalVariableExpressionArray getGlobalVariables() const {
   1165     return cast_or_null<MDTuple>(getRawGlobalVariables());
   1166   }
   1167   DIImportedEntityArray getImportedEntities() const {
   1168     return cast_or_null<MDTuple>(getRawImportedEntities());
   1169   }
   1170   DIMacroNodeArray getMacros() const {
   1171     return cast_or_null<MDTuple>(getRawMacros());
   1172   }
   1173   uint64_t getDWOId() const { return DWOId; }
   1174   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
   1175   bool getSplitDebugInlining() const { return SplitDebugInlining; }
   1176   void setSplitDebugInlining(bool SplitDebugInlining) {
   1177     this->SplitDebugInlining = SplitDebugInlining;
   1178   }
   1179 
   1180   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
   1181   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
   1182   MDString *getRawSplitDebugFilename() const {
   1183     return getOperandAs<MDString>(3);
   1184   }
   1185   Metadata *getRawEnumTypes() const { return getOperand(4); }
   1186   Metadata *getRawRetainedTypes() const { return getOperand(5); }
   1187   Metadata *getRawGlobalVariables() const { return getOperand(6); }
   1188   Metadata *getRawImportedEntities() const { return getOperand(7); }
   1189   Metadata *getRawMacros() const { return getOperand(8); }
   1190 
   1191   /// Replace arrays.
   1192   ///
   1193   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
   1194   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
   1195   /// DICompileUnit should be fairly rare.
   1196   /// @{
   1197   void replaceEnumTypes(DICompositeTypeArray N) {
   1198     replaceOperandWith(4, N.get());
   1199   }
   1200   void replaceRetainedTypes(DITypeArray N) {
   1201     replaceOperandWith(5, N.get());
   1202   }
   1203   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
   1204     replaceOperandWith(6, N.get());
   1205   }
   1206   void replaceImportedEntities(DIImportedEntityArray N) {
   1207     replaceOperandWith(7, N.get());
   1208   }
   1209   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
   1210   /// @}
   1211 
   1212   static bool classof(const Metadata *MD) {
   1213     return MD->getMetadataID() == DICompileUnitKind;
   1214   }
   1215 };
   1216 
   1217 /// A scope for locals.
   1218 ///
   1219 /// A legal scope for lexical blocks, local variables, and debug info
   1220 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
   1221 /// DILexicalBlockFile.
   1222 class DILocalScope : public DIScope {
   1223 protected:
   1224   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
   1225                ArrayRef<Metadata *> Ops)
   1226       : DIScope(C, ID, Storage, Tag, Ops) {}
   1227   ~DILocalScope() = default;
   1228 
   1229 public:
   1230   /// Get the subprogram for this scope.
   1231   ///
   1232   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
   1233   /// chain.
   1234   DISubprogram *getSubprogram() const;
   1235 
   1236   /// Get the first non DILexicalBlockFile scope of this scope.
   1237   ///
   1238   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
   1239   /// scope chain.
   1240   DILocalScope *getNonLexicalBlockFileScope() const;
   1241 
   1242   static bool classof(const Metadata *MD) {
   1243     return MD->getMetadataID() == DISubprogramKind ||
   1244            MD->getMetadataID() == DILexicalBlockKind ||
   1245            MD->getMetadataID() == DILexicalBlockFileKind;
   1246   }
   1247 };
   1248 
   1249 /// Debug location.
   1250 ///
   1251 /// A debug location in source code, used for debug info and otherwise.
   1252 class DILocation : public MDNode {
   1253   friend class LLVMContextImpl;
   1254   friend class MDNode;
   1255 
   1256   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
   1257              unsigned Column, ArrayRef<Metadata *> MDs);
   1258   ~DILocation() { dropAllReferences(); }
   1259 
   1260   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
   1261                              unsigned Column, Metadata *Scope,
   1262                              Metadata *InlinedAt, StorageType Storage,
   1263                              bool ShouldCreate = true);
   1264   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
   1265                              unsigned Column, DILocalScope *Scope,
   1266                              DILocation *InlinedAt, StorageType Storage,
   1267                              bool ShouldCreate = true) {
   1268     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
   1269                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
   1270   }
   1271 
   1272   /// With a given unsigned int \p U, use up to 13 bits to represent it.
   1273   /// old_bit 1~5  --> new_bit 1~5
   1274   /// old_bit 6~12 --> new_bit 7~13
   1275   /// new_bit_6 is 0 if higher bits (7~13) are all 0
   1276   static unsigned getPrefixEncodingFromUnsigned(unsigned U) {
   1277     U &= 0xfff;
   1278     return U > 0x1f ? (((U & 0xfe0) << 1) | (U & 0x1f) | 0x20) : U;
   1279   }
   1280 
   1281   /// Reverse transformation as getPrefixEncodingFromUnsigned.
   1282   static unsigned getUnsignedFromPrefixEncoding(unsigned U) {
   1283     return (U & 0x20) ? (((U >> 1) & 0xfe0) | (U & 0x1f)) : (U & 0x1f);
   1284   }
   1285 
   1286   /// Returns the next component stored in discriminator.
   1287   static unsigned getNextComponentInDiscriminator(unsigned D) {
   1288     if ((D & 1) == 0)
   1289       return D >> ((D & 0x40) ? 14 : 7);
   1290     else
   1291       return D >> 1;
   1292   }
   1293 
   1294   TempDILocation cloneImpl() const {
   1295     // Get the raw scope/inlinedAt since it is possible to invoke this on
   1296     // a DILocation containing temporary metadata.
   1297     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
   1298                         getRawInlinedAt());
   1299   }
   1300 
   1301 public:
   1302   // Disallow replacing operands.
   1303   void replaceOperandWith(unsigned I, Metadata *New) = delete;
   1304 
   1305   DEFINE_MDNODE_GET(DILocation,
   1306                     (unsigned Line, unsigned Column, Metadata *Scope,
   1307                      Metadata *InlinedAt = nullptr),
   1308                     (Line, Column, Scope, InlinedAt))
   1309   DEFINE_MDNODE_GET(DILocation,
   1310                     (unsigned Line, unsigned Column, DILocalScope *Scope,
   1311                      DILocation *InlinedAt = nullptr),
   1312                     (Line, Column, Scope, InlinedAt))
   1313 
   1314   /// Return a (temporary) clone of this.
   1315   TempDILocation clone() const { return cloneImpl(); }
   1316 
   1317   unsigned getLine() const { return SubclassData32; }
   1318   unsigned getColumn() const { return SubclassData16; }
   1319   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
   1320   DILocation *getInlinedAt() const {
   1321     return cast_or_null<DILocation>(getRawInlinedAt());
   1322   }
   1323 
   1324   DIFile *getFile() const { return getScope()->getFile(); }
   1325   StringRef getFilename() const { return getScope()->getFilename(); }
   1326   StringRef getDirectory() const { return getScope()->getDirectory(); }
   1327 
   1328   /// Get the scope where this is inlined.
   1329   ///
   1330   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
   1331   /// location.
   1332   DILocalScope *getInlinedAtScope() const {
   1333     if (auto *IA = getInlinedAt())
   1334       return IA->getInlinedAtScope();
   1335     return getScope();
   1336   }
   1337 
   1338   /// Check whether this can be discriminated from another location.
   1339   ///
   1340   /// Check \c this can be discriminated from \c RHS in a linetable entry.
   1341   /// Scope and inlined-at chains are not recorded in the linetable, so they
   1342   /// cannot be used to distinguish basic blocks.
   1343   bool canDiscriminate(const DILocation &RHS) const {
   1344     return getLine() != RHS.getLine() ||
   1345            getColumn() != RHS.getColumn() ||
   1346            getDiscriminator() != RHS.getDiscriminator() ||
   1347            getFilename() != RHS.getFilename() ||
   1348            getDirectory() != RHS.getDirectory();
   1349   }
   1350 
   1351   /// Get the DWARF discriminator.
   1352   ///
   1353   /// DWARF discriminators distinguish identical file locations between
   1354   /// instructions that are on different basic blocks.
   1355   ///
   1356   /// There are 3 components stored in discriminator, from lower bits:
   1357   ///
   1358   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
   1359   ///                     that are defined by the same source line, but
   1360   ///                     different basic blocks.
   1361   /// Duplication factor: assigned by optimizations that will scale down
   1362   ///                     the execution frequency of the original IR.
   1363   /// Copy Identifier: assigned by optimizations that clones the IR.
   1364   ///                  Each copy of the IR will be assigned an identifier.
   1365   ///
   1366   /// Encoding:
   1367   ///
   1368   /// The above 3 components are encoded into a 32bit unsigned integer in
   1369   /// order. If the lowest bit is 1, the current component is empty, and the
   1370   /// next component will start in the next bit. Otherwise, the the current
   1371   /// component is non-empty, and its content starts in the next bit. The
   1372   /// length of each components is either 5 bit or 12 bit: if the 7th bit
   1373   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
   1374   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
   1375   /// represent the component.
   1376 
   1377   inline unsigned getDiscriminator() const;
   1378 
   1379   /// Returns a new DILocation with updated \p Discriminator.
   1380   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
   1381 
   1382   /// Returns a new DILocation with updated base discriminator \p BD.
   1383   inline const DILocation *setBaseDiscriminator(unsigned BD) const;
   1384 
   1385   /// Returns the duplication factor stored in the discriminator.
   1386   inline unsigned getDuplicationFactor() const;
   1387 
   1388   /// Returns the copy identifier stored in the discriminator.
   1389   inline unsigned getCopyIdentifier() const;
   1390 
   1391   /// Returns the base discriminator stored in the discriminator.
   1392   inline unsigned getBaseDiscriminator() const;
   1393 
   1394   /// Returns a new DILocation with duplication factor \p DF encoded in the
   1395   /// discriminator.
   1396   inline const DILocation *cloneWithDuplicationFactor(unsigned DF) const;
   1397 
   1398   /// When two instructions are combined into a single instruction we also
   1399   /// need to combine the original locations into a single location.
   1400   ///
   1401   /// When the locations are the same we can use either location. When they
   1402   /// differ, we need a third location which is distinct from either. If
   1403   /// they have the same file/line but have a different discriminator we
   1404   /// could create a location with a new discriminator. If they are from
   1405   /// different files/lines the location is ambiguous and can't be
   1406   /// represented in a single line entry.  In this case, no location
   1407   /// should be set.
   1408   ///
   1409   /// Currently the function does not create a new location. If the locations
   1410   /// are the same, or cannot be discriminated, the first location is returned.
   1411   /// Otherwise an empty location will be used.
   1412   static const DILocation *getMergedLocation(const DILocation *LocA,
   1413                                              const DILocation *LocB) {
   1414     if (LocA && LocB && (LocA == LocB || !LocA->canDiscriminate(*LocB)))
   1415       return LocA;
   1416     return nullptr;
   1417   }
   1418 
   1419   /// Returns the base discriminator for a given encoded discriminator \p D.
   1420   static unsigned getBaseDiscriminatorFromDiscriminator(unsigned D) {
   1421     if ((D & 1) == 0)
   1422       return getUnsignedFromPrefixEncoding(D >> 1);
   1423     else
   1424       return 0;
   1425   }
   1426 
   1427   /// Returns the duplication factor for a given encoded discriminator \p D.
   1428   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
   1429     D = getNextComponentInDiscriminator(D);
   1430     if (D == 0 || (D & 1))
   1431       return 1;
   1432     else
   1433       return getUnsignedFromPrefixEncoding(D >> 1);
   1434   }
   1435 
   1436   /// Returns the copy identifier for a given encoded discriminator \p D.
   1437   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
   1438     return getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(
   1439         getNextComponentInDiscriminator(D)));
   1440   }
   1441 
   1442 
   1443   Metadata *getRawScope() const { return getOperand(0); }
   1444   Metadata *getRawInlinedAt() const {
   1445     if (getNumOperands() == 2)
   1446       return getOperand(1);
   1447     return nullptr;
   1448   }
   1449 
   1450   static bool classof(const Metadata *MD) {
   1451     return MD->getMetadataID() == DILocationKind;
   1452   }
   1453 
   1454 };
   1455 
   1456 /// Subprogram description.
   1457 ///
   1458 /// TODO: Remove DisplayName.  It's always equal to Name.
   1459 /// TODO: Split up flags.
   1460 class DISubprogram : public DILocalScope {
   1461   friend class LLVMContextImpl;
   1462   friend class MDNode;
   1463 
   1464   unsigned Line;
   1465   unsigned ScopeLine;
   1466   unsigned VirtualIndex;
   1467 
   1468   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
   1469   /// of method overrides from secondary bases by this amount. It may be
   1470   /// negative.
   1471   int ThisAdjustment;
   1472 
   1473   // Virtuality can only assume three values, so we can pack
   1474   // in 2 bits (none/pure/pure_virtual).
   1475   unsigned Virtuality : 2;
   1476 
   1477   // These are boolean flags so one bit is enough.
   1478   // MSVC starts a new container field every time the base
   1479   // type changes so we can't use 'bool' to ensure these bits
   1480   // are packed.
   1481   unsigned IsLocalToUnit : 1;
   1482   unsigned IsDefinition : 1;
   1483   unsigned IsOptimized : 1;
   1484 
   1485   unsigned Padding : 3;
   1486 
   1487   DIFlags Flags;
   1488 
   1489   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
   1490                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
   1491                int ThisAdjustment, DIFlags Flags, bool IsLocalToUnit,
   1492                bool IsDefinition, bool IsOptimized, ArrayRef<Metadata *> Ops)
   1493       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
   1494                      Ops),
   1495         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
   1496         ThisAdjustment(ThisAdjustment), Virtuality(Virtuality),
   1497         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition),
   1498         IsOptimized(IsOptimized), Flags(Flags) {
   1499     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
   1500     assert(Virtuality < 4 && "Virtuality out of range");
   1501   }
   1502   ~DISubprogram() = default;
   1503 
   1504   static DISubprogram *
   1505   getImpl(LLVMContext &Context, DIScopeRef Scope, StringRef Name,
   1506           StringRef LinkageName, DIFile *File, unsigned Line,
   1507           DISubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
   1508           unsigned ScopeLine, DITypeRef ContainingType, unsigned Virtuality,
   1509           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
   1510           bool IsOptimized, DICompileUnit *Unit,
   1511           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
   1512           DILocalVariableArray Variables, StorageType Storage,
   1513           bool ShouldCreate = true) {
   1514     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   1515                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
   1516                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
   1517                    Virtuality, VirtualIndex, ThisAdjustment, Flags, IsOptimized,
   1518                    Unit, TemplateParams.get(), Declaration, Variables.get(),
   1519                    Storage, ShouldCreate);
   1520   }
   1521   static DISubprogram *
   1522   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
   1523           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
   1524           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
   1525           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
   1526           int ThisAdjustment, DIFlags Flags, bool IsOptimized, Metadata *Unit,
   1527           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
   1528           StorageType Storage, bool ShouldCreate = true);
   1529 
   1530   TempDISubprogram cloneImpl() const {
   1531     return getTemporary(
   1532         getContext(), getScope(), getName(), getLinkageName(), getFile(),
   1533         getLine(), getType(), isLocalToUnit(), isDefinition(), getScopeLine(),
   1534         getContainingType(), getVirtuality(), getVirtualIndex(),
   1535         getThisAdjustment(), getFlags(), isOptimized(), getUnit(),
   1536         getTemplateParams(), getDeclaration(), getVariables());
   1537   }
   1538 
   1539 public:
   1540   DEFINE_MDNODE_GET(DISubprogram,
   1541                     (DIScopeRef Scope, StringRef Name, StringRef LinkageName,
   1542                      DIFile *File, unsigned Line, DISubroutineType *Type,
   1543                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
   1544                      DITypeRef ContainingType, unsigned Virtuality,
   1545                      unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
   1546                      bool IsOptimized, DICompileUnit *Unit,
   1547                      DITemplateParameterArray TemplateParams = nullptr,
   1548                      DISubprogram *Declaration = nullptr,
   1549                      DILocalVariableArray Variables = nullptr),
   1550                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
   1551                      IsDefinition, ScopeLine, ContainingType, Virtuality,
   1552                      VirtualIndex, ThisAdjustment, Flags, IsOptimized, Unit,
   1553                      TemplateParams, Declaration, Variables))
   1554   DEFINE_MDNODE_GET(
   1555       DISubprogram,
   1556       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
   1557        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
   1558        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
   1559        unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
   1560        bool IsOptimized, Metadata *Unit, Metadata *TemplateParams = nullptr,
   1561        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
   1562       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
   1563        ScopeLine, ContainingType, Virtuality, VirtualIndex, ThisAdjustment,
   1564        Flags, IsOptimized, Unit, TemplateParams, Declaration, Variables))
   1565 
   1566   TempDISubprogram clone() const { return cloneImpl(); }
   1567 
   1568 public:
   1569   unsigned getLine() const { return Line; }
   1570   unsigned getVirtuality() const { return Virtuality; }
   1571   unsigned getVirtualIndex() const { return VirtualIndex; }
   1572   int getThisAdjustment() const { return ThisAdjustment; }
   1573   unsigned getScopeLine() const { return ScopeLine; }
   1574   DIFlags getFlags() const { return Flags; }
   1575   bool isLocalToUnit() const { return IsLocalToUnit; }
   1576   bool isDefinition() const { return IsDefinition; }
   1577   bool isOptimized() const { return IsOptimized; }
   1578 
   1579   bool isArtificial() const { return getFlags() & FlagArtificial; }
   1580   bool isPrivate() const {
   1581     return (getFlags() & FlagAccessibility) == FlagPrivate;
   1582   }
   1583   bool isProtected() const {
   1584     return (getFlags() & FlagAccessibility) == FlagProtected;
   1585   }
   1586   bool isPublic() const {
   1587     return (getFlags() & FlagAccessibility) == FlagPublic;
   1588   }
   1589   bool isExplicit() const { return getFlags() & FlagExplicit; }
   1590   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
   1591   bool isMainSubprogram() const { return getFlags() & FlagMainSubprogram; }
   1592 
   1593   /// Check if this is reference-qualified.
   1594   ///
   1595   /// Return true if this subprogram is a C++11 reference-qualified non-static
   1596   /// member function (void foo() &).
   1597   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
   1598 
   1599   /// Check if this is rvalue-reference-qualified.
   1600   ///
   1601   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
   1602   /// non-static member function (void foo() &&).
   1603   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
   1604 
   1605   /// Check if this is marked as noreturn.
   1606   ///
   1607   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
   1608   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
   1609 
   1610   DIScopeRef getScope() const { return DIScopeRef(getRawScope()); }
   1611 
   1612   StringRef getName() const { return getStringOperand(2); }
   1613   StringRef getDisplayName() const { return getStringOperand(3); }
   1614   StringRef getLinkageName() const { return getStringOperand(4); }
   1615 
   1616   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   1617   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
   1618 
   1619   DISubroutineType *getType() const {
   1620     return cast_or_null<DISubroutineType>(getRawType());
   1621   }
   1622   DITypeRef getContainingType() const {
   1623     return DITypeRef(getRawContainingType());
   1624   }
   1625 
   1626   DICompileUnit *getUnit() const {
   1627     return cast_or_null<DICompileUnit>(getRawUnit());
   1628   }
   1629   void replaceUnit(DICompileUnit *CU) {
   1630     replaceOperandWith(7, CU);
   1631   }
   1632   DITemplateParameterArray getTemplateParams() const {
   1633     return cast_or_null<MDTuple>(getRawTemplateParams());
   1634   }
   1635   DISubprogram *getDeclaration() const {
   1636     return cast_or_null<DISubprogram>(getRawDeclaration());
   1637   }
   1638   DILocalVariableArray getVariables() const {
   1639     return cast_or_null<MDTuple>(getRawVariables());
   1640   }
   1641 
   1642   Metadata *getRawScope() const { return getOperand(1); }
   1643   Metadata *getRawType() const { return getOperand(5); }
   1644   Metadata *getRawContainingType() const { return getOperand(6); }
   1645   Metadata *getRawUnit() const { return getOperand(7); }
   1646   Metadata *getRawTemplateParams() const { return getOperand(8); }
   1647   Metadata *getRawDeclaration() const { return getOperand(9); }
   1648   Metadata *getRawVariables() const { return getOperand(10); }
   1649 
   1650   /// Check if this subprogram describes the given function.
   1651   ///
   1652   /// FIXME: Should this be looking through bitcasts?
   1653   bool describes(const Function *F) const;
   1654 
   1655   static bool classof(const Metadata *MD) {
   1656     return MD->getMetadataID() == DISubprogramKind;
   1657   }
   1658 };
   1659 
   1660 class DILexicalBlockBase : public DILocalScope {
   1661 protected:
   1662   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
   1663                      ArrayRef<Metadata *> Ops)
   1664       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
   1665   ~DILexicalBlockBase() = default;
   1666 
   1667 public:
   1668   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
   1669 
   1670   Metadata *getRawScope() const { return getOperand(1); }
   1671 
   1672   static bool classof(const Metadata *MD) {
   1673     return MD->getMetadataID() == DILexicalBlockKind ||
   1674            MD->getMetadataID() == DILexicalBlockFileKind;
   1675   }
   1676 };
   1677 
   1678 class DILexicalBlock : public DILexicalBlockBase {
   1679   friend class LLVMContextImpl;
   1680   friend class MDNode;
   1681 
   1682   unsigned Line;
   1683   uint16_t Column;
   1684 
   1685   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
   1686                  unsigned Column, ArrayRef<Metadata *> Ops)
   1687       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
   1688         Column(Column) {
   1689     assert(Column < (1u << 16) && "Expected 16-bit column");
   1690   }
   1691   ~DILexicalBlock() = default;
   1692 
   1693   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
   1694                                  DIFile *File, unsigned Line, unsigned Column,
   1695                                  StorageType Storage,
   1696                                  bool ShouldCreate = true) {
   1697     return getImpl(Context, static_cast<Metadata *>(Scope),
   1698                    static_cast<Metadata *>(File), Line, Column, Storage,
   1699                    ShouldCreate);
   1700   }
   1701 
   1702   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
   1703                                  Metadata *File, unsigned Line, unsigned Column,
   1704                                  StorageType Storage, bool ShouldCreate = true);
   1705 
   1706   TempDILexicalBlock cloneImpl() const {
   1707     return getTemporary(getContext(), getScope(), getFile(), getLine(),
   1708                         getColumn());
   1709   }
   1710 
   1711 public:
   1712   DEFINE_MDNODE_GET(DILexicalBlock, (DILocalScope * Scope, DIFile *File,
   1713                                      unsigned Line, unsigned Column),
   1714                     (Scope, File, Line, Column))
   1715   DEFINE_MDNODE_GET(DILexicalBlock, (Metadata * Scope, Metadata *File,
   1716                                      unsigned Line, unsigned Column),
   1717                     (Scope, File, Line, Column))
   1718 
   1719   TempDILexicalBlock clone() const { return cloneImpl(); }
   1720 
   1721   unsigned getLine() const { return Line; }
   1722   unsigned getColumn() const { return Column; }
   1723 
   1724   static bool classof(const Metadata *MD) {
   1725     return MD->getMetadataID() == DILexicalBlockKind;
   1726   }
   1727 };
   1728 
   1729 class DILexicalBlockFile : public DILexicalBlockBase {
   1730   friend class LLVMContextImpl;
   1731   friend class MDNode;
   1732 
   1733   unsigned Discriminator;
   1734 
   1735   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
   1736                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
   1737       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
   1738         Discriminator(Discriminator) {}
   1739   ~DILexicalBlockFile() = default;
   1740 
   1741   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
   1742                                      DIFile *File, unsigned Discriminator,
   1743                                      StorageType Storage,
   1744                                      bool ShouldCreate = true) {
   1745     return getImpl(Context, static_cast<Metadata *>(Scope),
   1746                    static_cast<Metadata *>(File), Discriminator, Storage,
   1747                    ShouldCreate);
   1748   }
   1749 
   1750   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
   1751                                      Metadata *File, unsigned Discriminator,
   1752                                      StorageType Storage,
   1753                                      bool ShouldCreate = true);
   1754 
   1755   TempDILexicalBlockFile cloneImpl() const {
   1756     return getTemporary(getContext(), getScope(), getFile(),
   1757                         getDiscriminator());
   1758   }
   1759 
   1760 public:
   1761   DEFINE_MDNODE_GET(DILexicalBlockFile, (DILocalScope * Scope, DIFile *File,
   1762                                          unsigned Discriminator),
   1763                     (Scope, File, Discriminator))
   1764   DEFINE_MDNODE_GET(DILexicalBlockFile,
   1765                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
   1766                     (Scope, File, Discriminator))
   1767 
   1768   TempDILexicalBlockFile clone() const { return cloneImpl(); }
   1769 
   1770   // TODO: Remove these once they're gone from DILexicalBlockBase.
   1771   unsigned getLine() const = delete;
   1772   unsigned getColumn() const = delete;
   1773 
   1774   unsigned getDiscriminator() const { return Discriminator; }
   1775 
   1776   static bool classof(const Metadata *MD) {
   1777     return MD->getMetadataID() == DILexicalBlockFileKind;
   1778   }
   1779 };
   1780 
   1781 unsigned DILocation::getDiscriminator() const {
   1782   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
   1783     return F->getDiscriminator();
   1784   return 0;
   1785 }
   1786 
   1787 const DILocation *
   1788 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
   1789   DIScope *Scope = getScope();
   1790   // Skip all parent DILexicalBlockFile that already have a discriminator
   1791   // assigned. We do not want to have nested DILexicalBlockFiles that have
   1792   // mutliple discriminators because only the leaf DILexicalBlockFile's
   1793   // dominator will be used.
   1794   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
   1795        LBF && LBF->getDiscriminator() != 0;
   1796        LBF = dyn_cast<DILexicalBlockFile>(Scope))
   1797     Scope = LBF->getScope();
   1798   DILexicalBlockFile *NewScope =
   1799       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
   1800   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
   1801                          getInlinedAt());
   1802 }
   1803 
   1804 unsigned DILocation::getBaseDiscriminator() const {
   1805   return getBaseDiscriminatorFromDiscriminator(getDiscriminator());
   1806 }
   1807 
   1808 unsigned DILocation::getDuplicationFactor() const {
   1809   return getDuplicationFactorFromDiscriminator(getDiscriminator());
   1810 }
   1811 
   1812 unsigned DILocation::getCopyIdentifier() const {
   1813   return getCopyIdentifierFromDiscriminator(getDiscriminator());
   1814 }
   1815 
   1816 const DILocation *DILocation::setBaseDiscriminator(unsigned D) const {
   1817   if (D == 0)
   1818     return this;
   1819   else
   1820     return cloneWithDiscriminator(getPrefixEncodingFromUnsigned(D) << 1);
   1821 }
   1822 
   1823 const DILocation *DILocation::cloneWithDuplicationFactor(unsigned DF) const {
   1824   DF *= getDuplicationFactor();
   1825   if (DF <= 1)
   1826     return this;
   1827 
   1828   unsigned BD = getBaseDiscriminator();
   1829   unsigned CI = getCopyIdentifier() << (DF > 0x1f ? 14 : 7);
   1830   unsigned D = CI | (getPrefixEncodingFromUnsigned(DF) << 1);
   1831 
   1832   if (BD == 0)
   1833     D = (D << 1) | 1;
   1834   else
   1835     D = (D << (BD > 0x1f ? 14 : 7)) | (getPrefixEncodingFromUnsigned(BD) << 1);
   1836 
   1837   return cloneWithDiscriminator(D);
   1838 }
   1839 
   1840 class DINamespace : public DIScope {
   1841   friend class LLVMContextImpl;
   1842   friend class MDNode;
   1843 
   1844   unsigned Line;
   1845   unsigned ExportSymbols : 1;
   1846 
   1847   DINamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
   1848               bool ExportSymbols, ArrayRef<Metadata *> Ops)
   1849       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
   1850                 Ops),
   1851         Line(Line), ExportSymbols(ExportSymbols) {}
   1852   ~DINamespace() = default;
   1853 
   1854   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
   1855                               DIFile *File, StringRef Name, unsigned Line,
   1856                               bool ExportSymbols, StorageType Storage,
   1857                               bool ShouldCreate = true) {
   1858     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
   1859                    Line, ExportSymbols, Storage, ShouldCreate);
   1860   }
   1861   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
   1862                               Metadata *File, MDString *Name, unsigned Line,
   1863                               bool ExportSymbols, StorageType Storage,
   1864                               bool ShouldCreate = true);
   1865 
   1866   TempDINamespace cloneImpl() const {
   1867     return getTemporary(getContext(), getScope(), getFile(), getName(),
   1868                         getLine(), getExportSymbols());
   1869   }
   1870 
   1871 public:
   1872   DEFINE_MDNODE_GET(DINamespace, (DIScope * Scope, DIFile *File, StringRef Name,
   1873                                   unsigned Line, bool ExportSymbols),
   1874                     (Scope, File, Name, Line, ExportSymbols))
   1875   DEFINE_MDNODE_GET(DINamespace,
   1876                     (Metadata * Scope, Metadata *File, MDString *Name,
   1877                      unsigned Line, bool ExportSymbols),
   1878                     (Scope, File, Name, Line, ExportSymbols))
   1879 
   1880   TempDINamespace clone() const { return cloneImpl(); }
   1881 
   1882   unsigned getLine() const { return Line; }
   1883   bool getExportSymbols() const { return ExportSymbols; }
   1884   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   1885   StringRef getName() const { return getStringOperand(2); }
   1886 
   1887   Metadata *getRawScope() const { return getOperand(1); }
   1888   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   1889 
   1890   static bool classof(const Metadata *MD) {
   1891     return MD->getMetadataID() == DINamespaceKind;
   1892   }
   1893 };
   1894 
   1895 /// A (clang) module that has been imported by the compile unit.
   1896 ///
   1897 class DIModule : public DIScope {
   1898   friend class LLVMContextImpl;
   1899   friend class MDNode;
   1900 
   1901   DIModule(LLVMContext &Context, StorageType Storage, ArrayRef<Metadata *> Ops)
   1902       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops) {}
   1903   ~DIModule() = default;
   1904 
   1905   static DIModule *getImpl(LLVMContext &Context, DIScope *Scope,
   1906                            StringRef Name, StringRef ConfigurationMacros,
   1907                            StringRef IncludePath, StringRef ISysRoot,
   1908                            StorageType Storage, bool ShouldCreate = true) {
   1909     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   1910                    getCanonicalMDString(Context, ConfigurationMacros),
   1911                    getCanonicalMDString(Context, IncludePath),
   1912                    getCanonicalMDString(Context, ISysRoot),
   1913                    Storage, ShouldCreate);
   1914   }
   1915   static DIModule *getImpl(LLVMContext &Context, Metadata *Scope,
   1916                            MDString *Name, MDString *ConfigurationMacros,
   1917                            MDString *IncludePath, MDString *ISysRoot,
   1918                            StorageType Storage, bool ShouldCreate = true);
   1919 
   1920   TempDIModule cloneImpl() const {
   1921     return getTemporary(getContext(), getScope(), getName(),
   1922                         getConfigurationMacros(), getIncludePath(),
   1923                         getISysRoot());
   1924   }
   1925 
   1926 public:
   1927   DEFINE_MDNODE_GET(DIModule, (DIScope *Scope, StringRef Name,
   1928                                StringRef ConfigurationMacros, StringRef IncludePath,
   1929                                StringRef ISysRoot),
   1930                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
   1931   DEFINE_MDNODE_GET(DIModule,
   1932                     (Metadata *Scope, MDString *Name, MDString *ConfigurationMacros,
   1933                      MDString *IncludePath, MDString *ISysRoot),
   1934                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
   1935 
   1936   TempDIModule clone() const { return cloneImpl(); }
   1937 
   1938   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   1939   StringRef getName() const { return getStringOperand(1); }
   1940   StringRef getConfigurationMacros() const { return getStringOperand(2); }
   1941   StringRef getIncludePath() const { return getStringOperand(3); }
   1942   StringRef getISysRoot() const { return getStringOperand(4); }
   1943 
   1944   Metadata *getRawScope() const { return getOperand(0); }
   1945   MDString *getRawName() const { return getOperandAs<MDString>(1); }
   1946   MDString *getRawConfigurationMacros() const { return getOperandAs<MDString>(2); }
   1947   MDString *getRawIncludePath() const { return getOperandAs<MDString>(3); }
   1948   MDString *getRawISysRoot() const { return getOperandAs<MDString>(4); }
   1949 
   1950   static bool classof(const Metadata *MD) {
   1951     return MD->getMetadataID() == DIModuleKind;
   1952   }
   1953 };
   1954 
   1955 /// Base class for template parameters.
   1956 class DITemplateParameter : public DINode {
   1957 protected:
   1958   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
   1959                       unsigned Tag, ArrayRef<Metadata *> Ops)
   1960       : DINode(Context, ID, Storage, Tag, Ops) {}
   1961   ~DITemplateParameter() = default;
   1962 
   1963 public:
   1964   StringRef getName() const { return getStringOperand(0); }
   1965   DITypeRef getType() const { return DITypeRef(getRawType()); }
   1966 
   1967   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   1968   Metadata *getRawType() const { return getOperand(1); }
   1969 
   1970   static bool classof(const Metadata *MD) {
   1971     return MD->getMetadataID() == DITemplateTypeParameterKind ||
   1972            MD->getMetadataID() == DITemplateValueParameterKind;
   1973   }
   1974 };
   1975 
   1976 class DITemplateTypeParameter : public DITemplateParameter {
   1977   friend class LLVMContextImpl;
   1978   friend class MDNode;
   1979 
   1980   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
   1981                           ArrayRef<Metadata *> Ops)
   1982       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
   1983                             dwarf::DW_TAG_template_type_parameter, Ops) {}
   1984   ~DITemplateTypeParameter() = default;
   1985 
   1986   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
   1987                                           DITypeRef Type, StorageType Storage,
   1988                                           bool ShouldCreate = true) {
   1989     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
   1990                    ShouldCreate);
   1991   }
   1992   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
   1993                                           Metadata *Type, StorageType Storage,
   1994                                           bool ShouldCreate = true);
   1995 
   1996   TempDITemplateTypeParameter cloneImpl() const {
   1997     return getTemporary(getContext(), getName(), getType());
   1998   }
   1999 
   2000 public:
   2001   DEFINE_MDNODE_GET(DITemplateTypeParameter, (StringRef Name, DITypeRef Type),
   2002                     (Name, Type))
   2003   DEFINE_MDNODE_GET(DITemplateTypeParameter, (MDString * Name, Metadata *Type),
   2004                     (Name, Type))
   2005 
   2006   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
   2007 
   2008   static bool classof(const Metadata *MD) {
   2009     return MD->getMetadataID() == DITemplateTypeParameterKind;
   2010   }
   2011 };
   2012 
   2013 class DITemplateValueParameter : public DITemplateParameter {
   2014   friend class LLVMContextImpl;
   2015   friend class MDNode;
   2016 
   2017   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
   2018                            unsigned Tag, ArrayRef<Metadata *> Ops)
   2019       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
   2020                             Ops) {}
   2021   ~DITemplateValueParameter() = default;
   2022 
   2023   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
   2024                                            StringRef Name, DITypeRef Type,
   2025                                            Metadata *Value, StorageType Storage,
   2026                                            bool ShouldCreate = true) {
   2027     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
   2028                    Value, Storage, ShouldCreate);
   2029   }
   2030   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
   2031                                            MDString *Name, Metadata *Type,
   2032                                            Metadata *Value, StorageType Storage,
   2033                                            bool ShouldCreate = true);
   2034 
   2035   TempDITemplateValueParameter cloneImpl() const {
   2036     return getTemporary(getContext(), getTag(), getName(), getType(),
   2037                         getValue());
   2038   }
   2039 
   2040 public:
   2041   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, StringRef Name,
   2042                                                DITypeRef Type, Metadata *Value),
   2043                     (Tag, Name, Type, Value))
   2044   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, MDString *Name,
   2045                                                Metadata *Type, Metadata *Value),
   2046                     (Tag, Name, Type, Value))
   2047 
   2048   TempDITemplateValueParameter clone() const { return cloneImpl(); }
   2049 
   2050   Metadata *getValue() const { return getOperand(2); }
   2051 
   2052   static bool classof(const Metadata *MD) {
   2053     return MD->getMetadataID() == DITemplateValueParameterKind;
   2054   }
   2055 };
   2056 
   2057 /// Base class for variables.
   2058 class DIVariable : public DINode {
   2059   unsigned Line;
   2060   uint32_t AlignInBits;
   2061 
   2062 protected:
   2063   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
   2064              ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0)
   2065       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
   2066         AlignInBits(AlignInBits) {}
   2067   ~DIVariable() = default;
   2068 
   2069 public:
   2070   unsigned getLine() const { return Line; }
   2071   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2072   StringRef getName() const { return getStringOperand(1); }
   2073   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   2074   DITypeRef getType() const { return DITypeRef(getRawType()); }
   2075   uint32_t getAlignInBits() const { return AlignInBits; }
   2076   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
   2077 
   2078   StringRef getFilename() const {
   2079     if (auto *F = getFile())
   2080       return F->getFilename();
   2081     return "";
   2082   }
   2083   StringRef getDirectory() const {
   2084     if (auto *F = getFile())
   2085       return F->getDirectory();
   2086     return "";
   2087   }
   2088 
   2089   Metadata *getRawScope() const { return getOperand(0); }
   2090   MDString *getRawName() const { return getOperandAs<MDString>(1); }
   2091   Metadata *getRawFile() const { return getOperand(2); }
   2092   Metadata *getRawType() const { return getOperand(3); }
   2093 
   2094   static bool classof(const Metadata *MD) {
   2095     return MD->getMetadataID() == DILocalVariableKind ||
   2096            MD->getMetadataID() == DIGlobalVariableKind;
   2097   }
   2098 };
   2099 
   2100 /// DWARF expression.
   2101 ///
   2102 /// This is (almost) a DWARF expression that modifies the location of a
   2103 /// variable, or the location of a single piece of a variable, or (when using
   2104 /// DW_OP_stack_value) is the constant variable value.
   2105 ///
   2106 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
   2107 /// and have DW_OP_plus consume the topmost elements on the stack.
   2108 ///
   2109 /// TODO: Co-allocate the expression elements.
   2110 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
   2111 /// storage types.
   2112 class DIExpression : public MDNode {
   2113   friend class LLVMContextImpl;
   2114   friend class MDNode;
   2115 
   2116   std::vector<uint64_t> Elements;
   2117 
   2118   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
   2119       : MDNode(C, DIExpressionKind, Storage, None),
   2120         Elements(Elements.begin(), Elements.end()) {}
   2121   ~DIExpression() = default;
   2122 
   2123   static DIExpression *getImpl(LLVMContext &Context,
   2124                                ArrayRef<uint64_t> Elements, StorageType Storage,
   2125                                bool ShouldCreate = true);
   2126 
   2127   TempDIExpression cloneImpl() const {
   2128     return getTemporary(getContext(), getElements());
   2129   }
   2130 
   2131 public:
   2132   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
   2133 
   2134   TempDIExpression clone() const { return cloneImpl(); }
   2135 
   2136   ArrayRef<uint64_t> getElements() const { return Elements; }
   2137 
   2138   unsigned getNumElements() const { return Elements.size(); }
   2139   uint64_t getElement(unsigned I) const {
   2140     assert(I < Elements.size() && "Index out of range");
   2141     return Elements[I];
   2142   }
   2143 
   2144   /// Determine whether this represents a standalone constant value.
   2145   bool isConstant() const;
   2146 
   2147   typedef ArrayRef<uint64_t>::iterator element_iterator;
   2148   element_iterator elements_begin() const { return getElements().begin(); }
   2149   element_iterator elements_end() const { return getElements().end(); }
   2150 
   2151   /// A lightweight wrapper around an expression operand.
   2152   ///
   2153   /// TODO: Store arguments directly and change \a DIExpression to store a
   2154   /// range of these.
   2155   class ExprOperand {
   2156     const uint64_t *Op = nullptr;
   2157 
   2158   public:
   2159     ExprOperand() = default;
   2160     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
   2161 
   2162     const uint64_t *get() const { return Op; }
   2163 
   2164     /// Get the operand code.
   2165     uint64_t getOp() const { return *Op; }
   2166 
   2167     /// Get an argument to the operand.
   2168     ///
   2169     /// Never returns the operand itself.
   2170     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
   2171 
   2172     unsigned getNumArgs() const { return getSize() - 1; }
   2173 
   2174     /// Return the size of the operand.
   2175     ///
   2176     /// Return the number of elements in the operand (1 + args).
   2177     unsigned getSize() const;
   2178   };
   2179 
   2180   /// An iterator for expression operands.
   2181   class expr_op_iterator
   2182       : public std::iterator<std::input_iterator_tag, ExprOperand> {
   2183     ExprOperand Op;
   2184 
   2185   public:
   2186     expr_op_iterator() = default;
   2187     explicit expr_op_iterator(element_iterator I) : Op(I) {}
   2188 
   2189     element_iterator getBase() const { return Op.get(); }
   2190     const ExprOperand &operator*() const { return Op; }
   2191     const ExprOperand *operator->() const { return &Op; }
   2192 
   2193     expr_op_iterator &operator++() {
   2194       increment();
   2195       return *this;
   2196     }
   2197     expr_op_iterator operator++(int) {
   2198       expr_op_iterator T(*this);
   2199       increment();
   2200       return T;
   2201     }
   2202 
   2203     /// Get the next iterator.
   2204     ///
   2205     /// \a std::next() doesn't work because this is technically an
   2206     /// input_iterator, but it's a perfectly valid operation.  This is an
   2207     /// accessor to provide the same functionality.
   2208     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
   2209 
   2210     bool operator==(const expr_op_iterator &X) const {
   2211       return getBase() == X.getBase();
   2212     }
   2213     bool operator!=(const expr_op_iterator &X) const {
   2214       return getBase() != X.getBase();
   2215     }
   2216 
   2217   private:
   2218     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
   2219   };
   2220 
   2221   /// Visit the elements via ExprOperand wrappers.
   2222   ///
   2223   /// These range iterators visit elements through \a ExprOperand wrappers.
   2224   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
   2225   /// true.
   2226   ///
   2227   /// \pre \a isValid() gives \c true.
   2228   /// @{
   2229   expr_op_iterator expr_op_begin() const {
   2230     return expr_op_iterator(elements_begin());
   2231   }
   2232   expr_op_iterator expr_op_end() const {
   2233     return expr_op_iterator(elements_end());
   2234   }
   2235   /// @}
   2236 
   2237   bool isValid() const;
   2238 
   2239   static bool classof(const Metadata *MD) {
   2240     return MD->getMetadataID() == DIExpressionKind;
   2241   }
   2242 
   2243   /// Is the first element a DW_OP_deref?.
   2244   bool startsWithDeref() const {
   2245     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
   2246   }
   2247 
   2248   /// Holds the characteristics of one fragment of a larger variable.
   2249   struct FragmentInfo {
   2250     uint64_t SizeInBits;
   2251     uint64_t OffsetInBits;
   2252   };
   2253 
   2254   /// Retrieve the details of this fragment expression.
   2255   static Optional<FragmentInfo> getFragmentInfo(expr_op_iterator Start,
   2256                                                 expr_op_iterator End);
   2257 
   2258   /// Retrieve the details of this fragment expression.
   2259   Optional<FragmentInfo> getFragmentInfo() const {
   2260     return getFragmentInfo(expr_op_begin(), expr_op_end());
   2261   }
   2262 
   2263   /// Return whether this is a piece of an aggregate variable.
   2264   bool isFragment() const { return getFragmentInfo().hasValue(); }
   2265 };
   2266 
   2267 /// Global variables.
   2268 ///
   2269 /// TODO: Remove DisplayName.  It's always equal to Name.
   2270 class DIGlobalVariable : public DIVariable {
   2271   friend class LLVMContextImpl;
   2272   friend class MDNode;
   2273 
   2274   bool IsLocalToUnit;
   2275   bool IsDefinition;
   2276 
   2277   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
   2278                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
   2279                    ArrayRef<Metadata *> Ops)
   2280       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
   2281         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
   2282   ~DIGlobalVariable() = default;
   2283 
   2284   static DIGlobalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
   2285                                    StringRef Name, StringRef LinkageName,
   2286                                    DIFile *File, unsigned Line, DITypeRef Type,
   2287                                    bool IsLocalToUnit, bool IsDefinition,
   2288                                    DIDerivedType *StaticDataMemberDeclaration,
   2289                                    uint32_t AlignInBits, StorageType Storage,
   2290                                    bool ShouldCreate = true) {
   2291     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
   2292                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
   2293                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
   2294                    AlignInBits, Storage, ShouldCreate);
   2295   }
   2296   static DIGlobalVariable *
   2297   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
   2298           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
   2299           bool IsLocalToUnit, bool IsDefinition,
   2300           Metadata *StaticDataMemberDeclaration, uint32_t AlignInBits,
   2301           StorageType Storage, bool ShouldCreate = true);
   2302 
   2303   TempDIGlobalVariable cloneImpl() const {
   2304     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
   2305                         getFile(), getLine(), getType(), isLocalToUnit(),
   2306                         isDefinition(), getStaticDataMemberDeclaration(),
   2307                         getAlignInBits());
   2308   }
   2309 
   2310 public:
   2311   DEFINE_MDNODE_GET(DIGlobalVariable,
   2312                     (DIScope * Scope, StringRef Name, StringRef LinkageName,
   2313                      DIFile *File, unsigned Line, DITypeRef Type,
   2314                      bool IsLocalToUnit, bool IsDefinition,
   2315                      DIDerivedType *StaticDataMemberDeclaration,
   2316                      uint32_t AlignInBits),
   2317                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
   2318                      IsDefinition, StaticDataMemberDeclaration, AlignInBits))
   2319   DEFINE_MDNODE_GET(DIGlobalVariable,
   2320                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
   2321                      Metadata *File, unsigned Line, Metadata *Type,
   2322                      bool IsLocalToUnit, bool IsDefinition,
   2323                      Metadata *StaticDataMemberDeclaration,
   2324                      uint32_t AlignInBits),
   2325                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
   2326                      IsDefinition, StaticDataMemberDeclaration, AlignInBits))
   2327 
   2328   TempDIGlobalVariable clone() const { return cloneImpl(); }
   2329 
   2330   bool isLocalToUnit() const { return IsLocalToUnit; }
   2331   bool isDefinition() const { return IsDefinition; }
   2332   StringRef getDisplayName() const { return getStringOperand(4); }
   2333   StringRef getLinkageName() const { return getStringOperand(5); }
   2334   DIDerivedType *getStaticDataMemberDeclaration() const {
   2335     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
   2336   }
   2337 
   2338   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
   2339   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
   2340 
   2341   static bool classof(const Metadata *MD) {
   2342     return MD->getMetadataID() == DIGlobalVariableKind;
   2343   }
   2344 };
   2345 
   2346 /// Local variable.
   2347 ///
   2348 /// TODO: Split up flags.
   2349 class DILocalVariable : public DIVariable {
   2350   friend class LLVMContextImpl;
   2351   friend class MDNode;
   2352 
   2353   unsigned Arg : 16;
   2354   DIFlags Flags;
   2355 
   2356   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
   2357                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
   2358                   ArrayRef<Metadata *> Ops)
   2359       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
   2360         Arg(Arg), Flags(Flags) {
   2361     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
   2362   }
   2363   ~DILocalVariable() = default;
   2364 
   2365   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
   2366                                   StringRef Name, DIFile *File, unsigned Line,
   2367                                   DITypeRef Type, unsigned Arg, DIFlags Flags,
   2368                                   uint32_t AlignInBits, StorageType Storage,
   2369                                   bool ShouldCreate = true) {
   2370     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
   2371                    Line, Type, Arg, Flags, AlignInBits, Storage, ShouldCreate);
   2372   }
   2373   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
   2374                                   MDString *Name, Metadata *File, unsigned Line,
   2375                                   Metadata *Type, unsigned Arg, DIFlags Flags,
   2376                                   uint32_t AlignInBits, StorageType Storage,
   2377                                   bool ShouldCreate = true);
   2378 
   2379   TempDILocalVariable cloneImpl() const {
   2380     return getTemporary(getContext(), getScope(), getName(), getFile(),
   2381                         getLine(), getType(), getArg(), getFlags(),
   2382                         getAlignInBits());
   2383   }
   2384 
   2385 public:
   2386   DEFINE_MDNODE_GET(DILocalVariable,
   2387                     (DILocalScope * Scope, StringRef Name, DIFile *File,
   2388                      unsigned Line, DITypeRef Type, unsigned Arg,
   2389                      DIFlags Flags, uint32_t AlignInBits),
   2390                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
   2391   DEFINE_MDNODE_GET(DILocalVariable,
   2392                     (Metadata * Scope, MDString *Name, Metadata *File,
   2393                      unsigned Line, Metadata *Type, unsigned Arg,
   2394                      DIFlags Flags, uint32_t AlignInBits),
   2395                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits))
   2396 
   2397   TempDILocalVariable clone() const { return cloneImpl(); }
   2398 
   2399   /// Get the local scope for this variable.
   2400   ///
   2401   /// Variables must be defined in a local scope.
   2402   DILocalScope *getScope() const {
   2403     return cast<DILocalScope>(DIVariable::getScope());
   2404   }
   2405 
   2406   bool isParameter() const { return Arg; }
   2407   unsigned getArg() const { return Arg; }
   2408   DIFlags getFlags() const { return Flags; }
   2409 
   2410   bool isArtificial() const { return getFlags() & FlagArtificial; }
   2411   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
   2412 
   2413   /// Check that a location is valid for this variable.
   2414   ///
   2415   /// Check that \c DL exists, is in the same subprogram, and has the same
   2416   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
   2417   /// to a \a DbgInfoIntrinsic.)
   2418   bool isValidLocationForIntrinsic(const DILocation *DL) const {
   2419     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
   2420   }
   2421 
   2422   static bool classof(const Metadata *MD) {
   2423     return MD->getMetadataID() == DILocalVariableKind;
   2424   }
   2425 };
   2426 
   2427 class DIObjCProperty : public DINode {
   2428   friend class LLVMContextImpl;
   2429   friend class MDNode;
   2430 
   2431   unsigned Line;
   2432   unsigned Attributes;
   2433 
   2434   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
   2435                  unsigned Attributes, ArrayRef<Metadata *> Ops)
   2436       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
   2437                Ops),
   2438         Line(Line), Attributes(Attributes) {}
   2439   ~DIObjCProperty() = default;
   2440 
   2441   static DIObjCProperty *
   2442   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
   2443           StringRef GetterName, StringRef SetterName, unsigned Attributes,
   2444           DITypeRef Type, StorageType Storage, bool ShouldCreate = true) {
   2445     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
   2446                    getCanonicalMDString(Context, GetterName),
   2447                    getCanonicalMDString(Context, SetterName), Attributes, Type,
   2448                    Storage, ShouldCreate);
   2449   }
   2450   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
   2451                                  Metadata *File, unsigned Line,
   2452                                  MDString *GetterName, MDString *SetterName,
   2453                                  unsigned Attributes, Metadata *Type,
   2454                                  StorageType Storage, bool ShouldCreate = true);
   2455 
   2456   TempDIObjCProperty cloneImpl() const {
   2457     return getTemporary(getContext(), getName(), getFile(), getLine(),
   2458                         getGetterName(), getSetterName(), getAttributes(),
   2459                         getType());
   2460   }
   2461 
   2462 public:
   2463   DEFINE_MDNODE_GET(DIObjCProperty,
   2464                     (StringRef Name, DIFile *File, unsigned Line,
   2465                      StringRef GetterName, StringRef SetterName,
   2466                      unsigned Attributes, DITypeRef Type),
   2467                     (Name, File, Line, GetterName, SetterName, Attributes,
   2468                      Type))
   2469   DEFINE_MDNODE_GET(DIObjCProperty,
   2470                     (MDString * Name, Metadata *File, unsigned Line,
   2471                      MDString *GetterName, MDString *SetterName,
   2472                      unsigned Attributes, Metadata *Type),
   2473                     (Name, File, Line, GetterName, SetterName, Attributes,
   2474                      Type))
   2475 
   2476   TempDIObjCProperty clone() const { return cloneImpl(); }
   2477 
   2478   unsigned getLine() const { return Line; }
   2479   unsigned getAttributes() const { return Attributes; }
   2480   StringRef getName() const { return getStringOperand(0); }
   2481   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   2482   StringRef getGetterName() const { return getStringOperand(2); }
   2483   StringRef getSetterName() const { return getStringOperand(3); }
   2484   DITypeRef getType() const { return DITypeRef(getRawType()); }
   2485 
   2486   StringRef getFilename() const {
   2487     if (auto *F = getFile())
   2488       return F->getFilename();
   2489     return "";
   2490   }
   2491   StringRef getDirectory() const {
   2492     if (auto *F = getFile())
   2493       return F->getDirectory();
   2494     return "";
   2495   }
   2496 
   2497   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   2498   Metadata *getRawFile() const { return getOperand(1); }
   2499   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
   2500   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
   2501   Metadata *getRawType() const { return getOperand(4); }
   2502 
   2503   static bool classof(const Metadata *MD) {
   2504     return MD->getMetadataID() == DIObjCPropertyKind;
   2505   }
   2506 };
   2507 
   2508 /// An imported module (C++ using directive or similar).
   2509 class DIImportedEntity : public DINode {
   2510   friend class LLVMContextImpl;
   2511   friend class MDNode;
   2512 
   2513   unsigned Line;
   2514 
   2515   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
   2516                    unsigned Line, ArrayRef<Metadata *> Ops)
   2517       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
   2518   ~DIImportedEntity() = default;
   2519 
   2520   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
   2521                                    DIScope *Scope, DINodeRef Entity,
   2522                                    unsigned Line, StringRef Name,
   2523                                    StorageType Storage,
   2524                                    bool ShouldCreate = true) {
   2525     return getImpl(Context, Tag, Scope, Entity, Line,
   2526                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
   2527   }
   2528   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
   2529                                    Metadata *Scope, Metadata *Entity,
   2530                                    unsigned Line, MDString *Name,
   2531                                    StorageType Storage,
   2532                                    bool ShouldCreate = true);
   2533 
   2534   TempDIImportedEntity cloneImpl() const {
   2535     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
   2536                         getLine(), getName());
   2537   }
   2538 
   2539 public:
   2540   DEFINE_MDNODE_GET(DIImportedEntity,
   2541                     (unsigned Tag, DIScope *Scope, DINodeRef Entity,
   2542                      unsigned Line, StringRef Name = ""),
   2543                     (Tag, Scope, Entity, Line, Name))
   2544   DEFINE_MDNODE_GET(DIImportedEntity,
   2545                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
   2546                      unsigned Line, MDString *Name),
   2547                     (Tag, Scope, Entity, Line, Name))
   2548 
   2549   TempDIImportedEntity clone() const { return cloneImpl(); }
   2550 
   2551   unsigned getLine() const { return Line; }
   2552   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
   2553   DINodeRef getEntity() const { return DINodeRef(getRawEntity()); }
   2554   StringRef getName() const { return getStringOperand(2); }
   2555 
   2556   Metadata *getRawScope() const { return getOperand(0); }
   2557   Metadata *getRawEntity() const { return getOperand(1); }
   2558   MDString *getRawName() const { return getOperandAs<MDString>(2); }
   2559 
   2560   static bool classof(const Metadata *MD) {
   2561     return MD->getMetadataID() == DIImportedEntityKind;
   2562   }
   2563 };
   2564 
   2565 /// A pair of DIGlobalVariable and DIExpression.
   2566 class DIGlobalVariableExpression : public MDNode {
   2567   friend class LLVMContextImpl;
   2568   friend class MDNode;
   2569 
   2570   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
   2571                              ArrayRef<Metadata *> Ops)
   2572       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
   2573   ~DIGlobalVariableExpression() = default;
   2574 
   2575   static DIGlobalVariableExpression *
   2576   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
   2577           StorageType Storage, bool ShouldCreate = true);
   2578 
   2579   TempDIGlobalVariableExpression cloneImpl() const {
   2580     return getTemporary(getContext(), getVariable(), getExpression());
   2581   }
   2582 
   2583 public:
   2584   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
   2585                     (Metadata * Variable, Metadata *Expression),
   2586                     (Variable, Expression))
   2587 
   2588   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
   2589 
   2590   Metadata *getRawVariable() const { return getOperand(0); }
   2591   DIGlobalVariable *getVariable() const {
   2592     return cast_or_null<DIGlobalVariable>(getRawVariable());
   2593   }
   2594   Metadata *getRawExpression() const { return getOperand(1); }
   2595   DIExpression *getExpression() const {
   2596     return cast_or_null<DIExpression>(getRawExpression());
   2597   }
   2598 
   2599   static bool classof(const Metadata *MD) {
   2600     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
   2601   }
   2602 };
   2603 
   2604 /// Macro Info DWARF-like metadata node.
   2605 ///
   2606 /// A metadata node with a DWARF macro info (i.e., a constant named
   2607 /// \c DW_MACINFO_*, defined in llvm/Support/Dwarf.h).  Called \a DIMacroNode
   2608 /// because it's potentially used for non-DWARF output.
   2609 class DIMacroNode : public MDNode {
   2610   friend class LLVMContextImpl;
   2611   friend class MDNode;
   2612 
   2613 protected:
   2614   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
   2615               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
   2616       : MDNode(C, ID, Storage, Ops1, Ops2) {
   2617     assert(MIType < 1u << 16);
   2618     SubclassData16 = MIType;
   2619   }
   2620   ~DIMacroNode() = default;
   2621 
   2622   template <class Ty> Ty *getOperandAs(unsigned I) const {
   2623     return cast_or_null<Ty>(getOperand(I));
   2624   }
   2625 
   2626   StringRef getStringOperand(unsigned I) const {
   2627     if (auto *S = getOperandAs<MDString>(I))
   2628       return S->getString();
   2629     return StringRef();
   2630   }
   2631 
   2632   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
   2633     if (S.empty())
   2634       return nullptr;
   2635     return MDString::get(Context, S);
   2636   }
   2637 
   2638 public:
   2639   unsigned getMacinfoType() const { return SubclassData16; }
   2640 
   2641   static bool classof(const Metadata *MD) {
   2642     switch (MD->getMetadataID()) {
   2643     default:
   2644       return false;
   2645     case DIMacroKind:
   2646     case DIMacroFileKind:
   2647       return true;
   2648     }
   2649   }
   2650 };
   2651 
   2652 class DIMacro : public DIMacroNode {
   2653   friend class LLVMContextImpl;
   2654   friend class MDNode;
   2655 
   2656   unsigned Line;
   2657 
   2658   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
   2659           ArrayRef<Metadata *> Ops)
   2660       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
   2661   ~DIMacro() = default;
   2662 
   2663   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
   2664                           StringRef Name, StringRef Value, StorageType Storage,
   2665                           bool ShouldCreate = true) {
   2666     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
   2667                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
   2668   }
   2669   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
   2670                           MDString *Name, MDString *Value, StorageType Storage,
   2671                           bool ShouldCreate = true);
   2672 
   2673   TempDIMacro cloneImpl() const {
   2674     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
   2675                         getValue());
   2676   }
   2677 
   2678 public:
   2679   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, StringRef Name,
   2680                               StringRef Value = ""),
   2681                     (MIType, Line, Name, Value))
   2682   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, MDString *Name,
   2683                               MDString *Value),
   2684                     (MIType, Line, Name, Value))
   2685 
   2686   TempDIMacro clone() const { return cloneImpl(); }
   2687 
   2688   unsigned getLine() const { return Line; }
   2689 
   2690   StringRef getName() const { return getStringOperand(0); }
   2691   StringRef getValue() const { return getStringOperand(1); }
   2692 
   2693   MDString *getRawName() const { return getOperandAs<MDString>(0); }
   2694   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
   2695 
   2696   static bool classof(const Metadata *MD) {
   2697     return MD->getMetadataID() == DIMacroKind;
   2698   }
   2699 };
   2700 
   2701 class DIMacroFile : public DIMacroNode {
   2702   friend class LLVMContextImpl;
   2703   friend class MDNode;
   2704 
   2705   unsigned Line;
   2706 
   2707   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
   2708               unsigned Line, ArrayRef<Metadata *> Ops)
   2709       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
   2710   ~DIMacroFile() = default;
   2711 
   2712   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
   2713                               unsigned Line, DIFile *File,
   2714                               DIMacroNodeArray Elements, StorageType Storage,
   2715                               bool ShouldCreate = true) {
   2716     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
   2717                    Elements.get(), Storage, ShouldCreate);
   2718   }
   2719 
   2720   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
   2721                               unsigned Line, Metadata *File, Metadata *Elements,
   2722                               StorageType Storage, bool ShouldCreate = true);
   2723 
   2724   TempDIMacroFile cloneImpl() const {
   2725     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
   2726                         getElements());
   2727   }
   2728 
   2729 public:
   2730   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line, DIFile *File,
   2731                                   DIMacroNodeArray Elements),
   2732                     (MIType, Line, File, Elements))
   2733   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line,
   2734                                   Metadata *File, Metadata *Elements),
   2735                     (MIType, Line, File, Elements))
   2736 
   2737   TempDIMacroFile clone() const { return cloneImpl(); }
   2738 
   2739   void replaceElements(DIMacroNodeArray Elements) {
   2740 #ifndef NDEBUG
   2741     for (DIMacroNode *Op : getElements())
   2742       assert(is_contained(Elements->operands(), Op) &&
   2743              "Lost a macro node during macro node list replacement");
   2744 #endif
   2745     replaceOperandWith(1, Elements.get());
   2746   }
   2747 
   2748   unsigned getLine() const { return Line; }
   2749   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
   2750 
   2751   DIMacroNodeArray getElements() const {
   2752     return cast_or_null<MDTuple>(getRawElements());
   2753   }
   2754 
   2755   Metadata *getRawFile() const { return getOperand(0); }
   2756   Metadata *getRawElements() const { return getOperand(1); }
   2757 
   2758   static bool classof(const Metadata *MD) {
   2759     return MD->getMetadataID() == DIMacroFileKind;
   2760   }
   2761 };
   2762 
   2763 } // end namespace llvm
   2764 
   2765 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
   2766 #undef DEFINE_MDNODE_GET_UNPACK
   2767 #undef DEFINE_MDNODE_GET
   2768 
   2769 #endif // LLVM_IR_DEBUGINFOMETADATA_H
   2770