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