IR: Remove MDTupleTypedArrayWrapper::operator MDTuple*()
[oota-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(CLASS, FORMAL, ARGS)                                 \
24   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
25     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
26   }                                                                            \
27   static CLASS *getIfExists(LLVMContext &Context,                              \
28                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
29     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
30                    /* ShouldCreate */ false);                                  \
31   }                                                                            \
32   static CLASS *getDistinct(LLVMContext &Context,                              \
33                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
34     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
35   }                                                                            \
36   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
37                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
38     return Temp##CLASS(                                                        \
39         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
40   }
41
42 namespace llvm {
43
44 /// \brief Pointer union between a subclass of DebugNode and MDString.
45 ///
46 /// \a MDCompositeType can be referenced via an \a MDString unique identifier.
47 /// This class allows some type safety in the face of that, requiring either a
48 /// node of a particular type or an \a MDString.
49 template <class T> class TypedDebugNodeRef {
50   const Metadata *MD = nullptr;
51
52 public:
53   TypedDebugNodeRef(std::nullptr_t) {}
54
55   /// \brief Construct from a raw pointer.
56   explicit TypedDebugNodeRef(const Metadata *MD) : MD(MD) {
57     assert((!MD || isa<MDString>(MD) || isa<T>(MD)) && "Expected valid ref");
58   }
59
60   template <class U>
61   TypedDebugNodeRef(
62       const TypedDebugNodeRef<U> &X,
63       typename std::enable_if<std::is_convertible<U *, T *>::value>::type * =
64           nullptr)
65       : MD(X) {}
66
67   operator Metadata *() const { return const_cast<Metadata *>(MD); }
68
69   bool operator==(const TypedDebugNodeRef<T> &X) const { return MD == X.MD; };
70   bool operator!=(const TypedDebugNodeRef<T> &X) const { return MD != X.MD; };
71
72   /// \brief Create a reference.
73   ///
74   /// Get a reference to \c N, using an \a MDString reference if available.
75   static TypedDebugNodeRef get(const T *N);
76
77   template <class MapTy> T *resolve(const MapTy &Map) const {
78     if (!MD)
79       return nullptr;
80
81     if (auto *Typed = dyn_cast<T>(MD))
82       return const_cast<T *>(Typed);
83
84     auto *S = cast<MDString>(MD);
85     auto I = Map.find(S);
86     assert(I != Map.end() && "Missing identifier in type map");
87     return cast<T>(I->second);
88   }
89 };
90
91 typedef TypedDebugNodeRef<DebugNode> DebugNodeRef;
92 typedef TypedDebugNodeRef<MDScope> MDScopeRef;
93 typedef TypedDebugNodeRef<MDType> MDTypeRef;
94
95 class MDTypeRefArray {
96   const MDTuple *N = nullptr;
97
98 public:
99   MDTypeRefArray(const MDTuple *N) : N(N) {}
100
101   explicit operator bool() const { return get(); }
102   explicit operator MDTuple *() const { return get(); }
103
104   MDTuple *get() const { return const_cast<MDTuple *>(N); }
105   MDTuple *operator->() const { return get(); }
106   MDTuple &operator*() const { return *get(); }
107
108   // FIXME: Fix callers and remove condition on N.
109   unsigned size() const { return N ? N->getNumOperands() : 0u; }
110   MDTypeRef operator[](unsigned I) const { return MDTypeRef(N->getOperand(I)); }
111
112   class iterator : std::iterator<std::input_iterator_tag, MDTypeRef,
113                                  std::ptrdiff_t, void, MDTypeRef> {
114     MDNode::op_iterator I = nullptr;
115
116   public:
117     iterator() = default;
118     explicit iterator(MDNode::op_iterator I) : I(I) {}
119     MDTypeRef operator*() const { return MDTypeRef(*I); }
120     iterator &operator++() {
121       ++I;
122       return *this;
123     }
124     iterator operator++(int) {
125       iterator Temp(*this);
126       ++I;
127       return Temp;
128     }
129     bool operator==(const iterator &X) const { return I == X.I; }
130     bool operator!=(const iterator &X) const { return I != X.I; }
131   };
132
133   // FIXME: Fix callers and remove condition on N.
134   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
135   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
136 };
137
138 /// \brief Tagged DWARF-like metadata node.
139 ///
140 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
141 /// defined in llvm/Support/Dwarf.h).  Called \a DebugNode because it's
142 /// potentially used for non-DWARF output.
143 class DebugNode : public MDNode {
144   friend class LLVMContextImpl;
145   friend class MDNode;
146
147 protected:
148   DebugNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
149             ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
150       : MDNode(C, ID, Storage, Ops1, Ops2) {
151     assert(Tag < 1u << 16);
152     SubclassData16 = Tag;
153   }
154   ~DebugNode() {}
155
156   template <class Ty> Ty *getOperandAs(unsigned I) const {
157     return cast_or_null<Ty>(getOperand(I));
158   }
159
160   StringRef getStringOperand(unsigned I) const {
161     if (auto *S = getOperandAs<MDString>(I))
162       return S->getString();
163     return StringRef();
164   }
165
166   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
167     if (S.empty())
168       return nullptr;
169     return MDString::get(Context, S);
170   }
171
172 public:
173   unsigned getTag() const { return SubclassData16; }
174
175   /// \brief Debug info flags.
176   ///
177   /// The three accessibility flags are mutually exclusive and rolled together
178   /// in the first two bits.
179   enum DIFlags {
180 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
181 #include "llvm/IR/DebugInfoFlags.def"
182     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic
183   };
184
185   static unsigned getFlag(StringRef Flag);
186   static const char *getFlagString(unsigned Flag);
187
188   /// \brief Split up a flags bitfield.
189   ///
190   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
191   /// any remaining (unrecognized) bits.
192   static unsigned splitFlags(unsigned Flags,
193                              SmallVectorImpl<unsigned> &SplitFlags);
194
195   DebugNodeRef getRef() const { return DebugNodeRef::get(this); }
196
197   static bool classof(const Metadata *MD) {
198     switch (MD->getMetadataID()) {
199     default:
200       return false;
201     case GenericDebugNodeKind:
202     case MDSubrangeKind:
203     case MDEnumeratorKind:
204     case MDBasicTypeKind:
205     case MDDerivedTypeKind:
206     case MDCompositeTypeKind:
207     case MDSubroutineTypeKind:
208     case MDFileKind:
209     case MDCompileUnitKind:
210     case MDSubprogramKind:
211     case MDLexicalBlockKind:
212     case MDLexicalBlockFileKind:
213     case MDNamespaceKind:
214     case MDTemplateTypeParameterKind:
215     case MDTemplateValueParameterKind:
216     case MDGlobalVariableKind:
217     case MDLocalVariableKind:
218     case MDObjCPropertyKind:
219     case MDImportedEntityKind:
220       return true;
221     }
222   }
223 };
224
225 template <class T>
226 struct simplify_type<const TypedDebugNodeRef<T>> {
227   typedef Metadata *SimpleType;
228   static SimpleType getSimplifiedValue(const TypedDebugNodeRef<T> &MD) {
229     return MD;
230   }
231 };
232
233 template <class T>
234 struct simplify_type<TypedDebugNodeRef<T>>
235     : simplify_type<const TypedDebugNodeRef<T>> {};
236
237 /// \brief Generic tagged DWARF-like metadata node.
238 ///
239 /// An un-specialized DWARF-like metadata node.  The first operand is a
240 /// (possibly empty) null-separated \a MDString header that contains arbitrary
241 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
242 /// to other metadata.
243 class GenericDebugNode : public DebugNode {
244   friend class LLVMContextImpl;
245   friend class MDNode;
246
247   GenericDebugNode(LLVMContext &C, StorageType Storage, unsigned Hash,
248                    unsigned Tag, ArrayRef<Metadata *> Ops1,
249                    ArrayRef<Metadata *> Ops2)
250       : DebugNode(C, GenericDebugNodeKind, Storage, Tag, Ops1, Ops2) {
251     setHash(Hash);
252   }
253   ~GenericDebugNode() { dropAllReferences(); }
254
255   void setHash(unsigned Hash) { SubclassData32 = Hash; }
256   void recalculateHash();
257
258   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
259                                    StringRef Header,
260                                    ArrayRef<Metadata *> DwarfOps,
261                                    StorageType Storage,
262                                    bool ShouldCreate = true) {
263     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
264                    DwarfOps, Storage, ShouldCreate);
265   }
266
267   static GenericDebugNode *getImpl(LLVMContext &Context, unsigned Tag,
268                                    MDString *Header,
269                                    ArrayRef<Metadata *> DwarfOps,
270                                    StorageType Storage,
271                                    bool ShouldCreate = true);
272
273   TempGenericDebugNode cloneImpl() const {
274     return getTemporary(
275         getContext(), getTag(), getHeader(),
276         SmallVector<Metadata *, 4>(dwarf_op_begin(), dwarf_op_end()));
277   }
278
279 public:
280   unsigned getHash() const { return SubclassData32; }
281
282   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, StringRef Header,
283                                        ArrayRef<Metadata *> DwarfOps),
284                     (Tag, Header, DwarfOps))
285   DEFINE_MDNODE_GET(GenericDebugNode, (unsigned Tag, MDString *Header,
286                                        ArrayRef<Metadata *> DwarfOps),
287                     (Tag, Header, DwarfOps))
288
289   /// \brief Return a (temporary) clone of this.
290   TempGenericDebugNode clone() const { return cloneImpl(); }
291
292   unsigned getTag() const { return SubclassData16; }
293   StringRef getHeader() const { return getStringOperand(0); }
294
295   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
296   op_iterator dwarf_op_end() const { return op_end(); }
297   op_range dwarf_operands() const {
298     return op_range(dwarf_op_begin(), dwarf_op_end());
299   }
300
301   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
302   const MDOperand &getDwarfOperand(unsigned I) const {
303     return getOperand(I + 1);
304   }
305   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
306     replaceOperandWith(I + 1, New);
307   }
308
309   static bool classof(const Metadata *MD) {
310     return MD->getMetadataID() == GenericDebugNodeKind;
311   }
312 };
313
314 /// \brief Array subrange.
315 ///
316 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
317 /// type.
318 class MDSubrange : public DebugNode {
319   friend class LLVMContextImpl;
320   friend class MDNode;
321
322   int64_t Count;
323   int64_t LowerBound;
324
325   MDSubrange(LLVMContext &C, StorageType Storage, int64_t Count,
326              int64_t LowerBound)
327       : DebugNode(C, MDSubrangeKind, Storage, dwarf::DW_TAG_subrange_type,
328                   None),
329         Count(Count), LowerBound(LowerBound) {}
330   ~MDSubrange() {}
331
332   static MDSubrange *getImpl(LLVMContext &Context, int64_t Count,
333                              int64_t LowerBound, StorageType Storage,
334                              bool ShouldCreate = true);
335
336   TempMDSubrange cloneImpl() const {
337     return getTemporary(getContext(), getCount(), getLowerBound());
338   }
339
340 public:
341   DEFINE_MDNODE_GET(MDSubrange, (int64_t Count, int64_t LowerBound = 0),
342                     (Count, LowerBound))
343
344   TempMDSubrange clone() const { return cloneImpl(); }
345
346   int64_t getLowerBound() const { return LowerBound; }
347   int64_t getCount() const { return Count; }
348
349   static bool classof(const Metadata *MD) {
350     return MD->getMetadataID() == MDSubrangeKind;
351   }
352 };
353
354 /// \brief Enumeration value.
355 ///
356 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
357 /// longer creates a type cycle.
358 class MDEnumerator : public DebugNode {
359   friend class LLVMContextImpl;
360   friend class MDNode;
361
362   int64_t Value;
363
364   MDEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
365                ArrayRef<Metadata *> Ops)
366       : DebugNode(C, MDEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
367         Value(Value) {}
368   ~MDEnumerator() {}
369
370   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
371                                StringRef Name, StorageType Storage,
372                                bool ShouldCreate = true) {
373     return getImpl(Context, Value, getCanonicalMDString(Context, Name), Storage,
374                    ShouldCreate);
375   }
376   static MDEnumerator *getImpl(LLVMContext &Context, int64_t Value,
377                                MDString *Name, StorageType Storage,
378                                bool ShouldCreate = true);
379
380   TempMDEnumerator cloneImpl() const {
381     return getTemporary(getContext(), getValue(), getName());
382   }
383
384 public:
385   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, StringRef Name),
386                     (Value, Name))
387   DEFINE_MDNODE_GET(MDEnumerator, (int64_t Value, MDString *Name),
388                     (Value, Name))
389
390   TempMDEnumerator clone() const { return cloneImpl(); }
391
392   int64_t getValue() const { return Value; }
393   StringRef getName() const { return getStringOperand(0); }
394
395   MDString *getRawName() const { return getOperandAs<MDString>(0); }
396
397   static bool classof(const Metadata *MD) {
398     return MD->getMetadataID() == MDEnumeratorKind;
399   }
400 };
401
402 /// \brief Base class for scope-like contexts.
403 ///
404 /// Base class for lexical scopes and types (which are also declaration
405 /// contexts).
406 ///
407 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
408 class MDScope : public DebugNode {
409 protected:
410   MDScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
411           ArrayRef<Metadata *> Ops)
412       : DebugNode(C, ID, Storage, Tag, Ops) {}
413   ~MDScope() {}
414
415 public:
416   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
417
418   /// \brief Return the raw underlying file.
419   ///
420   /// An \a MDFile is an \a MDScope, but it doesn't point at a separate file
421   /// (it\em is the file).  If \c this is an \a MDFile, we need to return \c
422   /// this.  Otherwise, return the first operand, which is where all other
423   /// subclasses store their file pointer.
424   Metadata *getRawFile() const {
425     return isa<MDFile>(this) ? const_cast<MDScope *>(this)
426                              : static_cast<Metadata *>(getOperand(0));
427   }
428
429   MDScopeRef getRef() const { return MDScopeRef::get(this); }
430
431   static bool classof(const Metadata *MD) {
432     switch (MD->getMetadataID()) {
433     default:
434       return false;
435     case MDBasicTypeKind:
436     case MDDerivedTypeKind:
437     case MDCompositeTypeKind:
438     case MDSubroutineTypeKind:
439     case MDFileKind:
440     case MDCompileUnitKind:
441     case MDSubprogramKind:
442     case MDLexicalBlockKind:
443     case MDLexicalBlockFileKind:
444     case MDNamespaceKind:
445       return true;
446     }
447   }
448 };
449
450 /// \brief File.
451 ///
452 /// TODO: Merge with directory/file node (including users).
453 /// TODO: Canonicalize paths on creation.
454 class MDFile : public MDScope {
455   friend class LLVMContextImpl;
456   friend class MDNode;
457
458   MDFile(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
459       : MDScope(C, MDFileKind, Storage, dwarf::DW_TAG_file_type, Ops) {}
460   ~MDFile() {}
461
462   static MDFile *getImpl(LLVMContext &Context, StringRef Filename,
463                          StringRef Directory, StorageType Storage,
464                          bool ShouldCreate = true) {
465     return getImpl(Context, getCanonicalMDString(Context, Filename),
466                    getCanonicalMDString(Context, Directory), Storage,
467                    ShouldCreate);
468   }
469   static MDFile *getImpl(LLVMContext &Context, MDString *Filename,
470                          MDString *Directory, StorageType Storage,
471                          bool ShouldCreate = true);
472
473   TempMDFile cloneImpl() const {
474     return getTemporary(getContext(), getFilename(), getDirectory());
475   }
476
477 public:
478   DEFINE_MDNODE_GET(MDFile, (StringRef Filename, StringRef Directory),
479                     (Filename, Directory))
480   DEFINE_MDNODE_GET(MDFile, (MDString * Filename, MDString *Directory),
481                     (Filename, Directory))
482
483   TempMDFile clone() const { return cloneImpl(); }
484
485   StringRef getFilename() const { return getStringOperand(0); }
486   StringRef getDirectory() const { return getStringOperand(1); }
487
488   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
489   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
490
491   static bool classof(const Metadata *MD) {
492     return MD->getMetadataID() == MDFileKind;
493   }
494 };
495
496 /// \brief Base class for types.
497 ///
498 /// TODO: Remove the hardcoded name and context, since many types don't use
499 /// them.
500 /// TODO: Split up flags.
501 class MDType : public MDScope {
502   unsigned Line;
503   unsigned Flags;
504   uint64_t SizeInBits;
505   uint64_t AlignInBits;
506   uint64_t OffsetInBits;
507
508 protected:
509   MDType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
510          unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
511          uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
512       : MDScope(C, ID, Storage, Tag, Ops), Line(Line), Flags(Flags),
513         SizeInBits(SizeInBits), AlignInBits(AlignInBits),
514         OffsetInBits(OffsetInBits) {}
515   ~MDType() {}
516
517 public:
518   TempMDType clone() const {
519     return TempMDType(cast<MDType>(MDNode::clone().release()));
520   }
521
522   unsigned getLine() const { return Line; }
523   uint64_t getSizeInBits() const { return SizeInBits; }
524   uint64_t getAlignInBits() const { return AlignInBits; }
525   uint64_t getOffsetInBits() const { return OffsetInBits; }
526   unsigned getFlags() const { return Flags; }
527
528   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
529   StringRef getName() const { return getStringOperand(2); }
530
531
532   Metadata *getRawScope() const { return getOperand(1); }
533   MDString *getRawName() const { return getOperandAs<MDString>(2); }
534
535   void setFlags(unsigned NewFlags) {
536     assert(!isUniqued() && "Cannot set flags on uniqued nodes");
537     Flags = NewFlags;
538   }
539
540   bool isPrivate() const {
541     return (getFlags() & FlagAccessibility) == FlagPrivate;
542   }
543   bool isProtected() const {
544     return (getFlags() & FlagAccessibility) == FlagProtected;
545   }
546   bool isPublic() const {
547     return (getFlags() & FlagAccessibility) == FlagPublic;
548   }
549   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
550   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
551   bool isBlockByrefStruct() const { return getFlags() & FlagBlockByrefStruct; }
552   bool isVirtual() const { return getFlags() & FlagVirtual; }
553   bool isArtificial() const { return getFlags() & FlagArtificial; }
554   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
555   bool isObjcClassComplete() const {
556     return getFlags() & FlagObjcClassComplete;
557   }
558   bool isVector() const { return getFlags() & FlagVector; }
559   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
560   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
561   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
562
563   MDTypeRef getRef() const { return MDTypeRef::get(this); }
564
565   static bool classof(const Metadata *MD) {
566     switch (MD->getMetadataID()) {
567     default:
568       return false;
569     case MDBasicTypeKind:
570     case MDDerivedTypeKind:
571     case MDCompositeTypeKind:
572     case MDSubroutineTypeKind:
573       return true;
574     }
575   }
576 };
577
578 /// \brief Basic type.
579 ///
580 /// TODO: Split out DW_TAG_unspecified_type.
581 /// TODO: Drop unused accessors.
582 class MDBasicType : public MDType {
583   friend class LLVMContextImpl;
584   friend class MDNode;
585
586   unsigned Encoding;
587
588   MDBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
589               uint64_t SizeInBits, uint64_t AlignInBits, unsigned Encoding,
590               ArrayRef<Metadata *> Ops)
591       : MDType(C, MDBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
592                0, Ops),
593         Encoding(Encoding) {}
594   ~MDBasicType() {}
595
596   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
597                               StringRef Name, uint64_t SizeInBits,
598                               uint64_t AlignInBits, unsigned Encoding,
599                               StorageType Storage, bool ShouldCreate = true) {
600     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
601                    SizeInBits, AlignInBits, Encoding, Storage, ShouldCreate);
602   }
603   static MDBasicType *getImpl(LLVMContext &Context, unsigned Tag,
604                               MDString *Name, uint64_t SizeInBits,
605                               uint64_t AlignInBits, unsigned Encoding,
606                               StorageType Storage, bool ShouldCreate = true);
607
608   TempMDBasicType cloneImpl() const {
609     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
610                         getAlignInBits(), getEncoding());
611   }
612
613 public:
614   DEFINE_MDNODE_GET(MDBasicType, (unsigned Tag, StringRef Name),
615                     (Tag, Name, 0, 0, 0))
616   DEFINE_MDNODE_GET(MDBasicType,
617                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
618                      uint64_t AlignInBits, unsigned Encoding),
619                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
620   DEFINE_MDNODE_GET(MDBasicType,
621                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
622                      uint64_t AlignInBits, unsigned Encoding),
623                     (Tag, Name, SizeInBits, AlignInBits, Encoding))
624
625   TempMDBasicType clone() const { return cloneImpl(); }
626
627   unsigned getEncoding() const { return Encoding; }
628
629   static bool classof(const Metadata *MD) {
630     return MD->getMetadataID() == MDBasicTypeKind;
631   }
632 };
633
634 /// \brief Base class for MDDerivedType and MDCompositeType.
635 ///
636 /// TODO: Delete; they're not really related.
637 class MDDerivedTypeBase : public MDType {
638 protected:
639   MDDerivedTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
640                     unsigned Tag, unsigned Line, uint64_t SizeInBits,
641                     uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
642                     ArrayRef<Metadata *> Ops)
643       : MDType(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
644                Flags, Ops) {}
645   ~MDDerivedTypeBase() {}
646
647 public:
648   MDTypeRef getBaseType() const { return MDTypeRef(getRawBaseType()); }
649   Metadata *getRawBaseType() const { return getOperand(3); }
650
651   static bool classof(const Metadata *MD) {
652     return MD->getMetadataID() == MDDerivedTypeKind ||
653            MD->getMetadataID() == MDCompositeTypeKind ||
654            MD->getMetadataID() == MDSubroutineTypeKind;
655   }
656 };
657
658 /// \brief Derived types.
659 ///
660 /// This includes qualified types, pointers, references, friends, typedefs, and
661 /// class members.
662 ///
663 /// TODO: Split out members (inheritance, fields, methods, etc.).
664 class MDDerivedType : public MDDerivedTypeBase {
665   friend class LLVMContextImpl;
666   friend class MDNode;
667
668   MDDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
669                 unsigned Line, uint64_t SizeInBits, uint64_t AlignInBits,
670                 uint64_t OffsetInBits, unsigned Flags, ArrayRef<Metadata *> Ops)
671       : MDDerivedTypeBase(C, MDDerivedTypeKind, Storage, Tag, Line, SizeInBits,
672                           AlignInBits, OffsetInBits, Flags, Ops) {}
673   ~MDDerivedType() {}
674
675   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
676                                 StringRef Name, MDFile *File, unsigned Line,
677                                 MDScopeRef Scope, MDTypeRef BaseType,
678                                 uint64_t SizeInBits, uint64_t AlignInBits,
679                                 uint64_t OffsetInBits, unsigned Flags,
680                                 Metadata *ExtraData, StorageType Storage,
681                                 bool ShouldCreate = true) {
682     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
683                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
684                    Flags, ExtraData, Storage, ShouldCreate);
685   }
686   static MDDerivedType *getImpl(LLVMContext &Context, unsigned Tag,
687                                 MDString *Name, Metadata *File, unsigned Line,
688                                 Metadata *Scope, Metadata *BaseType,
689                                 uint64_t SizeInBits, uint64_t AlignInBits,
690                                 uint64_t OffsetInBits, unsigned Flags,
691                                 Metadata *ExtraData, StorageType Storage,
692                                 bool ShouldCreate = true);
693
694   TempMDDerivedType cloneImpl() const {
695     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
696                         getScope(), getBaseType(), getSizeInBits(),
697                         getAlignInBits(), getOffsetInBits(), getFlags(),
698                         getExtraData());
699   }
700
701 public:
702   DEFINE_MDNODE_GET(MDDerivedType,
703                     (unsigned Tag, MDString *Name, Metadata *File,
704                      unsigned Line, Metadata *Scope, Metadata *BaseType,
705                      uint64_t SizeInBits, uint64_t AlignInBits,
706                      uint64_t OffsetInBits, unsigned Flags,
707                      Metadata *ExtraData = nullptr),
708                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
709                      AlignInBits, OffsetInBits, Flags, ExtraData))
710   DEFINE_MDNODE_GET(MDDerivedType,
711                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
712                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
713                      uint64_t AlignInBits, uint64_t OffsetInBits,
714                      unsigned Flags, Metadata *ExtraData = nullptr),
715                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
716                      AlignInBits, OffsetInBits, Flags, ExtraData))
717
718   TempMDDerivedType clone() const { return cloneImpl(); }
719
720   /// \brief Get extra data associated with this derived type.
721   ///
722   /// Class type for pointer-to-members, objective-c property node for ivars,
723   /// or global constant wrapper for static members.
724   ///
725   /// TODO: Separate out types that need this extra operand: pointer-to-member
726   /// types and member fields (static members and ivars).
727   Metadata *getExtraData() const { return getRawExtraData(); }
728   Metadata *getRawExtraData() const { return getOperand(4); }
729
730   static bool classof(const Metadata *MD) {
731     return MD->getMetadataID() == MDDerivedTypeKind;
732   }
733 };
734
735 /// \brief Base class for MDCompositeType and MDSubroutineType.
736 ///
737 /// TODO: Delete; they're not really related.
738 class MDCompositeTypeBase : public MDDerivedTypeBase {
739   unsigned RuntimeLang;
740
741 protected:
742   MDCompositeTypeBase(LLVMContext &C, unsigned ID, StorageType Storage,
743                       unsigned Tag, unsigned Line, unsigned RuntimeLang,
744                       uint64_t SizeInBits, uint64_t AlignInBits,
745                       uint64_t OffsetInBits, unsigned Flags,
746                       ArrayRef<Metadata *> Ops)
747       : MDDerivedTypeBase(C, ID, Storage, Tag, Line, SizeInBits, AlignInBits,
748                           OffsetInBits, Flags, Ops),
749         RuntimeLang(RuntimeLang) {}
750   ~MDCompositeTypeBase() {}
751
752 public:
753   DebugNodeArray getElements() const {
754     return cast_or_null<MDTuple>(getRawElements());
755   }
756   MDTypeRef getVTableHolder() const { return MDTypeRef(getRawVTableHolder()); }
757   MDTemplateParameterArray getTemplateParams() const {
758     return cast_or_null<MDTuple>(getRawTemplateParams());
759   }
760   StringRef getIdentifier() const { return getStringOperand(7); }
761   unsigned getRuntimeLang() const { return RuntimeLang; }
762
763   Metadata *getRawElements() const { return getOperand(4); }
764   Metadata *getRawVTableHolder() const { return getOperand(5); }
765   Metadata *getRawTemplateParams() const { return getOperand(6); }
766   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
767
768   /// \brief Replace operands.
769   ///
770   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
771   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
772   /// of its movement if necessary.
773   /// @{
774   void replaceElements(DebugNodeArray Elements) {
775 #ifndef NDEBUG
776     for (DebugNode *Op : getElements())
777       assert(std::find(Elements->op_begin(), Elements->op_end(), Op) &&
778              "Lost a member during member list replacement");
779 #endif
780     replaceOperandWith(4, Elements.get());
781   }
782   void replaceVTableHolder(MDTypeRef VTableHolder) {
783     replaceOperandWith(5, VTableHolder);
784   }
785   void replaceTemplateParams(MDTemplateParameterArray TemplateParams) {
786     replaceOperandWith(6, TemplateParams.get());
787   }
788   /// @}
789
790   static bool classof(const Metadata *MD) {
791     return MD->getMetadataID() == MDCompositeTypeKind ||
792            MD->getMetadataID() == MDSubroutineTypeKind;
793   }
794 };
795
796 /// \brief Composite types.
797 ///
798 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
799 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
800 class MDCompositeType : public MDCompositeTypeBase {
801   friend class LLVMContextImpl;
802   friend class MDNode;
803
804   MDCompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
805                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
806                   uint64_t AlignInBits, uint64_t OffsetInBits, unsigned Flags,
807                   ArrayRef<Metadata *> Ops)
808       : MDCompositeTypeBase(C, MDCompositeTypeKind, Storage, Tag, Line,
809                             RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
810                             Flags, Ops) {}
811   ~MDCompositeType() {}
812
813   static MDCompositeType *
814   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
815           unsigned Line, MDScopeRef Scope, MDTypeRef BaseType,
816           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
817           uint64_t Flags, DebugNodeArray Elements, unsigned RuntimeLang,
818           MDTypeRef VTableHolder, MDTemplateParameterArray TemplateParams,
819           StringRef Identifier, StorageType Storage, bool ShouldCreate = true) {
820     return getImpl(
821         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
822         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
823         RuntimeLang, VTableHolder, TemplateParams.get(),
824         getCanonicalMDString(Context, Identifier), Storage, ShouldCreate);
825   }
826   static MDCompositeType *
827   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
828           unsigned Line, Metadata *Scope, Metadata *BaseType,
829           uint64_t SizeInBits, uint64_t AlignInBits, uint64_t OffsetInBits,
830           unsigned Flags, Metadata *Elements, unsigned RuntimeLang,
831           Metadata *VTableHolder, Metadata *TemplateParams,
832           MDString *Identifier, StorageType Storage, bool ShouldCreate = true);
833
834   TempMDCompositeType cloneImpl() const {
835     return getTemporary(getContext(), getTag(), getName(), getFile(), getLine(),
836                         getScope(), getBaseType(), getSizeInBits(),
837                         getAlignInBits(), getOffsetInBits(), getFlags(),
838                         getElements(), getRuntimeLang(), getVTableHolder(),
839                         getTemplateParams(), getIdentifier());
840   }
841
842 public:
843   DEFINE_MDNODE_GET(MDCompositeType,
844                     (unsigned Tag, StringRef Name, MDFile *File, unsigned Line,
845                      MDScopeRef Scope, MDTypeRef BaseType, uint64_t SizeInBits,
846                      uint64_t AlignInBits, uint64_t OffsetInBits,
847                      unsigned Flags, DebugNodeArray Elements,
848                      unsigned RuntimeLang, MDTypeRef VTableHolder,
849                      MDTemplateParameterArray TemplateParams = nullptr,
850                      StringRef Identifier = ""),
851                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
852                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
853                      VTableHolder, TemplateParams, Identifier))
854   DEFINE_MDNODE_GET(MDCompositeType,
855                     (unsigned Tag, MDString *Name, Metadata *File,
856                      unsigned Line, Metadata *Scope, Metadata *BaseType,
857                      uint64_t SizeInBits, uint64_t AlignInBits,
858                      uint64_t OffsetInBits, unsigned Flags, Metadata *Elements,
859                      unsigned RuntimeLang, Metadata *VTableHolder,
860                      Metadata *TemplateParams = nullptr,
861                      MDString *Identifier = nullptr),
862                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
863                      AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
864                      VTableHolder, TemplateParams, Identifier))
865
866   TempMDCompositeType clone() const { return cloneImpl(); }
867
868   static bool classof(const Metadata *MD) {
869     return MD->getMetadataID() == MDCompositeTypeKind;
870   }
871 };
872
873 template <class T> TypedDebugNodeRef<T> TypedDebugNodeRef<T>::get(const T *N) {
874   if (N)
875     if (auto *Composite = dyn_cast<MDCompositeType>(N))
876       if (auto *S = Composite->getRawIdentifier())
877         return TypedDebugNodeRef<T>(S);
878   return TypedDebugNodeRef<T>(N);
879 }
880
881 /// \brief Type array for a subprogram.
882 ///
883 /// TODO: Detach from CompositeType, and fold the array of types in directly
884 /// as operands.
885 class MDSubroutineType : public MDCompositeTypeBase {
886   friend class LLVMContextImpl;
887   friend class MDNode;
888
889   MDSubroutineType(LLVMContext &C, StorageType Storage, unsigned Flags,
890                    ArrayRef<Metadata *> Ops)
891       : MDCompositeTypeBase(C, MDSubroutineTypeKind, Storage,
892                             dwarf::DW_TAG_subroutine_type, 0, 0, 0, 0, 0, Flags,
893                             Ops) {}
894   ~MDSubroutineType() {}
895
896   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
897                                    MDTypeRefArray TypeArray,
898                                    StorageType Storage,
899                                    bool ShouldCreate = true) {
900     return getImpl(Context, Flags, TypeArray.get(), Storage, ShouldCreate);
901   }
902   static MDSubroutineType *getImpl(LLVMContext &Context, unsigned Flags,
903                                    Metadata *TypeArray, StorageType Storage,
904                                    bool ShouldCreate = true);
905
906   TempMDSubroutineType cloneImpl() const {
907     return getTemporary(getContext(), getFlags(), getTypeArray());
908   }
909
910 public:
911   DEFINE_MDNODE_GET(MDSubroutineType,
912                     (unsigned Flags, MDTypeRefArray TypeArray),
913                     (Flags, TypeArray))
914   DEFINE_MDNODE_GET(MDSubroutineType, (unsigned Flags, Metadata *TypeArray),
915                     (Flags, TypeArray))
916
917   TempMDSubroutineType clone() const { return cloneImpl(); }
918
919   MDTypeRefArray getTypeArray() const {
920     return cast_or_null<MDTuple>(getRawTypeArray());
921   }
922   Metadata *getRawTypeArray() const { return getRawElements(); }
923
924   static bool classof(const Metadata *MD) {
925     return MD->getMetadataID() == MDSubroutineTypeKind;
926   }
927 };
928
929 /// \brief Compile unit.
930 class MDCompileUnit : public MDScope {
931   friend class LLVMContextImpl;
932   friend class MDNode;
933
934   unsigned SourceLanguage;
935   bool IsOptimized;
936   unsigned RuntimeVersion;
937   unsigned EmissionKind;
938
939   MDCompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
940                 bool IsOptimized, unsigned RuntimeVersion,
941                 unsigned EmissionKind, ArrayRef<Metadata *> Ops)
942       : MDScope(C, MDCompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
943         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
944         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind) {}
945   ~MDCompileUnit() {}
946
947   static MDCompileUnit *
948   getImpl(LLVMContext &Context, unsigned SourceLanguage, MDFile *File,
949           StringRef Producer, bool IsOptimized, StringRef Flags,
950           unsigned RuntimeVersion, StringRef SplitDebugFilename,
951           unsigned EmissionKind, MDCompositeTypeArray EnumTypes,
952           MDTypeArray RetainedTypes, MDSubprogramArray Subprograms,
953           MDGlobalVariableArray GlobalVariables,
954           MDImportedEntityArray ImportedEntities, StorageType Storage,
955           bool ShouldCreate = true) {
956     return getImpl(
957         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
958         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
959         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
960         EnumTypes.get(), RetainedTypes.get(), Subprograms.get(),
961         GlobalVariables.get(), ImportedEntities.get(), Storage, ShouldCreate);
962   }
963   static MDCompileUnit *
964   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
965           MDString *Producer, bool IsOptimized, MDString *Flags,
966           unsigned RuntimeVersion, MDString *SplitDebugFilename,
967           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
968           Metadata *Subprograms, Metadata *GlobalVariables,
969           Metadata *ImportedEntities, StorageType Storage,
970           bool ShouldCreate = true);
971
972   TempMDCompileUnit cloneImpl() const {
973     return getTemporary(
974         getContext(), getSourceLanguage(), getFile(), getProducer(),
975         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
976         getEmissionKind(), getEnumTypes(), getRetainedTypes(), getSubprograms(),
977         getGlobalVariables(), getImportedEntities());
978   }
979
980 public:
981   DEFINE_MDNODE_GET(MDCompileUnit,
982                     (unsigned SourceLanguage, MDFile *File, StringRef Producer,
983                      bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
984                      StringRef SplitDebugFilename, unsigned EmissionKind,
985                      MDCompositeTypeArray EnumTypes, MDTypeArray RetainedTypes,
986                      MDSubprogramArray Subprograms,
987                      MDGlobalVariableArray GlobalVariables,
988                      MDImportedEntityArray ImportedEntities),
989                     (SourceLanguage, File, Producer, IsOptimized, Flags,
990                      RuntimeVersion, SplitDebugFilename, EmissionKind,
991                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
992                      ImportedEntities))
993   DEFINE_MDNODE_GET(MDCompileUnit,
994                     (unsigned SourceLanguage, Metadata *File,
995                      MDString *Producer, bool IsOptimized, MDString *Flags,
996                      unsigned RuntimeVersion, MDString *SplitDebugFilename,
997                      unsigned EmissionKind, Metadata *EnumTypes,
998                      Metadata *RetainedTypes, Metadata *Subprograms,
999                      Metadata *GlobalVariables, Metadata *ImportedEntities),
1000                     (SourceLanguage, File, Producer, IsOptimized, Flags,
1001                      RuntimeVersion, SplitDebugFilename, EmissionKind,
1002                      EnumTypes, RetainedTypes, Subprograms, GlobalVariables,
1003                      ImportedEntities))
1004
1005   TempMDCompileUnit clone() const { return cloneImpl(); }
1006
1007   unsigned getSourceLanguage() const { return SourceLanguage; }
1008   bool isOptimized() const { return IsOptimized; }
1009   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1010   unsigned getEmissionKind() const { return EmissionKind; }
1011   StringRef getProducer() const { return getStringOperand(1); }
1012   StringRef getFlags() const { return getStringOperand(2); }
1013   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1014   MDCompositeTypeArray getEnumTypes() const {
1015     return cast_or_null<MDTuple>(getRawEnumTypes());
1016   }
1017   MDTypeArray getRetainedTypes() const {
1018     return cast_or_null<MDTuple>(getRawRetainedTypes());
1019   }
1020   MDSubprogramArray getSubprograms() const {
1021     return cast_or_null<MDTuple>(getRawSubprograms());
1022   }
1023   MDGlobalVariableArray getGlobalVariables() const {
1024     return cast_or_null<MDTuple>(getRawGlobalVariables());
1025   }
1026   MDImportedEntityArray getImportedEntities() const {
1027     return cast_or_null<MDTuple>(getRawImportedEntities());
1028   }
1029
1030   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1031   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1032   MDString *getRawSplitDebugFilename() const {
1033     return getOperandAs<MDString>(3);
1034   }
1035   Metadata *getRawEnumTypes() const { return getOperand(4); }
1036   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1037   Metadata *getRawSubprograms() const { return getOperand(6); }
1038   Metadata *getRawGlobalVariables() const { return getOperand(7); }
1039   Metadata *getRawImportedEntities() const { return getOperand(8); }
1040
1041   /// \brief Replace arrays.
1042   ///
1043   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1044   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1045   /// MDCompileUnit should be fairly rare.
1046   /// @{
1047   void replaceSubprograms(MDSubprogramArray N) {
1048     replaceOperandWith(6, N.get());
1049   }
1050   void replaceGlobalVariables(MDGlobalVariableArray N) {
1051     replaceOperandWith(7, N.get());
1052   }
1053   /// @}
1054
1055   static bool classof(const Metadata *MD) {
1056     return MD->getMetadataID() == MDCompileUnitKind;
1057   }
1058 };
1059
1060 /// \brief A scope for locals.
1061 ///
1062 /// A legal scope for lexical blocks, local variables, and debug info
1063 /// locations.  Subclasses are \a MDSubprogram, \a MDLexicalBlock, and \a
1064 /// MDLexicalBlockFile.
1065 class MDLocalScope : public MDScope {
1066 protected:
1067   MDLocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1068                ArrayRef<Metadata *> Ops)
1069       : MDScope(C, ID, Storage, Tag, Ops) {}
1070   ~MDLocalScope() {}
1071
1072 public:
1073   /// \brief Get the subprogram for this scope.
1074   ///
1075   /// Return this if it's an \a MDSubprogram; otherwise, look up the scope
1076   /// chain.
1077   MDSubprogram *getSubprogram() const;
1078
1079   static bool classof(const Metadata *MD) {
1080     return MD->getMetadataID() == MDSubprogramKind ||
1081            MD->getMetadataID() == MDLexicalBlockKind ||
1082            MD->getMetadataID() == MDLexicalBlockFileKind;
1083   }
1084 };
1085
1086 /// \brief Debug location.
1087 ///
1088 /// A debug location in source code, used for debug info and otherwise.
1089 class MDLocation : public MDNode {
1090   friend class LLVMContextImpl;
1091   friend class MDNode;
1092
1093   MDLocation(LLVMContext &C, StorageType Storage, unsigned Line,
1094              unsigned Column, ArrayRef<Metadata *> MDs);
1095   ~MDLocation() { dropAllReferences(); }
1096
1097   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1098                              unsigned Column, Metadata *Scope,
1099                              Metadata *InlinedAt, StorageType Storage,
1100                              bool ShouldCreate = true);
1101   static MDLocation *getImpl(LLVMContext &Context, unsigned Line,
1102                              unsigned Column, MDLocalScope *Scope,
1103                              MDLocation *InlinedAt, StorageType Storage,
1104                              bool ShouldCreate = true) {
1105     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1106                    static_cast<Metadata *>(InlinedAt), Storage, ShouldCreate);
1107   }
1108
1109   TempMDLocation cloneImpl() const {
1110     return getTemporary(getContext(), getLine(), getColumn(), getScope(),
1111                         getInlinedAt());
1112   }
1113
1114   // Disallow replacing operands.
1115   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1116
1117 public:
1118   DEFINE_MDNODE_GET(MDLocation,
1119                     (unsigned Line, unsigned Column, Metadata *Scope,
1120                      Metadata *InlinedAt = nullptr),
1121                     (Line, Column, Scope, InlinedAt))
1122   DEFINE_MDNODE_GET(MDLocation,
1123                     (unsigned Line, unsigned Column, MDLocalScope *Scope,
1124                      MDLocation *InlinedAt = nullptr),
1125                     (Line, Column, Scope, InlinedAt))
1126
1127   /// \brief Return a (temporary) clone of this.
1128   TempMDLocation clone() const { return cloneImpl(); }
1129
1130   unsigned getLine() const { return SubclassData32; }
1131   unsigned getColumn() const { return SubclassData16; }
1132   MDLocalScope *getScope() const {
1133     return cast<MDLocalScope>(getRawScope());
1134   }
1135   MDLocation *getInlinedAt() const {
1136     return cast_or_null<MDLocation>(getRawInlinedAt());
1137   }
1138
1139   /// \brief Get the scope where this is inlined.
1140   ///
1141   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1142   /// location.
1143   MDLocalScope *getInlinedAtScope() const {
1144     if (auto *IA = getInlinedAt())
1145       return IA->getInlinedAtScope();
1146     return getScope();
1147   }
1148
1149   Metadata *getRawScope() const { return getOperand(0); }
1150   Metadata *getRawInlinedAt() const {
1151     if (getNumOperands() == 2)
1152       return getOperand(1);
1153     return nullptr;
1154   }
1155
1156   static bool classof(const Metadata *MD) {
1157     return MD->getMetadataID() == MDLocationKind;
1158   }
1159 };
1160
1161 /// \brief Subprogram description.
1162 ///
1163 /// TODO: Remove DisplayName.  It's always equal to Name.
1164 /// TODO: Split up flags.
1165 class MDSubprogram : public MDLocalScope {
1166   friend class LLVMContextImpl;
1167   friend class MDNode;
1168
1169   unsigned Line;
1170   unsigned ScopeLine;
1171   unsigned Virtuality;
1172   unsigned VirtualIndex;
1173   unsigned Flags;
1174   bool IsLocalToUnit;
1175   bool IsDefinition;
1176   bool IsOptimized;
1177
1178   MDSubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1179                unsigned ScopeLine, unsigned Virtuality, unsigned VirtualIndex,
1180                unsigned Flags, bool IsLocalToUnit, bool IsDefinition,
1181                bool IsOptimized, ArrayRef<Metadata *> Ops)
1182       : MDLocalScope(C, MDSubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1183                      Ops),
1184         Line(Line), ScopeLine(ScopeLine), Virtuality(Virtuality),
1185         VirtualIndex(VirtualIndex), Flags(Flags), IsLocalToUnit(IsLocalToUnit),
1186         IsDefinition(IsDefinition), IsOptimized(IsOptimized) {}
1187   ~MDSubprogram() {}
1188
1189   static MDSubprogram *
1190   getImpl(LLVMContext &Context, MDScopeRef Scope, StringRef Name,
1191           StringRef LinkageName, MDFile *File, unsigned Line,
1192           MDSubroutineType *Type, bool IsLocalToUnit, bool IsDefinition,
1193           unsigned ScopeLine, MDTypeRef ContainingType, unsigned Virtuality,
1194           unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1195           ConstantAsMetadata *Function, MDTemplateParameterArray TemplateParams,
1196           MDSubprogram *Declaration, MDLocalVariableArray Variables,
1197           StorageType Storage, bool ShouldCreate = true) {
1198     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1199                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1200                    IsLocalToUnit, IsDefinition, ScopeLine, ContainingType,
1201                    Virtuality, VirtualIndex, Flags, IsOptimized, Function,
1202                    TemplateParams.get(), Declaration, Variables.get(), Storage,
1203                    ShouldCreate);
1204   }
1205   static MDSubprogram *
1206   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1207           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1208           bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1209           Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
1210           unsigned Flags, bool IsOptimized, Metadata *Function,
1211           Metadata *TemplateParams, Metadata *Declaration, Metadata *Variables,
1212           StorageType Storage, bool ShouldCreate = true);
1213
1214   TempMDSubprogram cloneImpl() const {
1215     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1216                         getFile(), getLine(), getType(), isLocalToUnit(),
1217                         isDefinition(), getScopeLine(), getContainingType(),
1218                         getVirtuality(), getVirtualIndex(), getFlags(),
1219                         isOptimized(), getFunction(), getTemplateParams(),
1220                         getDeclaration(), getVariables());
1221   }
1222
1223 public:
1224   DEFINE_MDNODE_GET(MDSubprogram,
1225                     (MDScopeRef Scope, StringRef Name, StringRef LinkageName,
1226                      MDFile *File, unsigned Line, MDSubroutineType *Type,
1227                      bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
1228                      MDTypeRef ContainingType, unsigned Virtuality,
1229                      unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1230                      ConstantAsMetadata *Function = nullptr,
1231                      MDTemplateParameterArray TemplateParams = nullptr,
1232                      MDSubprogram *Declaration = nullptr,
1233                      MDLocalVariableArray Variables = nullptr),
1234                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1235                      IsDefinition, ScopeLine, ContainingType, Virtuality,
1236                      VirtualIndex, Flags, IsOptimized, Function, TemplateParams,
1237                      Declaration, Variables))
1238   DEFINE_MDNODE_GET(
1239       MDSubprogram,
1240       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1241        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1242        unsigned ScopeLine, Metadata *ContainingType, unsigned Virtuality,
1243        unsigned VirtualIndex, unsigned Flags, bool IsOptimized,
1244        Metadata *Function = nullptr, Metadata *TemplateParams = nullptr,
1245        Metadata *Declaration = nullptr, Metadata *Variables = nullptr),
1246       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1247        ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags, IsOptimized,
1248        Function, TemplateParams, Declaration, Variables))
1249
1250   TempMDSubprogram clone() const { return cloneImpl(); }
1251
1252 public:
1253   unsigned getLine() const { return Line; }
1254   unsigned getVirtuality() const { return Virtuality; }
1255   unsigned getVirtualIndex() const { return VirtualIndex; }
1256   unsigned getScopeLine() const { return ScopeLine; }
1257   unsigned getFlags() const { return Flags; }
1258   bool isLocalToUnit() const { return IsLocalToUnit; }
1259   bool isDefinition() const { return IsDefinition; }
1260   bool isOptimized() const { return IsOptimized; }
1261
1262   unsigned isArtificial() const { return getFlags() & FlagArtificial; }
1263   bool isPrivate() const {
1264     return (getFlags() & FlagAccessibility) == FlagPrivate;
1265   }
1266   bool isProtected() const {
1267     return (getFlags() & FlagAccessibility) == FlagProtected;
1268   }
1269   bool isPublic() const {
1270     return (getFlags() & FlagAccessibility) == FlagPublic;
1271   }
1272   bool isExplicit() const { return getFlags() & FlagExplicit; }
1273   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1274
1275   /// \brief Check if this is reference-qualified.
1276   ///
1277   /// Return true if this subprogram is a C++11 reference-qualified non-static
1278   /// member function (void foo() &).
1279   unsigned isLValueReference() const {
1280     return getFlags() & FlagLValueReference;
1281   }
1282
1283   /// \brief Check if this is rvalue-reference-qualified.
1284   ///
1285   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
1286   /// non-static member function (void foo() &&).
1287   unsigned isRValueReference() const {
1288     return getFlags() & FlagRValueReference;
1289   }
1290
1291   MDScopeRef getScope() const { return MDScopeRef(getRawScope()); }
1292
1293   StringRef getName() const { return getStringOperand(2); }
1294   StringRef getDisplayName() const { return getStringOperand(3); }
1295   StringRef getLinkageName() const { return getStringOperand(4); }
1296
1297   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1298   MDString *getRawLinkageName() const { return getOperandAs<MDString>(4); }
1299
1300   MDSubroutineType *getType() const {
1301     return cast_or_null<MDSubroutineType>(getRawType());
1302   }
1303   MDTypeRef getContainingType() const {
1304     return MDTypeRef(getRawContainingType());
1305   }
1306
1307   ConstantAsMetadata *getFunction() const {
1308     return cast_or_null<ConstantAsMetadata>(getRawFunction());
1309   }
1310   MDTemplateParameterArray getTemplateParams() const {
1311     return cast_or_null<MDTuple>(getRawTemplateParams());
1312   }
1313   MDSubprogram *getDeclaration() const {
1314     return cast_or_null<MDSubprogram>(getRawDeclaration());
1315   }
1316   MDLocalVariableArray getVariables() const {
1317     return cast_or_null<MDTuple>(getRawVariables());
1318   }
1319
1320   Metadata *getRawScope() const { return getOperand(1); }
1321   Metadata *getRawType() const { return getOperand(5); }
1322   Metadata *getRawContainingType() const { return getOperand(6); }
1323   Metadata *getRawFunction() const { return getOperand(7); }
1324   Metadata *getRawTemplateParams() const { return getOperand(8); }
1325   Metadata *getRawDeclaration() const { return getOperand(9); }
1326   Metadata *getRawVariables() const { return getOperand(10); }
1327
1328   /// \brief Replace the function.
1329   ///
1330   /// If \a isUniqued() and not \a isResolved(), this could node will be
1331   /// RAUW'ed and deleted out from under the caller.  Use a \a TrackingMDRef if
1332   /// that's a problem.
1333   /// @{
1334   void replaceFunction(Function *F);
1335   void replaceFunction(ConstantAsMetadata *MD) { replaceOperandWith(7, MD); }
1336   void replaceFunction(std::nullptr_t) { replaceOperandWith(7, nullptr); }
1337   /// @}
1338
1339   static bool classof(const Metadata *MD) {
1340     return MD->getMetadataID() == MDSubprogramKind;
1341   }
1342 };
1343
1344 class MDLexicalBlockBase : public MDLocalScope {
1345 protected:
1346   MDLexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
1347                      ArrayRef<Metadata *> Ops)
1348       : MDLocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1349   ~MDLexicalBlockBase() {}
1350
1351 public:
1352   MDLocalScope *getScope() const { return cast<MDLocalScope>(getRawScope()); }
1353
1354   Metadata *getRawScope() const { return getOperand(1); }
1355
1356   static bool classof(const Metadata *MD) {
1357     return MD->getMetadataID() == MDLexicalBlockKind ||
1358            MD->getMetadataID() == MDLexicalBlockFileKind;
1359   }
1360 };
1361
1362 class MDLexicalBlock : public MDLexicalBlockBase {
1363   friend class LLVMContextImpl;
1364   friend class MDNode;
1365
1366   unsigned Line;
1367   unsigned Column;
1368
1369   MDLexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
1370                  unsigned Column, ArrayRef<Metadata *> Ops)
1371       : MDLexicalBlockBase(C, MDLexicalBlockKind, Storage, Ops), Line(Line),
1372         Column(Column) {}
1373   ~MDLexicalBlock() {}
1374
1375   static MDLexicalBlock *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1376                                  MDFile *File, unsigned Line, unsigned Column,
1377                                  StorageType Storage,
1378                                  bool ShouldCreate = true) {
1379     return getImpl(Context, static_cast<Metadata *>(Scope),
1380                    static_cast<Metadata *>(File), Line, Column, Storage,
1381                    ShouldCreate);
1382   }
1383
1384   static MDLexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
1385                                  Metadata *File, unsigned Line, unsigned Column,
1386                                  StorageType Storage, bool ShouldCreate = true);
1387
1388   TempMDLexicalBlock cloneImpl() const {
1389     return getTemporary(getContext(), getScope(), getFile(), getLine(),
1390                         getColumn());
1391   }
1392
1393 public:
1394   DEFINE_MDNODE_GET(MDLexicalBlock, (MDLocalScope * Scope, MDFile *File,
1395                                      unsigned Line, unsigned Column),
1396                     (Scope, File, Line, Column))
1397   DEFINE_MDNODE_GET(MDLexicalBlock, (Metadata * Scope, Metadata *File,
1398                                      unsigned Line, unsigned Column),
1399                     (Scope, File, Line, Column))
1400
1401   TempMDLexicalBlock clone() const { return cloneImpl(); }
1402
1403   unsigned getLine() const { return Line; }
1404   unsigned getColumn() const { return Column; }
1405
1406   static bool classof(const Metadata *MD) {
1407     return MD->getMetadataID() == MDLexicalBlockKind;
1408   }
1409 };
1410
1411 class MDLexicalBlockFile : public MDLexicalBlockBase {
1412   friend class LLVMContextImpl;
1413   friend class MDNode;
1414
1415   unsigned Discriminator;
1416
1417   MDLexicalBlockFile(LLVMContext &C, StorageType Storage,
1418                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
1419       : MDLexicalBlockBase(C, MDLexicalBlockFileKind, Storage, Ops),
1420         Discriminator(Discriminator) {}
1421   ~MDLexicalBlockFile() {}
1422
1423   static MDLexicalBlockFile *getImpl(LLVMContext &Context, MDLocalScope *Scope,
1424                                      MDFile *File, unsigned Discriminator,
1425                                      StorageType Storage,
1426                                      bool ShouldCreate = true) {
1427     return getImpl(Context, static_cast<Metadata *>(Scope),
1428                    static_cast<Metadata *>(File), Discriminator, Storage,
1429                    ShouldCreate);
1430   }
1431
1432   static MDLexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
1433                                      Metadata *File, unsigned Discriminator,
1434                                      StorageType Storage,
1435                                      bool ShouldCreate = true);
1436
1437   TempMDLexicalBlockFile cloneImpl() const {
1438     return getTemporary(getContext(), getScope(), getFile(),
1439                         getDiscriminator());
1440   }
1441
1442 public:
1443   DEFINE_MDNODE_GET(MDLexicalBlockFile, (MDLocalScope * Scope, MDFile *File,
1444                                          unsigned Discriminator),
1445                     (Scope, File, Discriminator))
1446   DEFINE_MDNODE_GET(MDLexicalBlockFile,
1447                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
1448                     (Scope, File, Discriminator))
1449
1450   TempMDLexicalBlockFile clone() const { return cloneImpl(); }
1451
1452   unsigned getDiscriminator() const { return Discriminator; }
1453
1454   static bool classof(const Metadata *MD) {
1455     return MD->getMetadataID() == MDLexicalBlockFileKind;
1456   }
1457 };
1458
1459 class MDNamespace : public MDScope {
1460   friend class LLVMContextImpl;
1461   friend class MDNode;
1462
1463   unsigned Line;
1464
1465   MDNamespace(LLVMContext &Context, StorageType Storage, unsigned Line,
1466               ArrayRef<Metadata *> Ops)
1467       : MDScope(Context, MDNamespaceKind, Storage, dwarf::DW_TAG_namespace,
1468                 Ops),
1469         Line(Line) {}
1470   ~MDNamespace() {}
1471
1472   static MDNamespace *getImpl(LLVMContext &Context, MDScope *Scope,
1473                               MDFile *File, StringRef Name, unsigned Line,
1474                               StorageType Storage, bool ShouldCreate = true) {
1475     return getImpl(Context, Scope, File, getCanonicalMDString(Context, Name),
1476                    Line, Storage, ShouldCreate);
1477   }
1478   static MDNamespace *getImpl(LLVMContext &Context, Metadata *Scope,
1479                               Metadata *File, MDString *Name, unsigned Line,
1480                               StorageType Storage, bool ShouldCreate = true);
1481
1482   TempMDNamespace cloneImpl() const {
1483     return getTemporary(getContext(), getScope(), getFile(), getName(),
1484                         getLine());
1485   }
1486
1487 public:
1488   DEFINE_MDNODE_GET(MDNamespace, (MDScope * Scope, MDFile *File, StringRef Name,
1489                                   unsigned Line),
1490                     (Scope, File, Name, Line))
1491   DEFINE_MDNODE_GET(MDNamespace, (Metadata * Scope, Metadata *File,
1492                                   MDString *Name, unsigned Line),
1493                     (Scope, File, Name, Line))
1494
1495   TempMDNamespace clone() const { return cloneImpl(); }
1496
1497   unsigned getLine() const { return Line; }
1498   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1499   StringRef getName() const { return getStringOperand(2); }
1500
1501   Metadata *getRawScope() const { return getOperand(1); }
1502   MDString *getRawName() const { return getOperandAs<MDString>(2); }
1503
1504   static bool classof(const Metadata *MD) {
1505     return MD->getMetadataID() == MDNamespaceKind;
1506   }
1507 };
1508
1509 /// \brief Base class for template parameters.
1510 class MDTemplateParameter : public DebugNode {
1511 protected:
1512   MDTemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
1513                       unsigned Tag, ArrayRef<Metadata *> Ops)
1514       : DebugNode(Context, ID, Storage, Tag, Ops) {}
1515   ~MDTemplateParameter() {}
1516
1517 public:
1518   StringRef getName() const { return getStringOperand(0); }
1519   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1520
1521   MDString *getRawName() const { return getOperandAs<MDString>(0); }
1522   Metadata *getRawType() const { return getOperand(1); }
1523
1524   static bool classof(const Metadata *MD) {
1525     return MD->getMetadataID() == MDTemplateTypeParameterKind ||
1526            MD->getMetadataID() == MDTemplateValueParameterKind;
1527   }
1528 };
1529
1530 class MDTemplateTypeParameter : public MDTemplateParameter {
1531   friend class LLVMContextImpl;
1532   friend class MDNode;
1533
1534   MDTemplateTypeParameter(LLVMContext &Context, StorageType Storage,
1535                           ArrayRef<Metadata *> Ops)
1536       : MDTemplateParameter(Context, MDTemplateTypeParameterKind, Storage,
1537                             dwarf::DW_TAG_template_type_parameter, Ops) {}
1538   ~MDTemplateTypeParameter() {}
1539
1540   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
1541                                           MDTypeRef Type, StorageType Storage,
1542                                           bool ShouldCreate = true) {
1543     return getImpl(Context, getCanonicalMDString(Context, Name), Type, Storage,
1544                    ShouldCreate);
1545   }
1546   static MDTemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
1547                                           Metadata *Type, StorageType Storage,
1548                                           bool ShouldCreate = true);
1549
1550   TempMDTemplateTypeParameter cloneImpl() const {
1551     return getTemporary(getContext(), getName(), getType());
1552   }
1553
1554 public:
1555   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (StringRef Name, MDTypeRef Type),
1556                     (Name, Type))
1557   DEFINE_MDNODE_GET(MDTemplateTypeParameter, (MDString * Name, Metadata *Type),
1558                     (Name, Type))
1559
1560   TempMDTemplateTypeParameter clone() const { return cloneImpl(); }
1561
1562   static bool classof(const Metadata *MD) {
1563     return MD->getMetadataID() == MDTemplateTypeParameterKind;
1564   }
1565 };
1566
1567 class MDTemplateValueParameter : public MDTemplateParameter {
1568   friend class LLVMContextImpl;
1569   friend class MDNode;
1570
1571   MDTemplateValueParameter(LLVMContext &Context, StorageType Storage,
1572                            unsigned Tag, ArrayRef<Metadata *> Ops)
1573       : MDTemplateParameter(Context, MDTemplateValueParameterKind, Storage, Tag,
1574                             Ops) {}
1575   ~MDTemplateValueParameter() {}
1576
1577   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1578                                            StringRef Name, MDTypeRef Type,
1579                                            Metadata *Value, StorageType Storage,
1580                                            bool ShouldCreate = true) {
1581     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
1582                    Value, Storage, ShouldCreate);
1583   }
1584   static MDTemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
1585                                            MDString *Name, Metadata *Type,
1586                                            Metadata *Value, StorageType Storage,
1587                                            bool ShouldCreate = true);
1588
1589   TempMDTemplateValueParameter cloneImpl() const {
1590     return getTemporary(getContext(), getTag(), getName(), getType(),
1591                         getValue());
1592   }
1593
1594 public:
1595   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, StringRef Name,
1596                                                MDTypeRef Type, Metadata *Value),
1597                     (Tag, Name, Type, Value))
1598   DEFINE_MDNODE_GET(MDTemplateValueParameter, (unsigned Tag, MDString *Name,
1599                                                Metadata *Type, Metadata *Value),
1600                     (Tag, Name, Type, Value))
1601
1602   TempMDTemplateValueParameter clone() const { return cloneImpl(); }
1603
1604   Metadata *getValue() const { return getOperand(2); }
1605
1606   static bool classof(const Metadata *MD) {
1607     return MD->getMetadataID() == MDTemplateValueParameterKind;
1608   }
1609 };
1610
1611 /// \brief Base class for variables.
1612 ///
1613 /// TODO: Hardcode to DW_TAG_variable.
1614 class MDVariable : public DebugNode {
1615   unsigned Line;
1616
1617 protected:
1618   MDVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1619              unsigned Line, ArrayRef<Metadata *> Ops)
1620       : DebugNode(C, ID, Storage, Tag, Ops), Line(Line) {}
1621   ~MDVariable() {}
1622
1623 public:
1624   unsigned getLine() const { return Line; }
1625   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
1626   StringRef getName() const { return getStringOperand(1); }
1627   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
1628   MDTypeRef getType() const { return MDTypeRef(getRawType()); }
1629
1630   Metadata *getRawScope() const { return getOperand(0); }
1631   MDString *getRawName() const { return getOperandAs<MDString>(1); }
1632   Metadata *getRawFile() const { return getOperand(2); }
1633   Metadata *getRawType() const { return getOperand(3); }
1634
1635   static bool classof(const Metadata *MD) {
1636     return MD->getMetadataID() == MDLocalVariableKind ||
1637            MD->getMetadataID() == MDGlobalVariableKind;
1638   }
1639 };
1640
1641 /// \brief Global variables.
1642 ///
1643 /// TODO: Remove DisplayName.  It's always equal to Name.
1644 class MDGlobalVariable : public MDVariable {
1645   friend class LLVMContextImpl;
1646   friend class MDNode;
1647
1648   bool IsLocalToUnit;
1649   bool IsDefinition;
1650
1651   MDGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
1652                    bool IsLocalToUnit, bool IsDefinition,
1653                    ArrayRef<Metadata *> Ops)
1654       : MDVariable(C, MDGlobalVariableKind, Storage, dwarf::DW_TAG_variable,
1655                    Line, Ops),
1656         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
1657   ~MDGlobalVariable() {}
1658
1659   static MDGlobalVariable *
1660   getImpl(LLVMContext &Context, MDScope *Scope, StringRef Name,
1661           StringRef LinkageName, MDFile *File, unsigned Line, MDTypeRef Type,
1662           bool IsLocalToUnit, bool IsDefinition, ConstantAsMetadata *Variable,
1663           MDDerivedType *StaticDataMemberDeclaration, StorageType Storage,
1664           bool ShouldCreate = true) {
1665     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1666                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1667                    IsLocalToUnit, IsDefinition, Variable,
1668                    StaticDataMemberDeclaration, Storage, ShouldCreate);
1669   }
1670   static MDGlobalVariable *
1671   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1672           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1673           bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1674           Metadata *StaticDataMemberDeclaration, StorageType Storage,
1675           bool ShouldCreate = true);
1676
1677   TempMDGlobalVariable cloneImpl() const {
1678     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1679                         getFile(), getLine(), getType(), isLocalToUnit(),
1680                         isDefinition(), getVariable(),
1681                         getStaticDataMemberDeclaration());
1682   }
1683
1684 public:
1685   DEFINE_MDNODE_GET(MDGlobalVariable,
1686                     (MDScope * Scope, StringRef Name, StringRef LinkageName,
1687                      MDFile *File, unsigned Line, MDTypeRef Type,
1688                      bool IsLocalToUnit, bool IsDefinition,
1689                      ConstantAsMetadata *Variable,
1690                      MDDerivedType *StaticDataMemberDeclaration),
1691                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1692                      IsDefinition, Variable, StaticDataMemberDeclaration))
1693   DEFINE_MDNODE_GET(MDGlobalVariable,
1694                     (Metadata * Scope, MDString *Name, MDString *LinkageName,
1695                      Metadata *File, unsigned Line, Metadata *Type,
1696                      bool IsLocalToUnit, bool IsDefinition, Metadata *Variable,
1697                      Metadata *StaticDataMemberDeclaration),
1698                     (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1699                      IsDefinition, Variable, StaticDataMemberDeclaration))
1700
1701   TempMDGlobalVariable clone() const { return cloneImpl(); }
1702
1703   bool isLocalToUnit() const { return IsLocalToUnit; }
1704   bool isDefinition() const { return IsDefinition; }
1705   StringRef getDisplayName() const { return getStringOperand(4); }
1706   StringRef getLinkageName() const { return getStringOperand(5); }
1707   ConstantAsMetadata *getVariable() const {
1708     return cast_or_null<ConstantAsMetadata>(getRawVariable());
1709   }
1710   MDDerivedType *getStaticDataMemberDeclaration() const {
1711     return cast_or_null<MDDerivedType>(getRawStaticDataMemberDeclaration());
1712   }
1713
1714   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
1715   Metadata *getRawVariable() const { return getOperand(6); }
1716   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(7); }
1717
1718   static bool classof(const Metadata *MD) {
1719     return MD->getMetadataID() == MDGlobalVariableKind;
1720   }
1721 };
1722
1723 /// \brief Local variable.
1724 ///
1725 /// TODO: Split between arguments and otherwise.
1726 /// TODO: Use \c DW_TAG_variable instead of fake tags.
1727 /// TODO: Split up flags.
1728 class MDLocalVariable : public MDVariable {
1729   friend class LLVMContextImpl;
1730   friend class MDNode;
1731
1732   unsigned Arg;
1733   unsigned Flags;
1734
1735   MDLocalVariable(LLVMContext &C, StorageType Storage, unsigned Tag,
1736                   unsigned Line, unsigned Arg, unsigned Flags,
1737                   ArrayRef<Metadata *> Ops)
1738       : MDVariable(C, MDLocalVariableKind, Storage, Tag, Line, Ops), Arg(Arg),
1739         Flags(Flags) {}
1740   ~MDLocalVariable() {}
1741
1742   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1743                                   MDScope *Scope, StringRef Name, MDFile *File,
1744                                   unsigned Line, MDTypeRef Type, unsigned Arg,
1745                                   unsigned Flags, MDLocation *InlinedAt,
1746                                   StorageType Storage,
1747                                   bool ShouldCreate = true) {
1748     return getImpl(Context, Tag, Scope, getCanonicalMDString(Context, Name),
1749                    File, Line, Type, Arg, Flags, InlinedAt, Storage,
1750                    ShouldCreate);
1751   }
1752   static MDLocalVariable *getImpl(LLVMContext &Context, unsigned Tag,
1753                                   Metadata *Scope, MDString *Name,
1754                                   Metadata *File, unsigned Line, Metadata *Type,
1755                                   unsigned Arg, unsigned Flags,
1756                                   Metadata *InlinedAt, StorageType Storage,
1757                                   bool ShouldCreate = true);
1758
1759   TempMDLocalVariable cloneImpl() const {
1760     return getTemporary(getContext(), getTag(), getScope(), getName(),
1761                         getFile(), getLine(), getType(), getArg(), getFlags(),
1762                         getInlinedAt());
1763   }
1764
1765 public:
1766   DEFINE_MDNODE_GET(MDLocalVariable,
1767                     (unsigned Tag, MDLocalScope *Scope, StringRef Name,
1768                      MDFile *File, unsigned Line, MDTypeRef Type, unsigned Arg,
1769                      unsigned Flags, MDLocation *InlinedAt = nullptr),
1770                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1771   DEFINE_MDNODE_GET(MDLocalVariable,
1772                     (unsigned Tag, Metadata *Scope, MDString *Name,
1773                      Metadata *File, unsigned Line, Metadata *Type,
1774                      unsigned Arg, unsigned Flags,
1775                      Metadata *InlinedAt = nullptr),
1776                     (Tag, Scope, Name, File, Line, Type, Arg, Flags, InlinedAt))
1777
1778   TempMDLocalVariable clone() const { return cloneImpl(); }
1779
1780   /// \brief Get the local scope for this variable.
1781   ///
1782   /// Variables must be defined in a local scope.
1783   MDLocalScope *getScope() const {
1784     return cast<MDLocalScope>(MDVariable::getScope());
1785   }
1786
1787   unsigned getArg() const { return Arg; }
1788   unsigned getFlags() const { return Flags; }
1789   MDLocation *getInlinedAt() const {
1790     return cast_or_null<MDLocation>(getRawInlinedAt());
1791   }
1792
1793   Metadata *getRawInlinedAt() const { return getOperand(4); }
1794
1795   bool isArtificial() const { return getFlags() & FlagArtificial; }
1796   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
1797
1798   /// \brief Check that a location is valid for this variable.
1799   ///
1800   /// Check that \c DL has the same inlined-at location as this variable,
1801   /// making them valid for the same \a DbgInfoIntrinsic.
1802   bool isValidLocationForIntrinsic(const MDLocation *DL) const {
1803     return getInlinedAt() == (DL ? DL->getInlinedAt() : nullptr);
1804   }
1805
1806   /// \brief Get an inlined version of this variable.
1807   ///
1808   /// Returns a version of this with \a getAlinedAt() set to \c InlinedAt.
1809   MDLocalVariable *withInline(MDLocation *InlinedAt) const {
1810     if (InlinedAt == getInlinedAt())
1811       return const_cast<MDLocalVariable *>(this);
1812     auto Temp = clone();
1813     Temp->replaceOperandWith(4, InlinedAt);
1814     return replaceWithUniqued(std::move(Temp));
1815   }
1816   MDLocalVariable *withoutInline() const { return withInline(nullptr); }
1817
1818   static bool classof(const Metadata *MD) {
1819     return MD->getMetadataID() == MDLocalVariableKind;
1820   }
1821 };
1822
1823 /// \brief DWARF expression.
1824 ///
1825 /// TODO: Co-allocate the expression elements.
1826 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
1827 /// storage types.
1828 class MDExpression : public MDNode {
1829   friend class LLVMContextImpl;
1830   friend class MDNode;
1831
1832   std::vector<uint64_t> Elements;
1833
1834   MDExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
1835       : MDNode(C, MDExpressionKind, Storage, None),
1836         Elements(Elements.begin(), Elements.end()) {}
1837   ~MDExpression() {}
1838
1839   static MDExpression *getImpl(LLVMContext &Context,
1840                                ArrayRef<uint64_t> Elements, StorageType Storage,
1841                                bool ShouldCreate = true);
1842
1843   TempMDExpression cloneImpl() const {
1844     return getTemporary(getContext(), getElements());
1845   }
1846
1847 public:
1848   DEFINE_MDNODE_GET(MDExpression, (ArrayRef<uint64_t> Elements), (Elements))
1849
1850   TempMDExpression clone() const { return cloneImpl(); }
1851
1852   ArrayRef<uint64_t> getElements() const { return Elements; }
1853
1854   unsigned getNumElements() const { return Elements.size(); }
1855   uint64_t getElement(unsigned I) const {
1856     assert(I < Elements.size() && "Index out of range");
1857     return Elements[I];
1858   }
1859
1860   /// \brief Return whether this is a piece of an aggregate variable.
1861   bool isBitPiece() const;
1862
1863   /// \brief Return the offset of this piece in bits.
1864   uint64_t getBitPieceOffset() const;
1865
1866   /// \brief Return the size of this piece in bits.
1867   uint64_t getBitPieceSize() const;
1868
1869   typedef ArrayRef<uint64_t>::iterator element_iterator;
1870   element_iterator elements_begin() const { return getElements().begin(); }
1871   element_iterator elements_end() const { return getElements().end(); }
1872
1873   /// \brief A lightweight wrapper around an expression operand.
1874   ///
1875   /// TODO: Store arguments directly and change \a MDExpression to store a
1876   /// range of these.
1877   class ExprOperand {
1878     const uint64_t *Op;
1879
1880   public:
1881     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
1882
1883     const uint64_t *get() const { return Op; }
1884
1885     /// \brief Get the operand code.
1886     uint64_t getOp() const { return *Op; }
1887
1888     /// \brief Get an argument to the operand.
1889     ///
1890     /// Never returns the operand itself.
1891     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
1892
1893     unsigned getNumArgs() const { return getSize() - 1; }
1894
1895     /// \brief Return the size of the operand.
1896     ///
1897     /// Return the number of elements in the operand (1 + args).
1898     unsigned getSize() const;
1899   };
1900
1901   /// \brief An iterator for expression operands.
1902   class expr_op_iterator
1903       : public std::iterator<std::input_iterator_tag, ExprOperand> {
1904     ExprOperand Op;
1905
1906   public:
1907     explicit expr_op_iterator(element_iterator I) : Op(I) {}
1908
1909     element_iterator getBase() const { return Op.get(); }
1910     const ExprOperand &operator*() const { return Op; }
1911     const ExprOperand *operator->() const { return &Op; }
1912
1913     expr_op_iterator &operator++() {
1914       increment();
1915       return *this;
1916     }
1917     expr_op_iterator operator++(int) {
1918       expr_op_iterator T(*this);
1919       increment();
1920       return T;
1921     }
1922
1923     /// \brief Get the next iterator.
1924     ///
1925     /// \a std::next() doesn't work because this is technically an
1926     /// input_iterator, but it's a perfectly valid operation.  This is an
1927     /// accessor to provide the same functionality.
1928     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
1929
1930     bool operator==(const expr_op_iterator &X) const {
1931       return getBase() == X.getBase();
1932     }
1933     bool operator!=(const expr_op_iterator &X) const {
1934       return getBase() != X.getBase();
1935     }
1936
1937   private:
1938     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
1939   };
1940
1941   /// \brief Visit the elements via ExprOperand wrappers.
1942   ///
1943   /// These range iterators visit elements through \a ExprOperand wrappers.
1944   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
1945   /// true.
1946   ///
1947   /// \pre \a isValid() gives \c true.
1948   /// @{
1949   expr_op_iterator expr_op_begin() const {
1950     return expr_op_iterator(elements_begin());
1951   }
1952   expr_op_iterator expr_op_end() const {
1953     return expr_op_iterator(elements_end());
1954   }
1955   /// @}
1956
1957   bool isValid() const;
1958
1959   static bool classof(const Metadata *MD) {
1960     return MD->getMetadataID() == MDExpressionKind;
1961   }
1962 };
1963
1964 class MDObjCProperty : public DebugNode {
1965   friend class LLVMContextImpl;
1966   friend class MDNode;
1967
1968   unsigned Line;
1969   unsigned Attributes;
1970
1971   MDObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
1972                  unsigned Attributes, ArrayRef<Metadata *> Ops)
1973       : DebugNode(C, MDObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
1974                   Ops),
1975         Line(Line), Attributes(Attributes) {}
1976   ~MDObjCProperty() {}
1977
1978   static MDObjCProperty *
1979   getImpl(LLVMContext &Context, StringRef Name, MDFile *File, unsigned Line,
1980           StringRef GetterName, StringRef SetterName, unsigned Attributes,
1981           MDType *Type, StorageType Storage, bool ShouldCreate = true) {
1982     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
1983                    getCanonicalMDString(Context, GetterName),
1984                    getCanonicalMDString(Context, SetterName), Attributes, Type,
1985                    Storage, ShouldCreate);
1986   }
1987   static MDObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
1988                                  Metadata *File, unsigned Line,
1989                                  MDString *GetterName, MDString *SetterName,
1990                                  unsigned Attributes, Metadata *Type,
1991                                  StorageType Storage, bool ShouldCreate = true);
1992
1993   TempMDObjCProperty cloneImpl() const {
1994     return getTemporary(getContext(), getName(), getFile(), getLine(),
1995                         getGetterName(), getSetterName(), getAttributes(),
1996                         getType());
1997   }
1998
1999 public:
2000   DEFINE_MDNODE_GET(MDObjCProperty,
2001                     (StringRef Name, MDFile *File, unsigned Line,
2002                      StringRef GetterName, StringRef SetterName,
2003                      unsigned Attributes, MDType *Type),
2004                     (Name, File, Line, GetterName, SetterName, Attributes,
2005                      Type))
2006   DEFINE_MDNODE_GET(MDObjCProperty,
2007                     (MDString * Name, Metadata *File, unsigned Line,
2008                      MDString *GetterName, MDString *SetterName,
2009                      unsigned Attributes, Metadata *Type),
2010                     (Name, File, Line, GetterName, SetterName, Attributes,
2011                      Type))
2012
2013   TempMDObjCProperty clone() const { return cloneImpl(); }
2014
2015   unsigned getLine() const { return Line; }
2016   unsigned getAttributes() const { return Attributes; }
2017   StringRef getName() const { return getStringOperand(0); }
2018   MDFile *getFile() const { return cast_or_null<MDFile>(getRawFile()); }
2019   StringRef getGetterName() const { return getStringOperand(2); }
2020   StringRef getSetterName() const { return getStringOperand(3); }
2021   MDType *getType() const { return cast_or_null<MDType>(getRawType()); }
2022
2023   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2024   Metadata *getRawFile() const { return getOperand(1); }
2025   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
2026   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
2027   Metadata *getRawType() const { return getOperand(4); }
2028
2029   static bool classof(const Metadata *MD) {
2030     return MD->getMetadataID() == MDObjCPropertyKind;
2031   }
2032 };
2033
2034 class MDImportedEntity : public DebugNode {
2035   friend class LLVMContextImpl;
2036   friend class MDNode;
2037
2038   unsigned Line;
2039
2040   MDImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
2041                    unsigned Line, ArrayRef<Metadata *> Ops)
2042       : DebugNode(C, MDImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
2043   ~MDImportedEntity() {}
2044
2045   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2046                                    MDScope *Scope, DebugNodeRef Entity,
2047                                    unsigned Line, StringRef Name,
2048                                    StorageType Storage,
2049                                    bool ShouldCreate = true) {
2050     return getImpl(Context, Tag, Scope, Entity, Line,
2051                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
2052   }
2053   static MDImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
2054                                    Metadata *Scope, Metadata *Entity,
2055                                    unsigned Line, MDString *Name,
2056                                    StorageType Storage,
2057                                    bool ShouldCreate = true);
2058
2059   TempMDImportedEntity cloneImpl() const {
2060     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
2061                         getLine(), getName());
2062   }
2063
2064 public:
2065   DEFINE_MDNODE_GET(MDImportedEntity,
2066                     (unsigned Tag, MDScope *Scope, DebugNodeRef Entity,
2067                      unsigned Line, StringRef Name = ""),
2068                     (Tag, Scope, Entity, Line, Name))
2069   DEFINE_MDNODE_GET(MDImportedEntity,
2070                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
2071                      unsigned Line, MDString *Name),
2072                     (Tag, Scope, Entity, Line, Name))
2073
2074   TempMDImportedEntity clone() const { return cloneImpl(); }
2075
2076   unsigned getLine() const { return Line; }
2077   MDScope *getScope() const { return cast_or_null<MDScope>(getRawScope()); }
2078   DebugNodeRef getEntity() const { return DebugNodeRef(getRawEntity()); }
2079   StringRef getName() const { return getStringOperand(2); }
2080
2081   Metadata *getRawScope() const { return getOperand(0); }
2082   Metadata *getRawEntity() const { return getOperand(1); }
2083   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2084
2085   static bool classof(const Metadata *MD) {
2086     return MD->getMetadataID() == MDImportedEntityKind;
2087   }
2088 };
2089
2090 } // end namespace llvm
2091
2092 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
2093 #undef DEFINE_MDNODE_GET_UNPACK
2094 #undef DEFINE_MDNODE_GET
2095
2096 #endif