xref: /freebsd-src/contrib/llvm-project/llvm/lib/IR/DebugInfoMetadata.cpp (revision 4824e7fd18a1223177218d4aec1b3c6c5c4a444e)
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 DILocation *
86 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,
143                                                    unsigned CI) {
144   std::array<unsigned, 3> Components = {BD, DF, CI};
145   uint64_t RemainingWork = 0U;
146   // We use RemainingWork to figure out if we have no remaining components to
147   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
148   // encode anything for the latter 2.
149   // Since any of the input components is at most 32 bits, their sum will be
150   // less than 34 bits, and thus RemainingWork won't overflow.
151   RemainingWork =
152       std::accumulate(Components.begin(), Components.end(), RemainingWork);
153 
154   int I = 0;
155   unsigned Ret = 0;
156   unsigned NextBitInsertionIndex = 0;
157   while (RemainingWork > 0) {
158     unsigned C = Components[I++];
159     RemainingWork -= C;
160     unsigned EC = encodeComponent(C);
161     Ret |= (EC << NextBitInsertionIndex);
162     NextBitInsertionIndex += encodingBits(C);
163   }
164 
165   // Encoding may be unsuccessful because of overflow. We determine success by
166   // checking equivalence of components before & after encoding. Alternatively,
167   // we could determine Success during encoding, but the current alternative is
168   // simpler.
169   unsigned TBD, TDF, TCI = 0;
170   decodeDiscriminator(Ret, TBD, TDF, TCI);
171   if (TBD == BD && TDF == DF && TCI == CI)
172     return Ret;
173   return None;
174 }
175 
176 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
177                                      unsigned &CI) {
178   BD = getUnsignedFromPrefixEncoding(D);
179   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
180   CI = getUnsignedFromPrefixEncoding(
181       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
182 }
183 
184 DINode::DIFlags DINode::getFlag(StringRef Flag) {
185   return StringSwitch<DIFlags>(Flag)
186 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
187 #include "llvm/IR/DebugInfoFlags.def"
188       .Default(DINode::FlagZero);
189 }
190 
191 StringRef DINode::getFlagString(DIFlags Flag) {
192   switch (Flag) {
193 #define HANDLE_DI_FLAG(ID, NAME)                                               \
194   case Flag##NAME:                                                             \
195     return "DIFlag" #NAME;
196 #include "llvm/IR/DebugInfoFlags.def"
197   }
198   return "";
199 }
200 
201 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
202                                    SmallVectorImpl<DIFlags> &SplitFlags) {
203   // Flags that are packed together need to be specially handled, so
204   // that, for example, we emit "DIFlagPublic" and not
205   // "DIFlagPrivate | DIFlagProtected".
206   if (DIFlags A = Flags & FlagAccessibility) {
207     if (A == FlagPrivate)
208       SplitFlags.push_back(FlagPrivate);
209     else if (A == FlagProtected)
210       SplitFlags.push_back(FlagProtected);
211     else
212       SplitFlags.push_back(FlagPublic);
213     Flags &= ~A;
214   }
215   if (DIFlags R = Flags & FlagPtrToMemberRep) {
216     if (R == FlagSingleInheritance)
217       SplitFlags.push_back(FlagSingleInheritance);
218     else if (R == FlagMultipleInheritance)
219       SplitFlags.push_back(FlagMultipleInheritance);
220     else
221       SplitFlags.push_back(FlagVirtualInheritance);
222     Flags &= ~R;
223   }
224   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
225     Flags &= ~FlagIndirectVirtualBase;
226     SplitFlags.push_back(FlagIndirectVirtualBase);
227   }
228 
229 #define HANDLE_DI_FLAG(ID, NAME)                                               \
230   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
231     SplitFlags.push_back(Bit);                                                 \
232     Flags &= ~Bit;                                                             \
233   }
234 #include "llvm/IR/DebugInfoFlags.def"
235   return Flags;
236 }
237 
238 DIScope *DIScope::getScope() const {
239   if (auto *T = dyn_cast<DIType>(this))
240     return T->getScope();
241 
242   if (auto *SP = dyn_cast<DISubprogram>(this))
243     return SP->getScope();
244 
245   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
246     return LB->getScope();
247 
248   if (auto *NS = dyn_cast<DINamespace>(this))
249     return NS->getScope();
250 
251   if (auto *CB = dyn_cast<DICommonBlock>(this))
252     return CB->getScope();
253 
254   if (auto *M = dyn_cast<DIModule>(this))
255     return M->getScope();
256 
257   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
258          "Unhandled type of scope.");
259   return nullptr;
260 }
261 
262 StringRef DIScope::getName() const {
263   if (auto *T = dyn_cast<DIType>(this))
264     return T->getName();
265   if (auto *SP = dyn_cast<DISubprogram>(this))
266     return SP->getName();
267   if (auto *NS = dyn_cast<DINamespace>(this))
268     return NS->getName();
269   if (auto *CB = dyn_cast<DICommonBlock>(this))
270     return CB->getName();
271   if (auto *M = dyn_cast<DIModule>(this))
272     return M->getName();
273   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
274           isa<DICompileUnit>(this)) &&
275          "Unhandled type of scope.");
276   return "";
277 }
278 
279 #ifndef NDEBUG
280 static bool isCanonical(const MDString *S) {
281   return !S || !S->getString().empty();
282 }
283 #endif
284 
285 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
286                                       MDString *Header,
287                                       ArrayRef<Metadata *> DwarfOps,
288                                       StorageType Storage, bool ShouldCreate) {
289   unsigned Hash = 0;
290   if (Storage == Uniqued) {
291     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
292     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
293       return N;
294     if (!ShouldCreate)
295       return nullptr;
296     Hash = Key.getHash();
297   } else {
298     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
299   }
300 
301   // Use a nullptr for empty headers.
302   assert(isCanonical(Header) && "Expected canonical MDString");
303   Metadata *PreOps[] = {Header};
304   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
305                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
306                    Storage, Context.pImpl->GenericDINodes);
307 }
308 
309 void GenericDINode::recalculateHash() {
310   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
311 }
312 
313 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
314 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
315 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
316   do {                                                                         \
317     if (Storage == Uniqued) {                                                  \
318       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
319                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
320         return N;                                                              \
321       if (!ShouldCreate)                                                       \
322         return nullptr;                                                        \
323     } else {                                                                   \
324       assert(ShouldCreate &&                                                   \
325              "Expected non-uniqued nodes to always be created");               \
326     }                                                                          \
327   } while (false)
328 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
329   return storeImpl(new (array_lengthof(OPS))                                   \
330                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
331                    Storage, Context.pImpl->CLASS##s)
332 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
333   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
334                    Storage, Context.pImpl->CLASS##s)
335 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
336   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
337                    Storage, Context.pImpl->CLASS##s)
338 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
339   return storeImpl(new (NUM_OPS)                                               \
340                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
341                    Storage, Context.pImpl->CLASS##s)
342 
343 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
344                                 StorageType Storage, bool ShouldCreate) {
345   auto *CountNode = ConstantAsMetadata::get(
346       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
347   auto *LB = ConstantAsMetadata::get(
348       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
349   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
350                  ShouldCreate);
351 }
352 
353 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
354                                 int64_t Lo, StorageType Storage,
355                                 bool ShouldCreate) {
356   auto *LB = ConstantAsMetadata::get(
357       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
358   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
359                  ShouldCreate);
360 }
361 
362 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
363                                 Metadata *LB, Metadata *UB, Metadata *Stride,
364                                 StorageType Storage, bool ShouldCreate) {
365   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
366   Metadata *Ops[] = {CountNode, LB, UB, Stride};
367   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
368 }
369 
370 DISubrange::BoundType DISubrange::getCount() const {
371   Metadata *CB = getRawCountNode();
372   if (!CB)
373     return BoundType();
374 
375   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
376           isa<DIExpression>(CB)) &&
377          "Count must be signed constant or DIVariable or DIExpression");
378 
379   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
380     return BoundType(cast<ConstantInt>(MD->getValue()));
381 
382   if (auto *MD = dyn_cast<DIVariable>(CB))
383     return BoundType(MD);
384 
385   if (auto *MD = dyn_cast<DIExpression>(CB))
386     return BoundType(MD);
387 
388   return BoundType();
389 }
390 
391 DISubrange::BoundType DISubrange::getLowerBound() const {
392   Metadata *LB = getRawLowerBound();
393   if (!LB)
394     return BoundType();
395 
396   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
397           isa<DIExpression>(LB)) &&
398          "LowerBound must be signed constant or DIVariable or DIExpression");
399 
400   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
401     return BoundType(cast<ConstantInt>(MD->getValue()));
402 
403   if (auto *MD = dyn_cast<DIVariable>(LB))
404     return BoundType(MD);
405 
406   if (auto *MD = dyn_cast<DIExpression>(LB))
407     return BoundType(MD);
408 
409   return BoundType();
410 }
411 
412 DISubrange::BoundType DISubrange::getUpperBound() const {
413   Metadata *UB = getRawUpperBound();
414   if (!UB)
415     return BoundType();
416 
417   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
418           isa<DIExpression>(UB)) &&
419          "UpperBound must be signed constant or DIVariable or DIExpression");
420 
421   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
422     return BoundType(cast<ConstantInt>(MD->getValue()));
423 
424   if (auto *MD = dyn_cast<DIVariable>(UB))
425     return BoundType(MD);
426 
427   if (auto *MD = dyn_cast<DIExpression>(UB))
428     return BoundType(MD);
429 
430   return BoundType();
431 }
432 
433 DISubrange::BoundType DISubrange::getStride() const {
434   Metadata *ST = getRawStride();
435   if (!ST)
436     return BoundType();
437 
438   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
439           isa<DIExpression>(ST)) &&
440          "Stride must be signed constant or DIVariable or DIExpression");
441 
442   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
443     return BoundType(cast<ConstantInt>(MD->getValue()));
444 
445   if (auto *MD = dyn_cast<DIVariable>(ST))
446     return BoundType(MD);
447 
448   if (auto *MD = dyn_cast<DIExpression>(ST))
449     return BoundType(MD);
450 
451   return BoundType();
452 }
453 
454 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
455                                               Metadata *CountNode, Metadata *LB,
456                                               Metadata *UB, Metadata *Stride,
457                                               StorageType Storage,
458                                               bool ShouldCreate) {
459   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
460   Metadata *Ops[] = {CountNode, LB, UB, Stride};
461   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
462 }
463 
464 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
465   Metadata *CB = getRawCountNode();
466   if (!CB)
467     return BoundType();
468 
469   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
470          "Count must be signed constant or DIVariable or DIExpression");
471 
472   if (auto *MD = dyn_cast<DIVariable>(CB))
473     return BoundType(MD);
474 
475   if (auto *MD = dyn_cast<DIExpression>(CB))
476     return BoundType(MD);
477 
478   return BoundType();
479 }
480 
481 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
482   Metadata *LB = getRawLowerBound();
483   if (!LB)
484     return BoundType();
485 
486   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
487          "LowerBound must be signed constant or DIVariable or DIExpression");
488 
489   if (auto *MD = dyn_cast<DIVariable>(LB))
490     return BoundType(MD);
491 
492   if (auto *MD = dyn_cast<DIExpression>(LB))
493     return BoundType(MD);
494 
495   return BoundType();
496 }
497 
498 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
499   Metadata *UB = getRawUpperBound();
500   if (!UB)
501     return BoundType();
502 
503   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
504          "UpperBound must be signed constant or DIVariable or DIExpression");
505 
506   if (auto *MD = dyn_cast<DIVariable>(UB))
507     return BoundType(MD);
508 
509   if (auto *MD = dyn_cast<DIExpression>(UB))
510     return BoundType(MD);
511 
512   return BoundType();
513 }
514 
515 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
516   Metadata *ST = getRawStride();
517   if (!ST)
518     return BoundType();
519 
520   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
521          "Stride must be signed constant or DIVariable or DIExpression");
522 
523   if (auto *MD = dyn_cast<DIVariable>(ST))
524     return BoundType(MD);
525 
526   if (auto *MD = dyn_cast<DIExpression>(ST))
527     return BoundType(MD);
528 
529   return BoundType();
530 }
531 
532 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
533                                     bool IsUnsigned, MDString *Name,
534                                     StorageType Storage, bool ShouldCreate) {
535   assert(isCanonical(Name) && "Expected canonical MDString");
536   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
537   Metadata *Ops[] = {Name};
538   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
539 }
540 
541 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
542                                   MDString *Name, uint64_t SizeInBits,
543                                   uint32_t AlignInBits, unsigned Encoding,
544                                   DIFlags Flags, StorageType Storage,
545                                   bool ShouldCreate) {
546   assert(isCanonical(Name) && "Expected canonical MDString");
547   DEFINE_GETIMPL_LOOKUP(DIBasicType,
548                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
549   Metadata *Ops[] = {nullptr, nullptr, Name};
550   DEFINE_GETIMPL_STORE(DIBasicType,
551                        (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops);
552 }
553 
554 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
555   switch (getEncoding()) {
556   case dwarf::DW_ATE_signed:
557   case dwarf::DW_ATE_signed_char:
558     return Signedness::Signed;
559   case dwarf::DW_ATE_unsigned:
560   case dwarf::DW_ATE_unsigned_char:
561     return Signedness::Unsigned;
562   default:
563     return None;
564   }
565 }
566 
567 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
568                                     MDString *Name, Metadata *StringLength,
569                                     Metadata *StringLengthExp,
570                                     uint64_t SizeInBits, uint32_t AlignInBits,
571                                     unsigned Encoding, StorageType Storage,
572                                     bool ShouldCreate) {
573   assert(isCanonical(Name) && "Expected canonical MDString");
574   DEFINE_GETIMPL_LOOKUP(DIStringType, (Tag, Name, StringLength, StringLengthExp,
575                                        SizeInBits, AlignInBits, Encoding));
576   Metadata *Ops[] = {nullptr, nullptr, Name, StringLength, StringLengthExp};
577   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
578                        Ops);
579 }
580 
581 DIDerivedType *DIDerivedType::getImpl(
582     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
583     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
584     uint32_t AlignInBits, uint64_t OffsetInBits,
585     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
586     Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
587   assert(isCanonical(Name) && "Expected canonical MDString");
588   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
589                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
590                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
591                          ExtraData, Annotations));
592   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
593   DEFINE_GETIMPL_STORE(DIDerivedType,
594                        (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
595                         DWARFAddressSpace, Flags),
596                        Ops);
597 }
598 
599 DICompositeType *DICompositeType::getImpl(
600     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
601     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
602     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
603     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
604     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
605     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
606     Metadata *Rank, Metadata *Annotations, StorageType Storage,
607     bool ShouldCreate) {
608   assert(isCanonical(Name) && "Expected canonical MDString");
609 
610   // Keep this in sync with buildODRType.
611   DEFINE_GETIMPL_LOOKUP(DICompositeType,
612                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
613                          AlignInBits, OffsetInBits, Flags, Elements,
614                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
615                          Discriminator, DataLocation, Associated, Allocated,
616                          Rank, Annotations));
617   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
618                      Elements,      VTableHolder, TemplateParams, Identifier,
619                      Discriminator, DataLocation, Associated,     Allocated,
620                      Rank,          Annotations};
621   DEFINE_GETIMPL_STORE(
622       DICompositeType,
623       (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags),
624       Ops);
625 }
626 
627 DICompositeType *DICompositeType::buildODRType(
628     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
629     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
630     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
631     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
632     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
633     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
634     Metadata *Rank, Metadata *Annotations) {
635   assert(!Identifier.getString().empty() && "Expected valid identifier");
636   if (!Context.isODRUniquingDebugTypes())
637     return nullptr;
638   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
639   if (!CT)
640     return CT = DICompositeType::getDistinct(
641                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
642                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
643                VTableHolder, TemplateParams, &Identifier, Discriminator,
644                DataLocation, Associated, Allocated, Rank, Annotations);
645 
646   if (CT->getTag() != Tag)
647     return nullptr;
648 
649   // Only mutate CT if it's a forward declaration and the new operands aren't.
650   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
651   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
652     return CT;
653 
654   // Mutate CT in place.  Keep this in sync with getImpl.
655   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
656              Flags);
657   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
658                      Elements,      VTableHolder, TemplateParams, &Identifier,
659                      Discriminator, DataLocation, Associated,     Allocated,
660                      Rank,          Annotations};
661   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
662          "Mismatched number of operands");
663   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
664     if (Ops[I] != CT->getOperand(I))
665       CT->setOperand(I, Ops[I]);
666   return CT;
667 }
668 
669 DICompositeType *DICompositeType::getODRType(
670     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
671     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
672     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
673     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
674     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
675     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
676     Metadata *Rank, Metadata *Annotations) {
677   assert(!Identifier.getString().empty() && "Expected valid identifier");
678   if (!Context.isODRUniquingDebugTypes())
679     return nullptr;
680   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
681   if (!CT) {
682     CT = DICompositeType::getDistinct(
683         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
684         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
685         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
686         Allocated, Rank, Annotations);
687   } else {
688     if (CT->getTag() != Tag)
689       return nullptr;
690   }
691   return CT;
692 }
693 
694 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
695                                                      MDString &Identifier) {
696   assert(!Identifier.getString().empty() && "Expected valid identifier");
697   if (!Context.isODRUniquingDebugTypes())
698     return nullptr;
699   return Context.pImpl->DITypeMap->lookup(&Identifier);
700 }
701 
702 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
703                                             uint8_t CC, Metadata *TypeArray,
704                                             StorageType Storage,
705                                             bool ShouldCreate) {
706   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
707   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
708   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
709 }
710 
711 // FIXME: Implement this string-enum correspondence with a .def file and macros,
712 // so that the association is explicit rather than implied.
713 static const char *ChecksumKindName[DIFile::CSK_Last] = {
714     "CSK_MD5",
715     "CSK_SHA1",
716     "CSK_SHA256",
717 };
718 
719 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
720   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
721   // The first space was originally the CSK_None variant, which is now
722   // obsolete, but the space is still reserved in ChecksumKind, so we account
723   // for it here.
724   return ChecksumKindName[CSKind - 1];
725 }
726 
727 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
728   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
729       .Case("CSK_MD5", DIFile::CSK_MD5)
730       .Case("CSK_SHA1", DIFile::CSK_SHA1)
731       .Case("CSK_SHA256", DIFile::CSK_SHA256)
732       .Default(None);
733 }
734 
735 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
736                         MDString *Directory,
737                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
738                         Optional<MDString *> Source, StorageType Storage,
739                         bool ShouldCreate) {
740   assert(isCanonical(Filename) && "Expected canonical MDString");
741   assert(isCanonical(Directory) && "Expected canonical MDString");
742   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
743   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
744   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
745   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
746                      Source.getValueOr(nullptr)};
747   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
748 }
749 
750 DICompileUnit *DICompileUnit::getImpl(
751     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
752     MDString *Producer, bool IsOptimized, MDString *Flags,
753     unsigned RuntimeVersion, MDString *SplitDebugFilename,
754     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
755     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
756     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
757     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
758     MDString *SDK, StorageType Storage, bool ShouldCreate) {
759   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
760   assert(isCanonical(Producer) && "Expected canonical MDString");
761   assert(isCanonical(Flags) && "Expected canonical MDString");
762   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
763 
764   Metadata *Ops[] = {File,
765                      Producer,
766                      Flags,
767                      SplitDebugFilename,
768                      EnumTypes,
769                      RetainedTypes,
770                      GlobalVariables,
771                      ImportedEntities,
772                      Macros,
773                      SysRoot,
774                      SDK};
775   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
776                        Context, Storage, SourceLanguage, IsOptimized,
777                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
778                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
779                        Ops),
780                    Storage);
781 }
782 
783 Optional<DICompileUnit::DebugEmissionKind>
784 DICompileUnit::getEmissionKind(StringRef Str) {
785   return StringSwitch<Optional<DebugEmissionKind>>(Str)
786       .Case("NoDebug", NoDebug)
787       .Case("FullDebug", FullDebug)
788       .Case("LineTablesOnly", LineTablesOnly)
789       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
790       .Default(None);
791 }
792 
793 Optional<DICompileUnit::DebugNameTableKind>
794 DICompileUnit::getNameTableKind(StringRef Str) {
795   return StringSwitch<Optional<DebugNameTableKind>>(Str)
796       .Case("Default", DebugNameTableKind::Default)
797       .Case("GNU", DebugNameTableKind::GNU)
798       .Case("None", DebugNameTableKind::None)
799       .Default(None);
800 }
801 
802 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
803   switch (EK) {
804   case NoDebug:
805     return "NoDebug";
806   case FullDebug:
807     return "FullDebug";
808   case LineTablesOnly:
809     return "LineTablesOnly";
810   case DebugDirectivesOnly:
811     return "DebugDirectivesOnly";
812   }
813   return nullptr;
814 }
815 
816 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
817   switch (NTK) {
818   case DebugNameTableKind::Default:
819     return nullptr;
820   case DebugNameTableKind::GNU:
821     return "GNU";
822   case DebugNameTableKind::None:
823     return "None";
824   }
825   return nullptr;
826 }
827 
828 DISubprogram *DILocalScope::getSubprogram() const {
829   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
830     return Block->getScope()->getSubprogram();
831   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
832 }
833 
834 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
835   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
836     return File->getScope()->getNonLexicalBlockFileScope();
837   return const_cast<DILocalScope *>(this);
838 }
839 
840 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
841   return StringSwitch<DISPFlags>(Flag)
842 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
843 #include "llvm/IR/DebugInfoFlags.def"
844       .Default(SPFlagZero);
845 }
846 
847 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
848   switch (Flag) {
849   // Appease a warning.
850   case SPFlagVirtuality:
851     return "";
852 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
853   case SPFlag##NAME:                                                           \
854     return "DISPFlag" #NAME;
855 #include "llvm/IR/DebugInfoFlags.def"
856   }
857   return "";
858 }
859 
860 DISubprogram::DISPFlags
861 DISubprogram::splitFlags(DISPFlags Flags,
862                          SmallVectorImpl<DISPFlags> &SplitFlags) {
863   // Multi-bit fields can require special handling. In our case, however, the
864   // only multi-bit field is virtuality, and all its values happen to be
865   // single-bit values, so the right behavior just falls out.
866 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
867   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
868     SplitFlags.push_back(Bit);                                                 \
869     Flags &= ~Bit;                                                             \
870   }
871 #include "llvm/IR/DebugInfoFlags.def"
872   return Flags;
873 }
874 
875 DISubprogram *DISubprogram::getImpl(
876     LLVMContext &Context, Metadata *Scope, MDString *Name,
877     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
878     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
879     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
880     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
881     Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage,
882     bool ShouldCreate) {
883   assert(isCanonical(Name) && "Expected canonical MDString");
884   assert(isCanonical(LinkageName) && "Expected canonical MDString");
885   DEFINE_GETIMPL_LOOKUP(DISubprogram,
886                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
887                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
888                          SPFlags, Unit, TemplateParams, Declaration,
889                          RetainedNodes, ThrownTypes, Annotations));
890   SmallVector<Metadata *, 12> Ops = {
891       File,           Scope,          Name,        LinkageName,
892       Type,           Unit,           Declaration, RetainedNodes,
893       ContainingType, TemplateParams, ThrownTypes, Annotations};
894   if (!Annotations) {
895     Ops.pop_back();
896     if (!ThrownTypes) {
897       Ops.pop_back();
898       if (!TemplateParams) {
899         Ops.pop_back();
900         if (!ContainingType)
901           Ops.pop_back();
902       }
903     }
904   }
905   DEFINE_GETIMPL_STORE_N(
906       DISubprogram,
907       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
908       Ops.size());
909 }
910 
911 bool DISubprogram::describes(const Function *F) const {
912   assert(F && "Invalid function");
913   return F->getSubprogram() == this;
914 }
915 
916 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
917                                         Metadata *File, unsigned Line,
918                                         unsigned Column, StorageType Storage,
919                                         bool ShouldCreate) {
920   // Fixup column.
921   adjustColumn(Column);
922 
923   assert(Scope && "Expected scope");
924   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
925   Metadata *Ops[] = {File, Scope};
926   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
927 }
928 
929 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
930                                                 Metadata *Scope, Metadata *File,
931                                                 unsigned Discriminator,
932                                                 StorageType Storage,
933                                                 bool ShouldCreate) {
934   assert(Scope && "Expected scope");
935   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
936   Metadata *Ops[] = {File, Scope};
937   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
938 }
939 
940 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
941                                   MDString *Name, bool ExportSymbols,
942                                   StorageType Storage, bool ShouldCreate) {
943   assert(isCanonical(Name) && "Expected canonical MDString");
944   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
945   // The nullptr is for DIScope's File operand. This should be refactored.
946   Metadata *Ops[] = {nullptr, Scope, Name};
947   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
948 }
949 
950 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
951                                       Metadata *Decl, MDString *Name,
952                                       Metadata *File, unsigned LineNo,
953                                       StorageType Storage, bool ShouldCreate) {
954   assert(isCanonical(Name) && "Expected canonical MDString");
955   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
956   // The nullptr is for DIScope's File operand. This should be refactored.
957   Metadata *Ops[] = {Scope, Decl, Name, File};
958   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
959 }
960 
961 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
962                             Metadata *Scope, MDString *Name,
963                             MDString *ConfigurationMacros,
964                             MDString *IncludePath, MDString *APINotesFile,
965                             unsigned LineNo, bool IsDecl, StorageType Storage,
966                             bool ShouldCreate) {
967   assert(isCanonical(Name) && "Expected canonical MDString");
968   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
969                                    IncludePath, APINotesFile, LineNo, IsDecl));
970   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
971                      IncludePath, APINotesFile};
972   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
973 }
974 
975 DITemplateTypeParameter *
976 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
977                                  Metadata *Type, bool isDefault,
978                                  StorageType Storage, bool ShouldCreate) {
979   assert(isCanonical(Name) && "Expected canonical MDString");
980   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
981   Metadata *Ops[] = {Name, Type};
982   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
983 }
984 
985 DITemplateValueParameter *DITemplateValueParameter::getImpl(
986     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
987     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
988   assert(isCanonical(Name) && "Expected canonical MDString");
989   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
990                         (Tag, Name, Type, isDefault, Value));
991   Metadata *Ops[] = {Name, Type, Value};
992   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
993 }
994 
995 DIGlobalVariable *
996 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
997                           MDString *LinkageName, Metadata *File, unsigned Line,
998                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
999                           Metadata *StaticDataMemberDeclaration,
1000                           Metadata *TemplateParams, uint32_t AlignInBits,
1001                           Metadata *Annotations, StorageType Storage,
1002                           bool ShouldCreate) {
1003   assert(isCanonical(Name) && "Expected canonical MDString");
1004   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1005   DEFINE_GETIMPL_LOOKUP(
1006       DIGlobalVariable,
1007       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1008        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations));
1009   Metadata *Ops[] = {Scope,
1010                      Name,
1011                      File,
1012                      Type,
1013                      Name,
1014                      LinkageName,
1015                      StaticDataMemberDeclaration,
1016                      TemplateParams,
1017                      Annotations};
1018   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1019                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1020 }
1021 
1022 DILocalVariable *
1023 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1024                          Metadata *File, unsigned Line, Metadata *Type,
1025                          unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
1026                          Metadata *Annotations, StorageType Storage,
1027                          bool ShouldCreate) {
1028   // 64K ought to be enough for any frontend.
1029   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1030 
1031   assert(Scope && "Expected scope");
1032   assert(isCanonical(Name) && "Expected canonical MDString");
1033   DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg,
1034                                           Flags, AlignInBits, Annotations));
1035   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1036   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1037 }
1038 
1039 Optional<uint64_t> DIVariable::getSizeInBits() const {
1040   // This is used by the Verifier so be mindful of broken types.
1041   const Metadata *RawType = getRawType();
1042   while (RawType) {
1043     // Try to get the size directly.
1044     if (auto *T = dyn_cast<DIType>(RawType))
1045       if (uint64_t Size = T->getSizeInBits())
1046         return Size;
1047 
1048     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1049       // Look at the base type.
1050       RawType = DT->getRawBaseType();
1051       continue;
1052     }
1053 
1054     // Missing type or size.
1055     break;
1056   }
1057 
1058   // Fail gracefully.
1059   return None;
1060 }
1061 
1062 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1063                           Metadata *File, unsigned Line, StorageType Storage,
1064                           bool ShouldCreate) {
1065   assert(Scope && "Expected scope");
1066   assert(isCanonical(Name) && "Expected canonical MDString");
1067   DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line));
1068   Metadata *Ops[] = {Scope, Name, File};
1069   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1070 }
1071 
1072 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1073                                     ArrayRef<uint64_t> Elements,
1074                                     StorageType Storage, bool ShouldCreate) {
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:
1220       return true;
1221     }
1222   }
1223 
1224   return false;
1225 }
1226 
1227 Optional<DIExpression::FragmentInfo>
1228 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1229   for (auto I = Start; I != End; ++I)
1230     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1231       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1232       return Info;
1233     }
1234   return None;
1235 }
1236 
1237 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1238                                 int64_t Offset) {
1239   if (Offset > 0) {
1240     Ops.push_back(dwarf::DW_OP_plus_uconst);
1241     Ops.push_back(Offset);
1242   } else if (Offset < 0) {
1243     Ops.push_back(dwarf::DW_OP_constu);
1244     Ops.push_back(-Offset);
1245     Ops.push_back(dwarf::DW_OP_minus);
1246   }
1247 }
1248 
1249 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1250   if (getNumElements() == 0) {
1251     Offset = 0;
1252     return true;
1253   }
1254 
1255   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1256     Offset = Elements[1];
1257     return true;
1258   }
1259 
1260   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1261     if (Elements[2] == dwarf::DW_OP_plus) {
1262       Offset = Elements[1];
1263       return true;
1264     }
1265     if (Elements[2] == dwarf::DW_OP_minus) {
1266       Offset = -Elements[1];
1267       return true;
1268     }
1269   }
1270 
1271   return false;
1272 }
1273 
1274 bool DIExpression::hasAllLocationOps(unsigned N) const {
1275   SmallDenseSet<uint64_t, 4> SeenOps;
1276   for (auto ExprOp : expr_ops())
1277     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1278       SeenOps.insert(ExprOp.getArg(0));
1279   for (uint64_t Idx = 0; Idx < N; ++Idx)
1280     if (!is_contained(SeenOps, Idx))
1281       return false;
1282   return true;
1283 }
1284 
1285 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1286                                                       unsigned &AddrClass) {
1287   // FIXME: This seems fragile. Nothing that verifies that these elements
1288   // actually map to ops and not operands.
1289   const unsigned PatternSize = 4;
1290   if (Expr->Elements.size() >= PatternSize &&
1291       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1292       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1293       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1294     AddrClass = Expr->Elements[PatternSize - 3];
1295 
1296     if (Expr->Elements.size() == PatternSize)
1297       return nullptr;
1298     return DIExpression::get(Expr->getContext(),
1299                              makeArrayRef(&*Expr->Elements.begin(),
1300                                           Expr->Elements.size() - PatternSize));
1301   }
1302   return Expr;
1303 }
1304 
1305 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1306                                     int64_t Offset) {
1307   SmallVector<uint64_t, 8> Ops;
1308   if (Flags & DIExpression::DerefBefore)
1309     Ops.push_back(dwarf::DW_OP_deref);
1310 
1311   appendOffset(Ops, Offset);
1312   if (Flags & DIExpression::DerefAfter)
1313     Ops.push_back(dwarf::DW_OP_deref);
1314 
1315   bool StackValue = Flags & DIExpression::StackValue;
1316   bool EntryValue = Flags & DIExpression::EntryValue;
1317 
1318   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1319 }
1320 
1321 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1322                                            ArrayRef<uint64_t> Ops,
1323                                            unsigned ArgNo, bool StackValue) {
1324   assert(Expr && "Can't add ops to this expression");
1325 
1326   // Handle non-variadic intrinsics by prepending the opcodes.
1327   if (!any_of(Expr->expr_ops(),
1328               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1329     assert(ArgNo == 0 &&
1330            "Location Index must be 0 for a non-variadic expression.");
1331     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1332     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1333   }
1334 
1335   SmallVector<uint64_t, 8> NewOps;
1336   for (auto Op : Expr->expr_ops()) {
1337     Op.appendToVector(NewOps);
1338     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1339       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1340   }
1341 
1342   return DIExpression::get(Expr->getContext(), NewOps);
1343 }
1344 
1345 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1346                                        uint64_t OldArg, uint64_t NewArg) {
1347   assert(Expr && "Can't replace args in this expression");
1348 
1349   SmallVector<uint64_t, 8> NewOps;
1350 
1351   for (auto Op : Expr->expr_ops()) {
1352     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1353       Op.appendToVector(NewOps);
1354       continue;
1355     }
1356     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1357     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1358     // OldArg has been deleted from the Op list, so decrement all indices
1359     // greater than it.
1360     if (Arg > OldArg)
1361       --Arg;
1362     NewOps.push_back(Arg);
1363   }
1364   return DIExpression::get(Expr->getContext(), NewOps);
1365 }
1366 
1367 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1368                                            SmallVectorImpl<uint64_t> &Ops,
1369                                            bool StackValue, 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:
1465         break;
1466       case dwarf::DW_OP_shr:
1467       case dwarf::DW_OP_shra:
1468       case dwarf::DW_OP_shl:
1469       case dwarf::DW_OP_plus:
1470       case dwarf::DW_OP_plus_uconst:
1471       case dwarf::DW_OP_minus:
1472         // We can't safely split arithmetic or shift operations into multiple
1473         // fragments because we can't express carry-over between fragments.
1474         //
1475         // FIXME: We *could* preserve the lowest fragment of a constant offset
1476         // operation if the offset fits into SizeInBits.
1477         return None;
1478       case dwarf::DW_OP_LLVM_fragment: {
1479         // Make the new offset point into the existing fragment.
1480         uint64_t FragmentOffsetInBits = Op.getArg(0);
1481         uint64_t FragmentSizeInBits = Op.getArg(1);
1482         (void)FragmentSizeInBits;
1483         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1484                "new fragment outside of original fragment");
1485         OffsetInBits += FragmentOffsetInBits;
1486         continue;
1487       }
1488       }
1489       Op.appendToVector(Ops);
1490     }
1491   }
1492   assert(Expr && "Unknown DIExpression");
1493   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1494   Ops.push_back(OffsetInBits);
1495   Ops.push_back(SizeInBits);
1496   return DIExpression::get(Expr->getContext(), Ops);
1497 }
1498 
1499 std::pair<DIExpression *, const ConstantInt *>
1500 DIExpression::constantFold(const ConstantInt *CI) {
1501   // Copy the APInt so we can modify it.
1502   APInt NewInt = CI->getValue();
1503   SmallVector<uint64_t, 8> Ops;
1504 
1505   // Fold operators only at the beginning of the expression.
1506   bool First = true;
1507   bool Changed = false;
1508   for (auto Op : expr_ops()) {
1509     switch (Op.getOp()) {
1510     default:
1511       // We fold only the leading part of the expression; if we get to a part
1512       // that we're going to copy unchanged, and haven't done any folding,
1513       // then the entire expression is unchanged and we can return early.
1514       if (!Changed)
1515         return {this, CI};
1516       First = false;
1517       break;
1518     case dwarf::DW_OP_LLVM_convert:
1519       if (!First)
1520         break;
1521       Changed = true;
1522       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1523         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1524       else {
1525         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1526         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1527       }
1528       continue;
1529     }
1530     Op.appendToVector(Ops);
1531   }
1532   if (!Changed)
1533     return {this, CI};
1534   return {DIExpression::get(getContext(), Ops),
1535           ConstantInt::get(getContext(), NewInt)};
1536 }
1537 
1538 uint64_t DIExpression::getNumLocationOperands() const {
1539   uint64_t Result = 0;
1540   for (auto ExprOp : expr_ops())
1541     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1542       Result = std::max(Result, ExprOp.getArg(0) + 1);
1543   assert(hasAllLocationOps(Result) &&
1544          "Expression is missing one or more location operands.");
1545   return Result;
1546 }
1547 
1548 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1549 DIExpression::isConstant() const {
1550 
1551   // Recognize signed and unsigned constants.
1552   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1553   // (DW_OP_LLVM_fragment of Len).
1554   // An unsigned constant can be represented as
1555   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1556 
1557   if ((getNumElements() != 2 && getNumElements() != 3 &&
1558        getNumElements() != 6) ||
1559       (getElement(0) != dwarf::DW_OP_consts &&
1560        getElement(0) != dwarf::DW_OP_constu))
1561     return None;
1562 
1563   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1564     return SignedOrUnsignedConstant::SignedConstant;
1565 
1566   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1567       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1568                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1569     return None;
1570   return getElement(0) == dwarf::DW_OP_constu
1571              ? SignedOrUnsignedConstant::UnsignedConstant
1572              : SignedOrUnsignedConstant::SignedConstant;
1573 }
1574 
1575 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1576                                              bool Signed) {
1577   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1578   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1579                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1580   return Ops;
1581 }
1582 
1583 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1584                                       unsigned FromSize, unsigned ToSize,
1585                                       bool Signed) {
1586   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1587 }
1588 
1589 DIGlobalVariableExpression *
1590 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1591                                     Metadata *Expression, StorageType Storage,
1592                                     bool ShouldCreate) {
1593   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1594   Metadata *Ops[] = {Variable, Expression};
1595   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1596 }
1597 
1598 DIObjCProperty *DIObjCProperty::getImpl(
1599     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1600     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1601     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1602   assert(isCanonical(Name) && "Expected canonical MDString");
1603   assert(isCanonical(GetterName) && "Expected canonical MDString");
1604   assert(isCanonical(SetterName) && "Expected canonical MDString");
1605   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1606                                          SetterName, Attributes, Type));
1607   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1608   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1609 }
1610 
1611 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1612                                             Metadata *Scope, Metadata *Entity,
1613                                             Metadata *File, unsigned Line,
1614                                             MDString *Name, Metadata *Elements,
1615                                             StorageType Storage,
1616                                             bool ShouldCreate) {
1617   assert(isCanonical(Name) && "Expected canonical MDString");
1618   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1619                         (Tag, Scope, Entity, File, Line, Name, Elements));
1620   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
1621   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1622 }
1623 
1624 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
1625                           MDString *Name, MDString *Value, StorageType Storage,
1626                           bool ShouldCreate) {
1627   assert(isCanonical(Name) && "Expected canonical MDString");
1628   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1629   Metadata *Ops[] = {Name, Value};
1630   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1631 }
1632 
1633 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1634                                   unsigned Line, Metadata *File,
1635                                   Metadata *Elements, StorageType Storage,
1636                                   bool ShouldCreate) {
1637   DEFINE_GETIMPL_LOOKUP(DIMacroFile, (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   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1646   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1647 }
1648 
1649 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1650   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1651   assert((!New || isa<ValueAsMetadata>(New)) &&
1652          "DIArgList must be passed a ValueAsMetadata");
1653   untrack();
1654   bool Uniq = isUniqued();
1655   if (Uniq) {
1656     // We need to update the uniqueness once the Args are updated since they
1657     // form the key to the DIArgLists store.
1658     eraseFromStore();
1659   }
1660   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1661   for (ValueAsMetadata *&VM : Args) {
1662     if (&VM == OldVMPtr) {
1663       if (NewVM)
1664         VM = NewVM;
1665       else
1666         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1667     }
1668   }
1669   if (Uniq) {
1670     if (uniquify() != this)
1671       storeDistinctInContext();
1672   }
1673   track();
1674 }
1675 void DIArgList::track() {
1676   for (ValueAsMetadata *&VAM : Args)
1677     if (VAM)
1678       MetadataTracking::track(&VAM, *VAM, *this);
1679 }
1680 void DIArgList::untrack() {
1681   for (ValueAsMetadata *&VAM : Args)
1682     if (VAM)
1683       MetadataTracking::untrack(&VAM, *VAM);
1684 }
1685 void DIArgList::dropAllReferences() {
1686   untrack();
1687   Args.clear();
1688   MDNode::dropAllReferences();
1689 }
1690