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