xref: /freebsd-src/contrib/llvm-project/llvm/include/llvm/IR/DebugInfoMetadata.h (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
1 //===- llvm/IR/DebugInfoMetadata.h - Debug info metadata --------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Declarations for metadata specific to debug info.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_DEBUGINFOMETADATA_H
14 #define LLVM_IR_DEBUGINFOMETADATA_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/BitmaskEnum.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/PointerUnion.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/iterator_range.h"
25 #include "llvm/BinaryFormat/Dwarf.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Metadata.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Discriminator.h"
31 #include <cassert>
32 #include <climits>
33 #include <cstddef>
34 #include <cstdint>
35 #include <iterator>
36 #include <type_traits>
37 #include <vector>
38 
39 // Helper macros for defining get() overrides.
40 #define DEFINE_MDNODE_GET_UNPACK_IMPL(...) __VA_ARGS__
41 #define DEFINE_MDNODE_GET_UNPACK(ARGS) DEFINE_MDNODE_GET_UNPACK_IMPL ARGS
42 #define DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)              \
43   static CLASS *getDistinct(LLVMContext &Context,                              \
44                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
45     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Distinct);         \
46   }                                                                            \
47   static Temp##CLASS getTemporary(LLVMContext &Context,                        \
48                                   DEFINE_MDNODE_GET_UNPACK(FORMAL)) {          \
49     return Temp##CLASS(                                                        \
50         getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Temporary));          \
51   }
52 #define DEFINE_MDNODE_GET(CLASS, FORMAL, ARGS)                                 \
53   static CLASS *get(LLVMContext &Context, DEFINE_MDNODE_GET_UNPACK(FORMAL)) {  \
54     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued);          \
55   }                                                                            \
56   static CLASS *getIfExists(LLVMContext &Context,                              \
57                             DEFINE_MDNODE_GET_UNPACK(FORMAL)) {                \
58     return getImpl(Context, DEFINE_MDNODE_GET_UNPACK(ARGS), Uniqued,           \
59                    /* ShouldCreate */ false);                                  \
60   }                                                                            \
61   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(CLASS, FORMAL, ARGS)
62 
63 namespace llvm {
64 
65 extern cl::opt<bool> EnableFSDiscriminator;
66 
67 class DITypeRefArray {
68   const MDTuple *N = nullptr;
69 
70 public:
71   DITypeRefArray() = default;
72   DITypeRefArray(const MDTuple *N) : N(N) {}
73 
74   explicit operator bool() const { return get(); }
75   explicit operator MDTuple *() const { return get(); }
76 
77   MDTuple *get() const { return const_cast<MDTuple *>(N); }
78   MDTuple *operator->() const { return get(); }
79   MDTuple &operator*() const { return *get(); }
80 
81   // FIXME: Fix callers and remove condition on N.
82   unsigned size() const { return N ? N->getNumOperands() : 0u; }
83   DIType *operator[](unsigned I) const {
84     return cast_or_null<DIType>(N->getOperand(I));
85   }
86 
87   class iterator {
88     MDNode::op_iterator I = nullptr;
89 
90   public:
91     using iterator_category = std::input_iterator_tag;
92     using value_type = DIType *;
93     using difference_type = std::ptrdiff_t;
94     using pointer = void;
95     using reference = DIType *;
96 
97     iterator() = default;
98     explicit iterator(MDNode::op_iterator I) : I(I) {}
99 
100     DIType *operator*() const { return cast_or_null<DIType>(*I); }
101 
102     iterator &operator++() {
103       ++I;
104       return *this;
105     }
106 
107     iterator operator++(int) {
108       iterator Temp(*this);
109       ++I;
110       return Temp;
111     }
112 
113     bool operator==(const iterator &X) const { return I == X.I; }
114     bool operator!=(const iterator &X) const { return I != X.I; }
115   };
116 
117   // FIXME: Fix callers and remove condition on N.
118   iterator begin() const { return N ? iterator(N->op_begin()) : iterator(); }
119   iterator end() const { return N ? iterator(N->op_end()) : iterator(); }
120 };
121 
122 /// Tagged DWARF-like metadata node.
123 ///
124 /// A metadata node with a DWARF tag (i.e., a constant named \c DW_TAG_*,
125 /// defined in llvm/BinaryFormat/Dwarf.h).  Called \a DINode because it's
126 /// potentially used for non-DWARF output.
127 class DINode : public MDNode {
128   friend class LLVMContextImpl;
129   friend class MDNode;
130 
131 protected:
132   DINode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
133          ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
134       : MDNode(C, ID, Storage, Ops1, Ops2) {
135     assert(Tag < 1u << 16);
136     SubclassData16 = Tag;
137   }
138   ~DINode() = default;
139 
140   template <class Ty> Ty *getOperandAs(unsigned I) const {
141     return cast_or_null<Ty>(getOperand(I));
142   }
143 
144   StringRef getStringOperand(unsigned I) const {
145     if (auto *S = getOperandAs<MDString>(I))
146       return S->getString();
147     return StringRef();
148   }
149 
150   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
151     if (S.empty())
152       return nullptr;
153     return MDString::get(Context, S);
154   }
155 
156   /// Allow subclasses to mutate the tag.
157   void setTag(unsigned Tag) { SubclassData16 = Tag; }
158 
159 public:
160   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
161 
162   /// Debug info flags.
163   ///
164   /// The three accessibility flags are mutually exclusive and rolled together
165   /// in the first two bits.
166   enum DIFlags : uint32_t {
167 #define HANDLE_DI_FLAG(ID, NAME) Flag##NAME = ID,
168 #define DI_FLAG_LARGEST_NEEDED
169 #include "llvm/IR/DebugInfoFlags.def"
170     FlagAccessibility = FlagPrivate | FlagProtected | FlagPublic,
171     FlagPtrToMemberRep = FlagSingleInheritance | FlagMultipleInheritance |
172                          FlagVirtualInheritance,
173     LLVM_MARK_AS_BITMASK_ENUM(FlagLargest)
174   };
175 
176   static DIFlags getFlag(StringRef Flag);
177   static StringRef getFlagString(DIFlags Flag);
178 
179   /// Split up a flags bitfield.
180   ///
181   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
182   /// any remaining (unrecognized) bits.
183   static DIFlags splitFlags(DIFlags Flags,
184                             SmallVectorImpl<DIFlags> &SplitFlags);
185 
186   static bool classof(const Metadata *MD) {
187     switch (MD->getMetadataID()) {
188     default:
189       return false;
190     case GenericDINodeKind:
191     case DISubrangeKind:
192     case DIEnumeratorKind:
193     case DIBasicTypeKind:
194     case DIStringTypeKind:
195     case DIDerivedTypeKind:
196     case DICompositeTypeKind:
197     case DISubroutineTypeKind:
198     case DIFileKind:
199     case DICompileUnitKind:
200     case DISubprogramKind:
201     case DILexicalBlockKind:
202     case DILexicalBlockFileKind:
203     case DINamespaceKind:
204     case DICommonBlockKind:
205     case DITemplateTypeParameterKind:
206     case DITemplateValueParameterKind:
207     case DIGlobalVariableKind:
208     case DILocalVariableKind:
209     case DILabelKind:
210     case DIObjCPropertyKind:
211     case DIImportedEntityKind:
212     case DIModuleKind:
213     case DIGenericSubrangeKind:
214       return true;
215     }
216   }
217 };
218 
219 /// Generic tagged DWARF-like metadata node.
220 ///
221 /// An un-specialized DWARF-like metadata node.  The first operand is a
222 /// (possibly empty) null-separated \a MDString header that contains arbitrary
223 /// fields.  The remaining operands are \a dwarf_operands(), and are pointers
224 /// to other metadata.
225 class GenericDINode : public DINode {
226   friend class LLVMContextImpl;
227   friend class MDNode;
228 
229   GenericDINode(LLVMContext &C, StorageType Storage, unsigned Hash,
230                 unsigned Tag, ArrayRef<Metadata *> Ops1,
231                 ArrayRef<Metadata *> Ops2)
232       : DINode(C, GenericDINodeKind, Storage, Tag, Ops1, Ops2) {
233     setHash(Hash);
234   }
235   ~GenericDINode() { dropAllReferences(); }
236 
237   void setHash(unsigned Hash) { SubclassData32 = Hash; }
238   void recalculateHash();
239 
240   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
241                                 StringRef Header, ArrayRef<Metadata *> DwarfOps,
242                                 StorageType Storage, bool ShouldCreate = true) {
243     return getImpl(Context, Tag, getCanonicalMDString(Context, Header),
244                    DwarfOps, Storage, ShouldCreate);
245   }
246 
247   static GenericDINode *getImpl(LLVMContext &Context, unsigned Tag,
248                                 MDString *Header, ArrayRef<Metadata *> DwarfOps,
249                                 StorageType Storage, bool ShouldCreate = true);
250 
251   TempGenericDINode cloneImpl() const {
252     return getTemporary(getContext(), getTag(), getHeader(),
253                         SmallVector<Metadata *, 4>(dwarf_operands()));
254   }
255 
256 public:
257   unsigned getHash() const { return SubclassData32; }
258 
259   DEFINE_MDNODE_GET(GenericDINode,
260                     (unsigned Tag, StringRef Header,
261                      ArrayRef<Metadata *> DwarfOps),
262                     (Tag, Header, DwarfOps))
263   DEFINE_MDNODE_GET(GenericDINode,
264                     (unsigned Tag, MDString *Header,
265                      ArrayRef<Metadata *> DwarfOps),
266                     (Tag, Header, DwarfOps))
267 
268   /// Return a (temporary) clone of this.
269   TempGenericDINode clone() const { return cloneImpl(); }
270 
271   dwarf::Tag getTag() const { return (dwarf::Tag)SubclassData16; }
272   StringRef getHeader() const { return getStringOperand(0); }
273   MDString *getRawHeader() const { return getOperandAs<MDString>(0); }
274 
275   op_iterator dwarf_op_begin() const { return op_begin() + 1; }
276   op_iterator dwarf_op_end() const { return op_end(); }
277   op_range dwarf_operands() const {
278     return op_range(dwarf_op_begin(), dwarf_op_end());
279   }
280 
281   unsigned getNumDwarfOperands() const { return getNumOperands() - 1; }
282   const MDOperand &getDwarfOperand(unsigned I) const {
283     return getOperand(I + 1);
284   }
285   void replaceDwarfOperandWith(unsigned I, Metadata *New) {
286     replaceOperandWith(I + 1, New);
287   }
288 
289   static bool classof(const Metadata *MD) {
290     return MD->getMetadataID() == GenericDINodeKind;
291   }
292 };
293 
294 /// Array subrange.
295 ///
296 /// TODO: Merge into node for DW_TAG_array_type, which should have a custom
297 /// type.
298 class DISubrange : public DINode {
299   friend class LLVMContextImpl;
300   friend class MDNode;
301 
302   DISubrange(LLVMContext &C, StorageType Storage, ArrayRef<Metadata *> Ops)
303       : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
304 
305   ~DISubrange() = default;
306 
307   static DISubrange *getImpl(LLVMContext &Context, int64_t Count,
308                              int64_t LowerBound, StorageType Storage,
309                              bool ShouldCreate = true);
310 
311   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
312                              int64_t LowerBound, StorageType Storage,
313                              bool ShouldCreate = true);
314 
315   static DISubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
316                              Metadata *LowerBound, Metadata *UpperBound,
317                              Metadata *Stride, StorageType Storage,
318                              bool ShouldCreate = true);
319 
320   TempDISubrange cloneImpl() const {
321     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
322                         getRawUpperBound(), getRawStride());
323   }
324 
325 public:
326   DEFINE_MDNODE_GET(DISubrange, (int64_t Count, int64_t LowerBound = 0),
327                     (Count, LowerBound))
328 
329   DEFINE_MDNODE_GET(DISubrange, (Metadata * CountNode, int64_t LowerBound = 0),
330                     (CountNode, LowerBound))
331 
332   DEFINE_MDNODE_GET(DISubrange,
333                     (Metadata * CountNode, Metadata *LowerBound,
334                      Metadata *UpperBound, Metadata *Stride),
335                     (CountNode, LowerBound, UpperBound, Stride))
336 
337   TempDISubrange clone() const { return cloneImpl(); }
338 
339   Metadata *getRawCountNode() const { return getOperand(0).get(); }
340 
341   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
342 
343   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
344 
345   Metadata *getRawStride() const { return getOperand(3).get(); }
346 
347   typedef PointerUnion<ConstantInt *, DIVariable *, DIExpression *> BoundType;
348 
349   BoundType getCount() const;
350 
351   BoundType getLowerBound() const;
352 
353   BoundType getUpperBound() const;
354 
355   BoundType getStride() const;
356 
357   static bool classof(const Metadata *MD) {
358     return MD->getMetadataID() == DISubrangeKind;
359   }
360 };
361 
362 class DIGenericSubrange : public DINode {
363   friend class LLVMContextImpl;
364   friend class MDNode;
365 
366   DIGenericSubrange(LLVMContext &C, StorageType Storage,
367                     ArrayRef<Metadata *> Ops)
368       : DINode(C, DIGenericSubrangeKind, Storage,
369                dwarf::DW_TAG_generic_subrange, Ops) {}
370 
371   ~DIGenericSubrange() = default;
372 
373   static DIGenericSubrange *getImpl(LLVMContext &Context, Metadata *CountNode,
374                                     Metadata *LowerBound, Metadata *UpperBound,
375                                     Metadata *Stride, StorageType Storage,
376                                     bool ShouldCreate = true);
377 
378   TempDIGenericSubrange cloneImpl() const {
379     return getTemporary(getContext(), getRawCountNode(), getRawLowerBound(),
380                         getRawUpperBound(), getRawStride());
381   }
382 
383 public:
384   DEFINE_MDNODE_GET(DIGenericSubrange,
385                     (Metadata * CountNode, Metadata *LowerBound,
386                      Metadata *UpperBound, Metadata *Stride),
387                     (CountNode, LowerBound, UpperBound, Stride))
388 
389   TempDIGenericSubrange clone() const { return cloneImpl(); }
390 
391   Metadata *getRawCountNode() const { return getOperand(0).get(); }
392   Metadata *getRawLowerBound() const { return getOperand(1).get(); }
393   Metadata *getRawUpperBound() const { return getOperand(2).get(); }
394   Metadata *getRawStride() const { return getOperand(3).get(); }
395 
396   using BoundType = PointerUnion<DIVariable *, DIExpression *>;
397 
398   BoundType getCount() const;
399   BoundType getLowerBound() const;
400   BoundType getUpperBound() const;
401   BoundType getStride() const;
402 
403   static bool classof(const Metadata *MD) {
404     return MD->getMetadataID() == DIGenericSubrangeKind;
405   }
406 };
407 
408 /// Enumeration value.
409 ///
410 /// TODO: Add a pointer to the context (DW_TAG_enumeration_type) once that no
411 /// longer creates a type cycle.
412 class DIEnumerator : public DINode {
413   friend class LLVMContextImpl;
414   friend class MDNode;
415 
416   APInt Value;
417   DIEnumerator(LLVMContext &C, StorageType Storage, const APInt &Value,
418                bool IsUnsigned, ArrayRef<Metadata *> Ops)
419       : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
420         Value(Value) {
421     SubclassData32 = IsUnsigned;
422   }
423   DIEnumerator(LLVMContext &C, StorageType Storage, int64_t Value,
424                bool IsUnsigned, ArrayRef<Metadata *> Ops)
425       : DIEnumerator(C, Storage, APInt(64, Value, !IsUnsigned), IsUnsigned,
426                      Ops) {}
427   ~DIEnumerator() = default;
428 
429   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
430                                bool IsUnsigned, StringRef Name,
431                                StorageType Storage, bool ShouldCreate = true) {
432     return getImpl(Context, Value, IsUnsigned,
433                    getCanonicalMDString(Context, Name), Storage, ShouldCreate);
434   }
435   static DIEnumerator *getImpl(LLVMContext &Context, const APInt &Value,
436                                bool IsUnsigned, MDString *Name,
437                                StorageType Storage, bool ShouldCreate = true);
438 
439   TempDIEnumerator cloneImpl() const {
440     return getTemporary(getContext(), getValue(), isUnsigned(), getName());
441   }
442 
443 public:
444   DEFINE_MDNODE_GET(DIEnumerator,
445                     (int64_t Value, bool IsUnsigned, StringRef Name),
446                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
447   DEFINE_MDNODE_GET(DIEnumerator,
448                     (int64_t Value, bool IsUnsigned, MDString *Name),
449                     (APInt(64, Value, !IsUnsigned), IsUnsigned, Name))
450   DEFINE_MDNODE_GET(DIEnumerator,
451                     (APInt Value, bool IsUnsigned, StringRef Name),
452                     (Value, IsUnsigned, Name))
453   DEFINE_MDNODE_GET(DIEnumerator,
454                     (APInt Value, bool IsUnsigned, MDString *Name),
455                     (Value, IsUnsigned, Name))
456 
457   TempDIEnumerator clone() const { return cloneImpl(); }
458 
459   const APInt &getValue() const { return Value; }
460   bool isUnsigned() const { return SubclassData32; }
461   StringRef getName() const { return getStringOperand(0); }
462 
463   MDString *getRawName() const { return getOperandAs<MDString>(0); }
464 
465   static bool classof(const Metadata *MD) {
466     return MD->getMetadataID() == DIEnumeratorKind;
467   }
468 };
469 
470 /// Base class for scope-like contexts.
471 ///
472 /// Base class for lexical scopes and types (which are also declaration
473 /// contexts).
474 ///
475 /// TODO: Separate the concepts of declaration contexts and lexical scopes.
476 class DIScope : public DINode {
477 protected:
478   DIScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
479           ArrayRef<Metadata *> Ops)
480       : DINode(C, ID, Storage, Tag, Ops) {}
481   ~DIScope() = default;
482 
483 public:
484   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
485 
486   inline StringRef getFilename() const;
487   inline StringRef getDirectory() const;
488   inline Optional<StringRef> getSource() const;
489 
490   StringRef getName() const;
491   DIScope *getScope() const;
492 
493   /// Return the raw underlying file.
494   ///
495   /// A \a DIFile is a \a DIScope, but it doesn't point at a separate file (it
496   /// \em is the file).  If \c this is an \a DIFile, we need to return \c this.
497   /// Otherwise, return the first operand, which is where all other subclasses
498   /// store their file pointer.
499   Metadata *getRawFile() const {
500     return isa<DIFile>(this) ? const_cast<DIScope *>(this)
501                              : static_cast<Metadata *>(getOperand(0));
502   }
503 
504   static bool classof(const Metadata *MD) {
505     switch (MD->getMetadataID()) {
506     default:
507       return false;
508     case DIBasicTypeKind:
509     case DIStringTypeKind:
510     case DIDerivedTypeKind:
511     case DICompositeTypeKind:
512     case DISubroutineTypeKind:
513     case DIFileKind:
514     case DICompileUnitKind:
515     case DISubprogramKind:
516     case DILexicalBlockKind:
517     case DILexicalBlockFileKind:
518     case DINamespaceKind:
519     case DICommonBlockKind:
520     case DIModuleKind:
521       return true;
522     }
523   }
524 };
525 
526 /// File.
527 ///
528 /// TODO: Merge with directory/file node (including users).
529 /// TODO: Canonicalize paths on creation.
530 class DIFile : public DIScope {
531   friend class LLVMContextImpl;
532   friend class MDNode;
533 
534 public:
535   /// Which algorithm (e.g. MD5) a checksum was generated with.
536   ///
537   /// The encoding is explicit because it is used directly in Bitcode. The
538   /// value 0 is reserved to indicate the absence of a checksum in Bitcode.
539   enum ChecksumKind {
540     // The first variant was originally CSK_None, encoded as 0. The new
541     // internal representation removes the need for this by wrapping the
542     // ChecksumInfo in an Optional, but to preserve Bitcode compatibility the 0
543     // encoding is reserved.
544     CSK_MD5 = 1,
545     CSK_SHA1 = 2,
546     CSK_SHA256 = 3,
547     CSK_Last = CSK_SHA256 // Should be last enumeration.
548   };
549 
550   /// A single checksum, represented by a \a Kind and a \a Value (a string).
551   template <typename T> struct ChecksumInfo {
552     /// The kind of checksum which \a Value encodes.
553     ChecksumKind Kind;
554     /// The string value of the checksum.
555     T Value;
556 
557     ChecksumInfo(ChecksumKind Kind, T Value) : Kind(Kind), Value(Value) {}
558     ~ChecksumInfo() = default;
559     bool operator==(const ChecksumInfo<T> &X) const {
560       return Kind == X.Kind && Value == X.Value;
561     }
562     bool operator!=(const ChecksumInfo<T> &X) const { return !(*this == X); }
563     StringRef getKindAsString() const { return getChecksumKindAsString(Kind); }
564   };
565 
566 private:
567   Optional<ChecksumInfo<MDString *>> Checksum;
568   Optional<MDString *> Source;
569 
570   DIFile(LLVMContext &C, StorageType Storage,
571          Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src,
572          ArrayRef<Metadata *> Ops)
573       : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
574         Checksum(CS), Source(Src) {}
575   ~DIFile() = default;
576 
577   static DIFile *getImpl(LLVMContext &Context, StringRef Filename,
578                          StringRef Directory,
579                          Optional<ChecksumInfo<StringRef>> CS,
580                          Optional<StringRef> Source, StorageType Storage,
581                          bool ShouldCreate = true) {
582     Optional<ChecksumInfo<MDString *>> MDChecksum;
583     if (CS)
584       MDChecksum.emplace(CS->Kind, getCanonicalMDString(Context, CS->Value));
585     return getImpl(
586         Context, getCanonicalMDString(Context, Filename),
587         getCanonicalMDString(Context, Directory), MDChecksum,
588         Source ? Optional<MDString *>(getCanonicalMDString(Context, *Source))
589                : None,
590         Storage, ShouldCreate);
591   }
592   static DIFile *getImpl(LLVMContext &Context, MDString *Filename,
593                          MDString *Directory,
594                          Optional<ChecksumInfo<MDString *>> CS,
595                          Optional<MDString *> Source, StorageType Storage,
596                          bool ShouldCreate = true);
597 
598   TempDIFile cloneImpl() const {
599     return getTemporary(getContext(), getFilename(), getDirectory(),
600                         getChecksum(), getSource());
601   }
602 
603 public:
604   DEFINE_MDNODE_GET(DIFile,
605                     (StringRef Filename, StringRef Directory,
606                      Optional<ChecksumInfo<StringRef>> CS = None,
607                      Optional<StringRef> Source = None),
608                     (Filename, Directory, CS, Source))
609   DEFINE_MDNODE_GET(DIFile,
610                     (MDString * Filename, MDString *Directory,
611                      Optional<ChecksumInfo<MDString *>> CS = None,
612                      Optional<MDString *> Source = None),
613                     (Filename, Directory, CS, Source))
614 
615   TempDIFile clone() const { return cloneImpl(); }
616 
617   StringRef getFilename() const { return getStringOperand(0); }
618   StringRef getDirectory() const { return getStringOperand(1); }
619   Optional<ChecksumInfo<StringRef>> getChecksum() const {
620     Optional<ChecksumInfo<StringRef>> StringRefChecksum;
621     if (Checksum)
622       StringRefChecksum.emplace(Checksum->Kind, Checksum->Value->getString());
623     return StringRefChecksum;
624   }
625   Optional<StringRef> getSource() const {
626     return Source ? Optional<StringRef>((*Source)->getString()) : None;
627   }
628 
629   MDString *getRawFilename() const { return getOperandAs<MDString>(0); }
630   MDString *getRawDirectory() const { return getOperandAs<MDString>(1); }
631   Optional<ChecksumInfo<MDString *>> getRawChecksum() const { return Checksum; }
632   Optional<MDString *> getRawSource() const { return Source; }
633 
634   static StringRef getChecksumKindAsString(ChecksumKind CSKind);
635   static Optional<ChecksumKind> getChecksumKind(StringRef CSKindStr);
636 
637   static bool classof(const Metadata *MD) {
638     return MD->getMetadataID() == DIFileKind;
639   }
640 };
641 
642 StringRef DIScope::getFilename() const {
643   if (auto *F = getFile())
644     return F->getFilename();
645   return "";
646 }
647 
648 StringRef DIScope::getDirectory() const {
649   if (auto *F = getFile())
650     return F->getDirectory();
651   return "";
652 }
653 
654 Optional<StringRef> DIScope::getSource() const {
655   if (auto *F = getFile())
656     return F->getSource();
657   return None;
658 }
659 
660 /// Base class for types.
661 ///
662 /// TODO: Remove the hardcoded name and context, since many types don't use
663 /// them.
664 /// TODO: Split up flags.
665 class DIType : public DIScope {
666   unsigned Line;
667   DIFlags Flags;
668   uint64_t SizeInBits;
669   uint64_t OffsetInBits;
670   uint32_t AlignInBits;
671 
672 protected:
673   DIType(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
674          unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
675          uint64_t OffsetInBits, DIFlags Flags, ArrayRef<Metadata *> Ops)
676       : DIScope(C, ID, Storage, Tag, Ops) {
677     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
678   }
679   ~DIType() = default;
680 
681   void init(unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
682             uint64_t OffsetInBits, DIFlags Flags) {
683     this->Line = Line;
684     this->Flags = Flags;
685     this->SizeInBits = SizeInBits;
686     this->AlignInBits = AlignInBits;
687     this->OffsetInBits = OffsetInBits;
688   }
689 
690   /// Change fields in place.
691   void mutate(unsigned Tag, unsigned Line, uint64_t SizeInBits,
692               uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags) {
693     assert(isDistinct() && "Only distinct nodes can mutate");
694     setTag(Tag);
695     init(Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
696   }
697 
698 public:
699   TempDIType clone() const {
700     return TempDIType(cast<DIType>(MDNode::clone().release()));
701   }
702 
703   unsigned getLine() const { return Line; }
704   uint64_t getSizeInBits() const { return SizeInBits; }
705   uint32_t getAlignInBits() const { return AlignInBits; }
706   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
707   uint64_t getOffsetInBits() const { return OffsetInBits; }
708   DIFlags getFlags() const { return Flags; }
709 
710   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
711   StringRef getName() const { return getStringOperand(2); }
712 
713   Metadata *getRawScope() const { return getOperand(1); }
714   MDString *getRawName() const { return getOperandAs<MDString>(2); }
715 
716   /// Returns a new temporary DIType with updated Flags
717   TempDIType cloneWithFlags(DIFlags NewFlags) const {
718     auto NewTy = clone();
719     NewTy->Flags = NewFlags;
720     return NewTy;
721   }
722 
723   bool isPrivate() const {
724     return (getFlags() & FlagAccessibility) == FlagPrivate;
725   }
726   bool isProtected() const {
727     return (getFlags() & FlagAccessibility) == FlagProtected;
728   }
729   bool isPublic() const {
730     return (getFlags() & FlagAccessibility) == FlagPublic;
731   }
732   bool isForwardDecl() const { return getFlags() & FlagFwdDecl; }
733   bool isAppleBlockExtension() const { return getFlags() & FlagAppleBlock; }
734   bool isVirtual() const { return getFlags() & FlagVirtual; }
735   bool isArtificial() const { return getFlags() & FlagArtificial; }
736   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
737   bool isObjcClassComplete() const {
738     return getFlags() & FlagObjcClassComplete;
739   }
740   bool isVector() const { return getFlags() & FlagVector; }
741   bool isBitField() const { return getFlags() & FlagBitField; }
742   bool isStaticMember() const { return getFlags() & FlagStaticMember; }
743   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
744   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
745   bool isTypePassByValue() const { return getFlags() & FlagTypePassByValue; }
746   bool isTypePassByReference() const {
747     return getFlags() & FlagTypePassByReference;
748   }
749   bool isBigEndian() const { return getFlags() & FlagBigEndian; }
750   bool isLittleEndian() const { return getFlags() & FlagLittleEndian; }
751   bool getExportSymbols() const { return getFlags() & FlagExportSymbols; }
752 
753   static bool classof(const Metadata *MD) {
754     switch (MD->getMetadataID()) {
755     default:
756       return false;
757     case DIBasicTypeKind:
758     case DIStringTypeKind:
759     case DIDerivedTypeKind:
760     case DICompositeTypeKind:
761     case DISubroutineTypeKind:
762       return true;
763     }
764   }
765 };
766 
767 /// Basic type, like 'int' or 'float'.
768 ///
769 /// TODO: Split out DW_TAG_unspecified_type.
770 /// TODO: Drop unused accessors.
771 class DIBasicType : public DIType {
772   friend class LLVMContextImpl;
773   friend class MDNode;
774 
775   unsigned Encoding;
776 
777   DIBasicType(LLVMContext &C, StorageType Storage, unsigned Tag,
778               uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
779               DIFlags Flags, ArrayRef<Metadata *> Ops)
780       : DIType(C, DIBasicTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
781                Flags, Ops),
782         Encoding(Encoding) {}
783   ~DIBasicType() = default;
784 
785   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
786                               StringRef Name, uint64_t SizeInBits,
787                               uint32_t AlignInBits, unsigned Encoding,
788                               DIFlags Flags, StorageType Storage,
789                               bool ShouldCreate = true) {
790     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
791                    SizeInBits, AlignInBits, Encoding, Flags, Storage,
792                    ShouldCreate);
793   }
794   static DIBasicType *getImpl(LLVMContext &Context, unsigned Tag,
795                               MDString *Name, uint64_t SizeInBits,
796                               uint32_t AlignInBits, unsigned Encoding,
797                               DIFlags Flags, StorageType Storage,
798                               bool ShouldCreate = true);
799 
800   TempDIBasicType cloneImpl() const {
801     return getTemporary(getContext(), getTag(), getName(), getSizeInBits(),
802                         getAlignInBits(), getEncoding(), getFlags());
803   }
804 
805 public:
806   DEFINE_MDNODE_GET(DIBasicType, (unsigned Tag, StringRef Name),
807                     (Tag, Name, 0, 0, 0, FlagZero))
808   DEFINE_MDNODE_GET(DIBasicType,
809                     (unsigned Tag, StringRef Name, uint64_t SizeInBits),
810                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
811   DEFINE_MDNODE_GET(DIBasicType,
812                     (unsigned Tag, MDString *Name, uint64_t SizeInBits),
813                     (Tag, Name, SizeInBits, 0, 0, FlagZero))
814   DEFINE_MDNODE_GET(DIBasicType,
815                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
816                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
817                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
818   DEFINE_MDNODE_GET(DIBasicType,
819                     (unsigned Tag, MDString *Name, uint64_t SizeInBits,
820                      uint32_t AlignInBits, unsigned Encoding, DIFlags Flags),
821                     (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags))
822 
823   TempDIBasicType clone() const { return cloneImpl(); }
824 
825   unsigned getEncoding() const { return Encoding; }
826 
827   enum class Signedness { Signed, Unsigned };
828 
829   /// Return the signedness of this type, or None if this type is neither
830   /// signed nor unsigned.
831   Optional<Signedness> getSignedness() const;
832 
833   static bool classof(const Metadata *MD) {
834     return MD->getMetadataID() == DIBasicTypeKind;
835   }
836 };
837 
838 /// String type, Fortran CHARACTER(n)
839 class DIStringType : public DIType {
840   friend class LLVMContextImpl;
841   friend class MDNode;
842 
843   unsigned Encoding;
844 
845   DIStringType(LLVMContext &C, StorageType Storage, unsigned Tag,
846                uint64_t SizeInBits, uint32_t AlignInBits, unsigned Encoding,
847                ArrayRef<Metadata *> Ops)
848       : DIType(C, DIStringTypeKind, Storage, Tag, 0, SizeInBits, AlignInBits, 0,
849                FlagZero, Ops),
850         Encoding(Encoding) {}
851   ~DIStringType() = default;
852 
853   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
854                                StringRef Name, Metadata *StringLength,
855                                Metadata *StrLenExp, uint64_t SizeInBits,
856                                uint32_t AlignInBits, unsigned Encoding,
857                                StorageType Storage, bool ShouldCreate = true) {
858     return getImpl(Context, Tag, getCanonicalMDString(Context, Name),
859                    StringLength, StrLenExp, SizeInBits, AlignInBits, Encoding,
860                    Storage, ShouldCreate);
861   }
862   static DIStringType *getImpl(LLVMContext &Context, unsigned Tag,
863                                MDString *Name, Metadata *StringLength,
864                                Metadata *StrLenExp, uint64_t SizeInBits,
865                                uint32_t AlignInBits, unsigned Encoding,
866                                StorageType Storage, bool ShouldCreate = true);
867 
868   TempDIStringType cloneImpl() const {
869     return getTemporary(getContext(), getTag(), getRawName(),
870                         getRawStringLength(), getRawStringLengthExp(),
871                         getSizeInBits(), getAlignInBits(), getEncoding());
872   }
873 
874 public:
875   DEFINE_MDNODE_GET(DIStringType,
876                     (unsigned Tag, StringRef Name, uint64_t SizeInBits,
877                      uint32_t AlignInBits),
878                     (Tag, Name, nullptr, nullptr, SizeInBits, AlignInBits, 0))
879   DEFINE_MDNODE_GET(DIStringType,
880                     (unsigned Tag, MDString *Name, Metadata *StringLength,
881                      Metadata *StringLengthExp, uint64_t SizeInBits,
882                      uint32_t AlignInBits, unsigned Encoding),
883                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
884                      AlignInBits, Encoding))
885   DEFINE_MDNODE_GET(DIStringType,
886                     (unsigned Tag, StringRef Name, Metadata *StringLength,
887                      Metadata *StringLengthExp, uint64_t SizeInBits,
888                      uint32_t AlignInBits, unsigned Encoding),
889                     (Tag, Name, StringLength, StringLengthExp, SizeInBits,
890                      AlignInBits, Encoding))
891 
892   TempDIStringType clone() const { return cloneImpl(); }
893 
894   static bool classof(const Metadata *MD) {
895     return MD->getMetadataID() == DIStringTypeKind;
896   }
897 
898   DIVariable *getStringLength() const {
899     return cast_or_null<DIVariable>(getRawStringLength());
900   }
901 
902   DIExpression *getStringLengthExp() const {
903     return cast_or_null<DIExpression>(getRawStringLengthExp());
904   }
905 
906   unsigned getEncoding() const { return Encoding; }
907 
908   Metadata *getRawStringLength() const { return getOperand(3); }
909 
910   Metadata *getRawStringLengthExp() const { return getOperand(4); }
911 };
912 
913 /// Derived types.
914 ///
915 /// This includes qualified types, pointers, references, friends, typedefs, and
916 /// class members.
917 ///
918 /// TODO: Split out members (inheritance, fields, methods, etc.).
919 class DIDerivedType : public DIType {
920   friend class LLVMContextImpl;
921   friend class MDNode;
922 
923   /// The DWARF address space of the memory pointed to or referenced by a
924   /// pointer or reference type respectively.
925   Optional<unsigned> DWARFAddressSpace;
926 
927   DIDerivedType(LLVMContext &C, StorageType Storage, unsigned Tag,
928                 unsigned Line, uint64_t SizeInBits, uint32_t AlignInBits,
929                 uint64_t OffsetInBits, Optional<unsigned> DWARFAddressSpace,
930                 DIFlags Flags, ArrayRef<Metadata *> Ops)
931       : DIType(C, DIDerivedTypeKind, Storage, Tag, Line, SizeInBits,
932                AlignInBits, OffsetInBits, Flags, Ops),
933         DWARFAddressSpace(DWARFAddressSpace) {}
934   ~DIDerivedType() = default;
935 
936   static DIDerivedType *
937   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, DIFile *File,
938           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
939           uint32_t AlignInBits, uint64_t OffsetInBits,
940           Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
941           Metadata *ExtraData, DINodeArray Annotations, StorageType Storage,
942           bool ShouldCreate = true) {
943     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), File,
944                    Line, Scope, BaseType, SizeInBits, AlignInBits, OffsetInBits,
945                    DWARFAddressSpace, Flags, ExtraData, Annotations.get(),
946                    Storage, ShouldCreate);
947   }
948   static DIDerivedType *
949   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
950           unsigned Line, Metadata *Scope, Metadata *BaseType,
951           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
952           Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
953           Metadata *ExtraData, Metadata *Annotations, StorageType Storage,
954           bool ShouldCreate = true);
955 
956   TempDIDerivedType cloneImpl() const {
957     return getTemporary(
958         getContext(), getTag(), getName(), getFile(), getLine(), getScope(),
959         getBaseType(), getSizeInBits(), getAlignInBits(), getOffsetInBits(),
960         getDWARFAddressSpace(), getFlags(), getExtraData(), getAnnotations());
961   }
962 
963 public:
964   DEFINE_MDNODE_GET(
965       DIDerivedType,
966       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
967        Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
968        uint32_t AlignInBits, uint64_t OffsetInBits,
969        Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
970        Metadata *ExtraData = nullptr, Metadata *Annotations = nullptr),
971       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
972        OffsetInBits, DWARFAddressSpace, Flags, ExtraData, Annotations))
973   DEFINE_MDNODE_GET(DIDerivedType,
974                     (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
975                      DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
976                      uint32_t AlignInBits, uint64_t OffsetInBits,
977                      Optional<unsigned> DWARFAddressSpace, DIFlags Flags,
978                      Metadata *ExtraData = nullptr,
979                      DINodeArray Annotations = nullptr),
980                     (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
981                      AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
982                      ExtraData, Annotations))
983 
984   TempDIDerivedType clone() const { return cloneImpl(); }
985 
986   /// Get the base type this is derived from.
987   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
988   Metadata *getRawBaseType() const { return getOperand(3); }
989 
990   /// \returns The DWARF address space of the memory pointed to or referenced by
991   /// a pointer or reference type respectively.
992   Optional<unsigned> getDWARFAddressSpace() const { return DWARFAddressSpace; }
993 
994   /// Get extra data associated with this derived type.
995   ///
996   /// Class type for pointer-to-members, objective-c property node for ivars,
997   /// global constant wrapper for static members, or virtual base pointer offset
998   /// for inheritance.
999   ///
1000   /// TODO: Separate out types that need this extra operand: pointer-to-member
1001   /// types and member fields (static members and ivars).
1002   Metadata *getExtraData() const { return getRawExtraData(); }
1003   Metadata *getRawExtraData() const { return getOperand(4); }
1004 
1005   /// Get annotations associated with this derived type.
1006   DINodeArray getAnnotations() const {
1007     return cast_or_null<MDTuple>(getRawAnnotations());
1008   }
1009   Metadata *getRawAnnotations() const { return getOperand(5); }
1010 
1011   /// Get casted version of extra data.
1012   /// @{
1013   DIType *getClassType() const {
1014     assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
1015     return cast_or_null<DIType>(getExtraData());
1016   }
1017 
1018   DIObjCProperty *getObjCProperty() const {
1019     return dyn_cast_or_null<DIObjCProperty>(getExtraData());
1020   }
1021 
1022   uint32_t getVBPtrOffset() const {
1023     assert(getTag() == dwarf::DW_TAG_inheritance);
1024     if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
1025       if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
1026         return static_cast<uint32_t>(CI->getZExtValue());
1027     return 0;
1028   }
1029 
1030   Constant *getStorageOffsetInBits() const {
1031     assert(getTag() == dwarf::DW_TAG_member && isBitField());
1032     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1033       return C->getValue();
1034     return nullptr;
1035   }
1036 
1037   Constant *getConstant() const {
1038     assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
1039     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1040       return C->getValue();
1041     return nullptr;
1042   }
1043   Constant *getDiscriminantValue() const {
1044     assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
1045     if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
1046       return C->getValue();
1047     return nullptr;
1048   }
1049   /// @}
1050 
1051   static bool classof(const Metadata *MD) {
1052     return MD->getMetadataID() == DIDerivedTypeKind;
1053   }
1054 };
1055 
1056 /// Composite types.
1057 ///
1058 /// TODO: Detach from DerivedTypeBase (split out MDEnumType?).
1059 /// TODO: Create a custom, unrelated node for DW_TAG_array_type.
1060 class DICompositeType : public DIType {
1061   friend class LLVMContextImpl;
1062   friend class MDNode;
1063 
1064   unsigned RuntimeLang;
1065 
1066   DICompositeType(LLVMContext &C, StorageType Storage, unsigned Tag,
1067                   unsigned Line, unsigned RuntimeLang, uint64_t SizeInBits,
1068                   uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1069                   ArrayRef<Metadata *> Ops)
1070       : DIType(C, DICompositeTypeKind, Storage, Tag, Line, SizeInBits,
1071                AlignInBits, OffsetInBits, Flags, Ops),
1072         RuntimeLang(RuntimeLang) {}
1073   ~DICompositeType() = default;
1074 
1075   /// Change fields in place.
1076   void mutate(unsigned Tag, unsigned Line, unsigned RuntimeLang,
1077               uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
1078               DIFlags Flags) {
1079     assert(isDistinct() && "Only distinct nodes can mutate");
1080     assert(getRawIdentifier() && "Only ODR-uniqued nodes should mutate");
1081     this->RuntimeLang = RuntimeLang;
1082     DIType::mutate(Tag, Line, SizeInBits, AlignInBits, OffsetInBits, Flags);
1083   }
1084 
1085   static DICompositeType *
1086   getImpl(LLVMContext &Context, unsigned Tag, StringRef Name, Metadata *File,
1087           unsigned Line, DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1088           uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1089           DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1090           DITemplateParameterArray TemplateParams, StringRef Identifier,
1091           DIDerivedType *Discriminator, Metadata *DataLocation,
1092           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1093           DINodeArray Annotations, StorageType Storage,
1094           bool ShouldCreate = true) {
1095     return getImpl(
1096         Context, Tag, getCanonicalMDString(Context, Name), File, Line, Scope,
1097         BaseType, SizeInBits, AlignInBits, OffsetInBits, Flags, Elements.get(),
1098         RuntimeLang, VTableHolder, TemplateParams.get(),
1099         getCanonicalMDString(Context, Identifier), Discriminator, DataLocation,
1100         Associated, Allocated, Rank, Annotations.get(), Storage, ShouldCreate);
1101   }
1102   static DICompositeType *
1103   getImpl(LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
1104           unsigned Line, Metadata *Scope, Metadata *BaseType,
1105           uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
1106           DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
1107           Metadata *VTableHolder, Metadata *TemplateParams,
1108           MDString *Identifier, Metadata *Discriminator, Metadata *DataLocation,
1109           Metadata *Associated, Metadata *Allocated, Metadata *Rank,
1110           Metadata *Annotations, StorageType Storage, bool ShouldCreate = true);
1111 
1112   TempDICompositeType cloneImpl() const {
1113     return getTemporary(
1114         getContext(), getTag(), getName(), getFile(), getLine(), getScope(),
1115         getBaseType(), getSizeInBits(), getAlignInBits(), getOffsetInBits(),
1116         getFlags(), getElements(), getRuntimeLang(), getVTableHolder(),
1117         getTemplateParams(), getIdentifier(), getDiscriminator(),
1118         getRawDataLocation(), getRawAssociated(), getRawAllocated(),
1119         getRawRank(), getAnnotations());
1120   }
1121 
1122 public:
1123   DEFINE_MDNODE_GET(
1124       DICompositeType,
1125       (unsigned Tag, StringRef Name, DIFile *File, unsigned Line,
1126        DIScope *Scope, DIType *BaseType, uint64_t SizeInBits,
1127        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1128        DINodeArray Elements, unsigned RuntimeLang, DIType *VTableHolder,
1129        DITemplateParameterArray TemplateParams = nullptr,
1130        StringRef Identifier = "", DIDerivedType *Discriminator = nullptr,
1131        Metadata *DataLocation = nullptr, Metadata *Associated = nullptr,
1132        Metadata *Allocated = nullptr, Metadata *Rank = nullptr,
1133        DINodeArray Annotations = nullptr),
1134       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1135        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
1136        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank,
1137        Annotations))
1138   DEFINE_MDNODE_GET(
1139       DICompositeType,
1140       (unsigned Tag, MDString *Name, Metadata *File, unsigned Line,
1141        Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
1142        uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
1143        Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
1144        Metadata *TemplateParams = nullptr, MDString *Identifier = nullptr,
1145        Metadata *Discriminator = nullptr, Metadata *DataLocation = nullptr,
1146        Metadata *Associated = nullptr, Metadata *Allocated = nullptr,
1147        Metadata *Rank = nullptr, Metadata *Annotations = nullptr),
1148       (Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1149        OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder, TemplateParams,
1150        Identifier, Discriminator, DataLocation, Associated, Allocated, Rank,
1151        Annotations))
1152 
1153   TempDICompositeType clone() const { return cloneImpl(); }
1154 
1155   /// Get a DICompositeType with the given ODR identifier.
1156   ///
1157   /// If \a LLVMContext::isODRUniquingDebugTypes(), gets the mapped
1158   /// DICompositeType for the given ODR \c Identifier.  If none exists, creates
1159   /// a new node.
1160   ///
1161   /// Else, returns \c nullptr.
1162   static DICompositeType *
1163   getODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1164              MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1165              Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
1166              uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
1167              unsigned RuntimeLang, Metadata *VTableHolder,
1168              Metadata *TemplateParams, Metadata *Discriminator,
1169              Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
1170              Metadata *Rank, Metadata *Annotations);
1171   static DICompositeType *getODRTypeIfExists(LLVMContext &Context,
1172                                              MDString &Identifier);
1173 
1174   /// Build a DICompositeType with the given ODR identifier.
1175   ///
1176   /// Looks up the mapped DICompositeType for the given ODR \c Identifier.  If
1177   /// it doesn't exist, creates a new one.  If it does exist and \a
1178   /// isForwardDecl(), and the new arguments would be a definition, mutates the
1179   /// the type in place.  In either case, returns the type.
1180   ///
1181   /// If not \a LLVMContext::isODRUniquingDebugTypes(), this function returns
1182   /// nullptr.
1183   static DICompositeType *
1184   buildODRType(LLVMContext &Context, MDString &Identifier, unsigned Tag,
1185                MDString *Name, Metadata *File, unsigned Line, Metadata *Scope,
1186                Metadata *BaseType, uint64_t SizeInBits, uint32_t AlignInBits,
1187                uint64_t OffsetInBits, DIFlags Flags, Metadata *Elements,
1188                unsigned RuntimeLang, Metadata *VTableHolder,
1189                Metadata *TemplateParams, Metadata *Discriminator,
1190                Metadata *DataLocation, Metadata *Associated,
1191                Metadata *Allocated, Metadata *Rank, Metadata *Annotations);
1192 
1193   DIType *getBaseType() const { return cast_or_null<DIType>(getRawBaseType()); }
1194   DINodeArray getElements() const {
1195     return cast_or_null<MDTuple>(getRawElements());
1196   }
1197   DIType *getVTableHolder() const {
1198     return cast_or_null<DIType>(getRawVTableHolder());
1199   }
1200   DITemplateParameterArray getTemplateParams() const {
1201     return cast_or_null<MDTuple>(getRawTemplateParams());
1202   }
1203   StringRef getIdentifier() const { return getStringOperand(7); }
1204   unsigned getRuntimeLang() const { return RuntimeLang; }
1205 
1206   Metadata *getRawBaseType() const { return getOperand(3); }
1207   Metadata *getRawElements() const { return getOperand(4); }
1208   Metadata *getRawVTableHolder() const { return getOperand(5); }
1209   Metadata *getRawTemplateParams() const { return getOperand(6); }
1210   MDString *getRawIdentifier() const { return getOperandAs<MDString>(7); }
1211   Metadata *getRawDiscriminator() const { return getOperand(8); }
1212   DIDerivedType *getDiscriminator() const {
1213     return getOperandAs<DIDerivedType>(8);
1214   }
1215   Metadata *getRawDataLocation() const { return getOperand(9); }
1216   DIVariable *getDataLocation() const {
1217     return dyn_cast_or_null<DIVariable>(getRawDataLocation());
1218   }
1219   DIExpression *getDataLocationExp() const {
1220     return dyn_cast_or_null<DIExpression>(getRawDataLocation());
1221   }
1222   Metadata *getRawAssociated() const { return getOperand(10); }
1223   DIVariable *getAssociated() const {
1224     return dyn_cast_or_null<DIVariable>(getRawAssociated());
1225   }
1226   DIExpression *getAssociatedExp() const {
1227     return dyn_cast_or_null<DIExpression>(getRawAssociated());
1228   }
1229   Metadata *getRawAllocated() const { return getOperand(11); }
1230   DIVariable *getAllocated() const {
1231     return dyn_cast_or_null<DIVariable>(getRawAllocated());
1232   }
1233   DIExpression *getAllocatedExp() const {
1234     return dyn_cast_or_null<DIExpression>(getRawAllocated());
1235   }
1236   Metadata *getRawRank() const { return getOperand(12); }
1237   ConstantInt *getRankConst() const {
1238     if (auto *MD = dyn_cast_or_null<ConstantAsMetadata>(getRawRank()))
1239       return dyn_cast_or_null<ConstantInt>(MD->getValue());
1240     return nullptr;
1241   }
1242   DIExpression *getRankExp() const {
1243     return dyn_cast_or_null<DIExpression>(getRawRank());
1244   }
1245 
1246   Metadata *getRawAnnotations() const { return getOperand(13); }
1247   DINodeArray getAnnotations() const {
1248     return cast_or_null<MDTuple>(getRawAnnotations());
1249   }
1250 
1251   /// Replace operands.
1252   ///
1253   /// If this \a isUniqued() and not \a isResolved(), on a uniquing collision
1254   /// this will be RAUW'ed and deleted.  Use a \a TrackingMDRef to keep track
1255   /// of its movement if necessary.
1256   /// @{
1257   void replaceElements(DINodeArray Elements) {
1258 #ifndef NDEBUG
1259     for (DINode *Op : getElements())
1260       assert(is_contained(Elements->operands(), Op) &&
1261              "Lost a member during member list replacement");
1262 #endif
1263     replaceOperandWith(4, Elements.get());
1264   }
1265 
1266   void replaceVTableHolder(DIType *VTableHolder) {
1267     replaceOperandWith(5, VTableHolder);
1268   }
1269 
1270   void replaceTemplateParams(DITemplateParameterArray TemplateParams) {
1271     replaceOperandWith(6, TemplateParams.get());
1272   }
1273   /// @}
1274 
1275   static bool classof(const Metadata *MD) {
1276     return MD->getMetadataID() == DICompositeTypeKind;
1277   }
1278 };
1279 
1280 /// Type array for a subprogram.
1281 ///
1282 /// TODO: Fold the array of types in directly as operands.
1283 class DISubroutineType : public DIType {
1284   friend class LLVMContextImpl;
1285   friend class MDNode;
1286 
1287   /// The calling convention used with DW_AT_calling_convention. Actually of
1288   /// type dwarf::CallingConvention.
1289   uint8_t CC;
1290 
1291   DISubroutineType(LLVMContext &C, StorageType Storage, DIFlags Flags,
1292                    uint8_t CC, ArrayRef<Metadata *> Ops)
1293       : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type,
1294                0, 0, 0, 0, Flags, Ops),
1295         CC(CC) {}
1296   ~DISubroutineType() = default;
1297 
1298   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1299                                    uint8_t CC, DITypeRefArray TypeArray,
1300                                    StorageType Storage,
1301                                    bool ShouldCreate = true) {
1302     return getImpl(Context, Flags, CC, TypeArray.get(), Storage, ShouldCreate);
1303   }
1304   static DISubroutineType *getImpl(LLVMContext &Context, DIFlags Flags,
1305                                    uint8_t CC, Metadata *TypeArray,
1306                                    StorageType Storage,
1307                                    bool ShouldCreate = true);
1308 
1309   TempDISubroutineType cloneImpl() const {
1310     return getTemporary(getContext(), getFlags(), getCC(), getTypeArray());
1311   }
1312 
1313 public:
1314   DEFINE_MDNODE_GET(DISubroutineType,
1315                     (DIFlags Flags, uint8_t CC, DITypeRefArray TypeArray),
1316                     (Flags, CC, TypeArray))
1317   DEFINE_MDNODE_GET(DISubroutineType,
1318                     (DIFlags Flags, uint8_t CC, Metadata *TypeArray),
1319                     (Flags, CC, TypeArray))
1320 
1321   TempDISubroutineType clone() const { return cloneImpl(); }
1322 
1323   uint8_t getCC() const { return CC; }
1324 
1325   DITypeRefArray getTypeArray() const {
1326     return cast_or_null<MDTuple>(getRawTypeArray());
1327   }
1328 
1329   Metadata *getRawTypeArray() const { return getOperand(3); }
1330 
1331   static bool classof(const Metadata *MD) {
1332     return MD->getMetadataID() == DISubroutineTypeKind;
1333   }
1334 };
1335 
1336 /// Compile unit.
1337 class DICompileUnit : public DIScope {
1338   friend class LLVMContextImpl;
1339   friend class MDNode;
1340 
1341 public:
1342   enum DebugEmissionKind : unsigned {
1343     NoDebug = 0,
1344     FullDebug,
1345     LineTablesOnly,
1346     DebugDirectivesOnly,
1347     LastEmissionKind = DebugDirectivesOnly
1348   };
1349 
1350   enum class DebugNameTableKind : unsigned {
1351     Default = 0,
1352     GNU = 1,
1353     None = 2,
1354     LastDebugNameTableKind = None
1355   };
1356 
1357   static Optional<DebugEmissionKind> getEmissionKind(StringRef Str);
1358   static const char *emissionKindString(DebugEmissionKind EK);
1359   static Optional<DebugNameTableKind> getNameTableKind(StringRef Str);
1360   static const char *nameTableKindString(DebugNameTableKind PK);
1361 
1362 private:
1363   unsigned SourceLanguage;
1364   bool IsOptimized;
1365   unsigned RuntimeVersion;
1366   unsigned EmissionKind;
1367   uint64_t DWOId;
1368   bool SplitDebugInlining;
1369   bool DebugInfoForProfiling;
1370   unsigned NameTableKind;
1371   bool RangesBaseAddress;
1372 
1373   DICompileUnit(LLVMContext &C, StorageType Storage, unsigned SourceLanguage,
1374                 bool IsOptimized, unsigned RuntimeVersion,
1375                 unsigned EmissionKind, uint64_t DWOId, bool SplitDebugInlining,
1376                 bool DebugInfoForProfiling, unsigned NameTableKind,
1377                 bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
1378       : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
1379         SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
1380         RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind),
1381         DWOId(DWOId), SplitDebugInlining(SplitDebugInlining),
1382         DebugInfoForProfiling(DebugInfoForProfiling),
1383         NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) {
1384     assert(Storage != Uniqued);
1385   }
1386   ~DICompileUnit() = default;
1387 
1388   static DICompileUnit *
1389   getImpl(LLVMContext &Context, unsigned SourceLanguage, DIFile *File,
1390           StringRef Producer, bool IsOptimized, StringRef Flags,
1391           unsigned RuntimeVersion, StringRef SplitDebugFilename,
1392           unsigned EmissionKind, DICompositeTypeArray EnumTypes,
1393           DIScopeArray RetainedTypes,
1394           DIGlobalVariableExpressionArray GlobalVariables,
1395           DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1396           uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
1397           unsigned NameTableKind, bool RangesBaseAddress, StringRef SysRoot,
1398           StringRef SDK, StorageType Storage, bool ShouldCreate = true) {
1399     return getImpl(
1400         Context, SourceLanguage, File, getCanonicalMDString(Context, Producer),
1401         IsOptimized, getCanonicalMDString(Context, Flags), RuntimeVersion,
1402         getCanonicalMDString(Context, SplitDebugFilename), EmissionKind,
1403         EnumTypes.get(), RetainedTypes.get(), GlobalVariables.get(),
1404         ImportedEntities.get(), Macros.get(), DWOId, SplitDebugInlining,
1405         DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
1406         getCanonicalMDString(Context, SysRoot),
1407         getCanonicalMDString(Context, SDK), Storage, ShouldCreate);
1408   }
1409   static DICompileUnit *
1410   getImpl(LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
1411           MDString *Producer, bool IsOptimized, MDString *Flags,
1412           unsigned RuntimeVersion, MDString *SplitDebugFilename,
1413           unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
1414           Metadata *GlobalVariables, Metadata *ImportedEntities,
1415           Metadata *Macros, uint64_t DWOId, bool SplitDebugInlining,
1416           bool DebugInfoForProfiling, unsigned NameTableKind,
1417           bool RangesBaseAddress, MDString *SysRoot, MDString *SDK,
1418           StorageType Storage, bool ShouldCreate = true);
1419 
1420   TempDICompileUnit cloneImpl() const {
1421     return getTemporary(
1422         getContext(), getSourceLanguage(), getFile(), getProducer(),
1423         isOptimized(), getFlags(), getRuntimeVersion(), getSplitDebugFilename(),
1424         getEmissionKind(), getEnumTypes(), getRetainedTypes(),
1425         getGlobalVariables(), getImportedEntities(), getMacros(), DWOId,
1426         getSplitDebugInlining(), getDebugInfoForProfiling(), getNameTableKind(),
1427         getRangesBaseAddress(), getSysRoot(), getSDK());
1428   }
1429 
1430 public:
1431   static void get() = delete;
1432   static void getIfExists() = delete;
1433 
1434   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1435       DICompileUnit,
1436       (unsigned SourceLanguage, DIFile *File, StringRef Producer,
1437        bool IsOptimized, StringRef Flags, unsigned RuntimeVersion,
1438        StringRef SplitDebugFilename, DebugEmissionKind EmissionKind,
1439        DICompositeTypeArray EnumTypes, DIScopeArray RetainedTypes,
1440        DIGlobalVariableExpressionArray GlobalVariables,
1441        DIImportedEntityArray ImportedEntities, DIMacroNodeArray Macros,
1442        uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
1443        DebugNameTableKind NameTableKind, bool RangesBaseAddress,
1444        StringRef SysRoot, StringRef SDK),
1445       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1446        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1447        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1448        DebugInfoForProfiling, (unsigned)NameTableKind, RangesBaseAddress,
1449        SysRoot, SDK))
1450   DEFINE_MDNODE_GET_DISTINCT_TEMPORARY(
1451       DICompileUnit,
1452       (unsigned SourceLanguage, Metadata *File, MDString *Producer,
1453        bool IsOptimized, MDString *Flags, unsigned RuntimeVersion,
1454        MDString *SplitDebugFilename, unsigned EmissionKind, Metadata *EnumTypes,
1455        Metadata *RetainedTypes, Metadata *GlobalVariables,
1456        Metadata *ImportedEntities, Metadata *Macros, uint64_t DWOId,
1457        bool SplitDebugInlining, bool DebugInfoForProfiling,
1458        unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
1459        MDString *SDK),
1460       (SourceLanguage, File, Producer, IsOptimized, Flags, RuntimeVersion,
1461        SplitDebugFilename, EmissionKind, EnumTypes, RetainedTypes,
1462        GlobalVariables, ImportedEntities, Macros, DWOId, SplitDebugInlining,
1463        DebugInfoForProfiling, NameTableKind, RangesBaseAddress, SysRoot, SDK))
1464 
1465   TempDICompileUnit clone() const { return cloneImpl(); }
1466 
1467   unsigned getSourceLanguage() const { return SourceLanguage; }
1468   bool isOptimized() const { return IsOptimized; }
1469   unsigned getRuntimeVersion() const { return RuntimeVersion; }
1470   DebugEmissionKind getEmissionKind() const {
1471     return (DebugEmissionKind)EmissionKind;
1472   }
1473   bool isDebugDirectivesOnly() const {
1474     return EmissionKind == DebugDirectivesOnly;
1475   }
1476   bool getDebugInfoForProfiling() const { return DebugInfoForProfiling; }
1477   DebugNameTableKind getNameTableKind() const {
1478     return (DebugNameTableKind)NameTableKind;
1479   }
1480   bool getRangesBaseAddress() const { return RangesBaseAddress; }
1481   StringRef getProducer() const { return getStringOperand(1); }
1482   StringRef getFlags() const { return getStringOperand(2); }
1483   StringRef getSplitDebugFilename() const { return getStringOperand(3); }
1484   DICompositeTypeArray getEnumTypes() const {
1485     return cast_or_null<MDTuple>(getRawEnumTypes());
1486   }
1487   DIScopeArray getRetainedTypes() const {
1488     return cast_or_null<MDTuple>(getRawRetainedTypes());
1489   }
1490   DIGlobalVariableExpressionArray getGlobalVariables() const {
1491     return cast_or_null<MDTuple>(getRawGlobalVariables());
1492   }
1493   DIImportedEntityArray getImportedEntities() const {
1494     return cast_or_null<MDTuple>(getRawImportedEntities());
1495   }
1496   DIMacroNodeArray getMacros() const {
1497     return cast_or_null<MDTuple>(getRawMacros());
1498   }
1499   uint64_t getDWOId() const { return DWOId; }
1500   void setDWOId(uint64_t DwoId) { DWOId = DwoId; }
1501   bool getSplitDebugInlining() const { return SplitDebugInlining; }
1502   void setSplitDebugInlining(bool SplitDebugInlining) {
1503     this->SplitDebugInlining = SplitDebugInlining;
1504   }
1505   StringRef getSysRoot() const { return getStringOperand(9); }
1506   StringRef getSDK() const { return getStringOperand(10); }
1507 
1508   MDString *getRawProducer() const { return getOperandAs<MDString>(1); }
1509   MDString *getRawFlags() const { return getOperandAs<MDString>(2); }
1510   MDString *getRawSplitDebugFilename() const {
1511     return getOperandAs<MDString>(3);
1512   }
1513   Metadata *getRawEnumTypes() const { return getOperand(4); }
1514   Metadata *getRawRetainedTypes() const { return getOperand(5); }
1515   Metadata *getRawGlobalVariables() const { return getOperand(6); }
1516   Metadata *getRawImportedEntities() const { return getOperand(7); }
1517   Metadata *getRawMacros() const { return getOperand(8); }
1518   MDString *getRawSysRoot() const { return getOperandAs<MDString>(9); }
1519   MDString *getRawSDK() const { return getOperandAs<MDString>(10); }
1520 
1521   /// Replace arrays.
1522   ///
1523   /// If this \a isUniqued() and not \a isResolved(), it will be RAUW'ed and
1524   /// deleted on a uniquing collision.  In practice, uniquing collisions on \a
1525   /// DICompileUnit should be fairly rare.
1526   /// @{
1527   void replaceEnumTypes(DICompositeTypeArray N) {
1528     replaceOperandWith(4, N.get());
1529   }
1530   void replaceRetainedTypes(DITypeArray N) { replaceOperandWith(5, N.get()); }
1531   void replaceGlobalVariables(DIGlobalVariableExpressionArray N) {
1532     replaceOperandWith(6, N.get());
1533   }
1534   void replaceImportedEntities(DIImportedEntityArray N) {
1535     replaceOperandWith(7, N.get());
1536   }
1537   void replaceMacros(DIMacroNodeArray N) { replaceOperandWith(8, N.get()); }
1538   /// @}
1539 
1540   static bool classof(const Metadata *MD) {
1541     return MD->getMetadataID() == DICompileUnitKind;
1542   }
1543 };
1544 
1545 /// A scope for locals.
1546 ///
1547 /// A legal scope for lexical blocks, local variables, and debug info
1548 /// locations.  Subclasses are \a DISubprogram, \a DILexicalBlock, and \a
1549 /// DILexicalBlockFile.
1550 class DILocalScope : public DIScope {
1551 protected:
1552   DILocalScope(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Tag,
1553                ArrayRef<Metadata *> Ops)
1554       : DIScope(C, ID, Storage, Tag, Ops) {}
1555   ~DILocalScope() = default;
1556 
1557 public:
1558   /// Get the subprogram for this scope.
1559   ///
1560   /// Return this if it's an \a DISubprogram; otherwise, look up the scope
1561   /// chain.
1562   DISubprogram *getSubprogram() const;
1563 
1564   /// Get the first non DILexicalBlockFile scope of this scope.
1565   ///
1566   /// Return this if it's not a \a DILexicalBlockFIle; otherwise, look up the
1567   /// scope chain.
1568   DILocalScope *getNonLexicalBlockFileScope() const;
1569 
1570   static bool classof(const Metadata *MD) {
1571     return MD->getMetadataID() == DISubprogramKind ||
1572            MD->getMetadataID() == DILexicalBlockKind ||
1573            MD->getMetadataID() == DILexicalBlockFileKind;
1574   }
1575 };
1576 
1577 /// Debug location.
1578 ///
1579 /// A debug location in source code, used for debug info and otherwise.
1580 class DILocation : public MDNode {
1581   friend class LLVMContextImpl;
1582   friend class MDNode;
1583 
1584   DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
1585              unsigned Column, ArrayRef<Metadata *> MDs, bool ImplicitCode);
1586   ~DILocation() { dropAllReferences(); }
1587 
1588   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1589                              unsigned Column, Metadata *Scope,
1590                              Metadata *InlinedAt, bool ImplicitCode,
1591                              StorageType Storage, bool ShouldCreate = true);
1592   static DILocation *getImpl(LLVMContext &Context, unsigned Line,
1593                              unsigned Column, DILocalScope *Scope,
1594                              DILocation *InlinedAt, bool ImplicitCode,
1595                              StorageType Storage, bool ShouldCreate = true) {
1596     return getImpl(Context, Line, Column, static_cast<Metadata *>(Scope),
1597                    static_cast<Metadata *>(InlinedAt), ImplicitCode, Storage,
1598                    ShouldCreate);
1599   }
1600 
1601   TempDILocation cloneImpl() const {
1602     // Get the raw scope/inlinedAt since it is possible to invoke this on
1603     // a DILocation containing temporary metadata.
1604     return getTemporary(getContext(), getLine(), getColumn(), getRawScope(),
1605                         getRawInlinedAt(), isImplicitCode());
1606   }
1607 
1608 public:
1609   // Disallow replacing operands.
1610   void replaceOperandWith(unsigned I, Metadata *New) = delete;
1611 
1612   DEFINE_MDNODE_GET(DILocation,
1613                     (unsigned Line, unsigned Column, Metadata *Scope,
1614                      Metadata *InlinedAt = nullptr, bool ImplicitCode = false),
1615                     (Line, Column, Scope, InlinedAt, ImplicitCode))
1616   DEFINE_MDNODE_GET(DILocation,
1617                     (unsigned Line, unsigned Column, DILocalScope *Scope,
1618                      DILocation *InlinedAt = nullptr,
1619                      bool ImplicitCode = false),
1620                     (Line, Column, Scope, InlinedAt, ImplicitCode))
1621 
1622   /// Return a (temporary) clone of this.
1623   TempDILocation clone() const { return cloneImpl(); }
1624 
1625   unsigned getLine() const { return SubclassData32; }
1626   unsigned getColumn() const { return SubclassData16; }
1627   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
1628 
1629   DILocation *getInlinedAt() const {
1630     return cast_or_null<DILocation>(getRawInlinedAt());
1631   }
1632 
1633   /// Check if the location corresponds to an implicit code.
1634   /// When the ImplicitCode flag is true, it means that the Instruction
1635   /// with this DILocation has been added by the front-end but it hasn't been
1636   /// written explicitly by the user (e.g. cleanup stuff in C++ put on a closing
1637   /// bracket). It's useful for code coverage to not show a counter on "empty"
1638   /// lines.
1639   bool isImplicitCode() const { return SubclassData1; }
1640   void setImplicitCode(bool ImplicitCode) { SubclassData1 = ImplicitCode; }
1641 
1642   DIFile *getFile() const { return getScope()->getFile(); }
1643   StringRef getFilename() const { return getScope()->getFilename(); }
1644   StringRef getDirectory() const { return getScope()->getDirectory(); }
1645   Optional<StringRef> getSource() const { return getScope()->getSource(); }
1646 
1647   /// Get the scope where this is inlined.
1648   ///
1649   /// Walk through \a getInlinedAt() and return \a getScope() from the deepest
1650   /// location.
1651   DILocalScope *getInlinedAtScope() const {
1652     if (auto *IA = getInlinedAt())
1653       return IA->getInlinedAtScope();
1654     return getScope();
1655   }
1656 
1657   /// Get the DWARF discriminator.
1658   ///
1659   /// DWARF discriminators distinguish identical file locations between
1660   /// instructions that are on different basic blocks.
1661   ///
1662   /// There are 3 components stored in discriminator, from lower bits:
1663   ///
1664   /// Base discriminator: assigned by AddDiscriminators pass to identify IRs
1665   ///                     that are defined by the same source line, but
1666   ///                     different basic blocks.
1667   /// Duplication factor: assigned by optimizations that will scale down
1668   ///                     the execution frequency of the original IR.
1669   /// Copy Identifier: assigned by optimizations that clones the IR.
1670   ///                  Each copy of the IR will be assigned an identifier.
1671   ///
1672   /// Encoding:
1673   ///
1674   /// The above 3 components are encoded into a 32bit unsigned integer in
1675   /// order. If the lowest bit is 1, the current component is empty, and the
1676   /// next component will start in the next bit. Otherwise, the current
1677   /// component is non-empty, and its content starts in the next bit. The
1678   /// value of each components is either 5 bit or 12 bit: if the 7th bit
1679   /// is 0, the bit 2~6 (5 bits) are used to represent the component; if the
1680   /// 7th bit is 1, the bit 2~6 (5 bits) and 8~14 (7 bits) are combined to
1681   /// represent the component. Thus, the number of bits used for a component
1682   /// is either 0 (if it and all the next components are empty); 1 - if it is
1683   /// empty; 7 - if its value is up to and including 0x1f (lsb and msb are both
1684   /// 0); or 14, if its value is up to and including 0x1ff. Note that the last
1685   /// component is also capped at 0x1ff, even in the case when both first
1686   /// components are 0, and we'd technically have 29 bits available.
1687   ///
1688   /// For precise control over the data being encoded in the discriminator,
1689   /// use encodeDiscriminator/decodeDiscriminator.
1690 
1691   inline unsigned getDiscriminator() const;
1692 
1693   // For the regular discriminator, it stands for all empty components if all
1694   // the lowest 3 bits are non-zero and all higher 29 bits are unused(zero by
1695   // default). Here we fully leverage the higher 29 bits for pseudo probe use.
1696   // This is the format:
1697   // [2:0] - 0x7
1698   // [31:3] - pseudo probe fields guaranteed to be non-zero as a whole
1699   // So if the lower 3 bits is non-zero and the others has at least one
1700   // non-zero bit, it guarantees to be a pseudo probe discriminator
1701   inline static bool isPseudoProbeDiscriminator(unsigned Discriminator) {
1702     return ((Discriminator & 0x7) == 0x7) && (Discriminator & 0xFFFFFFF8);
1703   }
1704 
1705   /// Returns a new DILocation with updated \p Discriminator.
1706   inline const DILocation *cloneWithDiscriminator(unsigned Discriminator) const;
1707 
1708   /// Returns a new DILocation with updated base discriminator \p BD. Only the
1709   /// base discriminator is set in the new DILocation, the other encoded values
1710   /// are elided.
1711   /// If the discriminator cannot be encoded, the function returns None.
1712   inline Optional<const DILocation *>
1713   cloneWithBaseDiscriminator(unsigned BD) const;
1714 
1715   /// Returns the duplication factor stored in the discriminator, or 1 if no
1716   /// duplication factor (or 0) is encoded.
1717   inline unsigned getDuplicationFactor() const;
1718 
1719   /// Returns the copy identifier stored in the discriminator.
1720   inline unsigned getCopyIdentifier() const;
1721 
1722   /// Returns the base discriminator stored in the discriminator.
1723   inline unsigned getBaseDiscriminator() const;
1724 
1725   /// Returns a new DILocation with duplication factor \p DF * current
1726   /// duplication factor encoded in the discriminator. The current duplication
1727   /// factor is as defined by getDuplicationFactor().
1728   /// Returns None if encoding failed.
1729   inline Optional<const DILocation *>
1730   cloneByMultiplyingDuplicationFactor(unsigned DF) const;
1731 
1732   /// When two instructions are combined into a single instruction we also
1733   /// need to combine the original locations into a single location.
1734   ///
1735   /// When the locations are the same we can use either location. When they
1736   /// differ, we need a third location which is distinct from either. If they
1737   /// have the same file/line but have a different discriminator we could
1738   /// create a location with a new discriminator. If they are from different
1739   /// files/lines the location is ambiguous and can't be represented in a line
1740   /// entry. In this case, if \p GenerateLocation is true, we will set the
1741   /// merged debug location as line 0 of the nearest common scope where the two
1742   /// locations are inlined from.
1743   ///
1744   /// \p GenerateLocation: Whether the merged location can be generated when
1745   /// \p LocA and \p LocB differ.
1746   static const DILocation *getMergedLocation(const DILocation *LocA,
1747                                              const DILocation *LocB);
1748 
1749   /// Try to combine the vector of locations passed as input in a single one.
1750   /// This function applies getMergedLocation() repeatedly left-to-right.
1751   ///
1752   /// \p Locs: The locations to be merged.
1753   static const DILocation *
1754   getMergedLocations(ArrayRef<const DILocation *> Locs);
1755 
1756   /// Return the masked discriminator value for an input discrimnator value D
1757   /// (i.e. zero out the (B+1)-th and above bits for D (B is 0-base).
1758   // Example: an input of (0x1FF, 7) returns 0xFF.
1759   static unsigned getMaskedDiscriminator(unsigned D, unsigned B) {
1760     return (D & getN1Bits(B));
1761   }
1762 
1763   /// Return the bits used for base discriminators.
1764   static unsigned getBaseDiscriminatorBits() { return getBaseFSBitEnd(); }
1765 
1766   /// Returns the base discriminator for a given encoded discriminator \p D.
1767   static unsigned
1768   getBaseDiscriminatorFromDiscriminator(unsigned D,
1769                                         bool IsFSDiscriminator = false) {
1770     if (IsFSDiscriminator)
1771       return getMaskedDiscriminator(D, getBaseDiscriminatorBits());
1772     return getUnsignedFromPrefixEncoding(D);
1773   }
1774 
1775   /// Raw encoding of the discriminator. APIs such as cloneWithDuplicationFactor
1776   /// have certain special case behavior (e.g. treating empty duplication factor
1777   /// as the value '1').
1778   /// This API, in conjunction with cloneWithDiscriminator, may be used to
1779   /// encode the raw values provided.
1780   ///
1781   /// \p BD: base discriminator
1782   /// \p DF: duplication factor
1783   /// \p CI: copy index
1784   ///
1785   /// The return is None if the values cannot be encoded in 32 bits - for
1786   /// example, values for BD or DF larger than 12 bits. Otherwise, the return is
1787   /// the encoded value.
1788   static Optional<unsigned> encodeDiscriminator(unsigned BD, unsigned DF,
1789                                                 unsigned CI);
1790 
1791   /// Raw decoder for values in an encoded discriminator D.
1792   static void decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
1793                                   unsigned &CI);
1794 
1795   /// Returns the duplication factor for a given encoded discriminator \p D, or
1796   /// 1 if no value or 0 is encoded.
1797   static unsigned getDuplicationFactorFromDiscriminator(unsigned D) {
1798     if (EnableFSDiscriminator)
1799       return 1;
1800     D = getNextComponentInDiscriminator(D);
1801     unsigned Ret = getUnsignedFromPrefixEncoding(D);
1802     if (Ret == 0)
1803       return 1;
1804     return Ret;
1805   }
1806 
1807   /// Returns the copy identifier for a given encoded discriminator \p D.
1808   static unsigned getCopyIdentifierFromDiscriminator(unsigned D) {
1809     return getUnsignedFromPrefixEncoding(
1810         getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
1811   }
1812 
1813   Metadata *getRawScope() const { return getOperand(0); }
1814   Metadata *getRawInlinedAt() const {
1815     if (getNumOperands() == 2)
1816       return getOperand(1);
1817     return nullptr;
1818   }
1819 
1820   static bool classof(const Metadata *MD) {
1821     return MD->getMetadataID() == DILocationKind;
1822   }
1823 };
1824 
1825 /// Subprogram description.
1826 class DISubprogram : public DILocalScope {
1827   friend class LLVMContextImpl;
1828   friend class MDNode;
1829 
1830   unsigned Line;
1831   unsigned ScopeLine;
1832   unsigned VirtualIndex;
1833 
1834   /// In the MS ABI, the implicit 'this' parameter is adjusted in the prologue
1835   /// of method overrides from secondary bases by this amount. It may be
1836   /// negative.
1837   int ThisAdjustment;
1838 
1839 public:
1840   /// Debug info subprogram flags.
1841   enum DISPFlags : uint32_t {
1842 #define HANDLE_DISP_FLAG(ID, NAME) SPFlag##NAME = ID,
1843 #define DISP_FLAG_LARGEST_NEEDED
1844 #include "llvm/IR/DebugInfoFlags.def"
1845     SPFlagNonvirtual = SPFlagZero,
1846     SPFlagVirtuality = SPFlagVirtual | SPFlagPureVirtual,
1847     LLVM_MARK_AS_BITMASK_ENUM(SPFlagLargest)
1848   };
1849 
1850   static DISPFlags getFlag(StringRef Flag);
1851   static StringRef getFlagString(DISPFlags Flag);
1852 
1853   /// Split up a flags bitfield for easier printing.
1854   ///
1855   /// Split \c Flags into \c SplitFlags, a vector of its components.  Returns
1856   /// any remaining (unrecognized) bits.
1857   static DISPFlags splitFlags(DISPFlags Flags,
1858                               SmallVectorImpl<DISPFlags> &SplitFlags);
1859 
1860   // Helper for converting old bitfields to new flags word.
1861   static DISPFlags toSPFlags(bool IsLocalToUnit, bool IsDefinition,
1862                              bool IsOptimized,
1863                              unsigned Virtuality = SPFlagNonvirtual,
1864                              bool IsMainSubprogram = false) {
1865     // We're assuming virtuality is the low-order field.
1866     static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
1867                       int(SPFlagPureVirtual) ==
1868                           int(dwarf::DW_VIRTUALITY_pure_virtual),
1869                   "Virtuality constant mismatch");
1870     return static_cast<DISPFlags>(
1871         (Virtuality & SPFlagVirtuality) |
1872         (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
1873         (IsDefinition ? SPFlagDefinition : SPFlagZero) |
1874         (IsOptimized ? SPFlagOptimized : SPFlagZero) |
1875         (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
1876   }
1877 
1878 private:
1879   DIFlags Flags;
1880   DISPFlags SPFlags;
1881 
1882   DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1883                unsigned ScopeLine, unsigned VirtualIndex, int ThisAdjustment,
1884                DIFlags Flags, DISPFlags SPFlags, ArrayRef<Metadata *> Ops)
1885       : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram,
1886                      Ops),
1887         Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1888         ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
1889     static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1890   }
1891   ~DISubprogram() = default;
1892 
1893   static DISubprogram *
1894   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
1895           StringRef LinkageName, DIFile *File, unsigned Line,
1896           DISubroutineType *Type, unsigned ScopeLine, DIType *ContainingType,
1897           unsigned VirtualIndex, int ThisAdjustment, DIFlags Flags,
1898           DISPFlags SPFlags, DICompileUnit *Unit,
1899           DITemplateParameterArray TemplateParams, DISubprogram *Declaration,
1900           DINodeArray RetainedNodes, DITypeArray ThrownTypes,
1901           DINodeArray Annotations, StorageType Storage,
1902           bool ShouldCreate = true) {
1903     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
1904                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
1905                    ScopeLine, ContainingType, VirtualIndex, ThisAdjustment,
1906                    Flags, SPFlags, Unit, TemplateParams.get(), Declaration,
1907                    RetainedNodes.get(), ThrownTypes.get(), Annotations.get(),
1908                    Storage, ShouldCreate);
1909   }
1910   static DISubprogram *
1911   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1912           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1913           unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
1914           int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1915           Metadata *TemplateParams, Metadata *Declaration,
1916           Metadata *RetainedNodes, Metadata *ThrownTypes, Metadata *Annotations,
1917           StorageType Storage, bool ShouldCreate = true);
1918 
1919   TempDISubprogram cloneImpl() const {
1920     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
1921                         getFile(), getLine(), getType(), getScopeLine(),
1922                         getContainingType(), getVirtualIndex(),
1923                         getThisAdjustment(), getFlags(), getSPFlags(),
1924                         getUnit(), getTemplateParams(), getDeclaration(),
1925                         getRetainedNodes(), getThrownTypes(), getAnnotations());
1926   }
1927 
1928 public:
1929   DEFINE_MDNODE_GET(
1930       DISubprogram,
1931       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
1932        unsigned Line, DISubroutineType *Type, unsigned ScopeLine,
1933        DIType *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
1934        DIFlags Flags, DISPFlags SPFlags, DICompileUnit *Unit,
1935        DITemplateParameterArray TemplateParams = nullptr,
1936        DISubprogram *Declaration = nullptr, DINodeArray RetainedNodes = nullptr,
1937        DITypeArray ThrownTypes = nullptr, DINodeArray Annotations = nullptr),
1938       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1939        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1940        Declaration, RetainedNodes, ThrownTypes, Annotations))
1941 
1942   DEFINE_MDNODE_GET(
1943       DISubprogram,
1944       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
1945        unsigned Line, Metadata *Type, unsigned ScopeLine,
1946        Metadata *ContainingType, unsigned VirtualIndex, int ThisAdjustment,
1947        DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1948        Metadata *TemplateParams = nullptr, Metadata *Declaration = nullptr,
1949        Metadata *RetainedNodes = nullptr, Metadata *ThrownTypes = nullptr,
1950        Metadata *Annotations = nullptr),
1951       (Scope, Name, LinkageName, File, Line, Type, ScopeLine, ContainingType,
1952        VirtualIndex, ThisAdjustment, Flags, SPFlags, Unit, TemplateParams,
1953        Declaration, RetainedNodes, ThrownTypes, Annotations))
1954 
1955   TempDISubprogram clone() const { return cloneImpl(); }
1956 
1957   /// Returns a new temporary DISubprogram with updated Flags
1958   TempDISubprogram cloneWithFlags(DIFlags NewFlags) const {
1959     auto NewSP = clone();
1960     NewSP->Flags = NewFlags;
1961     return NewSP;
1962   }
1963 
1964 public:
1965   unsigned getLine() const { return Line; }
1966   unsigned getVirtuality() const { return getSPFlags() & SPFlagVirtuality; }
1967   unsigned getVirtualIndex() const { return VirtualIndex; }
1968   int getThisAdjustment() const { return ThisAdjustment; }
1969   unsigned getScopeLine() const { return ScopeLine; }
1970   void setScopeLine(unsigned L) {
1971     assert(isDistinct());
1972     ScopeLine = L;
1973   }
1974   DIFlags getFlags() const { return Flags; }
1975   DISPFlags getSPFlags() const { return SPFlags; }
1976   bool isLocalToUnit() const { return getSPFlags() & SPFlagLocalToUnit; }
1977   bool isDefinition() const { return getSPFlags() & SPFlagDefinition; }
1978   bool isOptimized() const { return getSPFlags() & SPFlagOptimized; }
1979   bool isMainSubprogram() const { return getSPFlags() & SPFlagMainSubprogram; }
1980 
1981   bool isArtificial() const { return getFlags() & FlagArtificial; }
1982   bool isPrivate() const {
1983     return (getFlags() & FlagAccessibility) == FlagPrivate;
1984   }
1985   bool isProtected() const {
1986     return (getFlags() & FlagAccessibility) == FlagProtected;
1987   }
1988   bool isPublic() const {
1989     return (getFlags() & FlagAccessibility) == FlagPublic;
1990   }
1991   bool isExplicit() const { return getFlags() & FlagExplicit; }
1992   bool isPrototyped() const { return getFlags() & FlagPrototyped; }
1993   bool areAllCallsDescribed() const {
1994     return getFlags() & FlagAllCallsDescribed;
1995   }
1996   bool isPure() const { return getSPFlags() & SPFlagPure; }
1997   bool isElemental() const { return getSPFlags() & SPFlagElemental; }
1998   bool isRecursive() const { return getSPFlags() & SPFlagRecursive; }
1999   bool isObjCDirect() const { return getSPFlags() & SPFlagObjCDirect; }
2000 
2001   /// Check if this is deleted member function.
2002   ///
2003   /// Return true if this subprogram is a C++11 special
2004   /// member function declared deleted.
2005   bool isDeleted() const { return getSPFlags() & SPFlagDeleted; }
2006 
2007   /// Check if this is reference-qualified.
2008   ///
2009   /// Return true if this subprogram is a C++11 reference-qualified non-static
2010   /// member function (void foo() &).
2011   bool isLValueReference() const { return getFlags() & FlagLValueReference; }
2012 
2013   /// Check if this is rvalue-reference-qualified.
2014   ///
2015   /// Return true if this subprogram is a C++11 rvalue-reference-qualified
2016   /// non-static member function (void foo() &&).
2017   bool isRValueReference() const { return getFlags() & FlagRValueReference; }
2018 
2019   /// Check if this is marked as noreturn.
2020   ///
2021   /// Return true if this subprogram is C++11 noreturn or C11 _Noreturn
2022   bool isNoReturn() const { return getFlags() & FlagNoReturn; }
2023 
2024   // Check if this routine is a compiler-generated thunk.
2025   //
2026   // Returns true if this subprogram is a thunk generated by the compiler.
2027   bool isThunk() const { return getFlags() & FlagThunk; }
2028 
2029   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2030 
2031   StringRef getName() const { return getStringOperand(2); }
2032   StringRef getLinkageName() const { return getStringOperand(3); }
2033   /// Only used by clients of CloneFunction, and only right after the cloning.
2034   void replaceLinkageName(MDString *LN) { replaceOperandWith(3, LN); }
2035 
2036   DISubroutineType *getType() const {
2037     return cast_or_null<DISubroutineType>(getRawType());
2038   }
2039   DIType *getContainingType() const {
2040     return cast_or_null<DIType>(getRawContainingType());
2041   }
2042 
2043   DICompileUnit *getUnit() const {
2044     return cast_or_null<DICompileUnit>(getRawUnit());
2045   }
2046   void replaceUnit(DICompileUnit *CU) { replaceOperandWith(5, CU); }
2047   DITemplateParameterArray getTemplateParams() const {
2048     return cast_or_null<MDTuple>(getRawTemplateParams());
2049   }
2050   DISubprogram *getDeclaration() const {
2051     return cast_or_null<DISubprogram>(getRawDeclaration());
2052   }
2053   DINodeArray getRetainedNodes() const {
2054     return cast_or_null<MDTuple>(getRawRetainedNodes());
2055   }
2056   DITypeArray getThrownTypes() const {
2057     return cast_or_null<MDTuple>(getRawThrownTypes());
2058   }
2059   DINodeArray getAnnotations() const {
2060     return cast_or_null<MDTuple>(getRawAnnotations());
2061   }
2062 
2063   Metadata *getRawScope() const { return getOperand(1); }
2064   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2065   MDString *getRawLinkageName() const { return getOperandAs<MDString>(3); }
2066   Metadata *getRawType() const { return getOperand(4); }
2067   Metadata *getRawUnit() const { return getOperand(5); }
2068   Metadata *getRawDeclaration() const { return getOperand(6); }
2069   Metadata *getRawRetainedNodes() const { return getOperand(7); }
2070   Metadata *getRawContainingType() const {
2071     return getNumOperands() > 8 ? getOperandAs<Metadata>(8) : nullptr;
2072   }
2073   Metadata *getRawTemplateParams() const {
2074     return getNumOperands() > 9 ? getOperandAs<Metadata>(9) : nullptr;
2075   }
2076   Metadata *getRawThrownTypes() const {
2077     return getNumOperands() > 10 ? getOperandAs<Metadata>(10) : nullptr;
2078   }
2079   Metadata *getRawAnnotations() const {
2080     return getNumOperands() > 11 ? getOperandAs<Metadata>(11) : nullptr;
2081   }
2082 
2083   void replaceRawLinkageName(MDString *LinkageName) {
2084     replaceOperandWith(3, LinkageName);
2085   }
2086 
2087   /// Check if this subprogram describes the given function.
2088   ///
2089   /// FIXME: Should this be looking through bitcasts?
2090   bool describes(const Function *F) const;
2091 
2092   static bool classof(const Metadata *MD) {
2093     return MD->getMetadataID() == DISubprogramKind;
2094   }
2095 };
2096 
2097 class DILexicalBlockBase : public DILocalScope {
2098 protected:
2099   DILexicalBlockBase(LLVMContext &C, unsigned ID, StorageType Storage,
2100                      ArrayRef<Metadata *> Ops)
2101       : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
2102   ~DILexicalBlockBase() = default;
2103 
2104 public:
2105   DILocalScope *getScope() const { return cast<DILocalScope>(getRawScope()); }
2106 
2107   Metadata *getRawScope() const { return getOperand(1); }
2108 
2109   static bool classof(const Metadata *MD) {
2110     return MD->getMetadataID() == DILexicalBlockKind ||
2111            MD->getMetadataID() == DILexicalBlockFileKind;
2112   }
2113 };
2114 
2115 class DILexicalBlock : public DILexicalBlockBase {
2116   friend class LLVMContextImpl;
2117   friend class MDNode;
2118 
2119   unsigned Line;
2120   uint16_t Column;
2121 
2122   DILexicalBlock(LLVMContext &C, StorageType Storage, unsigned Line,
2123                  unsigned Column, ArrayRef<Metadata *> Ops)
2124       : DILexicalBlockBase(C, DILexicalBlockKind, Storage, Ops), Line(Line),
2125         Column(Column) {
2126     assert(Column < (1u << 16) && "Expected 16-bit column");
2127   }
2128   ~DILexicalBlock() = default;
2129 
2130   static DILexicalBlock *getImpl(LLVMContext &Context, DILocalScope *Scope,
2131                                  DIFile *File, unsigned Line, unsigned Column,
2132                                  StorageType Storage,
2133                                  bool ShouldCreate = true) {
2134     return getImpl(Context, static_cast<Metadata *>(Scope),
2135                    static_cast<Metadata *>(File), Line, Column, Storage,
2136                    ShouldCreate);
2137   }
2138 
2139   static DILexicalBlock *getImpl(LLVMContext &Context, Metadata *Scope,
2140                                  Metadata *File, unsigned Line, unsigned Column,
2141                                  StorageType Storage, bool ShouldCreate = true);
2142 
2143   TempDILexicalBlock cloneImpl() const {
2144     return getTemporary(getContext(), getScope(), getFile(), getLine(),
2145                         getColumn());
2146   }
2147 
2148 public:
2149   DEFINE_MDNODE_GET(DILexicalBlock,
2150                     (DILocalScope * Scope, DIFile *File, unsigned Line,
2151                      unsigned Column),
2152                     (Scope, File, Line, Column))
2153   DEFINE_MDNODE_GET(DILexicalBlock,
2154                     (Metadata * Scope, Metadata *File, unsigned Line,
2155                      unsigned Column),
2156                     (Scope, File, Line, Column))
2157 
2158   TempDILexicalBlock clone() const { return cloneImpl(); }
2159 
2160   unsigned getLine() const { return Line; }
2161   unsigned getColumn() const { return Column; }
2162 
2163   static bool classof(const Metadata *MD) {
2164     return MD->getMetadataID() == DILexicalBlockKind;
2165   }
2166 };
2167 
2168 class DILexicalBlockFile : public DILexicalBlockBase {
2169   friend class LLVMContextImpl;
2170   friend class MDNode;
2171 
2172   unsigned Discriminator;
2173 
2174   DILexicalBlockFile(LLVMContext &C, StorageType Storage,
2175                      unsigned Discriminator, ArrayRef<Metadata *> Ops)
2176       : DILexicalBlockBase(C, DILexicalBlockFileKind, Storage, Ops),
2177         Discriminator(Discriminator) {}
2178   ~DILexicalBlockFile() = default;
2179 
2180   static DILexicalBlockFile *getImpl(LLVMContext &Context, DILocalScope *Scope,
2181                                      DIFile *File, unsigned Discriminator,
2182                                      StorageType Storage,
2183                                      bool ShouldCreate = true) {
2184     return getImpl(Context, static_cast<Metadata *>(Scope),
2185                    static_cast<Metadata *>(File), Discriminator, Storage,
2186                    ShouldCreate);
2187   }
2188 
2189   static DILexicalBlockFile *getImpl(LLVMContext &Context, Metadata *Scope,
2190                                      Metadata *File, unsigned Discriminator,
2191                                      StorageType Storage,
2192                                      bool ShouldCreate = true);
2193 
2194   TempDILexicalBlockFile cloneImpl() const {
2195     return getTemporary(getContext(), getScope(), getFile(),
2196                         getDiscriminator());
2197   }
2198 
2199 public:
2200   DEFINE_MDNODE_GET(DILexicalBlockFile,
2201                     (DILocalScope * Scope, DIFile *File,
2202                      unsigned Discriminator),
2203                     (Scope, File, Discriminator))
2204   DEFINE_MDNODE_GET(DILexicalBlockFile,
2205                     (Metadata * Scope, Metadata *File, unsigned Discriminator),
2206                     (Scope, File, Discriminator))
2207 
2208   TempDILexicalBlockFile clone() const { return cloneImpl(); }
2209   unsigned getDiscriminator() const { return Discriminator; }
2210 
2211   static bool classof(const Metadata *MD) {
2212     return MD->getMetadataID() == DILexicalBlockFileKind;
2213   }
2214 };
2215 
2216 unsigned DILocation::getDiscriminator() const {
2217   if (auto *F = dyn_cast<DILexicalBlockFile>(getScope()))
2218     return F->getDiscriminator();
2219   return 0;
2220 }
2221 
2222 const DILocation *
2223 DILocation::cloneWithDiscriminator(unsigned Discriminator) const {
2224   DIScope *Scope = getScope();
2225   // Skip all parent DILexicalBlockFile that already have a discriminator
2226   // assigned. We do not want to have nested DILexicalBlockFiles that have
2227   // mutliple discriminators because only the leaf DILexicalBlockFile's
2228   // dominator will be used.
2229   for (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope);
2230        LBF && LBF->getDiscriminator() != 0;
2231        LBF = dyn_cast<DILexicalBlockFile>(Scope))
2232     Scope = LBF->getScope();
2233   DILexicalBlockFile *NewScope =
2234       DILexicalBlockFile::get(getContext(), Scope, getFile(), Discriminator);
2235   return DILocation::get(getContext(), getLine(), getColumn(), NewScope,
2236                          getInlinedAt());
2237 }
2238 
2239 unsigned DILocation::getBaseDiscriminator() const {
2240   return getBaseDiscriminatorFromDiscriminator(getDiscriminator(),
2241                                                EnableFSDiscriminator);
2242 }
2243 
2244 unsigned DILocation::getDuplicationFactor() const {
2245   return getDuplicationFactorFromDiscriminator(getDiscriminator());
2246 }
2247 
2248 unsigned DILocation::getCopyIdentifier() const {
2249   return getCopyIdentifierFromDiscriminator(getDiscriminator());
2250 }
2251 
2252 Optional<const DILocation *>
2253 DILocation::cloneWithBaseDiscriminator(unsigned D) const {
2254   unsigned BD, DF, CI;
2255 
2256   if (EnableFSDiscriminator) {
2257     BD = getBaseDiscriminator();
2258     if (D == BD)
2259       return this;
2260     return cloneWithDiscriminator(D);
2261   }
2262 
2263   decodeDiscriminator(getDiscriminator(), BD, DF, CI);
2264   if (D == BD)
2265     return this;
2266   if (Optional<unsigned> Encoded = encodeDiscriminator(D, DF, CI))
2267     return cloneWithDiscriminator(*Encoded);
2268   return None;
2269 }
2270 
2271 Optional<const DILocation *>
2272 DILocation::cloneByMultiplyingDuplicationFactor(unsigned DF) const {
2273   assert(!EnableFSDiscriminator && "FSDiscriminator should not call this.");
2274 
2275   DF *= getDuplicationFactor();
2276   if (DF <= 1)
2277     return this;
2278 
2279   unsigned BD = getBaseDiscriminator();
2280   unsigned CI = getCopyIdentifier();
2281   if (Optional<unsigned> D = encodeDiscriminator(BD, DF, CI))
2282     return cloneWithDiscriminator(*D);
2283   return None;
2284 }
2285 
2286 class DINamespace : public DIScope {
2287   friend class LLVMContextImpl;
2288   friend class MDNode;
2289 
2290   unsigned ExportSymbols : 1;
2291 
2292   DINamespace(LLVMContext &Context, StorageType Storage, bool ExportSymbols,
2293               ArrayRef<Metadata *> Ops)
2294       : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace,
2295                 Ops),
2296         ExportSymbols(ExportSymbols) {}
2297   ~DINamespace() = default;
2298 
2299   static DINamespace *getImpl(LLVMContext &Context, DIScope *Scope,
2300                               StringRef Name, bool ExportSymbols,
2301                               StorageType Storage, bool ShouldCreate = true) {
2302     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2303                    ExportSymbols, Storage, ShouldCreate);
2304   }
2305   static DINamespace *getImpl(LLVMContext &Context, Metadata *Scope,
2306                               MDString *Name, bool ExportSymbols,
2307                               StorageType Storage, bool ShouldCreate = true);
2308 
2309   TempDINamespace cloneImpl() const {
2310     return getTemporary(getContext(), getScope(), getName(),
2311                         getExportSymbols());
2312   }
2313 
2314 public:
2315   DEFINE_MDNODE_GET(DINamespace,
2316                     (DIScope * Scope, StringRef Name, bool ExportSymbols),
2317                     (Scope, Name, ExportSymbols))
2318   DEFINE_MDNODE_GET(DINamespace,
2319                     (Metadata * Scope, MDString *Name, bool ExportSymbols),
2320                     (Scope, Name, ExportSymbols))
2321 
2322   TempDINamespace clone() const { return cloneImpl(); }
2323 
2324   bool getExportSymbols() const { return ExportSymbols; }
2325   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2326   StringRef getName() const { return getStringOperand(2); }
2327 
2328   Metadata *getRawScope() const { return getOperand(1); }
2329   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2330 
2331   static bool classof(const Metadata *MD) {
2332     return MD->getMetadataID() == DINamespaceKind;
2333   }
2334 };
2335 
2336 /// Represents a module in the programming language, for example, a Clang
2337 /// module, or a Fortran module.
2338 class DIModule : public DIScope {
2339   friend class LLVMContextImpl;
2340   friend class MDNode;
2341   unsigned LineNo;
2342   bool IsDecl;
2343 
2344   DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
2345            bool IsDecl, ArrayRef<Metadata *> Ops)
2346       : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops),
2347         LineNo(LineNo), IsDecl(IsDecl) {}
2348   ~DIModule() = default;
2349 
2350   static DIModule *getImpl(LLVMContext &Context, DIFile *File, DIScope *Scope,
2351                            StringRef Name, StringRef ConfigurationMacros,
2352                            StringRef IncludePath, StringRef APINotesFile,
2353                            unsigned LineNo, bool IsDecl, StorageType Storage,
2354                            bool ShouldCreate = true) {
2355     return getImpl(Context, File, Scope, getCanonicalMDString(Context, Name),
2356                    getCanonicalMDString(Context, ConfigurationMacros),
2357                    getCanonicalMDString(Context, IncludePath),
2358                    getCanonicalMDString(Context, APINotesFile), LineNo, IsDecl,
2359                    Storage, ShouldCreate);
2360   }
2361   static DIModule *getImpl(LLVMContext &Context, Metadata *File,
2362                            Metadata *Scope, MDString *Name,
2363                            MDString *ConfigurationMacros, MDString *IncludePath,
2364                            MDString *APINotesFile, unsigned LineNo, bool IsDecl,
2365                            StorageType Storage, bool ShouldCreate = true);
2366 
2367   TempDIModule cloneImpl() const {
2368     return getTemporary(getContext(), getFile(), getScope(), getName(),
2369                         getConfigurationMacros(), getIncludePath(),
2370                         getAPINotesFile(), getLineNo(), getIsDecl());
2371   }
2372 
2373 public:
2374   DEFINE_MDNODE_GET(DIModule,
2375                     (DIFile * File, DIScope *Scope, StringRef Name,
2376                      StringRef ConfigurationMacros, StringRef IncludePath,
2377                      StringRef APINotesFile, unsigned LineNo,
2378                      bool IsDecl = false),
2379                     (File, Scope, Name, ConfigurationMacros, IncludePath,
2380                      APINotesFile, LineNo, IsDecl))
2381   DEFINE_MDNODE_GET(DIModule,
2382                     (Metadata * File, Metadata *Scope, MDString *Name,
2383                      MDString *ConfigurationMacros, MDString *IncludePath,
2384                      MDString *APINotesFile, unsigned LineNo,
2385                      bool IsDecl = false),
2386                     (File, Scope, Name, ConfigurationMacros, IncludePath,
2387                      APINotesFile, LineNo, IsDecl))
2388 
2389   TempDIModule clone() const { return cloneImpl(); }
2390 
2391   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2392   StringRef getName() const { return getStringOperand(2); }
2393   StringRef getConfigurationMacros() const { return getStringOperand(3); }
2394   StringRef getIncludePath() const { return getStringOperand(4); }
2395   StringRef getAPINotesFile() const { return getStringOperand(5); }
2396   unsigned getLineNo() const { return LineNo; }
2397   bool getIsDecl() const { return IsDecl; }
2398 
2399   Metadata *getRawScope() const { return getOperand(1); }
2400   MDString *getRawName() const { return getOperandAs<MDString>(2); }
2401   MDString *getRawConfigurationMacros() const {
2402     return getOperandAs<MDString>(3);
2403   }
2404   MDString *getRawIncludePath() const { return getOperandAs<MDString>(4); }
2405   MDString *getRawAPINotesFile() const { return getOperandAs<MDString>(5); }
2406 
2407   static bool classof(const Metadata *MD) {
2408     return MD->getMetadataID() == DIModuleKind;
2409   }
2410 };
2411 
2412 /// Base class for template parameters.
2413 class DITemplateParameter : public DINode {
2414 protected:
2415   bool IsDefault;
2416 
2417   DITemplateParameter(LLVMContext &Context, unsigned ID, StorageType Storage,
2418                       unsigned Tag, bool IsDefault, ArrayRef<Metadata *> Ops)
2419       : DINode(Context, ID, Storage, Tag, Ops), IsDefault(IsDefault) {}
2420   ~DITemplateParameter() = default;
2421 
2422 public:
2423   StringRef getName() const { return getStringOperand(0); }
2424   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
2425 
2426   MDString *getRawName() const { return getOperandAs<MDString>(0); }
2427   Metadata *getRawType() const { return getOperand(1); }
2428   bool isDefault() const { return IsDefault; }
2429 
2430   static bool classof(const Metadata *MD) {
2431     return MD->getMetadataID() == DITemplateTypeParameterKind ||
2432            MD->getMetadataID() == DITemplateValueParameterKind;
2433   }
2434 };
2435 
2436 class DITemplateTypeParameter : public DITemplateParameter {
2437   friend class LLVMContextImpl;
2438   friend class MDNode;
2439 
2440   DITemplateTypeParameter(LLVMContext &Context, StorageType Storage,
2441                           bool IsDefault, ArrayRef<Metadata *> Ops)
2442       : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
2443                             dwarf::DW_TAG_template_type_parameter, IsDefault,
2444                             Ops) {}
2445   ~DITemplateTypeParameter() = default;
2446 
2447   static DITemplateTypeParameter *getImpl(LLVMContext &Context, StringRef Name,
2448                                           DIType *Type, bool IsDefault,
2449                                           StorageType Storage,
2450                                           bool ShouldCreate = true) {
2451     return getImpl(Context, getCanonicalMDString(Context, Name), Type,
2452                    IsDefault, Storage, ShouldCreate);
2453   }
2454   static DITemplateTypeParameter *getImpl(LLVMContext &Context, MDString *Name,
2455                                           Metadata *Type, bool IsDefault,
2456                                           StorageType Storage,
2457                                           bool ShouldCreate = true);
2458 
2459   TempDITemplateTypeParameter cloneImpl() const {
2460     return getTemporary(getContext(), getName(), getType(), isDefault());
2461   }
2462 
2463 public:
2464   DEFINE_MDNODE_GET(DITemplateTypeParameter,
2465                     (StringRef Name, DIType *Type, bool IsDefault),
2466                     (Name, Type, IsDefault))
2467   DEFINE_MDNODE_GET(DITemplateTypeParameter,
2468                     (MDString * Name, Metadata *Type, bool IsDefault),
2469                     (Name, Type, IsDefault))
2470 
2471   TempDITemplateTypeParameter clone() const { return cloneImpl(); }
2472 
2473   static bool classof(const Metadata *MD) {
2474     return MD->getMetadataID() == DITemplateTypeParameterKind;
2475   }
2476 };
2477 
2478 class DITemplateValueParameter : public DITemplateParameter {
2479   friend class LLVMContextImpl;
2480   friend class MDNode;
2481 
2482   DITemplateValueParameter(LLVMContext &Context, StorageType Storage,
2483                            unsigned Tag, bool IsDefault,
2484                            ArrayRef<Metadata *> Ops)
2485       : DITemplateParameter(Context, DITemplateValueParameterKind, Storage, Tag,
2486                             IsDefault, Ops) {}
2487   ~DITemplateValueParameter() = default;
2488 
2489   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2490                                            StringRef Name, DIType *Type,
2491                                            bool IsDefault, Metadata *Value,
2492                                            StorageType Storage,
2493                                            bool ShouldCreate = true) {
2494     return getImpl(Context, Tag, getCanonicalMDString(Context, Name), Type,
2495                    IsDefault, Value, Storage, ShouldCreate);
2496   }
2497   static DITemplateValueParameter *getImpl(LLVMContext &Context, unsigned Tag,
2498                                            MDString *Name, Metadata *Type,
2499                                            bool IsDefault, Metadata *Value,
2500                                            StorageType Storage,
2501                                            bool ShouldCreate = true);
2502 
2503   TempDITemplateValueParameter cloneImpl() const {
2504     return getTemporary(getContext(), getTag(), getName(), getType(),
2505                         isDefault(), getValue());
2506   }
2507 
2508 public:
2509   DEFINE_MDNODE_GET(DITemplateValueParameter,
2510                     (unsigned Tag, StringRef Name, DIType *Type, bool IsDefault,
2511                      Metadata *Value),
2512                     (Tag, Name, Type, IsDefault, Value))
2513   DEFINE_MDNODE_GET(DITemplateValueParameter,
2514                     (unsigned Tag, MDString *Name, Metadata *Type,
2515                      bool IsDefault, Metadata *Value),
2516                     (Tag, Name, Type, IsDefault, Value))
2517 
2518   TempDITemplateValueParameter clone() const { return cloneImpl(); }
2519 
2520   Metadata *getValue() const { return getOperand(2); }
2521 
2522   static bool classof(const Metadata *MD) {
2523     return MD->getMetadataID() == DITemplateValueParameterKind;
2524   }
2525 };
2526 
2527 /// Base class for variables.
2528 class DIVariable : public DINode {
2529   unsigned Line;
2530   uint32_t AlignInBits;
2531 
2532 protected:
2533   DIVariable(LLVMContext &C, unsigned ID, StorageType Storage, unsigned Line,
2534              ArrayRef<Metadata *> Ops, uint32_t AlignInBits = 0)
2535       : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
2536         AlignInBits(AlignInBits) {}
2537   ~DIVariable() = default;
2538 
2539 public:
2540   unsigned getLine() const { return Line; }
2541   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
2542   StringRef getName() const { return getStringOperand(1); }
2543   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
2544   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
2545   uint32_t getAlignInBits() const { return AlignInBits; }
2546   uint32_t getAlignInBytes() const { return getAlignInBits() / CHAR_BIT; }
2547   /// Determines the size of the variable's type.
2548   Optional<uint64_t> getSizeInBits() const;
2549 
2550   /// Return the signedness of this variable's type, or None if this type is
2551   /// neither signed nor unsigned.
2552   Optional<DIBasicType::Signedness> getSignedness() const {
2553     if (auto *BT = dyn_cast<DIBasicType>(getType()))
2554       return BT->getSignedness();
2555     return None;
2556   }
2557 
2558   StringRef getFilename() const {
2559     if (auto *F = getFile())
2560       return F->getFilename();
2561     return "";
2562   }
2563 
2564   StringRef getDirectory() const {
2565     if (auto *F = getFile())
2566       return F->getDirectory();
2567     return "";
2568   }
2569 
2570   Optional<StringRef> getSource() const {
2571     if (auto *F = getFile())
2572       return F->getSource();
2573     return None;
2574   }
2575 
2576   Metadata *getRawScope() const { return getOperand(0); }
2577   MDString *getRawName() const { return getOperandAs<MDString>(1); }
2578   Metadata *getRawFile() const { return getOperand(2); }
2579   Metadata *getRawType() const { return getOperand(3); }
2580 
2581   static bool classof(const Metadata *MD) {
2582     return MD->getMetadataID() == DILocalVariableKind ||
2583            MD->getMetadataID() == DIGlobalVariableKind;
2584   }
2585 };
2586 
2587 /// DWARF expression.
2588 ///
2589 /// This is (almost) a DWARF expression that modifies the location of a
2590 /// variable, or the location of a single piece of a variable, or (when using
2591 /// DW_OP_stack_value) is the constant variable value.
2592 ///
2593 /// TODO: Co-allocate the expression elements.
2594 /// TODO: Separate from MDNode, or otherwise drop Distinct and Temporary
2595 /// storage types.
2596 class DIExpression : public MDNode {
2597   friend class LLVMContextImpl;
2598   friend class MDNode;
2599 
2600   std::vector<uint64_t> Elements;
2601 
2602   DIExpression(LLVMContext &C, StorageType Storage, ArrayRef<uint64_t> Elements)
2603       : MDNode(C, DIExpressionKind, Storage, None),
2604         Elements(Elements.begin(), Elements.end()) {}
2605   ~DIExpression() = default;
2606 
2607   static DIExpression *getImpl(LLVMContext &Context,
2608                                ArrayRef<uint64_t> Elements, StorageType Storage,
2609                                bool ShouldCreate = true);
2610 
2611   TempDIExpression cloneImpl() const {
2612     return getTemporary(getContext(), getElements());
2613   }
2614 
2615 public:
2616   DEFINE_MDNODE_GET(DIExpression, (ArrayRef<uint64_t> Elements), (Elements))
2617 
2618   TempDIExpression clone() const { return cloneImpl(); }
2619 
2620   ArrayRef<uint64_t> getElements() const { return Elements; }
2621 
2622   unsigned getNumElements() const { return Elements.size(); }
2623 
2624   uint64_t getElement(unsigned I) const {
2625     assert(I < Elements.size() && "Index out of range");
2626     return Elements[I];
2627   }
2628 
2629   enum SignedOrUnsignedConstant { SignedConstant, UnsignedConstant };
2630   /// Determine whether this represents a constant value, if so
2631   // return it's sign information.
2632   llvm::Optional<SignedOrUnsignedConstant> isConstant() const;
2633 
2634   /// Return the number of unique location operands referred to (via
2635   /// DW_OP_LLVM_arg) in this expression; this is not necessarily the number of
2636   /// instances of DW_OP_LLVM_arg within the expression.
2637   /// For example, for the expression:
2638   ///   (DW_OP_LLVM_arg 0, DW_OP_LLVM_arg 1, DW_OP_plus,
2639   ///    DW_OP_LLVM_arg 0, DW_OP_mul)
2640   /// This function would return 2, as there are two unique location operands
2641   /// (0 and 1).
2642   uint64_t getNumLocationOperands() const;
2643 
2644   using element_iterator = ArrayRef<uint64_t>::iterator;
2645 
2646   element_iterator elements_begin() const { return getElements().begin(); }
2647   element_iterator elements_end() const { return getElements().end(); }
2648 
2649   /// A lightweight wrapper around an expression operand.
2650   ///
2651   /// TODO: Store arguments directly and change \a DIExpression to store a
2652   /// range of these.
2653   class ExprOperand {
2654     const uint64_t *Op = nullptr;
2655 
2656   public:
2657     ExprOperand() = default;
2658     explicit ExprOperand(const uint64_t *Op) : Op(Op) {}
2659 
2660     const uint64_t *get() const { return Op; }
2661 
2662     /// Get the operand code.
2663     uint64_t getOp() const { return *Op; }
2664 
2665     /// Get an argument to the operand.
2666     ///
2667     /// Never returns the operand itself.
2668     uint64_t getArg(unsigned I) const { return Op[I + 1]; }
2669 
2670     unsigned getNumArgs() const { return getSize() - 1; }
2671 
2672     /// Return the size of the operand.
2673     ///
2674     /// Return the number of elements in the operand (1 + args).
2675     unsigned getSize() const;
2676 
2677     /// Append the elements of this operand to \p V.
2678     void appendToVector(SmallVectorImpl<uint64_t> &V) const {
2679       V.append(get(), get() + getSize());
2680     }
2681   };
2682 
2683   /// An iterator for expression operands.
2684   class expr_op_iterator {
2685     ExprOperand Op;
2686 
2687   public:
2688     using iterator_category = std::input_iterator_tag;
2689     using value_type = ExprOperand;
2690     using difference_type = std::ptrdiff_t;
2691     using pointer = value_type *;
2692     using reference = value_type &;
2693 
2694     expr_op_iterator() = default;
2695     explicit expr_op_iterator(element_iterator I) : Op(I) {}
2696 
2697     element_iterator getBase() const { return Op.get(); }
2698     const ExprOperand &operator*() const { return Op; }
2699     const ExprOperand *operator->() const { return &Op; }
2700 
2701     expr_op_iterator &operator++() {
2702       increment();
2703       return *this;
2704     }
2705     expr_op_iterator operator++(int) {
2706       expr_op_iterator T(*this);
2707       increment();
2708       return T;
2709     }
2710 
2711     /// Get the next iterator.
2712     ///
2713     /// \a std::next() doesn't work because this is technically an
2714     /// input_iterator, but it's a perfectly valid operation.  This is an
2715     /// accessor to provide the same functionality.
2716     expr_op_iterator getNext() const { return ++expr_op_iterator(*this); }
2717 
2718     bool operator==(const expr_op_iterator &X) const {
2719       return getBase() == X.getBase();
2720     }
2721     bool operator!=(const expr_op_iterator &X) const {
2722       return getBase() != X.getBase();
2723     }
2724 
2725   private:
2726     void increment() { Op = ExprOperand(getBase() + Op.getSize()); }
2727   };
2728 
2729   /// Visit the elements via ExprOperand wrappers.
2730   ///
2731   /// These range iterators visit elements through \a ExprOperand wrappers.
2732   /// This is not guaranteed to be a valid range unless \a isValid() gives \c
2733   /// true.
2734   ///
2735   /// \pre \a isValid() gives \c true.
2736   /// @{
2737   expr_op_iterator expr_op_begin() const {
2738     return expr_op_iterator(elements_begin());
2739   }
2740   expr_op_iterator expr_op_end() const {
2741     return expr_op_iterator(elements_end());
2742   }
2743   iterator_range<expr_op_iterator> expr_ops() const {
2744     return {expr_op_begin(), expr_op_end()};
2745   }
2746   /// @}
2747 
2748   bool isValid() const;
2749 
2750   static bool classof(const Metadata *MD) {
2751     return MD->getMetadataID() == DIExpressionKind;
2752   }
2753 
2754   /// Return whether the first element a DW_OP_deref.
2755   bool startsWithDeref() const {
2756     return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
2757   }
2758 
2759   /// Holds the characteristics of one fragment of a larger variable.
2760   struct FragmentInfo {
2761     uint64_t SizeInBits;
2762     uint64_t OffsetInBits;
2763   };
2764 
2765   /// Retrieve the details of this fragment expression.
2766   static Optional<FragmentInfo> getFragmentInfo(expr_op_iterator Start,
2767                                                 expr_op_iterator End);
2768 
2769   /// Retrieve the details of this fragment expression.
2770   Optional<FragmentInfo> getFragmentInfo() const {
2771     return getFragmentInfo(expr_op_begin(), expr_op_end());
2772   }
2773 
2774   /// Return whether this is a piece of an aggregate variable.
2775   bool isFragment() const { return getFragmentInfo().hasValue(); }
2776 
2777   /// Return whether this is an implicit location description.
2778   bool isImplicit() const;
2779 
2780   /// Return whether the location is computed on the expression stack, meaning
2781   /// it cannot be a simple register location.
2782   bool isComplex() const;
2783 
2784   /// Append \p Ops with operations to apply the \p Offset.
2785   static void appendOffset(SmallVectorImpl<uint64_t> &Ops, int64_t Offset);
2786 
2787   /// If this is a constant offset, extract it. If there is no expression,
2788   /// return true with an offset of zero.
2789   bool extractIfOffset(int64_t &Offset) const;
2790 
2791   /// Returns true iff this DIExpression contains at least one instance of
2792   /// `DW_OP_LLVM_arg, n` for all n in [0, N).
2793   bool hasAllLocationOps(unsigned N) const;
2794 
2795   /// Checks if the last 4 elements of the expression are DW_OP_constu <DWARF
2796   /// Address Space> DW_OP_swap DW_OP_xderef and extracts the <DWARF Address
2797   /// Space>.
2798   static const DIExpression *extractAddressClass(const DIExpression *Expr,
2799                                                  unsigned &AddrClass);
2800 
2801   /// Used for DIExpression::prepend.
2802   enum PrependOps : uint8_t {
2803     ApplyOffset = 0,
2804     DerefBefore = 1 << 0,
2805     DerefAfter = 1 << 1,
2806     StackValue = 1 << 2,
2807     EntryValue = 1 << 3
2808   };
2809 
2810   /// Prepend \p DIExpr with a deref and offset operation and optionally turn it
2811   /// into a stack value or/and an entry value.
2812   static DIExpression *prepend(const DIExpression *Expr, uint8_t Flags,
2813                                int64_t Offset = 0);
2814 
2815   /// Prepend \p DIExpr with the given opcodes and optionally turn it into a
2816   /// stack value.
2817   static DIExpression *prependOpcodes(const DIExpression *Expr,
2818                                       SmallVectorImpl<uint64_t> &Ops,
2819                                       bool StackValue = false,
2820                                       bool EntryValue = false);
2821 
2822   /// Append the opcodes \p Ops to \p DIExpr. Unlike \ref appendToStack, the
2823   /// returned expression is a stack value only if \p DIExpr is a stack value.
2824   /// If \p DIExpr describes a fragment, the returned expression will describe
2825   /// the same fragment.
2826   static DIExpression *append(const DIExpression *Expr, ArrayRef<uint64_t> Ops);
2827 
2828   /// Convert \p DIExpr into a stack value if it isn't one already by appending
2829   /// DW_OP_deref if needed, and appending \p Ops to the resulting expression.
2830   /// If \p DIExpr describes a fragment, the returned expression will describe
2831   /// the same fragment.
2832   static DIExpression *appendToStack(const DIExpression *Expr,
2833                                      ArrayRef<uint64_t> Ops);
2834 
2835   /// Create a copy of \p Expr by appending the given list of \p Ops to each
2836   /// instance of the operand `DW_OP_LLVM_arg, \p ArgNo`. This is used to
2837   /// modify a specific location used by \p Expr, such as when salvaging that
2838   /// location.
2839   static DIExpression *appendOpsToArg(const DIExpression *Expr,
2840                                       ArrayRef<uint64_t> Ops, unsigned ArgNo,
2841                                       bool StackValue = false);
2842 
2843   /// Create a copy of \p Expr with each instance of
2844   /// `DW_OP_LLVM_arg, \p OldArg` replaced with `DW_OP_LLVM_arg, \p NewArg`,
2845   /// and each instance of `DW_OP_LLVM_arg, Arg` with `DW_OP_LLVM_arg, Arg - 1`
2846   /// for all Arg > \p OldArg.
2847   /// This is used when replacing one of the operands of a debug value list
2848   /// with another operand in the same list and deleting the old operand.
2849   static DIExpression *replaceArg(const DIExpression *Expr, uint64_t OldArg,
2850                                   uint64_t NewArg);
2851 
2852   /// Create a DIExpression to describe one part of an aggregate variable that
2853   /// is fragmented across multiple Values. The DW_OP_LLVM_fragment operation
2854   /// will be appended to the elements of \c Expr. If \c Expr already contains
2855   /// a \c DW_OP_LLVM_fragment \c OffsetInBits is interpreted as an offset
2856   /// into the existing fragment.
2857   ///
2858   /// \param OffsetInBits Offset of the piece in bits.
2859   /// \param SizeInBits   Size of the piece in bits.
2860   /// \return             Creating a fragment expression may fail if \c Expr
2861   ///                     contains arithmetic operations that would be
2862   ///                     truncated.
2863   static Optional<DIExpression *>
2864   createFragmentExpression(const DIExpression *Expr, unsigned OffsetInBits,
2865                            unsigned SizeInBits);
2866 
2867   /// Determine the relative position of the fragments passed in.
2868   /// Returns -1 if this is entirely before Other, 0 if this and Other overlap,
2869   /// 1 if this is entirely after Other.
2870   static int fragmentCmp(const FragmentInfo &A, const FragmentInfo &B) {
2871     uint64_t l1 = A.OffsetInBits;
2872     uint64_t l2 = B.OffsetInBits;
2873     uint64_t r1 = l1 + A.SizeInBits;
2874     uint64_t r2 = l2 + B.SizeInBits;
2875     if (r1 <= l2)
2876       return -1;
2877     else if (r2 <= l1)
2878       return 1;
2879     else
2880       return 0;
2881   }
2882 
2883   using ExtOps = std::array<uint64_t, 6>;
2884 
2885   /// Returns the ops for a zero- or sign-extension in a DIExpression.
2886   static ExtOps getExtOps(unsigned FromSize, unsigned ToSize, bool Signed);
2887 
2888   /// Append a zero- or sign-extension to \p Expr. Converts the expression to a
2889   /// stack value if it isn't one already.
2890   static DIExpression *appendExt(const DIExpression *Expr, unsigned FromSize,
2891                                  unsigned ToSize, bool Signed);
2892 
2893   /// Check if fragments overlap between a pair of FragmentInfos.
2894   static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B) {
2895     return fragmentCmp(A, B) == 0;
2896   }
2897 
2898   /// Determine the relative position of the fragments described by this
2899   /// DIExpression and \p Other. Calls static fragmentCmp implementation.
2900   int fragmentCmp(const DIExpression *Other) const {
2901     auto Fragment1 = *getFragmentInfo();
2902     auto Fragment2 = *Other->getFragmentInfo();
2903     return fragmentCmp(Fragment1, Fragment2);
2904   }
2905 
2906   /// Check if fragments overlap between this DIExpression and \p Other.
2907   bool fragmentsOverlap(const DIExpression *Other) const {
2908     if (!isFragment() || !Other->isFragment())
2909       return true;
2910     return fragmentCmp(Other) == 0;
2911   }
2912 
2913   /// Check if the expression consists of exactly one entry value operand.
2914   /// (This is the only configuration of entry values that is supported.)
2915   bool isEntryValue() const {
2916     return getNumElements() > 0 &&
2917            getElement(0) == dwarf::DW_OP_LLVM_entry_value;
2918   }
2919 
2920   /// Try to shorten an expression with an initial constant operand.
2921   /// Returns a new expression and constant on success, or the original
2922   /// expression and constant on failure.
2923   std::pair<DIExpression *, const ConstantInt *>
2924   constantFold(const ConstantInt *CI);
2925 };
2926 
2927 inline bool operator==(const DIExpression::FragmentInfo &A,
2928                        const DIExpression::FragmentInfo &B) {
2929   return std::tie(A.SizeInBits, A.OffsetInBits) ==
2930          std::tie(B.SizeInBits, B.OffsetInBits);
2931 }
2932 
2933 inline bool operator<(const DIExpression::FragmentInfo &A,
2934                       const DIExpression::FragmentInfo &B) {
2935   return std::tie(A.SizeInBits, A.OffsetInBits) <
2936          std::tie(B.SizeInBits, B.OffsetInBits);
2937 }
2938 
2939 template <> struct DenseMapInfo<DIExpression::FragmentInfo> {
2940   using FragInfo = DIExpression::FragmentInfo;
2941   static const uint64_t MaxVal = std::numeric_limits<uint64_t>::max();
2942 
2943   static inline FragInfo getEmptyKey() { return {MaxVal, MaxVal}; }
2944 
2945   static inline FragInfo getTombstoneKey() { return {MaxVal - 1, MaxVal - 1}; }
2946 
2947   static unsigned getHashValue(const FragInfo &Frag) {
2948     return (Frag.SizeInBits & 0xffff) << 16 | (Frag.OffsetInBits & 0xffff);
2949   }
2950 
2951   static bool isEqual(const FragInfo &A, const FragInfo &B) { return A == B; }
2952 };
2953 
2954 /// Global variables.
2955 ///
2956 /// TODO: Remove DisplayName.  It's always equal to Name.
2957 class DIGlobalVariable : public DIVariable {
2958   friend class LLVMContextImpl;
2959   friend class MDNode;
2960 
2961   bool IsLocalToUnit;
2962   bool IsDefinition;
2963 
2964   DIGlobalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
2965                    bool IsLocalToUnit, bool IsDefinition, uint32_t AlignInBits,
2966                    ArrayRef<Metadata *> Ops)
2967       : DIVariable(C, DIGlobalVariableKind, Storage, Line, Ops, AlignInBits),
2968         IsLocalToUnit(IsLocalToUnit), IsDefinition(IsDefinition) {}
2969   ~DIGlobalVariable() = default;
2970 
2971   static DIGlobalVariable *
2972   getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
2973           StringRef LinkageName, DIFile *File, unsigned Line, DIType *Type,
2974           bool IsLocalToUnit, bool IsDefinition,
2975           DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
2976           uint32_t AlignInBits, DINodeArray Annotations, StorageType Storage,
2977           bool ShouldCreate = true) {
2978     return getImpl(Context, Scope, getCanonicalMDString(Context, Name),
2979                    getCanonicalMDString(Context, LinkageName), File, Line, Type,
2980                    IsLocalToUnit, IsDefinition, StaticDataMemberDeclaration,
2981                    cast_or_null<Metadata>(TemplateParams), AlignInBits,
2982                    Annotations.get(), Storage, ShouldCreate);
2983   }
2984   static DIGlobalVariable *
2985   getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
2986           MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
2987           bool IsLocalToUnit, bool IsDefinition,
2988           Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
2989           uint32_t AlignInBits, Metadata *Annotations, StorageType Storage,
2990           bool ShouldCreate = true);
2991 
2992   TempDIGlobalVariable cloneImpl() const {
2993     return getTemporary(getContext(), getScope(), getName(), getLinkageName(),
2994                         getFile(), getLine(), getType(), isLocalToUnit(),
2995                         isDefinition(), getStaticDataMemberDeclaration(),
2996                         getTemplateParams(), getAlignInBits(),
2997                         getAnnotations());
2998   }
2999 
3000 public:
3001   DEFINE_MDNODE_GET(
3002       DIGlobalVariable,
3003       (DIScope * Scope, StringRef Name, StringRef LinkageName, DIFile *File,
3004        unsigned Line, DIType *Type, bool IsLocalToUnit, bool IsDefinition,
3005        DIDerivedType *StaticDataMemberDeclaration, MDTuple *TemplateParams,
3006        uint32_t AlignInBits, DINodeArray Annotations),
3007       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3008        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations))
3009   DEFINE_MDNODE_GET(
3010       DIGlobalVariable,
3011       (Metadata * Scope, MDString *Name, MDString *LinkageName, Metadata *File,
3012        unsigned Line, Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
3013        Metadata *StaticDataMemberDeclaration, Metadata *TemplateParams,
3014        uint32_t AlignInBits, Metadata *Annotations),
3015       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
3016        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations))
3017 
3018   TempDIGlobalVariable clone() const { return cloneImpl(); }
3019 
3020   bool isLocalToUnit() const { return IsLocalToUnit; }
3021   bool isDefinition() const { return IsDefinition; }
3022   StringRef getDisplayName() const { return getStringOperand(4); }
3023   StringRef getLinkageName() const { return getStringOperand(5); }
3024   DIDerivedType *getStaticDataMemberDeclaration() const {
3025     return cast_or_null<DIDerivedType>(getRawStaticDataMemberDeclaration());
3026   }
3027   DINodeArray getAnnotations() const {
3028     return cast_or_null<MDTuple>(getRawAnnotations());
3029   }
3030 
3031   MDString *getRawLinkageName() const { return getOperandAs<MDString>(5); }
3032   Metadata *getRawStaticDataMemberDeclaration() const { return getOperand(6); }
3033   Metadata *getRawTemplateParams() const { return getOperand(7); }
3034   MDTuple *getTemplateParams() const { return getOperandAs<MDTuple>(7); }
3035   Metadata *getRawAnnotations() const { return getOperand(8); }
3036 
3037   static bool classof(const Metadata *MD) {
3038     return MD->getMetadataID() == DIGlobalVariableKind;
3039   }
3040 };
3041 
3042 class DICommonBlock : public DIScope {
3043   unsigned LineNo;
3044 
3045   friend class LLVMContextImpl;
3046   friend class MDNode;
3047 
3048   DICommonBlock(LLVMContext &Context, StorageType Storage, unsigned LineNo,
3049                 ArrayRef<Metadata *> Ops)
3050       : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
3051                 Ops),
3052         LineNo(LineNo) {}
3053 
3054   static DICommonBlock *getImpl(LLVMContext &Context, DIScope *Scope,
3055                                 DIGlobalVariable *Decl, StringRef Name,
3056                                 DIFile *File, unsigned LineNo,
3057                                 StorageType Storage, bool ShouldCreate = true) {
3058     return getImpl(Context, Scope, Decl, getCanonicalMDString(Context, Name),
3059                    File, LineNo, Storage, ShouldCreate);
3060   }
3061   static DICommonBlock *getImpl(LLVMContext &Context, Metadata *Scope,
3062                                 Metadata *Decl, MDString *Name, Metadata *File,
3063                                 unsigned LineNo, StorageType Storage,
3064                                 bool ShouldCreate = true);
3065 
3066   TempDICommonBlock cloneImpl() const {
3067     return getTemporary(getContext(), getScope(), getDecl(), getName(),
3068                         getFile(), getLineNo());
3069   }
3070 
3071 public:
3072   DEFINE_MDNODE_GET(DICommonBlock,
3073                     (DIScope * Scope, DIGlobalVariable *Decl, StringRef Name,
3074                      DIFile *File, unsigned LineNo),
3075                     (Scope, Decl, Name, File, LineNo))
3076   DEFINE_MDNODE_GET(DICommonBlock,
3077                     (Metadata * Scope, Metadata *Decl, MDString *Name,
3078                      Metadata *File, unsigned LineNo),
3079                     (Scope, Decl, Name, File, LineNo))
3080 
3081   TempDICommonBlock clone() const { return cloneImpl(); }
3082 
3083   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
3084   DIGlobalVariable *getDecl() const {
3085     return cast_or_null<DIGlobalVariable>(getRawDecl());
3086   }
3087   StringRef getName() const { return getStringOperand(2); }
3088   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3089   unsigned getLineNo() const { return LineNo; }
3090 
3091   Metadata *getRawScope() const { return getOperand(0); }
3092   Metadata *getRawDecl() const { return getOperand(1); }
3093   MDString *getRawName() const { return getOperandAs<MDString>(2); }
3094   Metadata *getRawFile() const { return getOperand(3); }
3095 
3096   static bool classof(const Metadata *MD) {
3097     return MD->getMetadataID() == DICommonBlockKind;
3098   }
3099 };
3100 
3101 /// Local variable.
3102 ///
3103 /// TODO: Split up flags.
3104 class DILocalVariable : public DIVariable {
3105   friend class LLVMContextImpl;
3106   friend class MDNode;
3107 
3108   unsigned Arg : 16;
3109   DIFlags Flags;
3110 
3111   DILocalVariable(LLVMContext &C, StorageType Storage, unsigned Line,
3112                   unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
3113                   ArrayRef<Metadata *> Ops)
3114       : DIVariable(C, DILocalVariableKind, Storage, Line, Ops, AlignInBits),
3115         Arg(Arg), Flags(Flags) {
3116     assert(Arg < (1 << 16) && "DILocalVariable: Arg out of range");
3117   }
3118   ~DILocalVariable() = default;
3119 
3120   static DILocalVariable *getImpl(LLVMContext &Context, DIScope *Scope,
3121                                   StringRef Name, DIFile *File, unsigned Line,
3122                                   DIType *Type, unsigned Arg, DIFlags Flags,
3123                                   uint32_t AlignInBits, DINodeArray Annotations,
3124                                   StorageType Storage,
3125                                   bool ShouldCreate = true) {
3126     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
3127                    Line, Type, Arg, Flags, AlignInBits, Annotations.get(),
3128                    Storage, ShouldCreate);
3129   }
3130   static DILocalVariable *getImpl(LLVMContext &Context, Metadata *Scope,
3131                                   MDString *Name, Metadata *File, unsigned Line,
3132                                   Metadata *Type, unsigned Arg, DIFlags Flags,
3133                                   uint32_t AlignInBits, Metadata *Annotations,
3134                                   StorageType Storage,
3135                                   bool ShouldCreate = true);
3136 
3137   TempDILocalVariable cloneImpl() const {
3138     return getTemporary(getContext(), getScope(), getName(), getFile(),
3139                         getLine(), getType(), getArg(), getFlags(),
3140                         getAlignInBits(), getAnnotations());
3141   }
3142 
3143 public:
3144   DEFINE_MDNODE_GET(DILocalVariable,
3145                     (DILocalScope * Scope, StringRef Name, DIFile *File,
3146                      unsigned Line, DIType *Type, unsigned Arg, DIFlags Flags,
3147                      uint32_t AlignInBits, DINodeArray Annotations),
3148                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits,
3149                      Annotations))
3150   DEFINE_MDNODE_GET(DILocalVariable,
3151                     (Metadata * Scope, MDString *Name, Metadata *File,
3152                      unsigned Line, Metadata *Type, unsigned Arg, DIFlags Flags,
3153                      uint32_t AlignInBits, Metadata *Annotations),
3154                     (Scope, Name, File, Line, Type, Arg, Flags, AlignInBits,
3155                      Annotations))
3156 
3157   TempDILocalVariable clone() const { return cloneImpl(); }
3158 
3159   /// Get the local scope for this variable.
3160   ///
3161   /// Variables must be defined in a local scope.
3162   DILocalScope *getScope() const {
3163     return cast<DILocalScope>(DIVariable::getScope());
3164   }
3165 
3166   bool isParameter() const { return Arg; }
3167   unsigned getArg() const { return Arg; }
3168   DIFlags getFlags() const { return Flags; }
3169 
3170   DINodeArray getAnnotations() const {
3171     return cast_or_null<MDTuple>(getRawAnnotations());
3172   }
3173   Metadata *getRawAnnotations() const { return getOperand(4); }
3174 
3175   bool isArtificial() const { return getFlags() & FlagArtificial; }
3176   bool isObjectPointer() const { return getFlags() & FlagObjectPointer; }
3177 
3178   /// Check that a location is valid for this variable.
3179   ///
3180   /// Check that \c DL exists, is in the same subprogram, and has the same
3181   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
3182   /// to a \a DbgInfoIntrinsic.)
3183   bool isValidLocationForIntrinsic(const DILocation *DL) const {
3184     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
3185   }
3186 
3187   static bool classof(const Metadata *MD) {
3188     return MD->getMetadataID() == DILocalVariableKind;
3189   }
3190 };
3191 
3192 /// Label.
3193 ///
3194 class DILabel : public DINode {
3195   friend class LLVMContextImpl;
3196   friend class MDNode;
3197 
3198   unsigned Line;
3199 
3200   DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
3201           ArrayRef<Metadata *> Ops)
3202       : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {}
3203   ~DILabel() = default;
3204 
3205   static DILabel *getImpl(LLVMContext &Context, DIScope *Scope, StringRef Name,
3206                           DIFile *File, unsigned Line, StorageType Storage,
3207                           bool ShouldCreate = true) {
3208     return getImpl(Context, Scope, getCanonicalMDString(Context, Name), File,
3209                    Line, Storage, ShouldCreate);
3210   }
3211   static DILabel *getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
3212                           Metadata *File, unsigned Line, StorageType Storage,
3213                           bool ShouldCreate = true);
3214 
3215   TempDILabel cloneImpl() const {
3216     return getTemporary(getContext(), getScope(), getName(), getFile(),
3217                         getLine());
3218   }
3219 
3220 public:
3221   DEFINE_MDNODE_GET(DILabel,
3222                     (DILocalScope * Scope, StringRef Name, DIFile *File,
3223                      unsigned Line),
3224                     (Scope, Name, File, Line))
3225   DEFINE_MDNODE_GET(DILabel,
3226                     (Metadata * Scope, MDString *Name, Metadata *File,
3227                      unsigned Line),
3228                     (Scope, Name, File, Line))
3229 
3230   TempDILabel clone() const { return cloneImpl(); }
3231 
3232   /// Get the local scope for this label.
3233   ///
3234   /// Labels must be defined in a local scope.
3235   DILocalScope *getScope() const {
3236     return cast_or_null<DILocalScope>(getRawScope());
3237   }
3238   unsigned getLine() const { return Line; }
3239   StringRef getName() const { return getStringOperand(1); }
3240   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3241 
3242   Metadata *getRawScope() const { return getOperand(0); }
3243   MDString *getRawName() const { return getOperandAs<MDString>(1); }
3244   Metadata *getRawFile() const { return getOperand(2); }
3245 
3246   /// Check that a location is valid for this label.
3247   ///
3248   /// Check that \c DL exists, is in the same subprogram, and has the same
3249   /// inlined-at location as \c this.  (Otherwise, it's not a valid attachment
3250   /// to a \a DbgInfoIntrinsic.)
3251   bool isValidLocationForIntrinsic(const DILocation *DL) const {
3252     return DL && getScope()->getSubprogram() == DL->getScope()->getSubprogram();
3253   }
3254 
3255   static bool classof(const Metadata *MD) {
3256     return MD->getMetadataID() == DILabelKind;
3257   }
3258 };
3259 
3260 class DIObjCProperty : public DINode {
3261   friend class LLVMContextImpl;
3262   friend class MDNode;
3263 
3264   unsigned Line;
3265   unsigned Attributes;
3266 
3267   DIObjCProperty(LLVMContext &C, StorageType Storage, unsigned Line,
3268                  unsigned Attributes, ArrayRef<Metadata *> Ops)
3269       : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property,
3270                Ops),
3271         Line(Line), Attributes(Attributes) {}
3272   ~DIObjCProperty() = default;
3273 
3274   static DIObjCProperty *
3275   getImpl(LLVMContext &Context, StringRef Name, DIFile *File, unsigned Line,
3276           StringRef GetterName, StringRef SetterName, unsigned Attributes,
3277           DIType *Type, StorageType Storage, bool ShouldCreate = true) {
3278     return getImpl(Context, getCanonicalMDString(Context, Name), File, Line,
3279                    getCanonicalMDString(Context, GetterName),
3280                    getCanonicalMDString(Context, SetterName), Attributes, Type,
3281                    Storage, ShouldCreate);
3282   }
3283   static DIObjCProperty *getImpl(LLVMContext &Context, MDString *Name,
3284                                  Metadata *File, unsigned Line,
3285                                  MDString *GetterName, MDString *SetterName,
3286                                  unsigned Attributes, Metadata *Type,
3287                                  StorageType Storage, bool ShouldCreate = true);
3288 
3289   TempDIObjCProperty cloneImpl() const {
3290     return getTemporary(getContext(), getName(), getFile(), getLine(),
3291                         getGetterName(), getSetterName(), getAttributes(),
3292                         getType());
3293   }
3294 
3295 public:
3296   DEFINE_MDNODE_GET(DIObjCProperty,
3297                     (StringRef Name, DIFile *File, unsigned Line,
3298                      StringRef GetterName, StringRef SetterName,
3299                      unsigned Attributes, DIType *Type),
3300                     (Name, File, Line, GetterName, SetterName, Attributes,
3301                      Type))
3302   DEFINE_MDNODE_GET(DIObjCProperty,
3303                     (MDString * Name, Metadata *File, unsigned Line,
3304                      MDString *GetterName, MDString *SetterName,
3305                      unsigned Attributes, Metadata *Type),
3306                     (Name, File, Line, GetterName, SetterName, Attributes,
3307                      Type))
3308 
3309   TempDIObjCProperty clone() const { return cloneImpl(); }
3310 
3311   unsigned getLine() const { return Line; }
3312   unsigned getAttributes() const { return Attributes; }
3313   StringRef getName() const { return getStringOperand(0); }
3314   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3315   StringRef getGetterName() const { return getStringOperand(2); }
3316   StringRef getSetterName() const { return getStringOperand(3); }
3317   DIType *getType() const { return cast_or_null<DIType>(getRawType()); }
3318 
3319   StringRef getFilename() const {
3320     if (auto *F = getFile())
3321       return F->getFilename();
3322     return "";
3323   }
3324 
3325   StringRef getDirectory() const {
3326     if (auto *F = getFile())
3327       return F->getDirectory();
3328     return "";
3329   }
3330 
3331   MDString *getRawName() const { return getOperandAs<MDString>(0); }
3332   Metadata *getRawFile() const { return getOperand(1); }
3333   MDString *getRawGetterName() const { return getOperandAs<MDString>(2); }
3334   MDString *getRawSetterName() const { return getOperandAs<MDString>(3); }
3335   Metadata *getRawType() const { return getOperand(4); }
3336 
3337   static bool classof(const Metadata *MD) {
3338     return MD->getMetadataID() == DIObjCPropertyKind;
3339   }
3340 };
3341 
3342 /// An imported module (C++ using directive or similar).
3343 class DIImportedEntity : public DINode {
3344   friend class LLVMContextImpl;
3345   friend class MDNode;
3346 
3347   unsigned Line;
3348 
3349   DIImportedEntity(LLVMContext &C, StorageType Storage, unsigned Tag,
3350                    unsigned Line, ArrayRef<Metadata *> Ops)
3351       : DINode(C, DIImportedEntityKind, Storage, Tag, Ops), Line(Line) {}
3352   ~DIImportedEntity() = default;
3353 
3354   static DIImportedEntity *getImpl(LLVMContext &Context, unsigned Tag,
3355                                    DIScope *Scope, DINode *Entity, DIFile *File,
3356                                    unsigned Line, StringRef Name,
3357                                    DINodeArray Elements, StorageType Storage,
3358                                    bool ShouldCreate = true) {
3359     return getImpl(Context, Tag, Scope, Entity, File, Line,
3360                    getCanonicalMDString(Context, Name), Elements.get(), Storage,
3361                    ShouldCreate);
3362   }
3363   static DIImportedEntity *
3364   getImpl(LLVMContext &Context, unsigned Tag, Metadata *Scope, Metadata *Entity,
3365           Metadata *File, unsigned Line, MDString *Name, Metadata *Elements,
3366           StorageType Storage, bool ShouldCreate = true);
3367 
3368   TempDIImportedEntity cloneImpl() const {
3369     return getTemporary(getContext(), getTag(), getScope(), getEntity(),
3370                         getFile(), getLine(), getName(), getElements());
3371   }
3372 
3373 public:
3374   DEFINE_MDNODE_GET(DIImportedEntity,
3375                     (unsigned Tag, DIScope *Scope, DINode *Entity, DIFile *File,
3376                      unsigned Line, StringRef Name = "",
3377                      DINodeArray Elements = nullptr),
3378                     (Tag, Scope, Entity, File, Line, Name, Elements))
3379   DEFINE_MDNODE_GET(DIImportedEntity,
3380                     (unsigned Tag, Metadata *Scope, Metadata *Entity,
3381                      Metadata *File, unsigned Line, MDString *Name,
3382                      Metadata *Elements = nullptr),
3383                     (Tag, Scope, Entity, File, Line, Name, Elements))
3384 
3385   TempDIImportedEntity clone() const { return cloneImpl(); }
3386 
3387   unsigned getLine() const { return Line; }
3388   DIScope *getScope() const { return cast_or_null<DIScope>(getRawScope()); }
3389   DINode *getEntity() const { return cast_or_null<DINode>(getRawEntity()); }
3390   StringRef getName() const { return getStringOperand(2); }
3391   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3392   DINodeArray getElements() const {
3393     return cast_or_null<MDTuple>(getRawElements());
3394   }
3395 
3396   Metadata *getRawScope() const { return getOperand(0); }
3397   Metadata *getRawEntity() const { return getOperand(1); }
3398   MDString *getRawName() const { return getOperandAs<MDString>(2); }
3399   Metadata *getRawFile() const { return getOperand(3); }
3400   Metadata *getRawElements() const { return getOperand(4); }
3401 
3402   static bool classof(const Metadata *MD) {
3403     return MD->getMetadataID() == DIImportedEntityKind;
3404   }
3405 };
3406 
3407 /// A pair of DIGlobalVariable and DIExpression.
3408 class DIGlobalVariableExpression : public MDNode {
3409   friend class LLVMContextImpl;
3410   friend class MDNode;
3411 
3412   DIGlobalVariableExpression(LLVMContext &C, StorageType Storage,
3413                              ArrayRef<Metadata *> Ops)
3414       : MDNode(C, DIGlobalVariableExpressionKind, Storage, Ops) {}
3415   ~DIGlobalVariableExpression() = default;
3416 
3417   static DIGlobalVariableExpression *
3418   getImpl(LLVMContext &Context, Metadata *Variable, Metadata *Expression,
3419           StorageType Storage, bool ShouldCreate = true);
3420 
3421   TempDIGlobalVariableExpression cloneImpl() const {
3422     return getTemporary(getContext(), getVariable(), getExpression());
3423   }
3424 
3425 public:
3426   DEFINE_MDNODE_GET(DIGlobalVariableExpression,
3427                     (Metadata * Variable, Metadata *Expression),
3428                     (Variable, Expression))
3429 
3430   TempDIGlobalVariableExpression clone() const { return cloneImpl(); }
3431 
3432   Metadata *getRawVariable() const { return getOperand(0); }
3433 
3434   DIGlobalVariable *getVariable() const {
3435     return cast_or_null<DIGlobalVariable>(getRawVariable());
3436   }
3437 
3438   Metadata *getRawExpression() const { return getOperand(1); }
3439 
3440   DIExpression *getExpression() const {
3441     return cast<DIExpression>(getRawExpression());
3442   }
3443 
3444   static bool classof(const Metadata *MD) {
3445     return MD->getMetadataID() == DIGlobalVariableExpressionKind;
3446   }
3447 };
3448 
3449 /// Macro Info DWARF-like metadata node.
3450 ///
3451 /// A metadata node with a DWARF macro info (i.e., a constant named
3452 /// \c DW_MACINFO_*, defined in llvm/BinaryFormat/Dwarf.h).  Called \a
3453 /// DIMacroNode
3454 /// because it's potentially used for non-DWARF output.
3455 class DIMacroNode : public MDNode {
3456   friend class LLVMContextImpl;
3457   friend class MDNode;
3458 
3459 protected:
3460   DIMacroNode(LLVMContext &C, unsigned ID, StorageType Storage, unsigned MIType,
3461               ArrayRef<Metadata *> Ops1, ArrayRef<Metadata *> Ops2 = None)
3462       : MDNode(C, ID, Storage, Ops1, Ops2) {
3463     assert(MIType < 1u << 16);
3464     SubclassData16 = MIType;
3465   }
3466   ~DIMacroNode() = default;
3467 
3468   template <class Ty> Ty *getOperandAs(unsigned I) const {
3469     return cast_or_null<Ty>(getOperand(I));
3470   }
3471 
3472   StringRef getStringOperand(unsigned I) const {
3473     if (auto *S = getOperandAs<MDString>(I))
3474       return S->getString();
3475     return StringRef();
3476   }
3477 
3478   static MDString *getCanonicalMDString(LLVMContext &Context, StringRef S) {
3479     if (S.empty())
3480       return nullptr;
3481     return MDString::get(Context, S);
3482   }
3483 
3484 public:
3485   unsigned getMacinfoType() const { return SubclassData16; }
3486 
3487   static bool classof(const Metadata *MD) {
3488     switch (MD->getMetadataID()) {
3489     default:
3490       return false;
3491     case DIMacroKind:
3492     case DIMacroFileKind:
3493       return true;
3494     }
3495   }
3496 };
3497 
3498 class DIMacro : public DIMacroNode {
3499   friend class LLVMContextImpl;
3500   friend class MDNode;
3501 
3502   unsigned Line;
3503 
3504   DIMacro(LLVMContext &C, StorageType Storage, unsigned MIType, unsigned Line,
3505           ArrayRef<Metadata *> Ops)
3506       : DIMacroNode(C, DIMacroKind, Storage, MIType, Ops), Line(Line) {}
3507   ~DIMacro() = default;
3508 
3509   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
3510                           StringRef Name, StringRef Value, StorageType Storage,
3511                           bool ShouldCreate = true) {
3512     return getImpl(Context, MIType, Line, getCanonicalMDString(Context, Name),
3513                    getCanonicalMDString(Context, Value), Storage, ShouldCreate);
3514   }
3515   static DIMacro *getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
3516                           MDString *Name, MDString *Value, StorageType Storage,
3517                           bool ShouldCreate = true);
3518 
3519   TempDIMacro cloneImpl() const {
3520     return getTemporary(getContext(), getMacinfoType(), getLine(), getName(),
3521                         getValue());
3522   }
3523 
3524 public:
3525   DEFINE_MDNODE_GET(DIMacro,
3526                     (unsigned MIType, unsigned Line, StringRef Name,
3527                      StringRef Value = ""),
3528                     (MIType, Line, Name, Value))
3529   DEFINE_MDNODE_GET(DIMacro,
3530                     (unsigned MIType, unsigned Line, MDString *Name,
3531                      MDString *Value),
3532                     (MIType, Line, Name, Value))
3533 
3534   TempDIMacro clone() const { return cloneImpl(); }
3535 
3536   unsigned getLine() const { return Line; }
3537 
3538   StringRef getName() const { return getStringOperand(0); }
3539   StringRef getValue() const { return getStringOperand(1); }
3540 
3541   MDString *getRawName() const { return getOperandAs<MDString>(0); }
3542   MDString *getRawValue() const { return getOperandAs<MDString>(1); }
3543 
3544   static bool classof(const Metadata *MD) {
3545     return MD->getMetadataID() == DIMacroKind;
3546   }
3547 };
3548 
3549 class DIMacroFile : public DIMacroNode {
3550   friend class LLVMContextImpl;
3551   friend class MDNode;
3552 
3553   unsigned Line;
3554 
3555   DIMacroFile(LLVMContext &C, StorageType Storage, unsigned MIType,
3556               unsigned Line, ArrayRef<Metadata *> Ops)
3557       : DIMacroNode(C, DIMacroFileKind, Storage, MIType, Ops), Line(Line) {}
3558   ~DIMacroFile() = default;
3559 
3560   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
3561                               unsigned Line, DIFile *File,
3562                               DIMacroNodeArray Elements, StorageType Storage,
3563                               bool ShouldCreate = true) {
3564     return getImpl(Context, MIType, Line, static_cast<Metadata *>(File),
3565                    Elements.get(), Storage, ShouldCreate);
3566   }
3567 
3568   static DIMacroFile *getImpl(LLVMContext &Context, unsigned MIType,
3569                               unsigned Line, Metadata *File, Metadata *Elements,
3570                               StorageType Storage, bool ShouldCreate = true);
3571 
3572   TempDIMacroFile cloneImpl() const {
3573     return getTemporary(getContext(), getMacinfoType(), getLine(), getFile(),
3574                         getElements());
3575   }
3576 
3577 public:
3578   DEFINE_MDNODE_GET(DIMacroFile,
3579                     (unsigned MIType, unsigned Line, DIFile *File,
3580                      DIMacroNodeArray Elements),
3581                     (MIType, Line, File, Elements))
3582   DEFINE_MDNODE_GET(DIMacroFile,
3583                     (unsigned MIType, unsigned Line, Metadata *File,
3584                      Metadata *Elements),
3585                     (MIType, Line, File, Elements))
3586 
3587   TempDIMacroFile clone() const { return cloneImpl(); }
3588 
3589   void replaceElements(DIMacroNodeArray Elements) {
3590 #ifndef NDEBUG
3591     for (DIMacroNode *Op : getElements())
3592       assert(is_contained(Elements->operands(), Op) &&
3593              "Lost a macro node during macro node list replacement");
3594 #endif
3595     replaceOperandWith(1, Elements.get());
3596   }
3597 
3598   unsigned getLine() const { return Line; }
3599   DIFile *getFile() const { return cast_or_null<DIFile>(getRawFile()); }
3600 
3601   DIMacroNodeArray getElements() const {
3602     return cast_or_null<MDTuple>(getRawElements());
3603   }
3604 
3605   Metadata *getRawFile() const { return getOperand(0); }
3606   Metadata *getRawElements() const { return getOperand(1); }
3607 
3608   static bool classof(const Metadata *MD) {
3609     return MD->getMetadataID() == DIMacroFileKind;
3610   }
3611 };
3612 
3613 /// List of ValueAsMetadata, to be used as an argument to a dbg.value
3614 /// intrinsic.
3615 class DIArgList : public MDNode {
3616   friend class LLVMContextImpl;
3617   friend class MDNode;
3618   using iterator = SmallVectorImpl<ValueAsMetadata *>::iterator;
3619 
3620   SmallVector<ValueAsMetadata *, 4> Args;
3621 
3622   DIArgList(LLVMContext &C, StorageType Storage,
3623             ArrayRef<ValueAsMetadata *> Args)
3624       : MDNode(C, DIArgListKind, Storage, None),
3625         Args(Args.begin(), Args.end()) {
3626     track();
3627   }
3628   ~DIArgList() { untrack(); }
3629 
3630   static DIArgList *getImpl(LLVMContext &Context,
3631                             ArrayRef<ValueAsMetadata *> Args,
3632                             StorageType Storage, bool ShouldCreate = true);
3633 
3634   TempDIArgList cloneImpl() const {
3635     return getTemporary(getContext(), getArgs());
3636   }
3637 
3638   void track();
3639   void untrack();
3640   void dropAllReferences();
3641 
3642 public:
3643   DEFINE_MDNODE_GET(DIArgList, (ArrayRef<ValueAsMetadata *> Args), (Args))
3644 
3645   TempDIArgList clone() const { return cloneImpl(); }
3646 
3647   ArrayRef<ValueAsMetadata *> getArgs() const { return Args; }
3648 
3649   iterator args_begin() { return Args.begin(); }
3650   iterator args_end() { return Args.end(); }
3651 
3652   static bool classof(const Metadata *MD) {
3653     return MD->getMetadataID() == DIArgListKind;
3654   }
3655 
3656   void handleChangedOperand(void *Ref, Metadata *New);
3657 };
3658 
3659 /// Identifies a unique instance of a variable.
3660 ///
3661 /// Storage for identifying a potentially inlined instance of a variable,
3662 /// or a fragment thereof. This guarantees that exactly one variable instance
3663 /// may be identified by this class, even when that variable is a fragment of
3664 /// an aggregate variable and/or there is another inlined instance of the same
3665 /// source code variable nearby.
3666 /// This class does not necessarily uniquely identify that variable: it is
3667 /// possible that a DebugVariable with different parameters may point to the
3668 /// same variable instance, but not that one DebugVariable points to multiple
3669 /// variable instances.
3670 class DebugVariable {
3671   using FragmentInfo = DIExpression::FragmentInfo;
3672 
3673   const DILocalVariable *Variable;
3674   Optional<FragmentInfo> Fragment;
3675   const DILocation *InlinedAt;
3676 
3677   /// Fragment that will overlap all other fragments. Used as default when
3678   /// caller demands a fragment.
3679   static const FragmentInfo DefaultFragment;
3680 
3681 public:
3682   DebugVariable(const DILocalVariable *Var, Optional<FragmentInfo> FragmentInfo,
3683                 const DILocation *InlinedAt)
3684       : Variable(Var), Fragment(FragmentInfo), InlinedAt(InlinedAt) {}
3685 
3686   DebugVariable(const DILocalVariable *Var, const DIExpression *DIExpr,
3687                 const DILocation *InlinedAt)
3688       : Variable(Var),
3689         Fragment(DIExpr ? DIExpr->getFragmentInfo() : NoneType()),
3690         InlinedAt(InlinedAt) {}
3691 
3692   const DILocalVariable *getVariable() const { return Variable; }
3693   Optional<FragmentInfo> getFragment() const { return Fragment; }
3694   const DILocation *getInlinedAt() const { return InlinedAt; }
3695 
3696   FragmentInfo getFragmentOrDefault() const {
3697     return Fragment.getValueOr(DefaultFragment);
3698   }
3699 
3700   static bool isDefaultFragment(const FragmentInfo F) {
3701     return F == DefaultFragment;
3702   }
3703 
3704   bool operator==(const DebugVariable &Other) const {
3705     return std::tie(Variable, Fragment, InlinedAt) ==
3706            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
3707   }
3708 
3709   bool operator<(const DebugVariable &Other) const {
3710     return std::tie(Variable, Fragment, InlinedAt) <
3711            std::tie(Other.Variable, Other.Fragment, Other.InlinedAt);
3712   }
3713 };
3714 
3715 template <> struct DenseMapInfo<DebugVariable> {
3716   using FragmentInfo = DIExpression::FragmentInfo;
3717 
3718   /// Empty key: no key should be generated that has no DILocalVariable.
3719   static inline DebugVariable getEmptyKey() {
3720     return DebugVariable(nullptr, NoneType(), nullptr);
3721   }
3722 
3723   /// Difference in tombstone is that the Optional is meaningful.
3724   static inline DebugVariable getTombstoneKey() {
3725     return DebugVariable(nullptr, {{0, 0}}, nullptr);
3726   }
3727 
3728   static unsigned getHashValue(const DebugVariable &D) {
3729     unsigned HV = 0;
3730     const Optional<FragmentInfo> Fragment = D.getFragment();
3731     if (Fragment)
3732       HV = DenseMapInfo<FragmentInfo>::getHashValue(*Fragment);
3733 
3734     return hash_combine(D.getVariable(), HV, D.getInlinedAt());
3735   }
3736 
3737   static bool isEqual(const DebugVariable &A, const DebugVariable &B) {
3738     return A == B;
3739   }
3740 };
3741 
3742 } // end namespace llvm
3743 
3744 #undef DEFINE_MDNODE_GET_UNPACK_IMPL
3745 #undef DEFINE_MDNODE_GET_UNPACK
3746 #undef DEFINE_MDNODE_GET
3747 
3748 #endif // LLVM_IR_DEBUGINFOMETADATA_H
3749