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