1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the debug info Metadata classes.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/DebugInfoMetadata.h"
15 #include "LLVMContextImpl.h"
16 #include "MetadataImpl.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/IR/DIBuilder.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/Instructions.h"
22 
23 using namespace llvm;
24 
25 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
26                        unsigned Column, ArrayRef<Metadata *> MDs)
27     : MDNode(C, DILocationKind, Storage, MDs) {
28   assert((MDs.size() == 1 || MDs.size() == 2) &&
29          "Expected a scope and optional inlined-at");
30 
31   // Set line and column.
32   assert(Column < (1u << 16) && "Expected 16-bit column");
33 
34   SubclassData32 = Line;
35   SubclassData16 = Column;
36 }
37 
38 static void adjustColumn(unsigned &Column) {
39   // Set to unknown on overflow.  We only have 16 bits to play with here.
40   if (Column >= (1u << 16))
41     Column = 0;
42 }
43 
44 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
45                                 unsigned Column, Metadata *Scope,
46                                 Metadata *InlinedAt, StorageType Storage,
47                                 bool ShouldCreate) {
48   // Fixup column.
49   adjustColumn(Column);
50 
51   if (Storage == Uniqued) {
52     if (auto *N =
53             getUniqued(Context.pImpl->DILocations,
54                        DILocationInfo::KeyTy(Line, Column, Scope, InlinedAt)))
55       return N;
56     if (!ShouldCreate)
57       return nullptr;
58   } else {
59     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
60   }
61 
62   SmallVector<Metadata *, 2> Ops;
63   Ops.push_back(Scope);
64   if (InlinedAt)
65     Ops.push_back(InlinedAt);
66   return storeImpl(new (Ops.size())
67                        DILocation(Context, Storage, Line, Column, Ops),
68                    Storage, Context.pImpl->DILocations);
69 }
70 
71 const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
72                                                 const DILocation *LocB) {
73   if (!LocA || !LocB)
74     return nullptr;
75 
76   if (LocA == LocB)
77     return LocA;
78 
79   SmallPtrSet<DILocation *, 5> InlinedLocationsA;
80   for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
81     InlinedLocationsA.insert(L);
82   SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
83   DIScope *S = LocA->getScope();
84   DILocation *L = LocA->getInlinedAt();
85   while (S) {
86     Locations.insert(std::make_pair(S, L));
87     S = S->getScope().resolve();
88     if (!S && L) {
89       S = L->getScope();
90       L = L->getInlinedAt();
91     }
92   }
93   const DILocation *Result = LocB;
94   S = LocB->getScope();
95   L = LocB->getInlinedAt();
96   while (S) {
97     if (Locations.count(std::make_pair(S, L)))
98       break;
99     S = S->getScope().resolve();
100     if (!S && L) {
101       S = L->getScope();
102       L = L->getInlinedAt();
103     }
104   }
105 
106   // If the two locations are irreconsilable, just pick one. This is misleading,
107   // but on the other hand, it's a "line 0" location.
108   if (!S || !isa<DILocalScope>(S))
109     S = LocA->getScope();
110   return DILocation::get(Result->getContext(), 0, 0, S, L);
111 }
112 
113 DINode::DIFlags DINode::getFlag(StringRef Flag) {
114   return StringSwitch<DIFlags>(Flag)
115 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
116 #include "llvm/IR/DebugInfoFlags.def"
117       .Default(DINode::FlagZero);
118 }
119 
120 StringRef DINode::getFlagString(DIFlags Flag) {
121   switch (Flag) {
122 #define HANDLE_DI_FLAG(ID, NAME)                                               \
123   case Flag##NAME:                                                             \
124     return "DIFlag" #NAME;
125 #include "llvm/IR/DebugInfoFlags.def"
126   }
127   return "";
128 }
129 
130 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
131                                    SmallVectorImpl<DIFlags> &SplitFlags) {
132   // Flags that are packed together need to be specially handled, so
133   // that, for example, we emit "DIFlagPublic" and not
134   // "DIFlagPrivate | DIFlagProtected".
135   if (DIFlags A = Flags & FlagAccessibility) {
136     if (A == FlagPrivate)
137       SplitFlags.push_back(FlagPrivate);
138     else if (A == FlagProtected)
139       SplitFlags.push_back(FlagProtected);
140     else
141       SplitFlags.push_back(FlagPublic);
142     Flags &= ~A;
143   }
144   if (DIFlags R = Flags & FlagPtrToMemberRep) {
145     if (R == FlagSingleInheritance)
146       SplitFlags.push_back(FlagSingleInheritance);
147     else if (R == FlagMultipleInheritance)
148       SplitFlags.push_back(FlagMultipleInheritance);
149     else
150       SplitFlags.push_back(FlagVirtualInheritance);
151     Flags &= ~R;
152   }
153   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
154     Flags &= ~FlagIndirectVirtualBase;
155     SplitFlags.push_back(FlagIndirectVirtualBase);
156   }
157 
158 #define HANDLE_DI_FLAG(ID, NAME)                                               \
159   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
160     SplitFlags.push_back(Bit);                                                 \
161     Flags &= ~Bit;                                                             \
162   }
163 #include "llvm/IR/DebugInfoFlags.def"
164   return Flags;
165 }
166 
167 DIScopeRef DIScope::getScope() const {
168   if (auto *T = dyn_cast<DIType>(this))
169     return T->getScope();
170 
171   if (auto *SP = dyn_cast<DISubprogram>(this))
172     return SP->getScope();
173 
174   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
175     return LB->getScope();
176 
177   if (auto *NS = dyn_cast<DINamespace>(this))
178     return NS->getScope();
179 
180   if (auto *M = dyn_cast<DIModule>(this))
181     return M->getScope();
182 
183   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
184          "Unhandled type of scope.");
185   return nullptr;
186 }
187 
188 StringRef DIScope::getName() const {
189   if (auto *T = dyn_cast<DIType>(this))
190     return T->getName();
191   if (auto *SP = dyn_cast<DISubprogram>(this))
192     return SP->getName();
193   if (auto *NS = dyn_cast<DINamespace>(this))
194     return NS->getName();
195   if (auto *M = dyn_cast<DIModule>(this))
196     return M->getName();
197   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
198           isa<DICompileUnit>(this)) &&
199          "Unhandled type of scope.");
200   return "";
201 }
202 
203 #ifndef NDEBUG
204 static bool isCanonical(const MDString *S) {
205   return !S || !S->getString().empty();
206 }
207 #endif
208 
209 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
210                                       MDString *Header,
211                                       ArrayRef<Metadata *> DwarfOps,
212                                       StorageType Storage, bool ShouldCreate) {
213   unsigned Hash = 0;
214   if (Storage == Uniqued) {
215     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
216     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
217       return N;
218     if (!ShouldCreate)
219       return nullptr;
220     Hash = Key.getHash();
221   } else {
222     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
223   }
224 
225   // Use a nullptr for empty headers.
226   assert(isCanonical(Header) && "Expected canonical MDString");
227   Metadata *PreOps[] = {Header};
228   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
229                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
230                    Storage, Context.pImpl->GenericDINodes);
231 }
232 
233 void GenericDINode::recalculateHash() {
234   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
235 }
236 
237 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
238 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
239 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
240   do {                                                                         \
241     if (Storage == Uniqued) {                                                  \
242       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
243                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
244         return N;                                                              \
245       if (!ShouldCreate)                                                       \
246         return nullptr;                                                        \
247     } else {                                                                   \
248       assert(ShouldCreate &&                                                   \
249              "Expected non-uniqued nodes to always be created");               \
250     }                                                                          \
251   } while (false)
252 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
253   return storeImpl(new (array_lengthof(OPS))                                   \
254                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
255                    Storage, Context.pImpl->CLASS##s)
256 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
257   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
258                    Storage, Context.pImpl->CLASS##s)
259 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
260   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
261                    Storage, Context.pImpl->CLASS##s)
262 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
263   return storeImpl(new (NUM_OPS)                                               \
264                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
265                    Storage, Context.pImpl->CLASS##s)
266 
267 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
268                                 StorageType Storage, bool ShouldCreate) {
269   auto *CountNode = ConstantAsMetadata::get(
270       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
271   return getImpl(Context, CountNode, Lo, Storage, ShouldCreate);
272 }
273 
274 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
275                                 int64_t Lo, StorageType Storage,
276                                 bool ShouldCreate) {
277   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, Lo));
278   Metadata *Ops[] = { CountNode };
279   DEFINE_GETIMPL_STORE(DISubrange, (CountNode, Lo), Ops);
280 }
281 
282 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, int64_t Value,
283                                     bool IsUnsigned, MDString *Name,
284                                     StorageType Storage, bool ShouldCreate) {
285   assert(isCanonical(Name) && "Expected canonical MDString");
286   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
287   Metadata *Ops[] = {Name};
288   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
289 }
290 
291 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
292                                   MDString *Name, uint64_t SizeInBits,
293                                   uint32_t AlignInBits, unsigned Encoding,
294                                   DIFlags Flags, StorageType Storage,
295                                   bool ShouldCreate) {
296   assert(isCanonical(Name) && "Expected canonical MDString");
297   DEFINE_GETIMPL_LOOKUP(DIBasicType,
298                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
299   Metadata *Ops[] = {nullptr, nullptr, Name};
300   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
301                       Flags), Ops);
302 }
303 
304 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
305   switch (getEncoding()) {
306   case dwarf::DW_ATE_signed:
307   case dwarf::DW_ATE_signed_char:
308     return Signedness::Signed;
309   case dwarf::DW_ATE_unsigned:
310   case dwarf::DW_ATE_unsigned_char:
311     return Signedness::Unsigned;
312   default:
313     return None;
314   }
315 }
316 
317 DIDerivedType *DIDerivedType::getImpl(
318     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
319     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
320     uint32_t AlignInBits, uint64_t OffsetInBits,
321     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
322     StorageType Storage, bool ShouldCreate) {
323   assert(isCanonical(Name) && "Expected canonical MDString");
324   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
325                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
326                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
327                          ExtraData));
328   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
329   DEFINE_GETIMPL_STORE(
330       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
331                       DWARFAddressSpace, Flags), Ops);
332 }
333 
334 DICompositeType *DICompositeType::getImpl(
335     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
336     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
337     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
338     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
339     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
340     StorageType Storage, bool ShouldCreate) {
341   assert(isCanonical(Name) && "Expected canonical MDString");
342 
343   // Keep this in sync with buildODRType.
344   DEFINE_GETIMPL_LOOKUP(
345       DICompositeType, (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
346                         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
347                         VTableHolder, TemplateParams, Identifier, Discriminator));
348   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
349                      Elements, VTableHolder, TemplateParams, Identifier,
350                      Discriminator};
351   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
352                                          AlignInBits, OffsetInBits, Flags),
353                        Ops);
354 }
355 
356 DICompositeType *DICompositeType::buildODRType(
357     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
358     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
359     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
360     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
361     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
362   assert(!Identifier.getString().empty() && "Expected valid identifier");
363   if (!Context.isODRUniquingDebugTypes())
364     return nullptr;
365   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
366   if (!CT)
367     return CT = DICompositeType::getDistinct(
368                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
369                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
370                VTableHolder, TemplateParams, &Identifier, Discriminator);
371 
372   // Only mutate CT if it's a forward declaration and the new operands aren't.
373   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
374   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
375     return CT;
376 
377   // Mutate CT in place.  Keep this in sync with getImpl.
378   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
379              Flags);
380   Metadata *Ops[] = {File,     Scope,        Name,           BaseType,
381                      Elements, VTableHolder, TemplateParams, &Identifier,
382                      Discriminator};
383   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
384          "Mismatched number of operands");
385   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
386     if (Ops[I] != CT->getOperand(I))
387       CT->setOperand(I, Ops[I]);
388   return CT;
389 }
390 
391 DICompositeType *DICompositeType::getODRType(
392     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
393     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
394     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
395     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
396     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator) {
397   assert(!Identifier.getString().empty() && "Expected valid identifier");
398   if (!Context.isODRUniquingDebugTypes())
399     return nullptr;
400   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
401   if (!CT)
402     CT = DICompositeType::getDistinct(
403         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
404         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
405         TemplateParams, &Identifier, Discriminator);
406   return CT;
407 }
408 
409 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
410                                                      MDString &Identifier) {
411   assert(!Identifier.getString().empty() && "Expected valid identifier");
412   if (!Context.isODRUniquingDebugTypes())
413     return nullptr;
414   return Context.pImpl->DITypeMap->lookup(&Identifier);
415 }
416 
417 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
418                                             uint8_t CC, Metadata *TypeArray,
419                                             StorageType Storage,
420                                             bool ShouldCreate) {
421   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
422   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
423   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
424 }
425 
426 // FIXME: Implement this string-enum correspondence with a .def file and macros,
427 // so that the association is explicit rather than implied.
428 static const char *ChecksumKindName[DIFile::CSK_Last] = {
429   "CSK_MD5",
430   "CSK_SHA1"
431 };
432 
433 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
434   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
435   // The first space was originally the CSK_None variant, which is now
436   // obsolete, but the space is still reserved in ChecksumKind, so we account
437   // for it here.
438   return ChecksumKindName[CSKind - 1];
439 }
440 
441 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
442   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
443       .Case("CSK_MD5", DIFile::CSK_MD5)
444       .Case("CSK_SHA1", DIFile::CSK_SHA1)
445       .Default(None);
446 }
447 
448 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
449                         MDString *Directory,
450                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
451                         Optional<MDString *> Source, StorageType Storage,
452                         bool ShouldCreate) {
453   assert(isCanonical(Filename) && "Expected canonical MDString");
454   assert(isCanonical(Directory) && "Expected canonical MDString");
455   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
456   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
457   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
458   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
459                      Source.getValueOr(nullptr)};
460   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
461 }
462 
463 DICompileUnit *DICompileUnit::getImpl(
464     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
465     MDString *Producer, bool IsOptimized, MDString *Flags,
466     unsigned RuntimeVersion, MDString *SplitDebugFilename,
467     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
468     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
469     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
470     unsigned NameTableKind, StorageType Storage, bool ShouldCreate) {
471   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
472   assert(isCanonical(Producer) && "Expected canonical MDString");
473   assert(isCanonical(Flags) && "Expected canonical MDString");
474   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
475 
476   Metadata *Ops[] = {
477       File,      Producer,      Flags,           SplitDebugFilename,
478       EnumTypes, RetainedTypes, GlobalVariables, ImportedEntities,
479       Macros};
480   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
481                        Context, Storage, SourceLanguage, IsOptimized,
482                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
483                        DebugInfoForProfiling, NameTableKind, Ops),
484                    Storage);
485 }
486 
487 Optional<DICompileUnit::DebugEmissionKind>
488 DICompileUnit::getEmissionKind(StringRef Str) {
489   return StringSwitch<Optional<DebugEmissionKind>>(Str)
490       .Case("NoDebug", NoDebug)
491       .Case("FullDebug", FullDebug)
492       .Case("LineTablesOnly", LineTablesOnly)
493       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
494       .Default(None);
495 }
496 
497 Optional<DICompileUnit::DebugNameTableKind>
498 DICompileUnit::getNameTableKind(StringRef Str) {
499   return StringSwitch<Optional<DebugNameTableKind>>(Str)
500       .Case("Default", DebugNameTableKind::Default)
501       .Case("GNU", DebugNameTableKind::GNU)
502       .Case("None", DebugNameTableKind::None)
503       .Default(None);
504 }
505 
506 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
507   switch (EK) {
508   case NoDebug:        return "NoDebug";
509   case FullDebug:      return "FullDebug";
510   case LineTablesOnly: return "LineTablesOnly";
511   case DebugDirectivesOnly: return "DebugDirectivesOnly";
512   }
513   return nullptr;
514 }
515 
516 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
517   switch (NTK) {
518   case DebugNameTableKind::Default:
519     return nullptr;
520   case DebugNameTableKind::GNU:
521     return "GNU";
522   case DebugNameTableKind::None:
523     return "None";
524   }
525   return nullptr;
526 }
527 
528 DISubprogram *DILocalScope::getSubprogram() const {
529   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
530     return Block->getScope()->getSubprogram();
531   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
532 }
533 
534 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
535   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
536     return File->getScope()->getNonLexicalBlockFileScope();
537   return const_cast<DILocalScope *>(this);
538 }
539 
540 DISubprogram *DISubprogram::getImpl(
541     LLVMContext &Context, Metadata *Scope, MDString *Name,
542     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
543     bool IsLocalToUnit, bool IsDefinition, unsigned ScopeLine,
544     Metadata *ContainingType, unsigned Virtuality, unsigned VirtualIndex,
545     int ThisAdjustment, DIFlags Flags, bool IsOptimized, Metadata *Unit,
546     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
547     Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
548   assert(isCanonical(Name) && "Expected canonical MDString");
549   assert(isCanonical(LinkageName) && "Expected canonical MDString");
550   DEFINE_GETIMPL_LOOKUP(
551       DISubprogram, (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
552                      IsDefinition, ScopeLine, ContainingType, Virtuality,
553                      VirtualIndex, ThisAdjustment, Flags, IsOptimized, Unit,
554                      TemplateParams, Declaration, RetainedNodes, ThrownTypes));
555   SmallVector<Metadata *, 11> Ops = {
556       File,        Scope,         Name,           LinkageName,    Type,       Unit,
557       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
558   if (!ThrownTypes) {
559     Ops.pop_back();
560     if (!TemplateParams) {
561       Ops.pop_back();
562       if (!ContainingType)
563         Ops.pop_back();
564     }
565   }
566   DEFINE_GETIMPL_STORE_N(DISubprogram,
567                          (Line, ScopeLine, Virtuality, VirtualIndex,
568                           ThisAdjustment, Flags, IsLocalToUnit, IsDefinition,
569                           IsOptimized),
570                          Ops, Ops.size());
571 }
572 
573 bool DISubprogram::describes(const Function *F) const {
574   assert(F && "Invalid function");
575   if (F->getSubprogram() == this)
576     return true;
577   StringRef Name = getLinkageName();
578   if (Name.empty())
579     Name = getName();
580   return F->getName() == Name;
581 }
582 
583 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
584                                         Metadata *File, unsigned Line,
585                                         unsigned Column, StorageType Storage,
586                                         bool ShouldCreate) {
587   // Fixup column.
588   adjustColumn(Column);
589 
590   assert(Scope && "Expected scope");
591   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
592   Metadata *Ops[] = {File, Scope};
593   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
594 }
595 
596 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
597                                                 Metadata *Scope, Metadata *File,
598                                                 unsigned Discriminator,
599                                                 StorageType Storage,
600                                                 bool ShouldCreate) {
601   assert(Scope && "Expected scope");
602   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
603   Metadata *Ops[] = {File, Scope};
604   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
605 }
606 
607 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
608                                   MDString *Name, bool ExportSymbols,
609                                   StorageType Storage, bool ShouldCreate) {
610   assert(isCanonical(Name) && "Expected canonical MDString");
611   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
612   // The nullptr is for DIScope's File operand. This should be refactored.
613   Metadata *Ops[] = {nullptr, Scope, Name};
614   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
615 }
616 
617 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *Scope,
618                             MDString *Name, MDString *ConfigurationMacros,
619                             MDString *IncludePath, MDString *ISysRoot,
620                             StorageType Storage, bool ShouldCreate) {
621   assert(isCanonical(Name) && "Expected canonical MDString");
622   DEFINE_GETIMPL_LOOKUP(
623       DIModule, (Scope, Name, ConfigurationMacros, IncludePath, ISysRoot));
624   Metadata *Ops[] = {Scope, Name, ConfigurationMacros, IncludePath, ISysRoot};
625   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIModule, Ops);
626 }
627 
628 DITemplateTypeParameter *DITemplateTypeParameter::getImpl(LLVMContext &Context,
629                                                           MDString *Name,
630                                                           Metadata *Type,
631                                                           StorageType Storage,
632                                                           bool ShouldCreate) {
633   assert(isCanonical(Name) && "Expected canonical MDString");
634   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type));
635   Metadata *Ops[] = {Name, Type};
636   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DITemplateTypeParameter, Ops);
637 }
638 
639 DITemplateValueParameter *DITemplateValueParameter::getImpl(
640     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
641     Metadata *Value, StorageType Storage, bool ShouldCreate) {
642   assert(isCanonical(Name) && "Expected canonical MDString");
643   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter, (Tag, Name, Type, Value));
644   Metadata *Ops[] = {Name, Type, Value};
645   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag), Ops);
646 }
647 
648 DIGlobalVariable *
649 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
650                           MDString *LinkageName, Metadata *File, unsigned Line,
651                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
652                           Metadata *StaticDataMemberDeclaration,
653                           uint32_t AlignInBits, StorageType Storage,
654                           bool ShouldCreate) {
655   assert(isCanonical(Name) && "Expected canonical MDString");
656   assert(isCanonical(LinkageName) && "Expected canonical MDString");
657   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable,
658                         (Scope, Name, LinkageName, File, Line, Type,
659                          IsLocalToUnit, IsDefinition,
660                          StaticDataMemberDeclaration, AlignInBits));
661   Metadata *Ops[] = {
662       Scope, Name, File, Type, Name, LinkageName, StaticDataMemberDeclaration};
663   DEFINE_GETIMPL_STORE(DIGlobalVariable,
664                        (Line, IsLocalToUnit, IsDefinition, AlignInBits),
665                        Ops);
666 }
667 
668 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
669                                           MDString *Name, Metadata *File,
670                                           unsigned Line, Metadata *Type,
671                                           unsigned Arg, DIFlags Flags,
672                                           uint32_t AlignInBits,
673                                           StorageType Storage,
674                                           bool ShouldCreate) {
675   // 64K ought to be enough for any frontend.
676   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
677 
678   assert(Scope && "Expected scope");
679   assert(isCanonical(Name) && "Expected canonical MDString");
680   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
681                         (Scope, Name, File, Line, Type, Arg, Flags,
682                          AlignInBits));
683   Metadata *Ops[] = {Scope, Name, File, Type};
684   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
685 }
686 
687 Optional<uint64_t> DIVariable::getSizeInBits() const {
688   // This is used by the Verifier so be mindful of broken types.
689   const Metadata *RawType = getRawType();
690   while (RawType) {
691     // Try to get the size directly.
692     if (auto *T = dyn_cast<DIType>(RawType))
693       if (uint64_t Size = T->getSizeInBits())
694         return Size;
695 
696     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
697       // Look at the base type.
698       RawType = DT->getRawBaseType();
699       continue;
700     }
701 
702     // Missing type or size.
703     break;
704   }
705 
706   // Fail gracefully.
707   return None;
708 }
709 
710 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
711                           MDString *Name, Metadata *File, unsigned Line,
712                           StorageType Storage,
713                           bool ShouldCreate) {
714   assert(Scope && "Expected scope");
715   assert(isCanonical(Name) && "Expected canonical MDString");
716   DEFINE_GETIMPL_LOOKUP(DILabel,
717                         (Scope, Name, File, Line));
718   Metadata *Ops[] = {Scope, Name, File};
719   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
720 }
721 
722 DIExpression *DIExpression::getImpl(LLVMContext &Context,
723                                     ArrayRef<uint64_t> Elements,
724                                     StorageType Storage, bool ShouldCreate) {
725   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
726   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
727 }
728 
729 unsigned DIExpression::ExprOperand::getSize() const {
730   switch (getOp()) {
731   case dwarf::DW_OP_LLVM_fragment:
732     return 3;
733   case dwarf::DW_OP_constu:
734   case dwarf::DW_OP_plus_uconst:
735     return 2;
736   default:
737     return 1;
738   }
739 }
740 
741 bool DIExpression::isValid() const {
742   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
743     // Check that there's space for the operand.
744     if (I->get() + I->getSize() > E->get())
745       return false;
746 
747     // Check that the operand is valid.
748     switch (I->getOp()) {
749     default:
750       return false;
751     case dwarf::DW_OP_LLVM_fragment:
752       // A fragment operator must appear at the end.
753       return I->get() + I->getSize() == E->get();
754     case dwarf::DW_OP_stack_value: {
755       // Must be the last one or followed by a DW_OP_LLVM_fragment.
756       if (I->get() + I->getSize() == E->get())
757         break;
758       auto J = I;
759       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
760         return false;
761       break;
762     }
763     case dwarf::DW_OP_swap: {
764       // Must be more than one implicit element on the stack.
765 
766       // FIXME: A better way to implement this would be to add a local variable
767       // that keeps track of the stack depth and introduce something like a
768       // DW_LLVM_OP_implicit_location as a placeholder for the location this
769       // DIExpression is attached to, or else pass the number of implicit stack
770       // elements into isValid.
771       if (getNumElements() == 1)
772         return false;
773       break;
774     }
775     case dwarf::DW_OP_constu:
776     case dwarf::DW_OP_plus_uconst:
777     case dwarf::DW_OP_plus:
778     case dwarf::DW_OP_minus:
779     case dwarf::DW_OP_mul:
780     case dwarf::DW_OP_div:
781     case dwarf::DW_OP_mod:
782     case dwarf::DW_OP_or:
783     case dwarf::DW_OP_and:
784     case dwarf::DW_OP_xor:
785     case dwarf::DW_OP_shl:
786     case dwarf::DW_OP_shr:
787     case dwarf::DW_OP_shra:
788     case dwarf::DW_OP_deref:
789     case dwarf::DW_OP_xderef:
790     case dwarf::DW_OP_lit0:
791     case dwarf::DW_OP_not:
792     case dwarf::DW_OP_dup:
793       break;
794     }
795   }
796   return true;
797 }
798 
799 Optional<DIExpression::FragmentInfo>
800 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
801   for (auto I = Start; I != End; ++I)
802     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
803       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
804       return Info;
805     }
806   return None;
807 }
808 
809 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
810                                 int64_t Offset) {
811   if (Offset > 0) {
812     Ops.push_back(dwarf::DW_OP_plus_uconst);
813     Ops.push_back(Offset);
814   } else if (Offset < 0) {
815     Ops.push_back(dwarf::DW_OP_constu);
816     Ops.push_back(-Offset);
817     Ops.push_back(dwarf::DW_OP_minus);
818   }
819 }
820 
821 bool DIExpression::extractIfOffset(int64_t &Offset) const {
822   if (getNumElements() == 0) {
823     Offset = 0;
824     return true;
825   }
826 
827   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
828     Offset = Elements[1];
829     return true;
830   }
831 
832   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
833     if (Elements[2] == dwarf::DW_OP_plus) {
834       Offset = Elements[1];
835       return true;
836     }
837     if (Elements[2] == dwarf::DW_OP_minus) {
838       Offset = -Elements[1];
839       return true;
840     }
841   }
842 
843   return false;
844 }
845 
846 DIExpression *DIExpression::prepend(const DIExpression *Expr, bool DerefBefore,
847                                     int64_t Offset, bool DerefAfter,
848                                     bool StackValue) {
849   SmallVector<uint64_t, 8> Ops;
850   if (DerefBefore)
851     Ops.push_back(dwarf::DW_OP_deref);
852 
853   appendOffset(Ops, Offset);
854   if (DerefAfter)
855     Ops.push_back(dwarf::DW_OP_deref);
856 
857   return prependOpcodes(Expr, Ops, StackValue);
858 }
859 
860 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
861                                            SmallVectorImpl<uint64_t> &Ops,
862                                            bool StackValue) {
863   assert(Expr && "Can't prepend ops to this expression");
864 
865   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
866   if (Ops.empty())
867     StackValue = false;
868   for (auto Op : Expr->expr_ops()) {
869     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
870     if (StackValue) {
871       if (Op.getOp() == dwarf::DW_OP_stack_value)
872         StackValue = false;
873       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
874         Ops.push_back(dwarf::DW_OP_stack_value);
875         StackValue = false;
876       }
877     }
878     Op.appendToVector(Ops);
879   }
880   if (StackValue)
881     Ops.push_back(dwarf::DW_OP_stack_value);
882   return DIExpression::get(Expr->getContext(), Ops);
883 }
884 
885 DIExpression *DIExpression::append(const DIExpression *Expr,
886                                    ArrayRef<uint64_t> Ops) {
887   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
888 
889   // Copy Expr's current op list.
890   SmallVector<uint64_t, 16> NewOps;
891   for (auto Op : Expr->expr_ops()) {
892     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
893     if (Op.getOp() == dwarf::DW_OP_stack_value ||
894         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
895       NewOps.append(Ops.begin(), Ops.end());
896 
897       // Ensure that the new opcodes are only appended once.
898       Ops = None;
899     }
900     Op.appendToVector(NewOps);
901   }
902 
903   NewOps.append(Ops.begin(), Ops.end());
904   return DIExpression::get(Expr->getContext(), NewOps);
905 }
906 
907 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
908                                           ArrayRef<uint64_t> Ops) {
909   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
910   assert(none_of(Ops,
911                  [](uint64_t Op) {
912                    return Op == dwarf::DW_OP_stack_value ||
913                           Op == dwarf::DW_OP_LLVM_fragment;
914                  }) &&
915          "Can't append this op");
916 
917   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
918   // has no DW_OP_stack_value.
919   //
920   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
921   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
922   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
923   ArrayRef<uint64_t> ExprOpsBeforeFragment =
924       Expr->getElements().drop_back(DropUntilStackValue);
925   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
926                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
927   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
928 
929   // Append a DW_OP_deref after Expr's current op list if needed, then append
930   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
931   SmallVector<uint64_t, 16> NewOps;
932   if (NeedsDeref)
933     NewOps.push_back(dwarf::DW_OP_deref);
934   NewOps.append(Ops.begin(), Ops.end());
935   if (NeedsStackValue)
936     NewOps.push_back(dwarf::DW_OP_stack_value);
937   return DIExpression::append(Expr, NewOps);
938 }
939 
940 Optional<DIExpression *> DIExpression::createFragmentExpression(
941     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
942   SmallVector<uint64_t, 8> Ops;
943   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
944   if (Expr) {
945     for (auto Op : Expr->expr_ops()) {
946       switch (Op.getOp()) {
947       default: break;
948       case dwarf::DW_OP_plus:
949       case dwarf::DW_OP_minus:
950         // We can't safely split arithmetic into multiple fragments because we
951         // can't express carry-over between fragments.
952         //
953         // FIXME: We *could* preserve the lowest fragment of a constant offset
954         // operation if the offset fits into SizeInBits.
955         return None;
956       case dwarf::DW_OP_LLVM_fragment: {
957         // Make the new offset point into the existing fragment.
958         uint64_t FragmentOffsetInBits = Op.getArg(0);
959         uint64_t FragmentSizeInBits = Op.getArg(1);
960         (void)FragmentSizeInBits;
961         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
962                "new fragment outside of original fragment");
963         OffsetInBits += FragmentOffsetInBits;
964         continue;
965       }
966       }
967       Op.appendToVector(Ops);
968     }
969   }
970   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
971   Ops.push_back(OffsetInBits);
972   Ops.push_back(SizeInBits);
973   return DIExpression::get(Expr->getContext(), Ops);
974 }
975 
976 bool DIExpression::isConstant() const {
977   // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
978   if (getNumElements() != 3 && getNumElements() != 6)
979     return false;
980   if (getElement(0) != dwarf::DW_OP_constu ||
981       getElement(2) != dwarf::DW_OP_stack_value)
982     return false;
983   if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
984     return false;
985   return true;
986 }
987 
988 DIGlobalVariableExpression *
989 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
990                                     Metadata *Expression, StorageType Storage,
991                                     bool ShouldCreate) {
992   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
993   Metadata *Ops[] = {Variable, Expression};
994   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
995 }
996 
997 DIObjCProperty *DIObjCProperty::getImpl(
998     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
999     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1000     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1001   assert(isCanonical(Name) && "Expected canonical MDString");
1002   assert(isCanonical(GetterName) && "Expected canonical MDString");
1003   assert(isCanonical(SetterName) && "Expected canonical MDString");
1004   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1005                                          SetterName, Attributes, Type));
1006   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1007   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1008 }
1009 
1010 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1011                                             Metadata *Scope, Metadata *Entity,
1012                                             Metadata *File, unsigned Line,
1013                                             MDString *Name, StorageType Storage,
1014                                             bool ShouldCreate) {
1015   assert(isCanonical(Name) && "Expected canonical MDString");
1016   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1017                         (Tag, Scope, Entity, File, Line, Name));
1018   Metadata *Ops[] = {Scope, Entity, Name, File};
1019   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1020 }
1021 
1022 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1023                           unsigned Line, MDString *Name, MDString *Value,
1024                           StorageType Storage, bool ShouldCreate) {
1025   assert(isCanonical(Name) && "Expected canonical MDString");
1026   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1027   Metadata *Ops[] = { Name, Value };
1028   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1029 }
1030 
1031 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1032                                   unsigned Line, Metadata *File,
1033                                   Metadata *Elements, StorageType Storage,
1034                                   bool ShouldCreate) {
1035   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1036                         (MIType, Line, File, Elements));
1037   Metadata *Ops[] = { File, Elements };
1038   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1039 }
1040