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