OSDN Git Service

Revert "DebugInfo: use strongly typed enum for debug info flags"
[android-x86/external-llvm.git] / include / llvm / IR / DebugInfoMetadata.h
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;
60   TypedDINodeRef(std::nullptr_t) {}
61   TypedDINodeRef(const T *MD) : MD(MD) {}
62
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)
72       : MD(X) {}
73
74   operator Metadata *() const { return const_cast<Metadata *>(MD); }
75
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;
91   DITypeRefArray(const MDTuple *N) : N(N) {}
92
93   explicit operator bool() const { return get(); }
94   explicit operator MDTuple *() const { return get(); }
95
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.
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;
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.
126   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
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)
142       : MDNode(C, ID, Storage, Ops1, Ops2) {
143     assert(Tag < 1u << 16);
144     SubclassData16 = Tag;
145   }
146   ~DINode() = default;
147
148   template <class Ty> Ty *getOperandAs(unsigned I) const {
149     return cast_or_null<Ty>(getOperand(I));
150   }
151
152   StringRef getStringOperand(unsigned I) const {
153     if (auto *S = getOperandAs<MDString>(I))
154       return S->getString();
155     return StringRef();
156   }
157
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.
165   void setTag(unsigned Tag) { SubclassData16 = Tag; }
166
167 public:
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
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(is_contained(Elements->operands(), 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   bool SplitDebugInlining;
1001
1002   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
1003                 bool IsOptimized, unsigned RuntimeVersion,
1004                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
1005                 ArrayRef<Metadata *> Ops)
1006       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
1007         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
1008         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
1009         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining) {
1010     assert(Storage != Uniqued);
1011   }
1012   ~DICompileUnit() = default;
1013
1014   static DICompileUnit *
1015   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
1016           StringRef Producer, bool IsOptimized, StringRef Flags,
1017           unsigned RuntimeVersion, StringRef SplitDebugFilename,
1018           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
1019           DIScopeArray RetainedTypes, DIGlobalVariableArray GlobalVariables,
1020           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1021           uint64_t DWOId, bool SplitDebugInlining, StorageType Storage,
1022           bool ShouldCreate = true) {
1023     return getImpl(Context, SourceLanguage, File,
1024                    getCanonicalMDString(Context, Producer), IsOptimized,
1025                    getCanonicalMDString(Context, Flags), RuntimeVersion,
1026                    getCanonicalMDString(Context, SplitDebugFilename),
1027                    EmissionKind, EnumTypes.get(), RetainedTypes.get(),
1028                    GlobalVariables.get(), ImportedEntities.get(), Macros.get(),
1029                    DWOId, SplitDebugInlining, Storage, ShouldCreate);
1030   }
1031   static DICompileUnit *
1032   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
1033           MDString *Producer, bool IsOptimized, MDString *Flags,
1034           unsigned RuntimeVersion, MDString *SplitDebugFilename,
1035           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
1036           Metadata *GlobalVariables, Metadata *ImportedEntities,
1037           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
1038           StorageType Storage, bool ShouldCreate = true);
1039
1040   TempDICompileUnit cloneImpl() const {
1041     return getTemporary(getContext(), getSourceLanguage(), getFile(),
1042                         getProducer(), isOptimized(), getFlags(),
1043                         getRuntimeVersion(), getSplitDebugFilename(),
1044                         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
1045                         getGlobalVariables(), getImportedEntities(),
1046                         getMacros(), DWOId, getSplitDebugInlining());
1047   }
1048
1049   static void get() = delete;
1050   static void getIfExists() = delete;
1051
1052 public:
1053   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1054       DICompileUnit,
1055       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
1056        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1057        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
1058        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
1059        DIGlobalVariableArray GlobalVariables,
1060        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1061        uint64_t DWOId, bool SplitDebugInlining),
1062       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1063        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1064        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining))
1065   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1066       DICompileUnit,
1067       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
1068        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
1069        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
1070        Metadata *RetainedTypes, Metadata *GlobalVariables,
1071        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
1072        bool SplitDebugInlining),
1073       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1074        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1075        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining))
1076
1077   TempDICompileUnit clone() const { return cloneImpl(); }
1078
1079   unsigned getSourceLanguage() const { return SourceLanguage; }
1080   bool isOptimized() const { return IsOptimized; }
1081   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1082   DebugEmissionKind getEmissionKind() const {
1083     return (DebugEmissionKind)EmissionKind;
1084   }
1085   StringRef getProducer() const { return getStringOperand(1); }
1086   StringRef getFlags() const { return getStringOperand(2); }
1087   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1088   DICompositeTypeArray getEnumTypes() const {
1089     return cast_or_null<MDTuple>(getRawEnumTypes());
1090   }
1091   DIScopeArray getRetainedTypes() const {
1092     return cast_or_null<MDTuple>(getRawRetainedTypes());
1093   }
1094   DIGlobalVariableArray getGlobalVariables() const {
1095     return cast_or_null<MDTuple>(getRawGlobalVariables());
1096   }
1097   DIImportedEntityArray getImportedEntities() const {
1098     return cast_or_null<MDTuple>(getRawImportedEntities());
1099   }
1100   DIMacroNodeArray getMacros() const {
1101     return cast_or_null<MDTuple>(getRawMacros());
1102   }
1103   uint64_t getDWOId() const { return DWOId; }
1104   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
1105   bool getSplitDebugInlining() const { return SplitDebugInlining; }
1106   void setSplitDebugInlining(bool SplitDebugInlining) {
1107     this->SplitDebugInlining = SplitDebugInlining;
1108   }
1109
1110   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1111   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1112   MDString *getRawSplitDebugFilename() const {
1113     return getOperandAs<MDString>(3);
1114   }
1115   Metadata *getRawEnumTypes() const { return getOperand(4); }
1116   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1117   Metadata *getRawGlobalVariables() const { return getOperand(6); }
1118   Metadata *getRawImportedEntities() const { return getOperand(7); }
1119   Metadata *getRawMacros() const { return getOperand(8); }
1120
1121   /// \brief Replace arrays.
1122   ///
1123   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1124   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1125   /// DICompileUnit should be fairly rare.
1126   /// @{
1127   void replaceEnumTypes(DICompositeTypeArray N) {
1128     replaceOperandWith(4, N.get());
1129   }
1130   void replaceRetainedTypes(DITypeArray N) {
1131     replaceOperandWith(5, N.get());
1132   }
1133   void replaceGlobalVariables(DIGlobalVariableArray N) {
1134     replaceOperandWith(6, N.get());
1135   }
1136   void replaceImportedEntities(DIImportedEntityArray N) {
1137     replaceOperandWith(7, N.get());
1138   }
1139   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
1140   /// @}
1141
1142   static bool classof(const Metadata *MD) {
1143     return MD->getMetadataID() == DICompileUnitKind;
1144   }
1145 };
1146
1147 /// \brief A scope for locals.
1148 ///
1149 /// A legal scope for lexical blocks, local variables, and debug info
1150 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
1151 /// DILexicalBlockFile.
1152 class DILocalScope : public DIScope {
1153 protected:
1154   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1155                ArrayRef<Metadata *> Ops)
1156       : DIScope(C, ID, Storage, Tag, Ops) {}
1157   ~DILocalScope() = default;
1158
1159 public:
1160   /// \brief Get the subprogram for this scope.
1161   ///
1162   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
1163   /// chain.
1164   DISubprogram *getSubprogram() const;
1165
1166   /// Get the first non DILexicalBlockFile scope of this scope.
1167   ///
1168   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
1169   /// scope chain.
1170   DILocalScope *getNonLexicalBlockFileScope() const;
1171
1172   static bool classof(const Metadata *MD) {
1173     return MD->getMetadataID() == DISubprogramKind ||
1174            MD->getMetadataID() == DILexicalBlockKind ||
1175            MD->getMetadataID() == DILexicalBlockFileKind;
1176   }
1177 };
1178
1179 /// \brief Debug location.
1180 ///
1181 /// A debug location in source code, used for debug info and otherwise.
1182 class DILocation : public MDNode {
1183   friend class LLVMContextImpl;
1184   friend class MDNode;
1185
1186   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
1187              unsigned Column, ArrayRef<Metadata *> MDs);
1188   ~DILocation() { dropAllReferences(); }
1189
1190   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1191                              unsigned Column, Metadata *Scope,
1192                              Metadata *InlinedAt, StorageType Storage,
1193                              bool ShouldCreate = true);
1194   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1195                              unsigned Column, DILocalScope *Scope,
1196                              DILocation *InlinedAt, StorageType Storage,
1197                              bool ShouldCreate = true) {
1198     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1199                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1200   }
1201
1202   TempDILocation cloneImpl() const {
1203     // Get the raw scope/inlinedAt since it is possible to invoke this on
1204     // a DILocation containing temporary metadata.
1205     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
1206                         getRawInlinedAt());
1207   }
1208
1209   // Disallow replacing operands.
1210   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1211
1212 public:
1213   DEFINE_MDNODE_GET(DILocation,
1214                     (unsigned Line, unsigned Column, Metadata *Scope,
1215                      Metadata *InlinedAt = nullptr),
1216                     (Line, Column, Scope, InlinedAt))
1217   DEFINE_MDNODE_GET(DILocation,
1218                     (unsigned Line, unsigned Column, DILocalScope *Scope,
1219                      DILocation *InlinedAt = nullptr),
1220                     (Line, Column, Scope, InlinedAt))
1221
1222   /// \brief Return a (temporary) clone of this.
1223   TempDILocation clone() const { return cloneImpl(); }
1224
1225   unsigned getLine() const { return SubclassData32; }
1226   unsigned getColumn() const { return SubclassData16; }
1227   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1228   DILocation *getInlinedAt() const {
1229     return cast_or_null<DILocation>(getRawInlinedAt());
1230   }
1231
1232   DIFile *getFile() const { return getScope()->getFile(); }
1233   StringRef getFilename() const { return getScope()->getFilename(); }
1234   StringRef getDirectory() const { return getScope()->getDirectory(); }
1235
1236   /// \brief Get the scope where this is inlined.
1237   ///
1238   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1239   /// location.
1240   DILocalScope *getInlinedAtScope() const {
1241     if (auto *IA = getInlinedAt())
1242       return IA->getInlinedAtScope();
1243     return getScope();
1244   }
1245
1246   /// \brief Check whether this can be discriminated from another location.
1247   ///
1248   /// Check \c this can be discriminated from \c RHS in a linetable entry.
1249   /// Scope and inlined-at chains are not recorded in the linetable, so they
1250   /// cannot be used to distinguish basic blocks.
1251   ///
1252   /// The current implementation is weaker than it should be, since it just
1253   /// checks filename and line.
1254   ///
1255   /// FIXME: Add a check for getDiscriminator().
1256   /// FIXME: Add a check for getColumn().
1257   /// FIXME: Change the getFilename() check to getFile() (or add one for
1258   /// getDirectory()).
1259   bool canDiscriminate(const DILocation &RHS) const {
1260     return getFilename() != RHS.getFilename() || getLine() != RHS.getLine();
1261   }
1262
1263   /// \brief Get the DWARF discriminator.
1264   ///
1265   /// DWARF discriminators distinguish identical file locations between
1266   /// instructions that are on different basic blocks.
1267   inline unsigned getDiscriminator() const;
1268
1269   Metadata *getRawScope() const { return getOperand(0); }
1270   Metadata *getRawInlinedAt() const {
1271     if (getNumOperands() == 2)
1272       return getOperand(1);
1273     return nullptr;
1274   }
1275
1276   static bool classof(const Metadata *MD) {
1277     return MD->getMetadataID() == DILocationKind;
1278   }
1279 };
1280
1281 /// \brief Subprogram description.
1282 ///
1283 /// TODO: Remove DisplayName.  It's always equal to Name.
1284 /// TODO: Split up flags.
1285 class DISubprogram : public DILocalScope {
1286   friend class LLVMContextImpl;
1287   friend class MDNode;
1288
1289   unsigned Line;
1290   unsigned ScopeLine;
1291   unsigned VirtualIndex;
1292
1293   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
1294   /// of method overrides from secondary bases by this amount. It may be
1295   /// negative.
1296   int ThisAdjustment;
1297
1298   // Virtuality can only assume three values, so we can pack
1299   // in 2 bits (none/pure/pure_virtual).
1300   unsigned Virtuality : 2;
1301
1302   unsigned Flags : 27;
1303
1304   // These are boolean flags so one bit is enough.
1305   // MSVC starts a new container field every time the base
1306   // type changes so we can't use 'bool' to ensure these bits
1307   // are packed.
1308   unsigned IsLocalToUnit : 1;
1309   unsigned IsDefinition : 1;
1310   unsigned IsOptimized : 1;
1311
1312   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1313                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1314                int ThisAdjustment, unsigned Flags, bool IsLocalToUnit,
1315                bool IsDefinition, bool IsOptimized, ArrayRef<Metadata *> Ops)
1316       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1317                      Ops),
1318         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1319         ThisAdjustment(ThisAdjustment), Virtuality(Virtuality), Flags(Flags),
1320         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition),
1321         IsOptimized(IsOptimized) {
1322     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1323     assert(Virtuality < 4 && "Virtuality out of range");
1324     assert((Flags < (1 << 27)) && "Flags out of range");
1325   }
1326   ~DISubprogram() = default;
1327
1328   static DISubprogram *
1329   getImpl(LLVMContext &Context, DIScopeRef Scope, StringRef Name,
1330           StringRef LinkageName, DIFile *File, unsigned Line,
1331           DISubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1332           unsigned ScopeLine, DITypeRef ContainingType, unsigned Virtuality,
1333           unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
1334           bool IsOptimized, DICompileUnit *Unit,
1335           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
1336           DILocalVariableArray Variables, StorageType Storage,
1337           bool ShouldCreate = true) {
1338     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1339                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1340                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1341                    Virtuality, VirtualIndex, ThisAdjustment, Flags, IsOptimized,
1342                    Unit, TemplateParams.get(), Declaration, Variables.get(),
1343                    Storage, ShouldCreate);
1344   }
1345   static DISubprogram *
1346   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1347           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1348           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1349           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1350           int ThisAdjustment, unsigned Flags, bool IsOptimized, Metadata *Unit,
1351           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1352           StorageType Storage, bool ShouldCreate = true);
1353
1354   TempDISubprogram cloneImpl() const {
1355     return getTemporary(
1356         getContext(), getScope(), getName(), getLinkageName(), getFile(),
1357         getLine(), getType(), isLocalToUnit(), isDefinition(), getScopeLine(),
1358         getContainingType(), getVirtuality(), getVirtualIndex(),
1359         getThisAdjustment(), getFlags(), isOptimized(), getUnit(),
1360         getTemplateParams(), getDeclaration(), getVariables());
1361   }
1362
1363 public:
1364   DEFINE_MDNODE_GET(DISubprogram,
1365                     (DIScopeRef Scope, StringRef Name, StringRef LinkageName,
1366                      DIFile *File, unsigned Line, DISubroutineType *Type,
1367                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1368                      DITypeRef ContainingType, unsigned Virtuality,
1369                      unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
1370                      bool IsOptimized, DICompileUnit *Unit,
1371                      DITemplateParameterArray TemplateParams = nullptr,
1372                      DISubprogram *Declaration = nullptr,
1373                      DILocalVariableArray Variables = nullptr),
1374                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1375                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1376                      VirtualIndex, ThisAdjustment, Flags, IsOptimized, Unit,
1377                      TemplateParams, Declaration, Variables))
1378   DEFINE_MDNODE_GET(
1379       DISubprogram,
1380       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1381        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1382        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1383        unsigned VirtualIndex, int ThisAdjustment, unsigned Flags,
1384        bool IsOptimized, Metadata *Unit, Metadata *TemplateParams = nullptr,
1385        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1386       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1387        ScopeLine, ContainingType, Virtuality, VirtualIndex, ThisAdjustment,
1388        Flags, IsOptimized, Unit, TemplateParams, Declaration, Variables))
1389
1390   TempDISubprogram clone() const { return cloneImpl(); }
1391
1392 public:
1393   unsigned getLine() const { return Line; }
1394   unsigned getVirtuality() const { return Virtuality; }
1395   unsigned getVirtualIndex() const { return VirtualIndex; }
1396   int getThisAdjustment() const { return ThisAdjustment; }
1397   unsigned getScopeLine() const { return ScopeLine; }
1398   unsigned getFlags() const { return Flags; }
1399   bool isLocalToUnit() const { return IsLocalToUnit; }
1400   bool isDefinition() const { return IsDefinition; }
1401   bool isOptimized() const { return IsOptimized; }
1402
1403   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1404   bool isPrivate() const {
1405     return (getFlags() & FlagAccessibility) == FlagPrivate;
1406   }
1407   bool isProtected() const {
1408     return (getFlags() & FlagAccessibility) == FlagProtected;
1409   }
1410   bool isPublic() const {
1411     return (getFlags() & FlagAccessibility) == FlagPublic;
1412   }
1413   bool isExplicit() const { return getFlags() & FlagExplicit; }
1414   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1415
1416   /// \brief Check if this is reference-qualified.
1417   ///
1418   /// Return true if this subprogram is a C++11 reference-qualified non-static
1419   /// member function (void foo() &).
1420   unsigned isLValueReference() const {
1421     return getFlags() & FlagLValueReference;
1422   }
1423
1424   /// \brief Check if this is rvalue-reference-qualified.
1425   ///
1426   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1427   /// non-static member function (void foo() &&).
1428   unsigned isRValueReference() const {
1429     return getFlags() & FlagRValueReference;
1430   }
1431
1432   /// \brief Check if this is marked as noreturn.
1433   ///
1434   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
1435   unsigned isNoReturn() const {
1436     return getFlags() & FlagNoReturn;
1437   }
1438
1439   DIScopeRef getScope() const { return DIScopeRef(getRawScope()); }
1440
1441   StringRef getName() const { return getStringOperand(2); }
1442   StringRef getDisplayName() const { return getStringOperand(3); }
1443   StringRef getLinkageName() const { return getStringOperand(4); }
1444
1445   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1446   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1447
1448   DISubroutineType *getType() const {
1449     return cast_or_null<DISubroutineType>(getRawType());
1450   }
1451   DITypeRef getContainingType() const {
1452     return DITypeRef(getRawContainingType());
1453   }
1454
1455   DICompileUnit *getUnit() const {
1456     return cast_or_null<DICompileUnit>(getRawUnit());
1457   }
1458   void replaceUnit(DICompileUnit *CU) {
1459     replaceOperandWith(7, CU);
1460   }
1461   DITemplateParameterArray getTemplateParams() const {
1462     return cast_or_null<MDTuple>(getRawTemplateParams());
1463   }
1464   DISubprogram *getDeclaration() const {
1465     return cast_or_null<DISubprogram>(getRawDeclaration());
1466   }
1467   DILocalVariableArray getVariables() const {
1468     return cast_or_null<MDTuple>(getRawVariables());
1469   }
1470
1471   Metadata *getRawScope() const { return getOperand(1); }
1472   Metadata *getRawType() const { return getOperand(5); }
1473   Metadata *getRawContainingType() const { return getOperand(6); }
1474   Metadata *getRawUnit() const { return getOperand(7); }
1475   Metadata *getRawTemplateParams() const { return getOperand(8); }
1476   Metadata *getRawDeclaration() const { return getOperand(9); }
1477   Metadata *getRawVariables() const { return getOperand(10); }
1478
1479   /// \brief Check if this subprogram describes the given function.
1480   ///
1481   /// FIXME: Should this be looking through bitcasts?
1482   bool describes(const Function *F) const;
1483
1484   static bool classof(const Metadata *MD) {
1485     return MD->getMetadataID() == DISubprogramKind;
1486   }
1487 };
1488
1489 class DILexicalBlockBase : public DILocalScope {
1490 protected:
1491   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1492                      ArrayRef<Metadata *> Ops)
1493       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1494   ~DILexicalBlockBase() = default;
1495
1496 public:
1497   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1498
1499   Metadata *getRawScope() const { return getOperand(1); }
1500
1501   static bool classof(const Metadata *MD) {
1502     return MD->getMetadataID() == DILexicalBlockKind ||
1503            MD->getMetadataID() == DILexicalBlockFileKind;
1504   }
1505 };
1506
1507 class DILexicalBlock : public DILexicalBlockBase {
1508   friend class LLVMContextImpl;
1509   friend class MDNode;
1510
1511   unsigned Line;
1512   uint16_t Column;
1513
1514   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1515                  unsigned Column, ArrayRef<Metadata *> Ops)
1516       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
1517         Column(Column) {
1518     assert(Column < (1u << 16) && "Expected 16-bit column");
1519   }
1520   ~DILexicalBlock() = default;
1521
1522   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
1523                                  DIFile *File, unsigned Line, unsigned Column,
1524                                  StorageType Storage,
1525                                  bool ShouldCreate = true) {
1526     return getImpl(Context, static_cast<Metadata *>(Scope),
1527                    static_cast<Metadata *>(File), Line, Column, Storage,
1528                    ShouldCreate);
1529   }
1530
1531   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1532                                  Metadata *File, unsigned Line, unsigned Column,
1533                                  StorageType Storage, bool ShouldCreate = true);
1534
1535   TempDILexicalBlock cloneImpl() const {
1536     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1537                         getColumn());
1538   }
1539
1540 public:
1541   DEFINE_MDNODE_GET(DILexicalBlock, (DILocalScope * Scope, DIFile *File,
1542                                      unsigned Line, unsigned Column),
1543                     (Scope, File, Line, Column))
1544   DEFINE_MDNODE_GET(DILexicalBlock, (Metadata * Scope, Metadata *File,
1545                                      unsigned Line, unsigned Column),
1546                     (Scope, File, Line, Column))
1547
1548   TempDILexicalBlock clone() const { return cloneImpl(); }
1549
1550   unsigned getLine() const { return Line; }
1551   unsigned getColumn() const { return Column; }
1552
1553   static bool classof(const Metadata *MD) {
1554     return MD->getMetadataID() == DILexicalBlockKind;
1555   }
1556 };
1557
1558 class DILexicalBlockFile : public DILexicalBlockBase {
1559   friend class LLVMContextImpl;
1560   friend class MDNode;
1561
1562   unsigned Discriminator;
1563
1564   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
1565                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1566       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
1567         Discriminator(Discriminator) {}
1568   ~DILexicalBlockFile() = default;
1569
1570   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
1571                                      DIFile *File, unsigned Discriminator,
1572                                      StorageType Storage,
1573                                      bool ShouldCreate = true) {
1574     return getImpl(Context, static_cast<Metadata *>(Scope),
1575                    static_cast<Metadata *>(File), Discriminator, Storage,
1576                    ShouldCreate);
1577   }
1578
1579   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1580                                      Metadata *File, unsigned Discriminator,
1581                                      StorageType Storage,
1582                                      bool ShouldCreate = true);
1583
1584   TempDILexicalBlockFile cloneImpl() const {
1585     return getTemporary(getContext(), getScope(), getFile(),
1586                         getDiscriminator());
1587   }
1588
1589 public:
1590   DEFINE_MDNODE_GET(DILexicalBlockFile, (DILocalScope * Scope, DIFile *File,
1591                                          unsigned Discriminator),
1592                     (Scope, File, Discriminator))
1593   DEFINE_MDNODE_GET(DILexicalBlockFile,
1594                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1595                     (Scope, File, Discriminator))
1596
1597   TempDILexicalBlockFile clone() const { return cloneImpl(); }
1598
1599   // TODO: Remove these once they're gone from DILexicalBlockBase.
1600   unsigned getLine() const = delete;
1601   unsigned getColumn() const = delete;
1602
1603   unsigned getDiscriminator() const { return Discriminator; }
1604
1605   static bool classof(const Metadata *MD) {
1606     return MD->getMetadataID() == DILexicalBlockFileKind;
1607   }
1608 };
1609
1610 unsigned DILocation::getDiscriminator() const {
1611   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
1612     return F->getDiscriminator();
1613   return 0;
1614 }
1615
1616 class DINamespace : public DIScope {
1617   friend class LLVMContextImpl;
1618   friend class MDNode;
1619
1620   unsigned Line;
1621
1622   DINamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1623               ArrayRef<Metadata *> Ops)
1624       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
1625                 Ops),
1626         Line(Line) {}
1627   ~DINamespace() = default;
1628
1629   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
1630                               DIFile *File, StringRef Name, unsigned Line,
1631                               StorageType Storage, bool ShouldCreate = true) {
1632     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1633                    Line, Storage, ShouldCreate);
1634   }
1635   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1636                               Metadata *File, MDString *Name, unsigned Line,
1637                               StorageType Storage, bool ShouldCreate = true);
1638
1639   TempDINamespace cloneImpl() const {
1640     return getTemporary(getContext(), getScope(), getFile(), getName(),
1641                         getLine());
1642   }
1643
1644 public:
1645   DEFINE_MDNODE_GET(DINamespace, (DIScope * Scope, DIFile *File, StringRef Name,
1646                                   unsigned Line),
1647                     (Scope, File, Name, Line))
1648   DEFINE_MDNODE_GET(DINamespace, (Metadata * Scope, Metadata *File,
1649                                   MDString *Name, unsigned Line),
1650                     (Scope, File, Name, Line))
1651
1652   TempDINamespace clone() const { return cloneImpl(); }
1653
1654   unsigned getLine() const { return Line; }
1655   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1656   StringRef getName() const { return getStringOperand(2); }
1657
1658   Metadata *getRawScope() const { return getOperand(1); }
1659   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1660
1661   static bool classof(const Metadata *MD) {
1662     return MD->getMetadataID() == DINamespaceKind;
1663   }
1664 };
1665
1666 /// \brief A (clang) module that has been imported by the compile unit.
1667 ///
1668 class DIModule : public DIScope {
1669   friend class LLVMContextImpl;
1670   friend class MDNode;
1671
1672   DIModule(LLVMContext &Context, StorageType Storage, ArrayRef<Metadata *> Ops)
1673       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops) {}
1674   ~DIModule() {}
1675
1676   static DIModule *getImpl(LLVMContext &Context, DIScope *Scope,
1677                            StringRef Name, StringRef ConfigurationMacros,
1678                            StringRef IncludePath, StringRef ISysRoot,
1679                            StorageType Storage, bool ShouldCreate = true) {
1680     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1681                    getCanonicalMDString(Context, ConfigurationMacros),
1682                    getCanonicalMDString(Context, IncludePath),
1683                    getCanonicalMDString(Context, ISysRoot),
1684                    Storage, ShouldCreate);
1685   }
1686   static DIModule *getImpl(LLVMContext &Context, Metadata *Scope,
1687                            MDString *Name, MDString *ConfigurationMacros,
1688                            MDString *IncludePath, MDString *ISysRoot,
1689                            StorageType Storage, bool ShouldCreate = true);
1690
1691   TempDIModule cloneImpl() const {
1692     return getTemporary(getContext(), getScope(), getName(),
1693                         getConfigurationMacros(), getIncludePath(),
1694                         getISysRoot());
1695   }
1696
1697 public:
1698   DEFINE_MDNODE_GET(DIModule, (DIScope *Scope, StringRef Name,
1699                                StringRef ConfigurationMacros, StringRef IncludePath,
1700                                StringRef ISysRoot),
1701                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
1702   DEFINE_MDNODE_GET(DIModule,
1703                     (Metadata *Scope, MDString *Name, MDString *ConfigurationMacros,
1704                      MDString *IncludePath, MDString *ISysRoot),
1705                     (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot))
1706
1707   TempDIModule clone() const { return cloneImpl(); }
1708
1709   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1710   StringRef getName() const { return getStringOperand(1); }
1711   StringRef getConfigurationMacros() const { return getStringOperand(2); }
1712   StringRef getIncludePath() const { return getStringOperand(3); }
1713   StringRef getISysRoot() const { return getStringOperand(4); }
1714
1715   Metadata *getRawScope() const { return getOperand(0); }
1716   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1717   MDString *getRawConfigurationMacros() const { return getOperandAs<MDString>(2); }
1718   MDString *getRawIncludePath() const { return getOperandAs<MDString>(3); }
1719   MDString *getRawISysRoot() const { return getOperandAs<MDString>(4); }
1720
1721   static bool classof(const Metadata *MD) {
1722     return MD->getMetadataID() == DIModuleKind;
1723   }
1724 };
1725
1726 /// \brief Base class for template parameters.
1727 class DITemplateParameter : public DINode {
1728 protected:
1729   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1730                       unsigned Tag, ArrayRef<Metadata *> Ops)
1731       : DINode(Context, ID, Storage, Tag, Ops) {}
1732   ~DITemplateParameter() = default;
1733
1734 public:
1735   StringRef getName() const { return getStringOperand(0); }
1736   DITypeRef getType() const { return DITypeRef(getRawType()); }
1737
1738   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1739   Metadata *getRawType() const { return getOperand(1); }
1740
1741   static bool classof(const Metadata *MD) {
1742     return MD->getMetadataID() == DITemplateTypeParameterKind ||
1743            MD->getMetadataID() == DITemplateValueParameterKind;
1744   }
1745 };
1746
1747 class DITemplateTypeParameter : public DITemplateParameter {
1748   friend class LLVMContextImpl;
1749   friend class MDNode;
1750
1751   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1752                           ArrayRef<Metadata *> Ops)
1753       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
1754                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1755   ~DITemplateTypeParameter() = default;
1756
1757   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1758                                           DITypeRef Type, StorageType Storage,
1759                                           bool ShouldCreate = true) {
1760     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1761                    ShouldCreate);
1762   }
1763   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1764                                           Metadata *Type, StorageType Storage,
1765                                           bool ShouldCreate = true);
1766
1767   TempDITemplateTypeParameter cloneImpl() const {
1768     return getTemporary(getContext(), getName(), getType());
1769   }
1770
1771 public:
1772   DEFINE_MDNODE_GET(DITemplateTypeParameter, (StringRef Name, DITypeRef Type),
1773                     (Name, Type))
1774   DEFINE_MDNODE_GET(DITemplateTypeParameter, (MDString * Name, Metadata *Type),
1775                     (Name, Type))
1776
1777   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
1778
1779   static bool classof(const Metadata *MD) {
1780     return MD->getMetadataID() == DITemplateTypeParameterKind;
1781   }
1782 };
1783
1784 class DITemplateValueParameter : public DITemplateParameter {
1785   friend class LLVMContextImpl;
1786   friend class MDNode;
1787
1788   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
1789                            unsigned Tag, ArrayRef<Metadata *> Ops)
1790       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
1791                             Ops) {}
1792   ~DITemplateValueParameter() = default;
1793
1794   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1795                                            StringRef Name, DITypeRef Type,
1796                                            Metadata *Value, StorageType Storage,
1797                                            bool ShouldCreate = true) {
1798     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1799                    Value, Storage, ShouldCreate);
1800   }
1801   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1802                                            MDString *Name, Metadata *Type,
1803                                            Metadata *Value, StorageType Storage,
1804                                            bool ShouldCreate = true);
1805
1806   TempDITemplateValueParameter cloneImpl() const {
1807     return getTemporary(getContext(), getTag(), getName(), getType(),
1808                         getValue());
1809   }
1810
1811 public:
1812   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, StringRef Name,
1813                                                DITypeRef Type, Metadata *Value),
1814                     (Tag, Name, Type, Value))
1815   DEFINE_MDNODE_GET(DITemplateValueParameter, (unsigned Tag, MDString *Name,
1816                                                Metadata *Type, Metadata *Value),
1817                     (Tag, Name, Type, Value))
1818
1819   TempDITemplateValueParameter clone() const { return cloneImpl(); }
1820
1821   Metadata *getValue() const { return getOperand(2); }
1822
1823   static bool classof(const Metadata *MD) {
1824     return MD->getMetadataID() == DITemplateValueParameterKind;
1825   }
1826 };
1827
1828 /// \brief Base class for variables.
1829 class DIVariable : public DINode {
1830   unsigned Line;
1831
1832 protected:
1833   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
1834              ArrayRef<Metadata *> Ops)
1835       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line) {}
1836   ~DIVariable() = default;
1837
1838 public:
1839   unsigned getLine() const { return Line; }
1840   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
1841   StringRef getName() const { return getStringOperand(1); }
1842   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
1843   DITypeRef getType() const { return DITypeRef(getRawType()); }
1844
1845   StringRef getFilename() const {
1846     if (auto *F = getFile())
1847       return F->getFilename();
1848     return "";
1849   }
1850   StringRef getDirectory() const {
1851     if (auto *F = getFile())
1852       return F->getDirectory();
1853     return "";
1854   }
1855
1856   Metadata *getRawScope() const { return getOperand(0); }
1857   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1858   Metadata *getRawFile() const { return getOperand(2); }
1859   Metadata *getRawType() const { return getOperand(3); }
1860
1861   static bool classof(const Metadata *MD) {
1862     return MD->getMetadataID() == DILocalVariableKind ||
1863            MD->getMetadataID() == DIGlobalVariableKind;
1864   }
1865 };
1866
1867 /// \brief Global variables.
1868 ///
1869 /// TODO: Remove DisplayName.  It's always equal to Name.
1870 class DIGlobalVariable : public DIVariable {
1871   friend class LLVMContextImpl;
1872   friend class MDNode;
1873
1874   bool IsLocalToUnit;
1875   bool IsDefinition;
1876
1877   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1878                    bool IsLocalToUnit, bool IsDefinition,
1879                    ArrayRef<Metadata *> Ops)
1880       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops),
1881         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1882   ~DIGlobalVariable() = default;
1883
1884   static DIGlobalVariable *
1885   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
1886           StringRef LinkageName, DIFile *File, unsigned Line, DITypeRef Type,
1887           bool IsLocalToUnit, bool IsDefinition, Constant *Variable,
1888           DIDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1889           bool ShouldCreate = true) {
1890     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1891                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1892                    IsLocalToUnit, IsDefinition,
1893                    Variable ? ConstantAsMetadata::get(Variable) : nullptr,
1894                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1895   }
1896   static DIGlobalVariable *
1897   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1898           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1899           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1900           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1901           bool ShouldCreate = true);
1902
1903   TempDIGlobalVariable cloneImpl() const {
1904     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1905                         getFile(), getLine(), getType(), isLocalToUnit(),
1906                         isDefinition(), getVariable(),
1907                         getStaticDataMemberDeclaration());
1908   }
1909
1910 public:
1911   DEFINE_MDNODE_GET(DIGlobalVariable,
1912                     (DIScope * Scope, StringRef Name, StringRef LinkageName,
1913                      DIFile *File, unsigned Line, DITypeRef Type,
1914                      bool IsLocalToUnit, bool IsDefinition, Constant *Variable,
1915                      DIDerivedType *StaticDataMemberDeclaration),
1916                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1917                      IsDefinition, Variable, StaticDataMemberDeclaration))
1918   DEFINE_MDNODE_GET(DIGlobalVariable,
1919                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1920                      Metadata *File, unsigned Line, Metadata *Type,
1921                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1922                      Metadata *StaticDataMemberDeclaration),
1923                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1924                      IsDefinition, Variable, StaticDataMemberDeclaration))
1925
1926   TempDIGlobalVariable clone() const { return cloneImpl(); }
1927
1928   bool isLocalToUnit() const { return IsLocalToUnit; }
1929   bool isDefinition() const { return IsDefinition; }
1930   StringRef getDisplayName() const { return getStringOperand(4); }
1931   StringRef getLinkageName() const { return getStringOperand(5); }
1932   Constant *getVariable() const {
1933     if (auto *C = cast_or_null<ConstantAsMetadata>(getRawVariable()))
1934       return dyn_cast<Constant>(C->getValue());
1935     return nullptr;
1936   }
1937   DIDerivedType *getStaticDataMemberDeclaration() const {
1938     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
1939   }
1940
1941   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1942   Metadata *getRawVariable() const { return getOperand(6); }
1943   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1944
1945   static bool classof(const Metadata *MD) {
1946     return MD->getMetadataID() == DIGlobalVariableKind;
1947   }
1948 };
1949
1950 /// \brief Local variable.
1951 ///
1952 /// TODO: Split up flags.
1953 class DILocalVariable : public DIVariable {
1954   friend class LLVMContextImpl;
1955   friend class MDNode;
1956
1957   unsigned Arg : 16;
1958   unsigned Flags : 16;
1959
1960   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1961                   unsigned Arg, unsigned Flags, ArrayRef<Metadata *> Ops)
1962       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops), Arg(Arg),
1963         Flags(Flags) {
1964     assert(Flags < (1 << 16) && "DILocalVariable: Flags out of range");
1965     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
1966   }
1967   ~DILocalVariable() = default;
1968
1969   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
1970                                   StringRef Name, DIFile *File, unsigned Line,
1971                                   DITypeRef Type, unsigned Arg, unsigned Flags,
1972                                   StorageType Storage,
1973                                   bool ShouldCreate = true) {
1974     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
1975                    Line, Type, Arg, Flags, Storage, ShouldCreate);
1976   }
1977   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
1978                                   MDString *Name, Metadata *File, unsigned Line,
1979                                   Metadata *Type, unsigned Arg, unsigned Flags,
1980                                   StorageType Storage,
1981                                   bool ShouldCreate = true);
1982
1983   TempDILocalVariable cloneImpl() const {
1984     return getTemporary(getContext(), getScope(), getName(), getFile(),
1985                         getLine(), getType(), getArg(), getFlags());
1986   }
1987
1988 public:
1989   DEFINE_MDNODE_GET(DILocalVariable,
1990                     (DILocalScope * Scope, StringRef Name, DIFile *File,
1991                      unsigned Line, DITypeRef Type, unsigned Arg,
1992                      unsigned Flags),
1993                     (Scope, Name, File, Line, Type, Arg, Flags))
1994   DEFINE_MDNODE_GET(DILocalVariable,
1995                     (Metadata * Scope, MDString *Name, Metadata *File,
1996                      unsigned Line, Metadata *Type, unsigned Arg,
1997                      unsigned Flags),
1998                     (Scope, Name, File, Line, Type, Arg, Flags))
1999
2000   TempDILocalVariable clone() const { return cloneImpl(); }
2001
2002   /// \brief Get the local scope for this variable.
2003   ///
2004   /// Variables must be defined in a local scope.
2005   DILocalScope *getScope() const {
2006     return cast<DILocalScope>(DIVariable::getScope());
2007   }
2008
2009   bool isParameter() const { return Arg; }
2010   unsigned getArg() const { return Arg; }
2011   unsigned getFlags() const { return Flags; }
2012
2013   bool isArtificial() const { return getFlags() & FlagArtificial; }
2014   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
2015
2016   /// \brief Check that a location is valid for this variable.
2017   ///
2018   /// Check that \c DL exists, is in the same subprogram, and has the same
2019   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
2020   /// to a \a DbgInfoIntrinsic.)
2021   bool isValidLocationForIntrinsic(const DILocation *DL) const {
2022     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
2023   }
2024
2025   static bool classof(const Metadata *MD) {
2026     return MD->getMetadataID() == DILocalVariableKind;
2027   }
2028 };
2029
2030 /// \brief DWARF expression.
2031 ///
2032 /// This is (almost) a DWARF expression that modifies the location of a
2033 /// variable or (or the location of a single piece of a variable).
2034 ///
2035 /// FIXME: Instead of DW_OP_plus taking an argument, this should use DW_OP_const
2036 /// and have DW_OP_plus consume the topmost elements on the stack.
2037 ///
2038 /// TODO: Co-allocate the expression elements.
2039 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
2040 /// storage types.
2041 class DIExpression : public MDNode {
2042   friend class LLVMContextImpl;
2043   friend class MDNode;
2044
2045   std::vector<uint64_t> Elements;
2046
2047   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
2048       : MDNode(C, DIExpressionKind, Storage, None),
2049         Elements(Elements.begin(), Elements.end()) {}
2050   ~DIExpression() = default;
2051
2052   static DIExpression *getImpl(LLVMContext &Context,
2053                                ArrayRef<uint64_t> Elements, StorageType Storage,
2054                                bool ShouldCreate = true);
2055
2056   TempDIExpression cloneImpl() const {
2057     return getTemporary(getContext(), getElements());
2058   }
2059
2060 public:
2061   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
2062
2063   TempDIExpression clone() const { return cloneImpl(); }
2064
2065   ArrayRef<uint64_t> getElements() const { return Elements; }
2066
2067   unsigned getNumElements() const { return Elements.size(); }
2068   uint64_t getElement(unsigned I) const {
2069     assert(I < Elements.size() && "Index out of range");
2070     return Elements[I];
2071   }
2072
2073   /// \brief Return whether this is a piece of an aggregate variable.
2074   bool isBitPiece() const;
2075
2076   /// \brief Return the offset of this piece in bits.
2077   uint64_t getBitPieceOffset() const;
2078
2079   /// \brief Return the size of this piece in bits.
2080   uint64_t getBitPieceSize() const;
2081
2082   typedef ArrayRef<uint64_t>::iterator element_iterator;
2083   element_iterator elements_begin() const { return getElements().begin(); }
2084   element_iterator elements_end() const { return getElements().end(); }
2085
2086   /// \brief A lightweight wrapper around an expression operand.
2087   ///
2088   /// TODO: Store arguments directly and change \a DIExpression to store a
2089   /// range of these.
2090   class ExprOperand {
2091     const uint64_t *Op;
2092
2093   public:
2094     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
2095
2096     const uint64_t *get() const { return Op; }
2097
2098     /// \brief Get the operand code.
2099     uint64_t getOp() const { return *Op; }
2100
2101     /// \brief Get an argument to the operand.
2102     ///
2103     /// Never returns the operand itself.
2104     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
2105
2106     unsigned getNumArgs() const { return getSize() - 1; }
2107
2108     /// \brief Return the size of the operand.
2109     ///
2110     /// Return the number of elements in the operand (1 + args).
2111     unsigned getSize() const;
2112   };
2113
2114   /// \brief An iterator for expression operands.
2115   class expr_op_iterator
2116       : public std::iterator<std::input_iterator_tag, ExprOperand> {
2117     ExprOperand Op;
2118
2119   public:
2120     explicit expr_op_iterator(element_iterator I) : Op(I) {}
2121
2122     element_iterator getBase() const { return Op.get(); }
2123     const ExprOperand &operator*() const { return Op; }
2124     const ExprOperand *operator->() const { return &Op; }
2125
2126     expr_op_iterator &operator++() {
2127       increment();
2128       return *this;
2129     }
2130     expr_op_iterator operator++(int) {
2131       expr_op_iterator T(*this);
2132       increment();
2133       return T;
2134     }
2135
2136     /// \brief Get the next iterator.
2137     ///
2138     /// \a std::next() doesn't work because this is technically an
2139     /// input_iterator, but it's a perfectly valid operation.  This is an
2140     /// accessor to provide the same functionality.
2141     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
2142
2143     bool operator==(const expr_op_iterator &X) const {
2144       return getBase() == X.getBase();
2145     }
2146     bool operator!=(const expr_op_iterator &X) const {
2147       return getBase() != X.getBase();
2148     }
2149
2150   private:
2151     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
2152   };
2153
2154   /// \brief Visit the elements via ExprOperand wrappers.
2155   ///
2156   /// These range iterators visit elements through \a ExprOperand wrappers.
2157   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
2158   /// true.
2159   ///
2160   /// \pre \a isValid() gives \c true.
2161   /// @{
2162   expr_op_iterator expr_op_begin() const {
2163     return expr_op_iterator(elements_begin());
2164   }
2165   expr_op_iterator expr_op_end() const {
2166     return expr_op_iterator(elements_end());
2167   }
2168   /// @}
2169
2170   bool isValid() const;
2171
2172   static bool classof(const Metadata *MD) {
2173     return MD->getMetadataID() == DIExpressionKind;
2174   }
2175
2176   /// \brief Is the first element a DW_OP_deref?.
2177   bool startsWithDeref() const {
2178     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
2179   }
2180 };
2181
2182 class DIObjCProperty : public DINode {
2183   friend class LLVMContextImpl;
2184   friend class MDNode;
2185
2186   unsigned Line;
2187   unsigned Attributes;
2188
2189   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
2190                  unsigned Attributes, ArrayRef<Metadata *> Ops)
2191       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
2192                Ops),
2193         Line(Line), Attributes(Attributes) {}
2194   ~DIObjCProperty() = default;
2195
2196   static DIObjCProperty *
2197   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
2198           StringRef GetterName, StringRef SetterName, unsigned Attributes,
2199           DITypeRef Type, StorageType Storage, bool ShouldCreate = true) {
2200     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
2201                    getCanonicalMDString(Context, GetterName),
2202                    getCanonicalMDString(Context, SetterName), Attributes, Type,
2203                    Storage, ShouldCreate);
2204   }
2205   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
2206                                  Metadata *File, unsigned Line,
2207                                  MDString *GetterName, MDString *SetterName,
2208                                  unsigned Attributes, Metadata *Type,
2209                                  StorageType Storage, bool ShouldCreate = true);
2210
2211   TempDIObjCProperty cloneImpl() const {
2212     return getTemporary(getContext(), getName(), getFile(), getLine(),
2213                         getGetterName(), getSetterName(), getAttributes(),
2214                         getType());
2215   }
2216
2217 public:
2218   DEFINE_MDNODE_GET(DIObjCProperty,
2219                     (StringRef Name, DIFile *File, unsigned Line,
2220                      StringRef GetterName, StringRef SetterName,
2221                      unsigned Attributes, DITypeRef Type),
2222                     (Name, File, Line, GetterName, SetterName, Attributes,
2223                      Type))
2224   DEFINE_MDNODE_GET(DIObjCProperty,
2225                     (MDString * Name, Metadata *File, unsigned Line,
2226                      MDString *GetterName, MDString *SetterName,
2227                      unsigned Attributes, Metadata *Type),
2228                     (Name, File, Line, GetterName, SetterName, Attributes,
2229                      Type))
2230
2231   TempDIObjCProperty clone() const { return cloneImpl(); }
2232
2233   unsigned getLine() const { return Line; }
2234   unsigned getAttributes() const { return Attributes; }
2235   StringRef getName() const { return getStringOperand(0); }
2236   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2237   StringRef getGetterName() const { return getStringOperand(2); }
2238   StringRef getSetterName() const { return getStringOperand(3); }
2239   DITypeRef getType() const { return DITypeRef(getRawType()); }
2240
2241   StringRef getFilename() const {
2242     if (auto *F = getFile())
2243       return F->getFilename();
2244     return "";
2245   }
2246   StringRef getDirectory() const {
2247     if (auto *F = getFile())
2248       return F->getDirectory();
2249     return "";
2250   }
2251
2252   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2253   Metadata *getRawFile() const { return getOperand(1); }
2254   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2255   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2256   Metadata *getRawType() const { return getOperand(4); }
2257
2258   static bool classof(const Metadata *MD) {
2259     return MD->getMetadataID() == DIObjCPropertyKind;
2260   }
2261 };
2262
2263 /// \brief An imported module (C++ using directive or similar).
2264 class DIImportedEntity : public DINode {
2265   friend class LLVMContextImpl;
2266   friend class MDNode;
2267
2268   unsigned Line;
2269
2270   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2271                    unsigned Line, ArrayRef<Metadata *> Ops)
2272       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2273   ~DIImportedEntity() = default;
2274
2275   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2276                                    DIScope *Scope, DINodeRef Entity,
2277                                    unsigned Line, StringRef Name,
2278                                    StorageType Storage,
2279                                    bool ShouldCreate = true) {
2280     return getImpl(Context, Tag, Scope, Entity, Line,
2281                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2282   }
2283   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2284                                    Metadata *Scope, Metadata *Entity,
2285                                    unsigned Line, MDString *Name,
2286                                    StorageType Storage,
2287                                    bool ShouldCreate = true);
2288
2289   TempDIImportedEntity cloneImpl() const {
2290     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2291                         getLine(), getName());
2292   }
2293
2294 public:
2295   DEFINE_MDNODE_GET(DIImportedEntity,
2296                     (unsigned Tag, DIScope *Scope, DINodeRef Entity,
2297                      unsigned Line, StringRef Name = ""),
2298                     (Tag, Scope, Entity, Line, Name))
2299   DEFINE_MDNODE_GET(DIImportedEntity,
2300                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2301                      unsigned Line, MDString *Name),
2302                     (Tag, Scope, Entity, Line, Name))
2303
2304   TempDIImportedEntity clone() const { return cloneImpl(); }
2305
2306   unsigned getLine() const { return Line; }
2307   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2308   DINodeRef getEntity() const { return DINodeRef(getRawEntity()); }
2309   StringRef getName() const { return getStringOperand(2); }
2310
2311   Metadata *getRawScope() const { return getOperand(0); }
2312   Metadata *getRawEntity() const { return getOperand(1); }
2313   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2314
2315   static bool classof(const Metadata *MD) {
2316     return MD->getMetadataID() == DIImportedEntityKind;
2317   }
2318 };
2319
2320 /// \brief Macro Info DWARF-like metadata node.
2321 ///
2322 /// A metadata node with a DWARF macro info (i.e., a constant named
2323 /// \c DW_MACINFO_*, defined in llvm/Support/Dwarf.h).  Called \a DIMacroNode
2324 /// because it's potentially used for non-DWARF output.
2325 class DIMacroNode : public MDNode {
2326   friend class LLVMContextImpl;
2327   friend class MDNode;
2328
2329 protected:
2330   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
2331               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
2332       : MDNode(C, ID, Storage, Ops1, Ops2) {
2333     assert(MIType < 1u << 16);
2334     SubclassData16 = MIType;
2335   }
2336   ~DIMacroNode() = default;
2337
2338   template <class Ty> Ty *getOperandAs(unsigned I) const {
2339     return cast_or_null<Ty>(getOperand(I));
2340   }
2341
2342   StringRef getStringOperand(unsigned I) const {
2343     if (auto *S = getOperandAs<MDString>(I))
2344       return S->getString();
2345     return StringRef();
2346   }
2347
2348   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
2349     if (S.empty())
2350       return nullptr;
2351     return MDString::get(Context, S);
2352   }
2353
2354 public:
2355   unsigned getMacinfoType() const { return SubclassData16; }
2356
2357   static bool classof(const Metadata *MD) {
2358     switch (MD->getMetadataID()) {
2359     default:
2360       return false;
2361     case DIMacroKind:
2362     case DIMacroFileKind:
2363       return true;
2364     }
2365   }
2366 };
2367
2368 class DIMacro : public DIMacroNode {
2369   friend class LLVMContextImpl;
2370   friend class MDNode;
2371
2372   unsigned Line;
2373
2374   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
2375           ArrayRef<Metadata *> Ops)
2376       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
2377   ~DIMacro() = default;
2378
2379   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2380                           StringRef Name, StringRef Value, StorageType Storage,
2381                           bool ShouldCreate = true) {
2382     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
2383                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
2384   }
2385   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2386                           MDString *Name, MDString *Value, StorageType Storage,
2387                           bool ShouldCreate = true);
2388
2389   TempDIMacro cloneImpl() const {
2390     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
2391                         getValue());
2392   }
2393
2394 public:
2395   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, StringRef Name,
2396                               StringRef Value = ""),
2397                     (MIType, Line, Name, Value))
2398   DEFINE_MDNODE_GET(DIMacro, (unsigned MIType, unsigned Line, MDString *Name,
2399                               MDString *Value),
2400                     (MIType, Line, Name, Value))
2401
2402   TempDIMacro clone() const { return cloneImpl(); }
2403
2404   unsigned getLine() const { return Line; }
2405
2406   StringRef getName() const { return getStringOperand(0); }
2407   StringRef getValue() const { return getStringOperand(1); }
2408
2409   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2410   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
2411
2412   static bool classof(const Metadata *MD) {
2413     return MD->getMetadataID() == DIMacroKind;
2414   }
2415 };
2416
2417 class DIMacroFile : public DIMacroNode {
2418   friend class LLVMContextImpl;
2419   friend class MDNode;
2420
2421   unsigned Line;
2422
2423   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
2424               unsigned Line, ArrayRef<Metadata *> Ops)
2425       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
2426   ~DIMacroFile() = default;
2427
2428   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
2429                               unsigned Line, DIFile *File,
2430                               DIMacroNodeArray Elements, StorageType Storage,
2431                               bool ShouldCreate = true) {
2432     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
2433                    Elements.get(), Storage, ShouldCreate);
2434   }
2435
2436   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
2437                               unsigned Line, Metadata *File, Metadata *Elements,
2438                               StorageType Storage, bool ShouldCreate = true);
2439
2440   TempDIMacroFile cloneImpl() const {
2441     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
2442                         getElements());
2443   }
2444
2445 public:
2446   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line, DIFile *File,
2447                                   DIMacroNodeArray Elements),
2448                     (MIType, Line, File, Elements))
2449   DEFINE_MDNODE_GET(DIMacroFile, (unsigned MIType, unsigned Line,
2450                                   Metadata *File, Metadata *Elements),
2451                     (MIType, Line, File, Elements))
2452
2453   TempDIMacroFile clone() const { return cloneImpl(); }
2454
2455   void replaceElements(DIMacroNodeArray Elements) {
2456 #ifndef NDEBUG
2457     for (DIMacroNode *Op : getElements())
2458       assert(is_contained(Elements->operands(), Op) &&
2459              "Lost a macro node during macro node list replacement");
2460 #endif
2461     replaceOperandWith(1, Elements.get());
2462   }
2463
2464   unsigned getLine() const { return Line; }
2465   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2466
2467   DIMacroNodeArray getElements() const {
2468     return cast_or_null<MDTuple>(getRawElements());
2469   }
2470
2471   Metadata *getRawFile() const { return getOperand(0); }
2472   Metadata *getRawElements() const { return getOperand(1); }
2473
2474   static bool classof(const Metadata *MD) {
2475     return MD->getMetadataID() == DIMacroFileKind;
2476   }
2477 };
2478
2479 } // end namespace llvm
2480
2481 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2482 #undef DEFINE_MDNODE_GET_UNPACK
2483 #undef DEFINE_MDNODE_GET
2484
2485 #endif