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   auto *LB = ConstantAsMetadata::get(
340       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
341   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
342                  ShouldCreate);
343 }
344 
345 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
346                                 int64_t Lo, StorageType Storage,
347                                 bool ShouldCreate) {
348   auto *LB = ConstantAsMetadata::get(
349       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
350   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
351                  ShouldCreate);
352 }
353 
354 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
355                                 Metadata *LB, Metadata *UB, Metadata *Stride,
356                                 StorageType Storage, bool ShouldCreate) {
357   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
358   Metadata *Ops[] = {CountNode, LB, UB, Stride};
359   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
360 }
361 
362 DISubrange::CountType DISubrange::getCount() const {
363   if (!getRawCountNode())
364     return CountType();
365 
366   if (auto *MD = dyn_cast<ConstantAsMetadata>(getRawCountNode()))
367     return CountType(cast<ConstantInt>(MD->getValue()));
368 
369   if (auto *DV = dyn_cast<DIVariable>(getRawCountNode()))
370     return CountType(DV);
371 
372   return CountType();
373 }
374 
375 DISubrange::BoundType DISubrange::getLowerBound() const {
376   Metadata *LB = getRawLowerBound();
377   if (!LB)
378     return BoundType();
379 
380   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
381           isa<DIExpression>(LB)) &&
382          "LowerBound must be signed constant or DIVariable or DIExpression");
383 
384   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
385     return BoundType(cast<ConstantInt>(MD->getValue()));
386 
387   if (auto *MD = dyn_cast<DIVariable>(LB))
388     return BoundType(MD);
389 
390   if (auto *MD = dyn_cast<DIExpression>(LB))
391     return BoundType(MD);
392 
393   return BoundType();
394 }
395 
396 DISubrange::BoundType DISubrange::getUpperBound() const {
397   Metadata *UB = getRawUpperBound();
398   if (!UB)
399     return BoundType();
400 
401   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
402           isa<DIExpression>(UB)) &&
403          "UpperBound must be signed constant or DIVariable or DIExpression");
404 
405   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
406     return BoundType(cast<ConstantInt>(MD->getValue()));
407 
408   if (auto *MD = dyn_cast<DIVariable>(UB))
409     return BoundType(MD);
410 
411   if (auto *MD = dyn_cast<DIExpression>(UB))
412     return BoundType(MD);
413 
414   return BoundType();
415 }
416 
417 DISubrange::BoundType DISubrange::getStride() const {
418   Metadata *ST = getRawStride();
419   if (!ST)
420     return BoundType();
421 
422   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
423           isa<DIExpression>(ST)) &&
424          "Stride must be signed constant or DIVariable or DIExpression");
425 
426   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
427     return BoundType(cast<ConstantInt>(MD->getValue()));
428 
429   if (auto *MD = dyn_cast<DIVariable>(ST))
430     return BoundType(MD);
431 
432   if (auto *MD = dyn_cast<DIExpression>(ST))
433     return BoundType(MD);
434 
435   return BoundType();
436 }
437 
438 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
439                                     bool IsUnsigned, MDString *Name,
440                                     StorageType Storage, bool ShouldCreate) {
441   assert(isCanonical(Name) && "Expected canonical MDString");
442   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
443   Metadata *Ops[] = {Name};
444   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
445 }
446 
447 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
448                                   MDString *Name, uint64_t SizeInBits,
449                                   uint32_t AlignInBits, unsigned Encoding,
450                                   DIFlags Flags, StorageType Storage,
451                                   bool ShouldCreate) {
452   assert(isCanonical(Name) && "Expected canonical MDString");
453   DEFINE_GETIMPL_LOOKUP(DIBasicType,
454                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
455   Metadata *Ops[] = {nullptr, nullptr, Name};
456   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
457                       Flags), Ops);
458 }
459 
460 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
461   switch (getEncoding()) {
462   case dwarf::DW_ATE_signed:
463   case dwarf::DW_ATE_signed_char:
464     return Signedness::Signed;
465   case dwarf::DW_ATE_unsigned:
466   case dwarf::DW_ATE_unsigned_char:
467     return Signedness::Unsigned;
468   default:
469     return None;
470   }
471 }
472 
473 DIDerivedType *DIDerivedType::getImpl(
474     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
475     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
476     uint32_t AlignInBits, uint64_t OffsetInBits,
477     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
478     StorageType Storage, bool ShouldCreate) {
479   assert(isCanonical(Name) && "Expected canonical MDString");
480   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
481                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
482                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
483                          ExtraData));
484   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
485   DEFINE_GETIMPL_STORE(
486       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
487                       DWARFAddressSpace, Flags), Ops);
488 }
489 
490 DICompositeType *DICompositeType::getImpl(
491     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
492     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
493     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
494     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
495     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
496     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
497     StorageType Storage, bool ShouldCreate) {
498   assert(isCanonical(Name) && "Expected canonical MDString");
499 
500   // Keep this in sync with buildODRType.
501   DEFINE_GETIMPL_LOOKUP(DICompositeType,
502                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
503                          AlignInBits, OffsetInBits, Flags, Elements,
504                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
505                          Discriminator, DataLocation, Associated, Allocated));
506   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
507                      Elements,      VTableHolder, TemplateParams, Identifier,
508                      Discriminator, DataLocation, Associated,     Allocated};
509   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
510                                          AlignInBits, OffsetInBits, Flags),
511                        Ops);
512 }
513 
514 DICompositeType *DICompositeType::buildODRType(
515     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
516     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
517     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
518     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
519     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
520     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated) {
521   assert(!Identifier.getString().empty() && "Expected valid identifier");
522   if (!Context.isODRUniquingDebugTypes())
523     return nullptr;
524   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
525   if (!CT)
526     return CT = DICompositeType::getDistinct(
527                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
528                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
529                VTableHolder, TemplateParams, &Identifier, Discriminator,
530                DataLocation, Associated, Allocated);
531 
532   // Only mutate CT if it's a forward declaration and the new operands aren't.
533   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
534   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
535     return CT;
536 
537   // Mutate CT in place.  Keep this in sync with getImpl.
538   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
539              Flags);
540   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
541                      Elements,      VTableHolder, TemplateParams, &Identifier,
542                      Discriminator, DataLocation, Associated,     Allocated};
543   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
544          "Mismatched number of operands");
545   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
546     if (Ops[I] != CT->getOperand(I))
547       CT->setOperand(I, Ops[I]);
548   return CT;
549 }
550 
551 DICompositeType *DICompositeType::getODRType(
552     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
553     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
554     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
555     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
556     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
557     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated) {
558   assert(!Identifier.getString().empty() && "Expected valid identifier");
559   if (!Context.isODRUniquingDebugTypes())
560     return nullptr;
561   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
562   if (!CT)
563     CT = DICompositeType::getDistinct(
564         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
565         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
566         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
567         Allocated);
568   return CT;
569 }
570 
571 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
572                                                      MDString &Identifier) {
573   assert(!Identifier.getString().empty() && "Expected valid identifier");
574   if (!Context.isODRUniquingDebugTypes())
575     return nullptr;
576   return Context.pImpl->DITypeMap->lookup(&Identifier);
577 }
578 
579 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
580                                             uint8_t CC, Metadata *TypeArray,
581                                             StorageType Storage,
582                                             bool ShouldCreate) {
583   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
584   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
585   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
586 }
587 
588 // FIXME: Implement this string-enum correspondence with a .def file and macros,
589 // so that the association is explicit rather than implied.
590 static const char *ChecksumKindName[DIFile::CSK_Last] = {
591     "CSK_MD5",
592     "CSK_SHA1",
593     "CSK_SHA256",
594 };
595 
596 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
597   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
598   // The first space was originally the CSK_None variant, which is now
599   // obsolete, but the space is still reserved in ChecksumKind, so we account
600   // for it here.
601   return ChecksumKindName[CSKind - 1];
602 }
603 
604 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
605   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
606       .Case("CSK_MD5", DIFile::CSK_MD5)
607       .Case("CSK_SHA1", DIFile::CSK_SHA1)
608       .Case("CSK_SHA256", DIFile::CSK_SHA256)
609       .Default(None);
610 }
611 
612 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
613                         MDString *Directory,
614                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
615                         Optional<MDString *> Source, StorageType Storage,
616                         bool ShouldCreate) {
617   assert(isCanonical(Filename) && "Expected canonical MDString");
618   assert(isCanonical(Directory) && "Expected canonical MDString");
619   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
620   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
621   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
622   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
623                      Source.getValueOr(nullptr)};
624   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
625 }
626 
627 DICompileUnit *DICompileUnit::getImpl(
628     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
629     MDString *Producer, bool IsOptimized, MDString *Flags,
630     unsigned RuntimeVersion, MDString *SplitDebugFilename,
631     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
632     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
633     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
634     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
635     MDString *SDK, StorageType Storage, bool ShouldCreate) {
636   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
637   assert(isCanonical(Producer) && "Expected canonical MDString");
638   assert(isCanonical(Flags) && "Expected canonical MDString");
639   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
640 
641   Metadata *Ops[] = {File,
642                      Producer,
643                      Flags,
644                      SplitDebugFilename,
645                      EnumTypes,
646                      RetainedTypes,
647                      GlobalVariables,
648                      ImportedEntities,
649                      Macros,
650                      SysRoot,
651                      SDK};
652   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
653                        Context, Storage, SourceLanguage, IsOptimized,
654                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
655                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
656                        Ops),
657                    Storage);
658 }
659 
660 Optional<DICompileUnit::DebugEmissionKind>
661 DICompileUnit::getEmissionKind(StringRef Str) {
662   return StringSwitch<Optional<DebugEmissionKind>>(Str)
663       .Case("NoDebug", NoDebug)
664       .Case("FullDebug", FullDebug)
665       .Case("LineTablesOnly", LineTablesOnly)
666       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
667       .Default(None);
668 }
669 
670 Optional<DICompileUnit::DebugNameTableKind>
671 DICompileUnit::getNameTableKind(StringRef Str) {
672   return StringSwitch<Optional<DebugNameTableKind>>(Str)
673       .Case("Default", DebugNameTableKind::Default)
674       .Case("GNU", DebugNameTableKind::GNU)
675       .Case("None", DebugNameTableKind::None)
676       .Default(None);
677 }
678 
679 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
680   switch (EK) {
681   case NoDebug:        return "NoDebug";
682   case FullDebug:      return "FullDebug";
683   case LineTablesOnly: return "LineTablesOnly";
684   case DebugDirectivesOnly: return "DebugDirectivesOnly";
685   }
686   return nullptr;
687 }
688 
689 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
690   switch (NTK) {
691   case DebugNameTableKind::Default:
692     return nullptr;
693   case DebugNameTableKind::GNU:
694     return "GNU";
695   case DebugNameTableKind::None:
696     return "None";
697   }
698   return nullptr;
699 }
700 
701 DISubprogram *DILocalScope::getSubprogram() const {
702   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
703     return Block->getScope()->getSubprogram();
704   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
705 }
706 
707 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
708   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
709     return File->getScope()->getNonLexicalBlockFileScope();
710   return const_cast<DILocalScope *>(this);
711 }
712 
713 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
714   return StringSwitch<DISPFlags>(Flag)
715 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
716 #include "llvm/IR/DebugInfoFlags.def"
717       .Default(SPFlagZero);
718 }
719 
720 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
721   switch (Flag) {
722   // Appease a warning.
723   case SPFlagVirtuality:
724     return "";
725 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
726   case SPFlag##NAME:                                                           \
727     return "DISPFlag" #NAME;
728 #include "llvm/IR/DebugInfoFlags.def"
729   }
730   return "";
731 }
732 
733 DISubprogram::DISPFlags
734 DISubprogram::splitFlags(DISPFlags Flags,
735                          SmallVectorImpl<DISPFlags> &SplitFlags) {
736   // Multi-bit fields can require special handling. In our case, however, the
737   // only multi-bit field is virtuality, and all its values happen to be
738   // single-bit values, so the right behavior just falls out.
739 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
740   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
741     SplitFlags.push_back(Bit);                                                 \
742     Flags &= ~Bit;                                                             \
743   }
744 #include "llvm/IR/DebugInfoFlags.def"
745   return Flags;
746 }
747 
748 DISubprogram *DISubprogram::getImpl(
749     LLVMContext &Context, Metadata *Scope, MDString *Name,
750     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
751     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
752     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
753     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
754     Metadata *ThrownTypes, StorageType Storage, bool ShouldCreate) {
755   assert(isCanonical(Name) && "Expected canonical MDString");
756   assert(isCanonical(LinkageName) && "Expected canonical MDString");
757   DEFINE_GETIMPL_LOOKUP(DISubprogram,
758                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
759                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
760                          SPFlags, Unit, TemplateParams, Declaration,
761                          RetainedNodes, ThrownTypes));
762   SmallVector<Metadata *, 11> Ops = {
763       File,        Scope,         Name,           LinkageName,    Type,       Unit,
764       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
765   if (!ThrownTypes) {
766     Ops.pop_back();
767     if (!TemplateParams) {
768       Ops.pop_back();
769       if (!ContainingType)
770         Ops.pop_back();
771     }
772   }
773   DEFINE_GETIMPL_STORE_N(
774       DISubprogram,
775       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
776       Ops.size());
777 }
778 
779 bool DISubprogram::describes(const Function *F) const {
780   assert(F && "Invalid function");
781   return F->getSubprogram() == this;
782 }
783 
784 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
785                                         Metadata *File, unsigned Line,
786                                         unsigned Column, StorageType Storage,
787                                         bool ShouldCreate) {
788   // Fixup column.
789   adjustColumn(Column);
790 
791   assert(Scope && "Expected scope");
792   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
793   Metadata *Ops[] = {File, Scope};
794   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
795 }
796 
797 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
798                                                 Metadata *Scope, Metadata *File,
799                                                 unsigned Discriminator,
800                                                 StorageType Storage,
801                                                 bool ShouldCreate) {
802   assert(Scope && "Expected scope");
803   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
804   Metadata *Ops[] = {File, Scope};
805   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
806 }
807 
808 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
809                                   MDString *Name, bool ExportSymbols,
810                                   StorageType Storage, bool ShouldCreate) {
811   assert(isCanonical(Name) && "Expected canonical MDString");
812   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
813   // The nullptr is for DIScope's File operand. This should be refactored.
814   Metadata *Ops[] = {nullptr, Scope, Name};
815   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
816 }
817 
818 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
819                                       Metadata *Decl, MDString *Name,
820                                       Metadata *File, unsigned LineNo,
821                                       StorageType Storage, bool ShouldCreate) {
822   assert(isCanonical(Name) && "Expected canonical MDString");
823   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
824   // The nullptr is for DIScope's File operand. This should be refactored.
825   Metadata *Ops[] = {Scope, Decl, Name, File};
826   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
827 }
828 
829 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
830                             Metadata *Scope, MDString *Name,
831                             MDString *ConfigurationMacros,
832                             MDString *IncludePath, MDString *APINotesFile,
833                             unsigned LineNo, StorageType Storage,
834                             bool ShouldCreate) {
835   assert(isCanonical(Name) && "Expected canonical MDString");
836   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
837                                    IncludePath, APINotesFile, LineNo));
838   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
839                      IncludePath, APINotesFile};
840   DEFINE_GETIMPL_STORE(DIModule, (LineNo), Ops);
841 }
842 
843 DITemplateTypeParameter *
844 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
845                                  Metadata *Type, bool isDefault,
846                                  StorageType Storage, bool ShouldCreate) {
847   assert(isCanonical(Name) && "Expected canonical MDString");
848   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
849   Metadata *Ops[] = {Name, Type};
850   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
851 }
852 
853 DITemplateValueParameter *DITemplateValueParameter::getImpl(
854     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
855     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
856   assert(isCanonical(Name) && "Expected canonical MDString");
857   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
858                         (Tag, Name, Type, isDefault, Value));
859   Metadata *Ops[] = {Name, Type, Value};
860   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
861 }
862 
863 DIGlobalVariable *
864 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
865                           MDString *LinkageName, Metadata *File, unsigned Line,
866                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
867                           Metadata *StaticDataMemberDeclaration,
868                           Metadata *TemplateParams, uint32_t AlignInBits,
869                           StorageType Storage, bool ShouldCreate) {
870   assert(isCanonical(Name) && "Expected canonical MDString");
871   assert(isCanonical(LinkageName) && "Expected canonical MDString");
872   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
873                                            Type, IsLocalToUnit, IsDefinition,
874                                            StaticDataMemberDeclaration,
875                                            TemplateParams, AlignInBits));
876   Metadata *Ops[] = {Scope,
877                      Name,
878                      File,
879                      Type,
880                      Name,
881                      LinkageName,
882                      StaticDataMemberDeclaration,
883                      TemplateParams};
884   DEFINE_GETIMPL_STORE(DIGlobalVariable,
885                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
886 }
887 
888 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
889                                           MDString *Name, Metadata *File,
890                                           unsigned Line, Metadata *Type,
891                                           unsigned Arg, DIFlags Flags,
892                                           uint32_t AlignInBits,
893                                           StorageType Storage,
894                                           bool ShouldCreate) {
895   // 64K ought to be enough for any frontend.
896   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
897 
898   assert(Scope && "Expected scope");
899   assert(isCanonical(Name) && "Expected canonical MDString");
900   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
901                         (Scope, Name, File, Line, Type, Arg, Flags,
902                          AlignInBits));
903   Metadata *Ops[] = {Scope, Name, File, Type};
904   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
905 }
906 
907 Optional<uint64_t> DIVariable::getSizeInBits() const {
908   // This is used by the Verifier so be mindful of broken types.
909   const Metadata *RawType = getRawType();
910   while (RawType) {
911     // Try to get the size directly.
912     if (auto *T = dyn_cast<DIType>(RawType))
913       if (uint64_t Size = T->getSizeInBits())
914         return Size;
915 
916     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
917       // Look at the base type.
918       RawType = DT->getRawBaseType();
919       continue;
920     }
921 
922     // Missing type or size.
923     break;
924   }
925 
926   // Fail gracefully.
927   return None;
928 }
929 
930 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
931                           MDString *Name, Metadata *File, unsigned Line,
932                           StorageType Storage,
933                           bool ShouldCreate) {
934   assert(Scope && "Expected scope");
935   assert(isCanonical(Name) && "Expected canonical MDString");
936   DEFINE_GETIMPL_LOOKUP(DILabel,
937                         (Scope, Name, File, Line));
938   Metadata *Ops[] = {Scope, Name, File};
939   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
940 }
941 
942 DIExpression *DIExpression::getImpl(LLVMContext &Context,
943                                     ArrayRef<uint64_t> Elements,
944                                     StorageType Storage, bool ShouldCreate) {
945   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
946   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
947 }
948 
949 unsigned DIExpression::ExprOperand::getSize() const {
950   uint64_t Op = getOp();
951 
952   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
953     return 2;
954 
955   switch (Op) {
956   case dwarf::DW_OP_LLVM_convert:
957   case dwarf::DW_OP_LLVM_fragment:
958   case dwarf::DW_OP_bregx:
959     return 3;
960   case dwarf::DW_OP_constu:
961   case dwarf::DW_OP_consts:
962   case dwarf::DW_OP_deref_size:
963   case dwarf::DW_OP_plus_uconst:
964   case dwarf::DW_OP_LLVM_tag_offset:
965   case dwarf::DW_OP_LLVM_entry_value:
966   case dwarf::DW_OP_regx:
967     return 2;
968   default:
969     return 1;
970   }
971 }
972 
973 bool DIExpression::isValid() const {
974   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
975     // Check that there's space for the operand.
976     if (I->get() + I->getSize() > E->get())
977       return false;
978 
979     uint64_t Op = I->getOp();
980     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
981         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
982       return true;
983 
984     // Check that the operand is valid.
985     switch (Op) {
986     default:
987       return false;
988     case dwarf::DW_OP_LLVM_fragment:
989       // A fragment operator must appear at the end.
990       return I->get() + I->getSize() == E->get();
991     case dwarf::DW_OP_stack_value: {
992       // Must be the last one or followed by a DW_OP_LLVM_fragment.
993       if (I->get() + I->getSize() == E->get())
994         break;
995       auto J = I;
996       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
997         return false;
998       break;
999     }
1000     case dwarf::DW_OP_swap: {
1001       // Must be more than one implicit element on the stack.
1002 
1003       // FIXME: A better way to implement this would be to add a local variable
1004       // that keeps track of the stack depth and introduce something like a
1005       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1006       // DIExpression is attached to, or else pass the number of implicit stack
1007       // elements into isValid.
1008       if (getNumElements() == 1)
1009         return false;
1010       break;
1011     }
1012     case dwarf::DW_OP_LLVM_entry_value: {
1013       // An entry value operator must appear at the beginning and the number of
1014       // operations it cover can currently only be 1, because we support only
1015       // entry values of a simple register location. One reason for this is that
1016       // we currently can't calculate the size of the resulting DWARF block for
1017       // other expressions.
1018       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1 &&
1019              getNumElements() == 2;
1020     }
1021     case dwarf::DW_OP_LLVM_convert:
1022     case dwarf::DW_OP_LLVM_tag_offset:
1023     case dwarf::DW_OP_constu:
1024     case dwarf::DW_OP_plus_uconst:
1025     case dwarf::DW_OP_plus:
1026     case dwarf::DW_OP_minus:
1027     case dwarf::DW_OP_mul:
1028     case dwarf::DW_OP_div:
1029     case dwarf::DW_OP_mod:
1030     case dwarf::DW_OP_or:
1031     case dwarf::DW_OP_and:
1032     case dwarf::DW_OP_xor:
1033     case dwarf::DW_OP_shl:
1034     case dwarf::DW_OP_shr:
1035     case dwarf::DW_OP_shra:
1036     case dwarf::DW_OP_deref:
1037     case dwarf::DW_OP_deref_size:
1038     case dwarf::DW_OP_xderef:
1039     case dwarf::DW_OP_lit0:
1040     case dwarf::DW_OP_not:
1041     case dwarf::DW_OP_dup:
1042     case dwarf::DW_OP_regx:
1043     case dwarf::DW_OP_bregx:
1044     case dwarf::DW_OP_push_object_address:
1045       break;
1046     }
1047   }
1048   return true;
1049 }
1050 
1051 bool DIExpression::isImplicit() const {
1052   if (!isValid())
1053     return false;
1054 
1055   if (getNumElements() == 0)
1056     return false;
1057 
1058   for (const auto &It : expr_ops()) {
1059     switch (It.getOp()) {
1060     default:
1061       break;
1062     case dwarf::DW_OP_stack_value:
1063     case dwarf::DW_OP_LLVM_tag_offset:
1064       return true;
1065     }
1066   }
1067 
1068   return false;
1069 }
1070 
1071 bool DIExpression::isComplex() const {
1072   if (!isValid())
1073     return false;
1074 
1075   if (getNumElements() == 0)
1076     return false;
1077 
1078   // If there are any elements other than fragment or tag_offset, then some
1079   // kind of complex computation occurs.
1080   for (const auto &It : expr_ops()) {
1081     switch (It.getOp()) {
1082       case dwarf::DW_OP_LLVM_tag_offset:
1083       case dwarf::DW_OP_LLVM_fragment:
1084         continue;
1085       default: return true;
1086     }
1087   }
1088 
1089   return false;
1090 }
1091 
1092 Optional<DIExpression::FragmentInfo>
1093 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1094   for (auto I = Start; I != End; ++I)
1095     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1096       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1097       return Info;
1098     }
1099   return None;
1100 }
1101 
1102 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1103                                 int64_t Offset) {
1104   if (Offset > 0) {
1105     Ops.push_back(dwarf::DW_OP_plus_uconst);
1106     Ops.push_back(Offset);
1107   } else if (Offset < 0) {
1108     Ops.push_back(dwarf::DW_OP_constu);
1109     Ops.push_back(-Offset);
1110     Ops.push_back(dwarf::DW_OP_minus);
1111   }
1112 }
1113 
1114 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1115   if (getNumElements() == 0) {
1116     Offset = 0;
1117     return true;
1118   }
1119 
1120   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1121     Offset = Elements[1];
1122     return true;
1123   }
1124 
1125   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1126     if (Elements[2] == dwarf::DW_OP_plus) {
1127       Offset = Elements[1];
1128       return true;
1129     }
1130     if (Elements[2] == dwarf::DW_OP_minus) {
1131       Offset = -Elements[1];
1132       return true;
1133     }
1134   }
1135 
1136   return false;
1137 }
1138 
1139 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1140                                                       unsigned &AddrClass) {
1141   // FIXME: This seems fragile. Nothing that verifies that these elements
1142   // actually map to ops and not operands.
1143   const unsigned PatternSize = 4;
1144   if (Expr->Elements.size() >= PatternSize &&
1145       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1146       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1147       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1148     AddrClass = Expr->Elements[PatternSize - 3];
1149 
1150     if (Expr->Elements.size() == PatternSize)
1151       return nullptr;
1152     return DIExpression::get(Expr->getContext(),
1153                              makeArrayRef(&*Expr->Elements.begin(),
1154                                           Expr->Elements.size() - PatternSize));
1155   }
1156   return Expr;
1157 }
1158 
1159 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1160                                     int64_t Offset) {
1161   SmallVector<uint64_t, 8> Ops;
1162   if (Flags & DIExpression::DerefBefore)
1163     Ops.push_back(dwarf::DW_OP_deref);
1164 
1165   appendOffset(Ops, Offset);
1166   if (Flags & DIExpression::DerefAfter)
1167     Ops.push_back(dwarf::DW_OP_deref);
1168 
1169   bool StackValue = Flags & DIExpression::StackValue;
1170   bool EntryValue = Flags & DIExpression::EntryValue;
1171 
1172   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1173 }
1174 
1175 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1176                                            SmallVectorImpl<uint64_t> &Ops,
1177                                            bool StackValue,
1178                                            bool EntryValue) {
1179   assert(Expr && "Can't prepend ops to this expression");
1180 
1181   if (EntryValue) {
1182     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1183     // Add size info needed for entry value expression.
1184     // Add plus one for target register operand.
1185     Ops.push_back(Expr->getNumElements() + 1);
1186   }
1187 
1188   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1189   if (Ops.empty())
1190     StackValue = false;
1191   for (auto Op : Expr->expr_ops()) {
1192     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1193     if (StackValue) {
1194       if (Op.getOp() == dwarf::DW_OP_stack_value)
1195         StackValue = false;
1196       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1197         Ops.push_back(dwarf::DW_OP_stack_value);
1198         StackValue = false;
1199       }
1200     }
1201     Op.appendToVector(Ops);
1202   }
1203   if (StackValue)
1204     Ops.push_back(dwarf::DW_OP_stack_value);
1205   return DIExpression::get(Expr->getContext(), Ops);
1206 }
1207 
1208 DIExpression *DIExpression::append(const DIExpression *Expr,
1209                                    ArrayRef<uint64_t> Ops) {
1210   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1211 
1212   // Copy Expr's current op list.
1213   SmallVector<uint64_t, 16> NewOps;
1214   for (auto Op : Expr->expr_ops()) {
1215     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1216     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1217         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1218       NewOps.append(Ops.begin(), Ops.end());
1219 
1220       // Ensure that the new opcodes are only appended once.
1221       Ops = None;
1222     }
1223     Op.appendToVector(NewOps);
1224   }
1225 
1226   NewOps.append(Ops.begin(), Ops.end());
1227   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1228   assert(result->isValid() && "concatenated expression is not valid");
1229   return result;
1230 }
1231 
1232 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1233                                           ArrayRef<uint64_t> Ops) {
1234   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1235   assert(none_of(Ops,
1236                  [](uint64_t Op) {
1237                    return Op == dwarf::DW_OP_stack_value ||
1238                           Op == dwarf::DW_OP_LLVM_fragment;
1239                  }) &&
1240          "Can't append this op");
1241 
1242   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1243   // has no DW_OP_stack_value.
1244   //
1245   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1246   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1247   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1248   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1249       Expr->getElements().drop_back(DropUntilStackValue);
1250   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1251                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1252   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1253 
1254   // Append a DW_OP_deref after Expr's current op list if needed, then append
1255   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1256   SmallVector<uint64_t, 16> NewOps;
1257   if (NeedsDeref)
1258     NewOps.push_back(dwarf::DW_OP_deref);
1259   NewOps.append(Ops.begin(), Ops.end());
1260   if (NeedsStackValue)
1261     NewOps.push_back(dwarf::DW_OP_stack_value);
1262   return DIExpression::append(Expr, NewOps);
1263 }
1264 
1265 Optional<DIExpression *> DIExpression::createFragmentExpression(
1266     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1267   SmallVector<uint64_t, 8> Ops;
1268   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1269   if (Expr) {
1270     for (auto Op : Expr->expr_ops()) {
1271       switch (Op.getOp()) {
1272       default: break;
1273       case dwarf::DW_OP_shr:
1274       case dwarf::DW_OP_shra:
1275       case dwarf::DW_OP_shl:
1276       case dwarf::DW_OP_plus:
1277       case dwarf::DW_OP_plus_uconst:
1278       case dwarf::DW_OP_minus:
1279         // We can't safely split arithmetic or shift operations into multiple
1280         // fragments because we can't express carry-over between fragments.
1281         //
1282         // FIXME: We *could* preserve the lowest fragment of a constant offset
1283         // operation if the offset fits into SizeInBits.
1284         return None;
1285       case dwarf::DW_OP_LLVM_fragment: {
1286         // Make the new offset point into the existing fragment.
1287         uint64_t FragmentOffsetInBits = Op.getArg(0);
1288         uint64_t FragmentSizeInBits = Op.getArg(1);
1289         (void)FragmentSizeInBits;
1290         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1291                "new fragment outside of original fragment");
1292         OffsetInBits += FragmentOffsetInBits;
1293         continue;
1294       }
1295       }
1296       Op.appendToVector(Ops);
1297     }
1298   }
1299   assert(Expr && "Unknown DIExpression");
1300   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1301   Ops.push_back(OffsetInBits);
1302   Ops.push_back(SizeInBits);
1303   return DIExpression::get(Expr->getContext(), Ops);
1304 }
1305 
1306 bool DIExpression::isConstant() const {
1307   // Recognize DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment Len Ofs)?.
1308   if (getNumElements() != 3 && getNumElements() != 6)
1309     return false;
1310   if (getElement(0) != dwarf::DW_OP_constu ||
1311       getElement(2) != dwarf::DW_OP_stack_value)
1312     return false;
1313   if (getNumElements() == 6 && getElement(3) != dwarf::DW_OP_LLVM_fragment)
1314     return false;
1315   return true;
1316 }
1317 
1318 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1319                                              bool Signed) {
1320   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1321   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1322                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1323   return Ops;
1324 }
1325 
1326 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1327                                       unsigned FromSize, unsigned ToSize,
1328                                       bool Signed) {
1329   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1330 }
1331 
1332 DIGlobalVariableExpression *
1333 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1334                                     Metadata *Expression, StorageType Storage,
1335                                     bool ShouldCreate) {
1336   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1337   Metadata *Ops[] = {Variable, Expression};
1338   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1339 }
1340 
1341 DIObjCProperty *DIObjCProperty::getImpl(
1342     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1343     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1344     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1345   assert(isCanonical(Name) && "Expected canonical MDString");
1346   assert(isCanonical(GetterName) && "Expected canonical MDString");
1347   assert(isCanonical(SetterName) && "Expected canonical MDString");
1348   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1349                                          SetterName, Attributes, Type));
1350   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1351   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1352 }
1353 
1354 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1355                                             Metadata *Scope, Metadata *Entity,
1356                                             Metadata *File, unsigned Line,
1357                                             MDString *Name, StorageType Storage,
1358                                             bool ShouldCreate) {
1359   assert(isCanonical(Name) && "Expected canonical MDString");
1360   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1361                         (Tag, Scope, Entity, File, Line, Name));
1362   Metadata *Ops[] = {Scope, Entity, Name, File};
1363   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1364 }
1365 
1366 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1367                           unsigned Line, MDString *Name, MDString *Value,
1368                           StorageType Storage, bool ShouldCreate) {
1369   assert(isCanonical(Name) && "Expected canonical MDString");
1370   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1371   Metadata *Ops[] = { Name, Value };
1372   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1373 }
1374 
1375 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1376                                   unsigned Line, Metadata *File,
1377                                   Metadata *Elements, StorageType Storage,
1378                                   bool ShouldCreate) {
1379   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1380                         (MIType, Line, File, Elements));
1381   Metadata *Ops[] = { File, Elements };
1382   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1383 }
1384