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