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