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