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 namespace llvm {
27 // Use FS-AFDO discriminator.
28 cl::opt<bool> EnableFSDiscriminator(
29     "enable-fs-discriminator", cl::Hidden, cl::init(false),
30     cl::desc("Enable adding flow sensitive discriminators"));
31 } // namespace llvm
32 
33 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
34     std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
35 
36 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
37                        unsigned Column, ArrayRef<Metadata *> MDs,
38                        bool ImplicitCode)
39     : MDNode(C, DILocationKind, Storage, MDs) {
40   assert((MDs.size() == 1 || MDs.size() == 2) &&
41          "Expected a scope and optional inlined-at");
42 
43   // Set line and column.
44   assert(Column < (1u << 16) && "Expected 16-bit column");
45 
46   SubclassData32 = Line;
47   SubclassData16 = Column;
48 
49   setImplicitCode(ImplicitCode);
50 }
51 
52 static void adjustColumn(unsigned &Column) {
53   // Set to unknown on overflow.  We only have 16 bits to play with here.
54   if (Column >= (1u << 16))
55     Column = 0;
56 }
57 
58 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
59                                 unsigned Column, Metadata *Scope,
60                                 Metadata *InlinedAt, bool ImplicitCode,
61                                 StorageType Storage, bool ShouldCreate) {
62   // Fixup column.
63   adjustColumn(Column);
64 
65   if (Storage == Uniqued) {
66     if (auto *N = getUniqued(Context.pImpl->DILocations,
67                              DILocationInfo::KeyTy(Line, Column, Scope,
68                                                    InlinedAt, ImplicitCode)))
69       return N;
70     if (!ShouldCreate)
71       return nullptr;
72   } else {
73     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
74   }
75 
76   SmallVector<Metadata *, 2> Ops;
77   Ops.push_back(Scope);
78   if (InlinedAt)
79     Ops.push_back(InlinedAt);
80   return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
81                                                Ops, ImplicitCode),
82                    Storage, Context.pImpl->DILocations);
83 }
84 
85 const
86 DILocation *DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) {
87   if (Locs.empty())
88     return nullptr;
89   if (Locs.size() == 1)
90     return Locs[0];
91   auto *Merged = Locs[0];
92   for (const DILocation *L : llvm::drop_begin(Locs)) {
93     Merged = getMergedLocation(Merged, L);
94     if (Merged == nullptr)
95       break;
96   }
97   return Merged;
98 }
99 
100 const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
101                                                 const DILocation *LocB) {
102   if (!LocA || !LocB)
103     return nullptr;
104 
105   if (LocA == LocB)
106     return LocA;
107 
108   SmallPtrSet<DILocation *, 5> InlinedLocationsA;
109   for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
110     InlinedLocationsA.insert(L);
111   SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
112   DIScope *S = LocA->getScope();
113   DILocation *L = LocA->getInlinedAt();
114   while (S) {
115     Locations.insert(std::make_pair(S, L));
116     S = S->getScope();
117     if (!S && L) {
118       S = L->getScope();
119       L = L->getInlinedAt();
120     }
121   }
122   const DILocation *Result = LocB;
123   S = LocB->getScope();
124   L = LocB->getInlinedAt();
125   while (S) {
126     if (Locations.count(std::make_pair(S, L)))
127       break;
128     S = S->getScope();
129     if (!S && L) {
130       S = L->getScope();
131       L = L->getInlinedAt();
132     }
133   }
134 
135   // If the two locations are irreconsilable, just pick one. This is misleading,
136   // but on the other hand, it's a "line 0" location.
137   if (!S || !isa<DILocalScope>(S))
138     S = LocA->getScope();
139   return DILocation::get(Result->getContext(), 0, 0, S, L);
140 }
141 
142 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
143   std::array<unsigned, 3> Components = {BD, DF, CI};
144   uint64_t RemainingWork = 0U;
145   // We use RemainingWork to figure out if we have no remaining components to
146   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
147   // encode anything for the latter 2.
148   // Since any of the input components is at most 32 bits, their sum will be
149   // less than 34 bits, and thus RemainingWork won't overflow.
150   RemainingWork = std::accumulate(Components.begin(), Components.end(), RemainingWork);
151 
152   int I = 0;
153   unsigned Ret = 0;
154   unsigned NextBitInsertionIndex = 0;
155   while (RemainingWork > 0) {
156     unsigned C = Components[I++];
157     RemainingWork -= C;
158     unsigned EC = encodeComponent(C);
159     Ret |= (EC << NextBitInsertionIndex);
160     NextBitInsertionIndex += encodingBits(C);
161   }
162 
163   // Encoding may be unsuccessful because of overflow. We determine success by
164   // checking equivalence of components before & after encoding. Alternatively,
165   // we could determine Success during encoding, but the current alternative is
166   // simpler.
167   unsigned TBD, TDF, TCI = 0;
168   decodeDiscriminator(Ret, TBD, TDF, TCI);
169   if (TBD == BD && TDF == DF && TCI == CI)
170     return Ret;
171   return None;
172 }
173 
174 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
175                                      unsigned &CI) {
176   BD = getUnsignedFromPrefixEncoding(D);
177   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
178   CI = getUnsignedFromPrefixEncoding(
179       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
180 }
181 
182 
183 DINode::DIFlags DINode::getFlag(StringRef Flag) {
184   return StringSwitch<DIFlags>(Flag)
185 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
186 #include "llvm/IR/DebugInfoFlags.def"
187       .Default(DINode::FlagZero);
188 }
189 
190 StringRef DINode::getFlagString(DIFlags Flag) {
191   switch (Flag) {
192 #define HANDLE_DI_FLAG(ID, NAME)                                               \
193   case Flag##NAME:                                                             \
194     return "DIFlag" #NAME;
195 #include "llvm/IR/DebugInfoFlags.def"
196   }
197   return "";
198 }
199 
200 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
201                                    SmallVectorImpl<DIFlags> &SplitFlags) {
202   // Flags that are packed together need to be specially handled, so
203   // that, for example, we emit "DIFlagPublic" and not
204   // "DIFlagPrivate | DIFlagProtected".
205   if (DIFlags A = Flags & FlagAccessibility) {
206     if (A == FlagPrivate)
207       SplitFlags.push_back(FlagPrivate);
208     else if (A == FlagProtected)
209       SplitFlags.push_back(FlagProtected);
210     else
211       SplitFlags.push_back(FlagPublic);
212     Flags &= ~A;
213   }
214   if (DIFlags R = Flags & FlagPtrToMemberRep) {
215     if (R == FlagSingleInheritance)
216       SplitFlags.push_back(FlagSingleInheritance);
217     else if (R == FlagMultipleInheritance)
218       SplitFlags.push_back(FlagMultipleInheritance);
219     else
220       SplitFlags.push_back(FlagVirtualInheritance);
221     Flags &= ~R;
222   }
223   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
224     Flags &= ~FlagIndirectVirtualBase;
225     SplitFlags.push_back(FlagIndirectVirtualBase);
226   }
227 
228 #define HANDLE_DI_FLAG(ID, NAME)                                               \
229   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
230     SplitFlags.push_back(Bit);                                                 \
231     Flags &= ~Bit;                                                             \
232   }
233 #include "llvm/IR/DebugInfoFlags.def"
234   return Flags;
235 }
236 
237 DIScope *DIScope::getScope() const {
238   if (auto *T = dyn_cast<DIType>(this))
239     return T->getScope();
240 
241   if (auto *SP = dyn_cast<DISubprogram>(this))
242     return SP->getScope();
243 
244   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
245     return LB->getScope();
246 
247   if (auto *NS = dyn_cast<DINamespace>(this))
248     return NS->getScope();
249 
250   if (auto *CB = dyn_cast<DICommonBlock>(this))
251     return CB->getScope();
252 
253   if (auto *M = dyn_cast<DIModule>(this))
254     return M->getScope();
255 
256   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
257          "Unhandled type of scope.");
258   return nullptr;
259 }
260 
261 StringRef DIScope::getName() const {
262   if (auto *T = dyn_cast<DIType>(this))
263     return T->getName();
264   if (auto *SP = dyn_cast<DISubprogram>(this))
265     return SP->getName();
266   if (auto *NS = dyn_cast<DINamespace>(this))
267     return NS->getName();
268   if (auto *CB = dyn_cast<DICommonBlock>(this))
269     return CB->getName();
270   if (auto *M = dyn_cast<DIModule>(this))
271     return M->getName();
272   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
273           isa<DICompileUnit>(this)) &&
274          "Unhandled type of scope.");
275   return "";
276 }
277 
278 #ifndef NDEBUG
279 static bool isCanonical(const MDString *S) {
280   return !S || !S->getString().empty();
281 }
282 #endif
283 
284 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
285                                       MDString *Header,
286                                       ArrayRef<Metadata *> DwarfOps,
287                                       StorageType Storage, bool ShouldCreate) {
288   unsigned Hash = 0;
289   if (Storage == Uniqued) {
290     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
291     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
292       return N;
293     if (!ShouldCreate)
294       return nullptr;
295     Hash = Key.getHash();
296   } else {
297     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
298   }
299 
300   // Use a nullptr for empty headers.
301   assert(isCanonical(Header) && "Expected canonical MDString");
302   Metadata *PreOps[] = {Header};
303   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
304                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
305                    Storage, Context.pImpl->GenericDINodes);
306 }
307 
308 void GenericDINode::recalculateHash() {
309   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
310 }
311 
312 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
313 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
314 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
315   do {                                                                         \
316     if (Storage == Uniqued) {                                                  \
317       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
318                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
319         return N;                                                              \
320       if (!ShouldCreate)                                                       \
321         return nullptr;                                                        \
322     } else {                                                                   \
323       assert(ShouldCreate &&                                                   \
324              "Expected non-uniqued nodes to always be created");               \
325     }                                                                          \
326   } while (false)
327 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
328   return storeImpl(new (array_lengthof(OPS))                                   \
329                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
330                    Storage, Context.pImpl->CLASS##s)
331 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
332   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
333                    Storage, Context.pImpl->CLASS##s)
334 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
335   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
336                    Storage, Context.pImpl->CLASS##s)
337 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
338   return storeImpl(new (NUM_OPS)                                               \
339                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
340                    Storage, Context.pImpl->CLASS##s)
341 
342 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
343                                 StorageType Storage, bool ShouldCreate) {
344   auto *CountNode = ConstantAsMetadata::get(
345       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
346   auto *LB = ConstantAsMetadata::get(
347       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
348   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
349                  ShouldCreate);
350 }
351 
352 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
353                                 int64_t Lo, StorageType Storage,
354                                 bool ShouldCreate) {
355   auto *LB = ConstantAsMetadata::get(
356       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
357   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
358                  ShouldCreate);
359 }
360 
361 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
362                                 Metadata *LB, Metadata *UB, Metadata *Stride,
363                                 StorageType Storage, bool ShouldCreate) {
364   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
365   Metadata *Ops[] = {CountNode, LB, UB, Stride};
366   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
367 }
368 
369 DISubrange::BoundType DISubrange::getCount() const {
370   Metadata *CB = getRawCountNode();
371   if (!CB)
372     return BoundType();
373 
374   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
375           isa<DIExpression>(CB)) &&
376          "Count must be signed constant or DIVariable or DIExpression");
377 
378   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
379     return BoundType(cast<ConstantInt>(MD->getValue()));
380 
381   if (auto *MD = dyn_cast<DIVariable>(CB))
382     return BoundType(MD);
383 
384   if (auto *MD = dyn_cast<DIExpression>(CB))
385     return BoundType(MD);
386 
387   return BoundType();
388 }
389 
390 DISubrange::BoundType DISubrange::getLowerBound() const {
391   Metadata *LB = getRawLowerBound();
392   if (!LB)
393     return BoundType();
394 
395   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
396           isa<DIExpression>(LB)) &&
397          "LowerBound must be signed constant or DIVariable or DIExpression");
398 
399   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
400     return BoundType(cast<ConstantInt>(MD->getValue()));
401 
402   if (auto *MD = dyn_cast<DIVariable>(LB))
403     return BoundType(MD);
404 
405   if (auto *MD = dyn_cast<DIExpression>(LB))
406     return BoundType(MD);
407 
408   return BoundType();
409 }
410 
411 DISubrange::BoundType DISubrange::getUpperBound() const {
412   Metadata *UB = getRawUpperBound();
413   if (!UB)
414     return BoundType();
415 
416   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
417           isa<DIExpression>(UB)) &&
418          "UpperBound must be signed constant or DIVariable or DIExpression");
419 
420   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
421     return BoundType(cast<ConstantInt>(MD->getValue()));
422 
423   if (auto *MD = dyn_cast<DIVariable>(UB))
424     return BoundType(MD);
425 
426   if (auto *MD = dyn_cast<DIExpression>(UB))
427     return BoundType(MD);
428 
429   return BoundType();
430 }
431 
432 DISubrange::BoundType DISubrange::getStride() const {
433   Metadata *ST = getRawStride();
434   if (!ST)
435     return BoundType();
436 
437   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
438           isa<DIExpression>(ST)) &&
439          "Stride must be signed constant or DIVariable or DIExpression");
440 
441   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
442     return BoundType(cast<ConstantInt>(MD->getValue()));
443 
444   if (auto *MD = dyn_cast<DIVariable>(ST))
445     return BoundType(MD);
446 
447   if (auto *MD = dyn_cast<DIExpression>(ST))
448     return BoundType(MD);
449 
450   return BoundType();
451 }
452 
453 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
454                                               Metadata *CountNode, Metadata *LB,
455                                               Metadata *UB, Metadata *Stride,
456                                               StorageType Storage,
457                                               bool ShouldCreate) {
458   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
459   Metadata *Ops[] = {CountNode, LB, UB, Stride};
460   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
461 }
462 
463 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
464   Metadata *CB = getRawCountNode();
465   if (!CB)
466     return BoundType();
467 
468   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
469          "Count must be signed constant or DIVariable or DIExpression");
470 
471   if (auto *MD = dyn_cast<DIVariable>(CB))
472     return BoundType(MD);
473 
474   if (auto *MD = dyn_cast<DIExpression>(CB))
475     return BoundType(MD);
476 
477   return BoundType();
478 }
479 
480 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
481   Metadata *LB = getRawLowerBound();
482   if (!LB)
483     return BoundType();
484 
485   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
486          "LowerBound must be signed constant or DIVariable or DIExpression");
487 
488   if (auto *MD = dyn_cast<DIVariable>(LB))
489     return BoundType(MD);
490 
491   if (auto *MD = dyn_cast<DIExpression>(LB))
492     return BoundType(MD);
493 
494   return BoundType();
495 }
496 
497 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
498   Metadata *UB = getRawUpperBound();
499   if (!UB)
500     return BoundType();
501 
502   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
503          "UpperBound must be signed constant or DIVariable or DIExpression");
504 
505   if (auto *MD = dyn_cast<DIVariable>(UB))
506     return BoundType(MD);
507 
508   if (auto *MD = dyn_cast<DIExpression>(UB))
509     return BoundType(MD);
510 
511   return BoundType();
512 }
513 
514 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
515   Metadata *ST = getRawStride();
516   if (!ST)
517     return BoundType();
518 
519   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
520          "Stride must be signed constant or DIVariable or DIExpression");
521 
522   if (auto *MD = dyn_cast<DIVariable>(ST))
523     return BoundType(MD);
524 
525   if (auto *MD = dyn_cast<DIExpression>(ST))
526     return BoundType(MD);
527 
528   return BoundType();
529 }
530 
531 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
532                                     bool IsUnsigned, MDString *Name,
533                                     StorageType Storage, bool ShouldCreate) {
534   assert(isCanonical(Name) && "Expected canonical MDString");
535   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
536   Metadata *Ops[] = {Name};
537   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
538 }
539 
540 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
541                                   MDString *Name, uint64_t SizeInBits,
542                                   uint32_t AlignInBits, unsigned Encoding,
543                                   DIFlags Flags, StorageType Storage,
544                                   bool ShouldCreate) {
545   assert(isCanonical(Name) && "Expected canonical MDString");
546   DEFINE_GETIMPL_LOOKUP(DIBasicType,
547                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
548   Metadata *Ops[] = {nullptr, nullptr, Name};
549   DEFINE_GETIMPL_STORE(DIBasicType, (Tag, SizeInBits, AlignInBits, Encoding,
550                       Flags), Ops);
551 }
552 
553 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
554   switch (getEncoding()) {
555   case dwarf::DW_ATE_signed:
556   case dwarf::DW_ATE_signed_char:
557     return Signedness::Signed;
558   case dwarf::DW_ATE_unsigned:
559   case dwarf::DW_ATE_unsigned_char:
560     return Signedness::Unsigned;
561   default:
562     return None;
563   }
564 }
565 
566 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
567                                     MDString *Name, Metadata *StringLength,
568                                     Metadata *StringLengthExp,
569                                     uint64_t SizeInBits, uint32_t AlignInBits,
570                                     unsigned Encoding, StorageType Storage,
571                                     bool ShouldCreate) {
572   assert(isCanonical(Name) && "Expected canonical MDString");
573   DEFINE_GETIMPL_LOOKUP(DIStringType, (Tag, Name, StringLength, StringLengthExp,
574                                        SizeInBits, AlignInBits, Encoding));
575   Metadata *Ops[] = {nullptr, nullptr, Name, StringLength, StringLengthExp};
576   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
577                        Ops);
578 }
579 
580 DIDerivedType *DIDerivedType::getImpl(
581     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
582     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
583     uint32_t AlignInBits, uint64_t OffsetInBits,
584     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
585     Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
586   assert(isCanonical(Name) && "Expected canonical MDString");
587   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
588                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
589                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
590                          ExtraData, Annotations));
591   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
592   DEFINE_GETIMPL_STORE(
593       DIDerivedType, (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
594                       DWARFAddressSpace, Flags), Ops);
595 }
596 
597 DICompositeType *DICompositeType::getImpl(
598     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
599     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
600     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
601     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
602     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
603     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
604     Metadata *Rank, Metadata *Annotations, StorageType Storage,
605     bool ShouldCreate) {
606   assert(isCanonical(Name) && "Expected canonical MDString");
607 
608   // Keep this in sync with buildODRType.
609   DEFINE_GETIMPL_LOOKUP(DICompositeType,
610                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
611                          AlignInBits, OffsetInBits, Flags, Elements,
612                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
613                          Discriminator, DataLocation, Associated, Allocated,
614                          Rank, Annotations));
615   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
616                      Elements,      VTableHolder, TemplateParams, Identifier,
617                      Discriminator, DataLocation, Associated,     Allocated,
618                      Rank,          Annotations};
619   DEFINE_GETIMPL_STORE(DICompositeType, (Tag, Line, RuntimeLang, SizeInBits,
620                                          AlignInBits, OffsetInBits, Flags),
621                        Ops);
622 }
623 
624 DICompositeType *DICompositeType::buildODRType(
625     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
626     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
627     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
628     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
629     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
630     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
631     Metadata *Rank, Metadata *Annotations) {
632   assert(!Identifier.getString().empty() && "Expected valid identifier");
633   if (!Context.isODRUniquingDebugTypes())
634     return nullptr;
635   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
636   if (!CT)
637     return CT = DICompositeType::getDistinct(
638                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
639                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
640                VTableHolder, TemplateParams, &Identifier, Discriminator,
641                DataLocation, Associated, Allocated, Rank, Annotations);
642 
643   if (CT->getTag() != Tag)
644     return nullptr;
645 
646   // Only mutate CT if it's a forward declaration and the new operands aren't.
647   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
648   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
649     return CT;
650 
651   // Mutate CT in place.  Keep this in sync with getImpl.
652   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
653              Flags);
654   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
655                      Elements,      VTableHolder, TemplateParams, &Identifier,
656                      Discriminator, DataLocation, Associated,     Allocated,
657                      Rank,          Annotations};
658   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
659          "Mismatched number of operands");
660   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
661     if (Ops[I] != CT->getOperand(I))
662       CT->setOperand(I, Ops[I]);
663   return CT;
664 }
665 
666 DICompositeType *DICompositeType::getODRType(
667     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
668     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
669     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
670     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
671     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
672     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
673     Metadata *Rank, Metadata *Annotations) {
674   assert(!Identifier.getString().empty() && "Expected valid identifier");
675   if (!Context.isODRUniquingDebugTypes())
676     return nullptr;
677   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
678   if (!CT) {
679     CT = DICompositeType::getDistinct(
680         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
681         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
682         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
683         Allocated, Rank, Annotations);
684   } else {
685     if (CT->getTag() != Tag)
686       return nullptr;
687   }
688   return CT;
689 }
690 
691 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
692                                                      MDString &Identifier) {
693   assert(!Identifier.getString().empty() && "Expected valid identifier");
694   if (!Context.isODRUniquingDebugTypes())
695     return nullptr;
696   return Context.pImpl->DITypeMap->lookup(&Identifier);
697 }
698 
699 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
700                                             uint8_t CC, Metadata *TypeArray,
701                                             StorageType Storage,
702                                             bool ShouldCreate) {
703   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
704   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
705   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
706 }
707 
708 // FIXME: Implement this string-enum correspondence with a .def file and macros,
709 // so that the association is explicit rather than implied.
710 static const char *ChecksumKindName[DIFile::CSK_Last] = {
711     "CSK_MD5",
712     "CSK_SHA1",
713     "CSK_SHA256",
714 };
715 
716 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
717   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
718   // The first space was originally the CSK_None variant, which is now
719   // obsolete, but the space is still reserved in ChecksumKind, so we account
720   // for it here.
721   return ChecksumKindName[CSKind - 1];
722 }
723 
724 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
725   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
726       .Case("CSK_MD5", DIFile::CSK_MD5)
727       .Case("CSK_SHA1", DIFile::CSK_SHA1)
728       .Case("CSK_SHA256", DIFile::CSK_SHA256)
729       .Default(None);
730 }
731 
732 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
733                         MDString *Directory,
734                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
735                         Optional<MDString *> Source, StorageType Storage,
736                         bool ShouldCreate) {
737   assert(isCanonical(Filename) && "Expected canonical MDString");
738   assert(isCanonical(Directory) && "Expected canonical MDString");
739   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
740   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
741   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
742   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
743                      Source.getValueOr(nullptr)};
744   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
745 }
746 
747 DICompileUnit *DICompileUnit::getImpl(
748     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
749     MDString *Producer, bool IsOptimized, MDString *Flags,
750     unsigned RuntimeVersion, MDString *SplitDebugFilename,
751     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
752     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
753     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
754     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
755     MDString *SDK, StorageType Storage, bool ShouldCreate) {
756   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
757   assert(isCanonical(Producer) && "Expected canonical MDString");
758   assert(isCanonical(Flags) && "Expected canonical MDString");
759   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
760 
761   Metadata *Ops[] = {File,
762                      Producer,
763                      Flags,
764                      SplitDebugFilename,
765                      EnumTypes,
766                      RetainedTypes,
767                      GlobalVariables,
768                      ImportedEntities,
769                      Macros,
770                      SysRoot,
771                      SDK};
772   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
773                        Context, Storage, SourceLanguage, IsOptimized,
774                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
775                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
776                        Ops),
777                    Storage);
778 }
779 
780 Optional<DICompileUnit::DebugEmissionKind>
781 DICompileUnit::getEmissionKind(StringRef Str) {
782   return StringSwitch<Optional<DebugEmissionKind>>(Str)
783       .Case("NoDebug", NoDebug)
784       .Case("FullDebug", FullDebug)
785       .Case("LineTablesOnly", LineTablesOnly)
786       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
787       .Default(None);
788 }
789 
790 Optional<DICompileUnit::DebugNameTableKind>
791 DICompileUnit::getNameTableKind(StringRef Str) {
792   return StringSwitch<Optional<DebugNameTableKind>>(Str)
793       .Case("Default", DebugNameTableKind::Default)
794       .Case("GNU", DebugNameTableKind::GNU)
795       .Case("None", DebugNameTableKind::None)
796       .Default(None);
797 }
798 
799 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
800   switch (EK) {
801   case NoDebug:        return "NoDebug";
802   case FullDebug:      return "FullDebug";
803   case LineTablesOnly: return "LineTablesOnly";
804   case DebugDirectivesOnly: return "DebugDirectivesOnly";
805   }
806   return nullptr;
807 }
808 
809 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
810   switch (NTK) {
811   case DebugNameTableKind::Default:
812     return nullptr;
813   case DebugNameTableKind::GNU:
814     return "GNU";
815   case DebugNameTableKind::None:
816     return "None";
817   }
818   return nullptr;
819 }
820 
821 DISubprogram *DILocalScope::getSubprogram() const {
822   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
823     return Block->getScope()->getSubprogram();
824   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
825 }
826 
827 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
828   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
829     return File->getScope()->getNonLexicalBlockFileScope();
830   return const_cast<DILocalScope *>(this);
831 }
832 
833 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
834   return StringSwitch<DISPFlags>(Flag)
835 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
836 #include "llvm/IR/DebugInfoFlags.def"
837       .Default(SPFlagZero);
838 }
839 
840 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
841   switch (Flag) {
842   // Appease a warning.
843   case SPFlagVirtuality:
844     return "";
845 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
846   case SPFlag##NAME:                                                           \
847     return "DISPFlag" #NAME;
848 #include "llvm/IR/DebugInfoFlags.def"
849   }
850   return "";
851 }
852 
853 DISubprogram::DISPFlags
854 DISubprogram::splitFlags(DISPFlags Flags,
855                          SmallVectorImpl<DISPFlags> &SplitFlags) {
856   // Multi-bit fields can require special handling. In our case, however, the
857   // only multi-bit field is virtuality, and all its values happen to be
858   // single-bit values, so the right behavior just falls out.
859 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
860   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
861     SplitFlags.push_back(Bit);                                                 \
862     Flags &= ~Bit;                                                             \
863   }
864 #include "llvm/IR/DebugInfoFlags.def"
865   return Flags;
866 }
867 
868 DISubprogram *DISubprogram::getImpl(
869     LLVMContext &Context, Metadata *Scope, MDString *Name,
870     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
871     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
872     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
873     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
874     Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage,
875     bool ShouldCreate) {
876   assert(isCanonical(Name) && "Expected canonical MDString");
877   assert(isCanonical(LinkageName) && "Expected canonical MDString");
878   DEFINE_GETIMPL_LOOKUP(DISubprogram,
879                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
880                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
881                          SPFlags, Unit, TemplateParams, Declaration,
882                          RetainedNodes, ThrownTypes, Annotations));
883   SmallVector<Metadata *, 12> Ops = {
884       File,        Scope,         Name,           LinkageName,    Type,       Unit,
885       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes,
886       Annotations};
887   if (!Annotations) {
888     Ops.pop_back();
889     if (!ThrownTypes) {
890       Ops.pop_back();
891       if (!TemplateParams) {
892         Ops.pop_back();
893         if (!ContainingType)
894           Ops.pop_back();
895       }
896     }
897   }
898   DEFINE_GETIMPL_STORE_N(
899       DISubprogram,
900       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
901       Ops.size());
902 }
903 
904 bool DISubprogram::describes(const Function *F) const {
905   assert(F && "Invalid function");
906   return F->getSubprogram() == this;
907 }
908 
909 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
910                                         Metadata *File, unsigned Line,
911                                         unsigned Column, StorageType Storage,
912                                         bool ShouldCreate) {
913   // Fixup column.
914   adjustColumn(Column);
915 
916   assert(Scope && "Expected scope");
917   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
918   Metadata *Ops[] = {File, Scope};
919   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
920 }
921 
922 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
923                                                 Metadata *Scope, Metadata *File,
924                                                 unsigned Discriminator,
925                                                 StorageType Storage,
926                                                 bool ShouldCreate) {
927   assert(Scope && "Expected scope");
928   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
929   Metadata *Ops[] = {File, Scope};
930   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
931 }
932 
933 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
934                                   MDString *Name, bool ExportSymbols,
935                                   StorageType Storage, bool ShouldCreate) {
936   assert(isCanonical(Name) && "Expected canonical MDString");
937   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
938   // The nullptr is for DIScope's File operand. This should be refactored.
939   Metadata *Ops[] = {nullptr, Scope, Name};
940   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
941 }
942 
943 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
944                                       Metadata *Decl, MDString *Name,
945                                       Metadata *File, unsigned LineNo,
946                                       StorageType Storage, bool ShouldCreate) {
947   assert(isCanonical(Name) && "Expected canonical MDString");
948   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
949   // The nullptr is for DIScope's File operand. This should be refactored.
950   Metadata *Ops[] = {Scope, Decl, Name, File};
951   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
952 }
953 
954 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
955                             Metadata *Scope, MDString *Name,
956                             MDString *ConfigurationMacros,
957                             MDString *IncludePath, MDString *APINotesFile,
958                             unsigned LineNo, bool IsDecl, StorageType Storage,
959                             bool ShouldCreate) {
960   assert(isCanonical(Name) && "Expected canonical MDString");
961   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
962                                    IncludePath, APINotesFile, LineNo, IsDecl));
963   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
964                      IncludePath, APINotesFile};
965   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
966 }
967 
968 DITemplateTypeParameter *
969 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
970                                  Metadata *Type, bool isDefault,
971                                  StorageType Storage, bool ShouldCreate) {
972   assert(isCanonical(Name) && "Expected canonical MDString");
973   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
974   Metadata *Ops[] = {Name, Type};
975   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
976 }
977 
978 DITemplateValueParameter *DITemplateValueParameter::getImpl(
979     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
980     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
981   assert(isCanonical(Name) && "Expected canonical MDString");
982   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
983                         (Tag, Name, Type, isDefault, Value));
984   Metadata *Ops[] = {Name, Type, Value};
985   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
986 }
987 
988 DIGlobalVariable *
989 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
990                           MDString *LinkageName, Metadata *File, unsigned Line,
991                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
992                           Metadata *StaticDataMemberDeclaration,
993                           Metadata *TemplateParams, uint32_t AlignInBits,
994                           Metadata *Annotations, StorageType Storage,
995                           bool ShouldCreate) {
996   assert(isCanonical(Name) && "Expected canonical MDString");
997   assert(isCanonical(LinkageName) && "Expected canonical MDString");
998   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
999                                            Type, IsLocalToUnit, IsDefinition,
1000                                            StaticDataMemberDeclaration,
1001                                            TemplateParams, AlignInBits,
1002                                            Annotations));
1003   Metadata *Ops[] = {Scope,
1004                      Name,
1005                      File,
1006                      Type,
1007                      Name,
1008                      LinkageName,
1009                      StaticDataMemberDeclaration,
1010                      TemplateParams,
1011                      Annotations};
1012   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1013                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1014 }
1015 
1016 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
1017                                           MDString *Name, Metadata *File,
1018                                           unsigned Line, Metadata *Type,
1019                                           unsigned Arg, DIFlags Flags,
1020                                           uint32_t AlignInBits,
1021                                           Metadata *Annotations,
1022                                           StorageType Storage,
1023                                           bool ShouldCreate) {
1024   // 64K ought to be enough for any frontend.
1025   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1026 
1027   assert(Scope && "Expected scope");
1028   assert(isCanonical(Name) && "Expected canonical MDString");
1029   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
1030                         (Scope, Name, File, Line, Type, Arg, Flags,
1031                          AlignInBits, Annotations));
1032   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1033   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1034 }
1035 
1036 Optional<uint64_t> DIVariable::getSizeInBits() const {
1037   // This is used by the Verifier so be mindful of broken types.
1038   const Metadata *RawType = getRawType();
1039   while (RawType) {
1040     // Try to get the size directly.
1041     if (auto *T = dyn_cast<DIType>(RawType))
1042       if (uint64_t Size = T->getSizeInBits())
1043         return Size;
1044 
1045     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1046       // Look at the base type.
1047       RawType = DT->getRawBaseType();
1048       continue;
1049     }
1050 
1051     // Missing type or size.
1052     break;
1053   }
1054 
1055   // Fail gracefully.
1056   return None;
1057 }
1058 
1059 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
1060                           MDString *Name, Metadata *File, unsigned Line,
1061                           StorageType Storage,
1062                           bool ShouldCreate) {
1063   assert(Scope && "Expected scope");
1064   assert(isCanonical(Name) && "Expected canonical MDString");
1065   DEFINE_GETIMPL_LOOKUP(DILabel,
1066                         (Scope, Name, File, Line));
1067   Metadata *Ops[] = {Scope, Name, File};
1068   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1069 }
1070 
1071 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1072                                     ArrayRef<uint64_t> Elements,
1073                                     StorageType Storage, bool ShouldCreate) {
1074   assert(Storage != Distinct && "DIExpression cannot be distinct");
1075   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1076   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1077 }
1078 
1079 unsigned DIExpression::ExprOperand::getSize() const {
1080   uint64_t Op = getOp();
1081 
1082   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1083     return 2;
1084 
1085   switch (Op) {
1086   case dwarf::DW_OP_LLVM_convert:
1087   case dwarf::DW_OP_LLVM_fragment:
1088   case dwarf::DW_OP_bregx:
1089     return 3;
1090   case dwarf::DW_OP_constu:
1091   case dwarf::DW_OP_consts:
1092   case dwarf::DW_OP_deref_size:
1093   case dwarf::DW_OP_plus_uconst:
1094   case dwarf::DW_OP_LLVM_tag_offset:
1095   case dwarf::DW_OP_LLVM_entry_value:
1096   case dwarf::DW_OP_LLVM_arg:
1097   case dwarf::DW_OP_regx:
1098     return 2;
1099   default:
1100     return 1;
1101   }
1102 }
1103 
1104 bool DIExpression::isValid() const {
1105   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1106     // Check that there's space for the operand.
1107     if (I->get() + I->getSize() > E->get())
1108       return false;
1109 
1110     uint64_t Op = I->getOp();
1111     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1112         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1113       return true;
1114 
1115     // Check that the operand is valid.
1116     switch (Op) {
1117     default:
1118       return false;
1119     case dwarf::DW_OP_LLVM_fragment:
1120       // A fragment operator must appear at the end.
1121       return I->get() + I->getSize() == E->get();
1122     case dwarf::DW_OP_stack_value: {
1123       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1124       if (I->get() + I->getSize() == E->get())
1125         break;
1126       auto J = I;
1127       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1128         return false;
1129       break;
1130     }
1131     case dwarf::DW_OP_swap: {
1132       // Must be more than one implicit element on the stack.
1133 
1134       // FIXME: A better way to implement this would be to add a local variable
1135       // that keeps track of the stack depth and introduce something like a
1136       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1137       // DIExpression is attached to, or else pass the number of implicit stack
1138       // elements into isValid.
1139       if (getNumElements() == 1)
1140         return false;
1141       break;
1142     }
1143     case dwarf::DW_OP_LLVM_entry_value: {
1144       // An entry value operator must appear at the beginning and the number of
1145       // operations it cover can currently only be 1, because we support only
1146       // entry values of a simple register location. One reason for this is that
1147       // we currently can't calculate the size of the resulting DWARF block for
1148       // other expressions.
1149       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
1150     }
1151     case dwarf::DW_OP_LLVM_implicit_pointer:
1152     case dwarf::DW_OP_LLVM_convert:
1153     case dwarf::DW_OP_LLVM_arg:
1154     case dwarf::DW_OP_LLVM_tag_offset:
1155     case dwarf::DW_OP_constu:
1156     case dwarf::DW_OP_plus_uconst:
1157     case dwarf::DW_OP_plus:
1158     case dwarf::DW_OP_minus:
1159     case dwarf::DW_OP_mul:
1160     case dwarf::DW_OP_div:
1161     case dwarf::DW_OP_mod:
1162     case dwarf::DW_OP_or:
1163     case dwarf::DW_OP_and:
1164     case dwarf::DW_OP_xor:
1165     case dwarf::DW_OP_shl:
1166     case dwarf::DW_OP_shr:
1167     case dwarf::DW_OP_shra:
1168     case dwarf::DW_OP_deref:
1169     case dwarf::DW_OP_deref_size:
1170     case dwarf::DW_OP_xderef:
1171     case dwarf::DW_OP_lit0:
1172     case dwarf::DW_OP_not:
1173     case dwarf::DW_OP_dup:
1174     case dwarf::DW_OP_regx:
1175     case dwarf::DW_OP_bregx:
1176     case dwarf::DW_OP_push_object_address:
1177     case dwarf::DW_OP_over:
1178     case dwarf::DW_OP_consts:
1179       break;
1180     }
1181   }
1182   return true;
1183 }
1184 
1185 bool DIExpression::isImplicit() const {
1186   if (!isValid())
1187     return false;
1188 
1189   if (getNumElements() == 0)
1190     return false;
1191 
1192   for (const auto &It : expr_ops()) {
1193     switch (It.getOp()) {
1194     default:
1195       break;
1196     case dwarf::DW_OP_stack_value:
1197     case dwarf::DW_OP_LLVM_tag_offset:
1198       return true;
1199     }
1200   }
1201 
1202   return false;
1203 }
1204 
1205 bool DIExpression::isComplex() const {
1206   if (!isValid())
1207     return false;
1208 
1209   if (getNumElements() == 0)
1210     return false;
1211 
1212   // If there are any elements other than fragment or tag_offset, then some
1213   // kind of complex computation occurs.
1214   for (const auto &It : expr_ops()) {
1215     switch (It.getOp()) {
1216       case dwarf::DW_OP_LLVM_tag_offset:
1217       case dwarf::DW_OP_LLVM_fragment:
1218         continue;
1219       default: return true;
1220     }
1221   }
1222 
1223   return false;
1224 }
1225 
1226 Optional<DIExpression::FragmentInfo>
1227 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1228   for (auto I = Start; I != End; ++I)
1229     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1230       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1231       return Info;
1232     }
1233   return None;
1234 }
1235 
1236 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1237                                 int64_t Offset) {
1238   if (Offset > 0) {
1239     Ops.push_back(dwarf::DW_OP_plus_uconst);
1240     Ops.push_back(Offset);
1241   } else if (Offset < 0) {
1242     Ops.push_back(dwarf::DW_OP_constu);
1243     Ops.push_back(-Offset);
1244     Ops.push_back(dwarf::DW_OP_minus);
1245   }
1246 }
1247 
1248 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1249   if (getNumElements() == 0) {
1250     Offset = 0;
1251     return true;
1252   }
1253 
1254   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1255     Offset = Elements[1];
1256     return true;
1257   }
1258 
1259   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1260     if (Elements[2] == dwarf::DW_OP_plus) {
1261       Offset = Elements[1];
1262       return true;
1263     }
1264     if (Elements[2] == dwarf::DW_OP_minus) {
1265       Offset = -Elements[1];
1266       return true;
1267     }
1268   }
1269 
1270   return false;
1271 }
1272 
1273 bool DIExpression::hasAllLocationOps(unsigned N) const {
1274   SmallDenseSet<uint64_t, 4> SeenOps;
1275   for (auto ExprOp : expr_ops())
1276     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1277       SeenOps.insert(ExprOp.getArg(0));
1278   for (uint64_t Idx = 0; Idx < N; ++Idx)
1279     if (!is_contained(SeenOps, Idx))
1280       return false;
1281   return true;
1282 }
1283 
1284 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1285                                                       unsigned &AddrClass) {
1286   // FIXME: This seems fragile. Nothing that verifies that these elements
1287   // actually map to ops and not operands.
1288   const unsigned PatternSize = 4;
1289   if (Expr->Elements.size() >= PatternSize &&
1290       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1291       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1292       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1293     AddrClass = Expr->Elements[PatternSize - 3];
1294 
1295     if (Expr->Elements.size() == PatternSize)
1296       return nullptr;
1297     return DIExpression::get(Expr->getContext(),
1298                              makeArrayRef(&*Expr->Elements.begin(),
1299                                           Expr->Elements.size() - PatternSize));
1300   }
1301   return Expr;
1302 }
1303 
1304 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1305                                     int64_t Offset) {
1306   SmallVector<uint64_t, 8> Ops;
1307   if (Flags & DIExpression::DerefBefore)
1308     Ops.push_back(dwarf::DW_OP_deref);
1309 
1310   appendOffset(Ops, Offset);
1311   if (Flags & DIExpression::DerefAfter)
1312     Ops.push_back(dwarf::DW_OP_deref);
1313 
1314   bool StackValue = Flags & DIExpression::StackValue;
1315   bool EntryValue = Flags & DIExpression::EntryValue;
1316 
1317   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1318 }
1319 
1320 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1321                                            ArrayRef<uint64_t> Ops,
1322                                            unsigned ArgNo, bool StackValue) {
1323   assert(Expr && "Can't add ops to this expression");
1324 
1325   // Handle non-variadic intrinsics by prepending the opcodes.
1326   if (!any_of(Expr->expr_ops(),
1327               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1328     assert(ArgNo == 0 &&
1329            "Location Index must be 0 for a non-variadic expression.");
1330     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1331     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1332   }
1333 
1334   SmallVector<uint64_t, 8> NewOps;
1335   for (auto Op : Expr->expr_ops()) {
1336     Op.appendToVector(NewOps);
1337     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1338       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1339   }
1340 
1341   return DIExpression::get(Expr->getContext(), NewOps);
1342 }
1343 
1344 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1345                                        uint64_t OldArg, uint64_t NewArg) {
1346   assert(Expr && "Can't replace args in this expression");
1347 
1348   SmallVector<uint64_t, 8> NewOps;
1349 
1350   for (auto Op : Expr->expr_ops()) {
1351     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1352       Op.appendToVector(NewOps);
1353       continue;
1354     }
1355     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1356     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1357     // OldArg has been deleted from the Op list, so decrement all indices
1358     // greater than it.
1359     if (Arg > OldArg)
1360       --Arg;
1361     NewOps.push_back(Arg);
1362   }
1363   return DIExpression::get(Expr->getContext(), NewOps);
1364 }
1365 
1366 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1367                                            SmallVectorImpl<uint64_t> &Ops,
1368                                            bool StackValue,
1369                                            bool EntryValue) {
1370   assert(Expr && "Can't prepend ops to this expression");
1371 
1372   if (EntryValue) {
1373     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1374     // Use a block size of 1 for the target register operand.  The
1375     // DWARF backend currently cannot emit entry values with a block
1376     // size > 1.
1377     Ops.push_back(1);
1378   }
1379 
1380   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1381   if (Ops.empty())
1382     StackValue = false;
1383   for (auto Op : Expr->expr_ops()) {
1384     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1385     if (StackValue) {
1386       if (Op.getOp() == dwarf::DW_OP_stack_value)
1387         StackValue = false;
1388       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1389         Ops.push_back(dwarf::DW_OP_stack_value);
1390         StackValue = false;
1391       }
1392     }
1393     Op.appendToVector(Ops);
1394   }
1395   if (StackValue)
1396     Ops.push_back(dwarf::DW_OP_stack_value);
1397   return DIExpression::get(Expr->getContext(), Ops);
1398 }
1399 
1400 DIExpression *DIExpression::append(const DIExpression *Expr,
1401                                    ArrayRef<uint64_t> Ops) {
1402   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1403 
1404   // Copy Expr's current op list.
1405   SmallVector<uint64_t, 16> NewOps;
1406   for (auto Op : Expr->expr_ops()) {
1407     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1408     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1409         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1410       NewOps.append(Ops.begin(), Ops.end());
1411 
1412       // Ensure that the new opcodes are only appended once.
1413       Ops = None;
1414     }
1415     Op.appendToVector(NewOps);
1416   }
1417 
1418   NewOps.append(Ops.begin(), Ops.end());
1419   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1420   assert(result->isValid() && "concatenated expression is not valid");
1421   return result;
1422 }
1423 
1424 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1425                                           ArrayRef<uint64_t> Ops) {
1426   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1427   assert(none_of(Ops,
1428                  [](uint64_t Op) {
1429                    return Op == dwarf::DW_OP_stack_value ||
1430                           Op == dwarf::DW_OP_LLVM_fragment;
1431                  }) &&
1432          "Can't append this op");
1433 
1434   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1435   // has no DW_OP_stack_value.
1436   //
1437   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1438   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1439   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1440   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1441       Expr->getElements().drop_back(DropUntilStackValue);
1442   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1443                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1444   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1445 
1446   // Append a DW_OP_deref after Expr's current op list if needed, then append
1447   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1448   SmallVector<uint64_t, 16> NewOps;
1449   if (NeedsDeref)
1450     NewOps.push_back(dwarf::DW_OP_deref);
1451   NewOps.append(Ops.begin(), Ops.end());
1452   if (NeedsStackValue)
1453     NewOps.push_back(dwarf::DW_OP_stack_value);
1454   return DIExpression::append(Expr, NewOps);
1455 }
1456 
1457 Optional<DIExpression *> DIExpression::createFragmentExpression(
1458     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1459   SmallVector<uint64_t, 8> Ops;
1460   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1461   if (Expr) {
1462     for (auto Op : Expr->expr_ops()) {
1463       switch (Op.getOp()) {
1464       default: break;
1465       case dwarf::DW_OP_shr:
1466       case dwarf::DW_OP_shra:
1467       case dwarf::DW_OP_shl:
1468       case dwarf::DW_OP_plus:
1469       case dwarf::DW_OP_plus_uconst:
1470       case dwarf::DW_OP_minus:
1471         // We can't safely split arithmetic or shift operations into multiple
1472         // fragments because we can't express carry-over between fragments.
1473         //
1474         // FIXME: We *could* preserve the lowest fragment of a constant offset
1475         // operation if the offset fits into SizeInBits.
1476         return None;
1477       case dwarf::DW_OP_LLVM_fragment: {
1478         // Make the new offset point into the existing fragment.
1479         uint64_t FragmentOffsetInBits = Op.getArg(0);
1480         uint64_t FragmentSizeInBits = Op.getArg(1);
1481         (void)FragmentSizeInBits;
1482         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1483                "new fragment outside of original fragment");
1484         OffsetInBits += FragmentOffsetInBits;
1485         continue;
1486       }
1487       }
1488       Op.appendToVector(Ops);
1489     }
1490   }
1491   assert(Expr && "Unknown DIExpression");
1492   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1493   Ops.push_back(OffsetInBits);
1494   Ops.push_back(SizeInBits);
1495   return DIExpression::get(Expr->getContext(), Ops);
1496 }
1497 
1498 std::pair<DIExpression *, const ConstantInt *>
1499 DIExpression::constantFold(const ConstantInt *CI) {
1500   // Copy the APInt so we can modify it.
1501   APInt NewInt = CI->getValue();
1502   SmallVector<uint64_t, 8> Ops;
1503 
1504   // Fold operators only at the beginning of the expression.
1505   bool First = true;
1506   bool Changed = false;
1507   for (auto Op : expr_ops()) {
1508     switch (Op.getOp()) {
1509     default:
1510       // We fold only the leading part of the expression; if we get to a part
1511       // that we're going to copy unchanged, and haven't done any folding,
1512       // then the entire expression is unchanged and we can return early.
1513       if (!Changed)
1514         return {this, CI};
1515       First = false;
1516       break;
1517     case dwarf::DW_OP_LLVM_convert:
1518       if (!First)
1519         break;
1520       Changed = true;
1521       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1522         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1523       else {
1524         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1525         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1526       }
1527       continue;
1528     }
1529     Op.appendToVector(Ops);
1530   }
1531   if (!Changed)
1532     return {this, CI};
1533   return {DIExpression::get(getContext(), Ops),
1534           ConstantInt::get(getContext(), NewInt)};
1535 }
1536 
1537 uint64_t DIExpression::getNumLocationOperands() const {
1538   uint64_t Result = 0;
1539   for (auto ExprOp : expr_ops())
1540     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1541       Result = std::max(Result, ExprOp.getArg(0) + 1);
1542   assert(hasAllLocationOps(Result) &&
1543          "Expression is missing one or more location operands.");
1544   return Result;
1545 }
1546 
1547 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1548 DIExpression::isConstant() const {
1549 
1550   // Recognize signed and unsigned constants.
1551   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1552   // (DW_OP_LLVM_fragment of Len).
1553   // An unsigned constant can be represented as
1554   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1555 
1556   if ((getNumElements() != 2 && getNumElements() != 3 &&
1557        getNumElements() != 6) ||
1558       (getElement(0) != dwarf::DW_OP_consts &&
1559        getElement(0) != dwarf::DW_OP_constu))
1560     return None;
1561 
1562   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1563     return SignedOrUnsignedConstant::SignedConstant;
1564 
1565   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1566       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1567                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1568     return None;
1569   return getElement(0) == dwarf::DW_OP_constu
1570              ? SignedOrUnsignedConstant::UnsignedConstant
1571              : SignedOrUnsignedConstant::SignedConstant;
1572 }
1573 
1574 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1575                                              bool Signed) {
1576   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1577   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1578                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1579   return Ops;
1580 }
1581 
1582 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1583                                       unsigned FromSize, unsigned ToSize,
1584                                       bool Signed) {
1585   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1586 }
1587 
1588 DIGlobalVariableExpression *
1589 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1590                                     Metadata *Expression, StorageType Storage,
1591                                     bool ShouldCreate) {
1592   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1593   Metadata *Ops[] = {Variable, Expression};
1594   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1595 }
1596 
1597 DIObjCProperty *DIObjCProperty::getImpl(
1598     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1599     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1600     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1601   assert(isCanonical(Name) && "Expected canonical MDString");
1602   assert(isCanonical(GetterName) && "Expected canonical MDString");
1603   assert(isCanonical(SetterName) && "Expected canonical MDString");
1604   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1605                                          SetterName, Attributes, Type));
1606   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1607   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1608 }
1609 
1610 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1611                                             Metadata *Scope, Metadata *Entity,
1612                                             Metadata *File, unsigned Line,
1613                                             MDString *Name, Metadata *Elements,
1614                                             StorageType Storage,
1615                                             bool ShouldCreate) {
1616   assert(isCanonical(Name) && "Expected canonical MDString");
1617   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1618                         (Tag, Scope, Entity, File, Line, Name, Elements));
1619   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
1620   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1621 }
1622 
1623 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1624                           unsigned Line, MDString *Name, MDString *Value,
1625                           StorageType Storage, bool ShouldCreate) {
1626   assert(isCanonical(Name) && "Expected canonical MDString");
1627   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1628   Metadata *Ops[] = { Name, Value };
1629   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1630 }
1631 
1632 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1633                                   unsigned Line, Metadata *File,
1634                                   Metadata *Elements, StorageType Storage,
1635                                   bool ShouldCreate) {
1636   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1637                         (MIType, Line, File, Elements));
1638   Metadata *Ops[] = { File, Elements };
1639   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1640 }
1641 
1642 DIArgList *DIArgList::getImpl(LLVMContext &Context,
1643                               ArrayRef<ValueAsMetadata *> Args,
1644                               StorageType Storage, bool ShouldCreate) {
1645   assert(Storage != Distinct && "DIArgList cannot be distinct");
1646   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1647   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1648 }
1649 
1650 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1651   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1652   assert((!New || isa<ValueAsMetadata>(New)) &&
1653          "DIArgList must be passed a ValueAsMetadata");
1654   untrack();
1655   bool Uniq = isUniqued();
1656   if (Uniq) {
1657     // We need to update the uniqueness once the Args are updated since they
1658     // form the key to the DIArgLists store.
1659     eraseFromStore();
1660   }
1661   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1662   for (ValueAsMetadata *&VM : Args) {
1663     if (&VM == OldVMPtr) {
1664       if (NewVM)
1665         VM = NewVM;
1666       else
1667         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1668     }
1669   }
1670   if (Uniq) {
1671     if (uniquify() != this)
1672       storeDistinctInContext();
1673   }
1674   track();
1675 }
1676 void DIArgList::track() {
1677   for (ValueAsMetadata *&VAM : Args)
1678     if (VAM)
1679       MetadataTracking::track(&VAM, *VAM, *this);
1680 }
1681 void DIArgList::untrack() {
1682   for (ValueAsMetadata *&VAM : Args)
1683     if (VAM)
1684       MetadataTracking::untrack(&VAM, *VAM);
1685 }
1686 void DIArgList::dropAllReferences() {
1687   untrack();
1688   Args.clear();
1689   MDNode::dropAllReferences();
1690 }
1691