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