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   // Only mutate CT if it's a forward declaration and the new operands aren't.
644   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
645   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
646     return CT;
647 
648   // Mutate CT in place.  Keep this in sync with getImpl.
649   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
650              Flags);
651   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
652                      Elements,      VTableHolder, TemplateParams, &Identifier,
653                      Discriminator, DataLocation, Associated,     Allocated,
654                      Rank,          Annotations};
655   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
656          "Mismatched number of operands");
657   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
658     if (Ops[I] != CT->getOperand(I))
659       CT->setOperand(I, Ops[I]);
660   return CT;
661 }
662 
663 DICompositeType *DICompositeType::getODRType(
664     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
665     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
666     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
667     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
668     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
669     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
670     Metadata *Rank, Metadata *Annotations) {
671   assert(!Identifier.getString().empty() && "Expected valid identifier");
672   if (!Context.isODRUniquingDebugTypes())
673     return nullptr;
674   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
675   if (!CT)
676     CT = DICompositeType::getDistinct(
677         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
678         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
679         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
680         Allocated, Rank, Annotations);
681   return CT;
682 }
683 
684 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
685                                                      MDString &Identifier) {
686   assert(!Identifier.getString().empty() && "Expected valid identifier");
687   if (!Context.isODRUniquingDebugTypes())
688     return nullptr;
689   return Context.pImpl->DITypeMap->lookup(&Identifier);
690 }
691 
692 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
693                                             uint8_t CC, Metadata *TypeArray,
694                                             StorageType Storage,
695                                             bool ShouldCreate) {
696   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
697   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
698   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
699 }
700 
701 // FIXME: Implement this string-enum correspondence with a .def file and macros,
702 // so that the association is explicit rather than implied.
703 static const char *ChecksumKindName[DIFile::CSK_Last] = {
704     "CSK_MD5",
705     "CSK_SHA1",
706     "CSK_SHA256",
707 };
708 
709 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
710   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
711   // The first space was originally the CSK_None variant, which is now
712   // obsolete, but the space is still reserved in ChecksumKind, so we account
713   // for it here.
714   return ChecksumKindName[CSKind - 1];
715 }
716 
717 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
718   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
719       .Case("CSK_MD5", DIFile::CSK_MD5)
720       .Case("CSK_SHA1", DIFile::CSK_SHA1)
721       .Case("CSK_SHA256", DIFile::CSK_SHA256)
722       .Default(None);
723 }
724 
725 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
726                         MDString *Directory,
727                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
728                         Optional<MDString *> Source, StorageType Storage,
729                         bool ShouldCreate) {
730   assert(isCanonical(Filename) && "Expected canonical MDString");
731   assert(isCanonical(Directory) && "Expected canonical MDString");
732   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
733   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
734   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
735   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
736                      Source.getValueOr(nullptr)};
737   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
738 }
739 
740 DICompileUnit *DICompileUnit::getImpl(
741     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
742     MDString *Producer, bool IsOptimized, MDString *Flags,
743     unsigned RuntimeVersion, MDString *SplitDebugFilename,
744     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
745     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
746     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
747     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
748     MDString *SDK, StorageType Storage, bool ShouldCreate) {
749   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
750   assert(isCanonical(Producer) && "Expected canonical MDString");
751   assert(isCanonical(Flags) && "Expected canonical MDString");
752   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
753 
754   Metadata *Ops[] = {File,
755                      Producer,
756                      Flags,
757                      SplitDebugFilename,
758                      EnumTypes,
759                      RetainedTypes,
760                      GlobalVariables,
761                      ImportedEntities,
762                      Macros,
763                      SysRoot,
764                      SDK};
765   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
766                        Context, Storage, SourceLanguage, IsOptimized,
767                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
768                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
769                        Ops),
770                    Storage);
771 }
772 
773 Optional<DICompileUnit::DebugEmissionKind>
774 DICompileUnit::getEmissionKind(StringRef Str) {
775   return StringSwitch<Optional<DebugEmissionKind>>(Str)
776       .Case("NoDebug", NoDebug)
777       .Case("FullDebug", FullDebug)
778       .Case("LineTablesOnly", LineTablesOnly)
779       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
780       .Default(None);
781 }
782 
783 Optional<DICompileUnit::DebugNameTableKind>
784 DICompileUnit::getNameTableKind(StringRef Str) {
785   return StringSwitch<Optional<DebugNameTableKind>>(Str)
786       .Case("Default", DebugNameTableKind::Default)
787       .Case("GNU", DebugNameTableKind::GNU)
788       .Case("None", DebugNameTableKind::None)
789       .Default(None);
790 }
791 
792 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
793   switch (EK) {
794   case NoDebug:        return "NoDebug";
795   case FullDebug:      return "FullDebug";
796   case LineTablesOnly: return "LineTablesOnly";
797   case DebugDirectivesOnly: return "DebugDirectivesOnly";
798   }
799   return nullptr;
800 }
801 
802 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
803   switch (NTK) {
804   case DebugNameTableKind::Default:
805     return nullptr;
806   case DebugNameTableKind::GNU:
807     return "GNU";
808   case DebugNameTableKind::None:
809     return "None";
810   }
811   return nullptr;
812 }
813 
814 DISubprogram *DILocalScope::getSubprogram() const {
815   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
816     return Block->getScope()->getSubprogram();
817   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
818 }
819 
820 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
821   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
822     return File->getScope()->getNonLexicalBlockFileScope();
823   return const_cast<DILocalScope *>(this);
824 }
825 
826 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
827   return StringSwitch<DISPFlags>(Flag)
828 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
829 #include "llvm/IR/DebugInfoFlags.def"
830       .Default(SPFlagZero);
831 }
832 
833 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
834   switch (Flag) {
835   // Appease a warning.
836   case SPFlagVirtuality:
837     return "";
838 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
839   case SPFlag##NAME:                                                           \
840     return "DISPFlag" #NAME;
841 #include "llvm/IR/DebugInfoFlags.def"
842   }
843   return "";
844 }
845 
846 DISubprogram::DISPFlags
847 DISubprogram::splitFlags(DISPFlags Flags,
848                          SmallVectorImpl<DISPFlags> &SplitFlags) {
849   // Multi-bit fields can require special handling. In our case, however, the
850   // only multi-bit field is virtuality, and all its values happen to be
851   // single-bit values, so the right behavior just falls out.
852 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
853   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
854     SplitFlags.push_back(Bit);                                                 \
855     Flags &= ~Bit;                                                             \
856   }
857 #include "llvm/IR/DebugInfoFlags.def"
858   return Flags;
859 }
860 
861 DISubprogram *DISubprogram::getImpl(
862     LLVMContext &Context, Metadata *Scope, MDString *Name,
863     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
864     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
865     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
866     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
867     Metadata *ThrownTypes, Metadata *Annotations, StorageType Storage,
868     bool ShouldCreate) {
869   assert(isCanonical(Name) && "Expected canonical MDString");
870   assert(isCanonical(LinkageName) && "Expected canonical MDString");
871   DEFINE_GETIMPL_LOOKUP(DISubprogram,
872                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
873                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
874                          SPFlags, Unit, TemplateParams, Declaration,
875                          RetainedNodes, ThrownTypes, Annotations));
876   SmallVector<Metadata *, 12> Ops = {
877       File,        Scope,         Name,           LinkageName,    Type,       Unit,
878       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes,
879       Annotations};
880   if (!Annotations) {
881     Ops.pop_back();
882     if (!ThrownTypes) {
883       Ops.pop_back();
884       if (!TemplateParams) {
885         Ops.pop_back();
886         if (!ContainingType)
887           Ops.pop_back();
888       }
889     }
890   }
891   DEFINE_GETIMPL_STORE_N(
892       DISubprogram,
893       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
894       Ops.size());
895 }
896 
897 bool DISubprogram::describes(const Function *F) const {
898   assert(F && "Invalid function");
899   return F->getSubprogram() == this;
900 }
901 
902 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
903                                         Metadata *File, unsigned Line,
904                                         unsigned Column, StorageType Storage,
905                                         bool ShouldCreate) {
906   // Fixup column.
907   adjustColumn(Column);
908 
909   assert(Scope && "Expected scope");
910   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
911   Metadata *Ops[] = {File, Scope};
912   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
913 }
914 
915 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
916                                                 Metadata *Scope, Metadata *File,
917                                                 unsigned Discriminator,
918                                                 StorageType Storage,
919                                                 bool ShouldCreate) {
920   assert(Scope && "Expected scope");
921   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
922   Metadata *Ops[] = {File, Scope};
923   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
924 }
925 
926 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
927                                   MDString *Name, bool ExportSymbols,
928                                   StorageType Storage, bool ShouldCreate) {
929   assert(isCanonical(Name) && "Expected canonical MDString");
930   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
931   // The nullptr is for DIScope's File operand. This should be refactored.
932   Metadata *Ops[] = {nullptr, Scope, Name};
933   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
934 }
935 
936 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
937                                       Metadata *Decl, MDString *Name,
938                                       Metadata *File, unsigned LineNo,
939                                       StorageType Storage, bool ShouldCreate) {
940   assert(isCanonical(Name) && "Expected canonical MDString");
941   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
942   // The nullptr is for DIScope's File operand. This should be refactored.
943   Metadata *Ops[] = {Scope, Decl, Name, File};
944   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
945 }
946 
947 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
948                             Metadata *Scope, MDString *Name,
949                             MDString *ConfigurationMacros,
950                             MDString *IncludePath, MDString *APINotesFile,
951                             unsigned LineNo, bool IsDecl, StorageType Storage,
952                             bool ShouldCreate) {
953   assert(isCanonical(Name) && "Expected canonical MDString");
954   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
955                                    IncludePath, APINotesFile, LineNo, IsDecl));
956   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
957                      IncludePath, APINotesFile};
958   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
959 }
960 
961 DITemplateTypeParameter *
962 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
963                                  Metadata *Type, bool isDefault,
964                                  StorageType Storage, bool ShouldCreate) {
965   assert(isCanonical(Name) && "Expected canonical MDString");
966   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
967   Metadata *Ops[] = {Name, Type};
968   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
969 }
970 
971 DITemplateValueParameter *DITemplateValueParameter::getImpl(
972     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
973     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
974   assert(isCanonical(Name) && "Expected canonical MDString");
975   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
976                         (Tag, Name, Type, isDefault, Value));
977   Metadata *Ops[] = {Name, Type, Value};
978   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
979 }
980 
981 DIGlobalVariable *
982 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
983                           MDString *LinkageName, Metadata *File, unsigned Line,
984                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
985                           Metadata *StaticDataMemberDeclaration,
986                           Metadata *TemplateParams, uint32_t AlignInBits,
987                           Metadata *Annotations, StorageType Storage,
988                           bool ShouldCreate) {
989   assert(isCanonical(Name) && "Expected canonical MDString");
990   assert(isCanonical(LinkageName) && "Expected canonical MDString");
991   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
992                                            Type, IsLocalToUnit, IsDefinition,
993                                            StaticDataMemberDeclaration,
994                                            TemplateParams, AlignInBits,
995                                            Annotations));
996   Metadata *Ops[] = {Scope,
997                      Name,
998                      File,
999                      Type,
1000                      Name,
1001                      LinkageName,
1002                      StaticDataMemberDeclaration,
1003                      TemplateParams,
1004                      Annotations};
1005   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1006                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1007 }
1008 
1009 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
1010                                           MDString *Name, Metadata *File,
1011                                           unsigned Line, Metadata *Type,
1012                                           unsigned Arg, DIFlags Flags,
1013                                           uint32_t AlignInBits,
1014                                           Metadata *Annotations,
1015                                           StorageType Storage,
1016                                           bool ShouldCreate) {
1017   // 64K ought to be enough for any frontend.
1018   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1019 
1020   assert(Scope && "Expected scope");
1021   assert(isCanonical(Name) && "Expected canonical MDString");
1022   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
1023                         (Scope, Name, File, Line, Type, Arg, Flags,
1024                          AlignInBits, Annotations));
1025   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1026   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1027 }
1028 
1029 Optional<uint64_t> DIVariable::getSizeInBits() const {
1030   // This is used by the Verifier so be mindful of broken types.
1031   const Metadata *RawType = getRawType();
1032   while (RawType) {
1033     // Try to get the size directly.
1034     if (auto *T = dyn_cast<DIType>(RawType))
1035       if (uint64_t Size = T->getSizeInBits())
1036         return Size;
1037 
1038     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1039       // Look at the base type.
1040       RawType = DT->getRawBaseType();
1041       continue;
1042     }
1043 
1044     // Missing type or size.
1045     break;
1046   }
1047 
1048   // Fail gracefully.
1049   return None;
1050 }
1051 
1052 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
1053                           MDString *Name, Metadata *File, unsigned Line,
1054                           StorageType Storage,
1055                           bool ShouldCreate) {
1056   assert(Scope && "Expected scope");
1057   assert(isCanonical(Name) && "Expected canonical MDString");
1058   DEFINE_GETIMPL_LOOKUP(DILabel,
1059                         (Scope, Name, File, Line));
1060   Metadata *Ops[] = {Scope, Name, File};
1061   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1062 }
1063 
1064 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1065                                     ArrayRef<uint64_t> Elements,
1066                                     StorageType Storage, bool ShouldCreate) {
1067   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1068   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1069 }
1070 
1071 unsigned DIExpression::ExprOperand::getSize() const {
1072   uint64_t Op = getOp();
1073 
1074   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1075     return 2;
1076 
1077   switch (Op) {
1078   case dwarf::DW_OP_LLVM_convert:
1079   case dwarf::DW_OP_LLVM_fragment:
1080   case dwarf::DW_OP_bregx:
1081     return 3;
1082   case dwarf::DW_OP_constu:
1083   case dwarf::DW_OP_consts:
1084   case dwarf::DW_OP_deref_size:
1085   case dwarf::DW_OP_plus_uconst:
1086   case dwarf::DW_OP_LLVM_tag_offset:
1087   case dwarf::DW_OP_LLVM_entry_value:
1088   case dwarf::DW_OP_LLVM_arg:
1089   case dwarf::DW_OP_regx:
1090     return 2;
1091   default:
1092     return 1;
1093   }
1094 }
1095 
1096 bool DIExpression::isValid() const {
1097   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1098     // Check that there's space for the operand.
1099     if (I->get() + I->getSize() > E->get())
1100       return false;
1101 
1102     uint64_t Op = I->getOp();
1103     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1104         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1105       return true;
1106 
1107     // Check that the operand is valid.
1108     switch (Op) {
1109     default:
1110       return false;
1111     case dwarf::DW_OP_LLVM_fragment:
1112       // A fragment operator must appear at the end.
1113       return I->get() + I->getSize() == E->get();
1114     case dwarf::DW_OP_stack_value: {
1115       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1116       if (I->get() + I->getSize() == E->get())
1117         break;
1118       auto J = I;
1119       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1120         return false;
1121       break;
1122     }
1123     case dwarf::DW_OP_swap: {
1124       // Must be more than one implicit element on the stack.
1125 
1126       // FIXME: A better way to implement this would be to add a local variable
1127       // that keeps track of the stack depth and introduce something like a
1128       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1129       // DIExpression is attached to, or else pass the number of implicit stack
1130       // elements into isValid.
1131       if (getNumElements() == 1)
1132         return false;
1133       break;
1134     }
1135     case dwarf::DW_OP_LLVM_entry_value: {
1136       // An entry value operator must appear at the beginning and the number of
1137       // operations it cover can currently only be 1, because we support only
1138       // entry values of a simple register location. One reason for this is that
1139       // we currently can't calculate the size of the resulting DWARF block for
1140       // other expressions.
1141       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
1142     }
1143     case dwarf::DW_OP_LLVM_implicit_pointer:
1144     case dwarf::DW_OP_LLVM_convert:
1145     case dwarf::DW_OP_LLVM_arg:
1146     case dwarf::DW_OP_LLVM_tag_offset:
1147     case dwarf::DW_OP_constu:
1148     case dwarf::DW_OP_plus_uconst:
1149     case dwarf::DW_OP_plus:
1150     case dwarf::DW_OP_minus:
1151     case dwarf::DW_OP_mul:
1152     case dwarf::DW_OP_div:
1153     case dwarf::DW_OP_mod:
1154     case dwarf::DW_OP_or:
1155     case dwarf::DW_OP_and:
1156     case dwarf::DW_OP_xor:
1157     case dwarf::DW_OP_shl:
1158     case dwarf::DW_OP_shr:
1159     case dwarf::DW_OP_shra:
1160     case dwarf::DW_OP_deref:
1161     case dwarf::DW_OP_deref_size:
1162     case dwarf::DW_OP_xderef:
1163     case dwarf::DW_OP_lit0:
1164     case dwarf::DW_OP_not:
1165     case dwarf::DW_OP_dup:
1166     case dwarf::DW_OP_regx:
1167     case dwarf::DW_OP_bregx:
1168     case dwarf::DW_OP_push_object_address:
1169     case dwarf::DW_OP_over:
1170     case dwarf::DW_OP_consts:
1171       break;
1172     }
1173   }
1174   return true;
1175 }
1176 
1177 bool DIExpression::isImplicit() const {
1178   if (!isValid())
1179     return false;
1180 
1181   if (getNumElements() == 0)
1182     return false;
1183 
1184   for (const auto &It : expr_ops()) {
1185     switch (It.getOp()) {
1186     default:
1187       break;
1188     case dwarf::DW_OP_stack_value:
1189     case dwarf::DW_OP_LLVM_tag_offset:
1190       return true;
1191     }
1192   }
1193 
1194   return false;
1195 }
1196 
1197 bool DIExpression::isComplex() const {
1198   if (!isValid())
1199     return false;
1200 
1201   if (getNumElements() == 0)
1202     return false;
1203 
1204   // If there are any elements other than fragment or tag_offset, then some
1205   // kind of complex computation occurs.
1206   for (const auto &It : expr_ops()) {
1207     switch (It.getOp()) {
1208       case dwarf::DW_OP_LLVM_tag_offset:
1209       case dwarf::DW_OP_LLVM_fragment:
1210         continue;
1211       default: return true;
1212     }
1213   }
1214 
1215   return false;
1216 }
1217 
1218 Optional<DIExpression::FragmentInfo>
1219 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1220   for (auto I = Start; I != End; ++I)
1221     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1222       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1223       return Info;
1224     }
1225   return None;
1226 }
1227 
1228 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1229                                 int64_t Offset) {
1230   if (Offset > 0) {
1231     Ops.push_back(dwarf::DW_OP_plus_uconst);
1232     Ops.push_back(Offset);
1233   } else if (Offset < 0) {
1234     Ops.push_back(dwarf::DW_OP_constu);
1235     Ops.push_back(-Offset);
1236     Ops.push_back(dwarf::DW_OP_minus);
1237   }
1238 }
1239 
1240 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1241   if (getNumElements() == 0) {
1242     Offset = 0;
1243     return true;
1244   }
1245 
1246   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1247     Offset = Elements[1];
1248     return true;
1249   }
1250 
1251   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1252     if (Elements[2] == dwarf::DW_OP_plus) {
1253       Offset = Elements[1];
1254       return true;
1255     }
1256     if (Elements[2] == dwarf::DW_OP_minus) {
1257       Offset = -Elements[1];
1258       return true;
1259     }
1260   }
1261 
1262   return false;
1263 }
1264 
1265 bool DIExpression::hasAllLocationOps(unsigned N) const {
1266   SmallDenseSet<uint64_t, 4> SeenOps;
1267   for (auto ExprOp : expr_ops())
1268     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1269       SeenOps.insert(ExprOp.getArg(0));
1270   for (uint64_t Idx = 0; Idx < N; ++Idx)
1271     if (!is_contained(SeenOps, Idx))
1272       return false;
1273   return true;
1274 }
1275 
1276 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1277                                                       unsigned &AddrClass) {
1278   // FIXME: This seems fragile. Nothing that verifies that these elements
1279   // actually map to ops and not operands.
1280   const unsigned PatternSize = 4;
1281   if (Expr->Elements.size() >= PatternSize &&
1282       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1283       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1284       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1285     AddrClass = Expr->Elements[PatternSize - 3];
1286 
1287     if (Expr->Elements.size() == PatternSize)
1288       return nullptr;
1289     return DIExpression::get(Expr->getContext(),
1290                              makeArrayRef(&*Expr->Elements.begin(),
1291                                           Expr->Elements.size() - PatternSize));
1292   }
1293   return Expr;
1294 }
1295 
1296 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1297                                     int64_t Offset) {
1298   SmallVector<uint64_t, 8> Ops;
1299   if (Flags & DIExpression::DerefBefore)
1300     Ops.push_back(dwarf::DW_OP_deref);
1301 
1302   appendOffset(Ops, Offset);
1303   if (Flags & DIExpression::DerefAfter)
1304     Ops.push_back(dwarf::DW_OP_deref);
1305 
1306   bool StackValue = Flags & DIExpression::StackValue;
1307   bool EntryValue = Flags & DIExpression::EntryValue;
1308 
1309   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1310 }
1311 
1312 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1313                                            ArrayRef<uint64_t> Ops,
1314                                            unsigned ArgNo, bool StackValue) {
1315   assert(Expr && "Can't add ops to this expression");
1316 
1317   // Handle non-variadic intrinsics by prepending the opcodes.
1318   if (!any_of(Expr->expr_ops(),
1319               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1320     assert(ArgNo == 0 &&
1321            "Location Index must be 0 for a non-variadic expression.");
1322     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1323     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1324   }
1325 
1326   SmallVector<uint64_t, 8> NewOps;
1327   for (auto Op : Expr->expr_ops()) {
1328     Op.appendToVector(NewOps);
1329     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1330       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1331   }
1332 
1333   return DIExpression::get(Expr->getContext(), NewOps);
1334 }
1335 
1336 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1337                                        uint64_t OldArg, uint64_t NewArg) {
1338   assert(Expr && "Can't replace args in this expression");
1339 
1340   SmallVector<uint64_t, 8> NewOps;
1341 
1342   for (auto Op : Expr->expr_ops()) {
1343     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1344       Op.appendToVector(NewOps);
1345       continue;
1346     }
1347     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1348     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1349     // OldArg has been deleted from the Op list, so decrement all indices
1350     // greater than it.
1351     if (Arg > OldArg)
1352       --Arg;
1353     NewOps.push_back(Arg);
1354   }
1355   return DIExpression::get(Expr->getContext(), NewOps);
1356 }
1357 
1358 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1359                                            SmallVectorImpl<uint64_t> &Ops,
1360                                            bool StackValue,
1361                                            bool EntryValue) {
1362   assert(Expr && "Can't prepend ops to this expression");
1363 
1364   if (EntryValue) {
1365     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1366     // Use a block size of 1 for the target register operand.  The
1367     // DWARF backend currently cannot emit entry values with a block
1368     // size > 1.
1369     Ops.push_back(1);
1370   }
1371 
1372   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1373   if (Ops.empty())
1374     StackValue = false;
1375   for (auto Op : Expr->expr_ops()) {
1376     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1377     if (StackValue) {
1378       if (Op.getOp() == dwarf::DW_OP_stack_value)
1379         StackValue = false;
1380       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1381         Ops.push_back(dwarf::DW_OP_stack_value);
1382         StackValue = false;
1383       }
1384     }
1385     Op.appendToVector(Ops);
1386   }
1387   if (StackValue)
1388     Ops.push_back(dwarf::DW_OP_stack_value);
1389   return DIExpression::get(Expr->getContext(), Ops);
1390 }
1391 
1392 DIExpression *DIExpression::append(const DIExpression *Expr,
1393                                    ArrayRef<uint64_t> Ops) {
1394   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1395 
1396   // Copy Expr's current op list.
1397   SmallVector<uint64_t, 16> NewOps;
1398   for (auto Op : Expr->expr_ops()) {
1399     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1400     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1401         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1402       NewOps.append(Ops.begin(), Ops.end());
1403 
1404       // Ensure that the new opcodes are only appended once.
1405       Ops = None;
1406     }
1407     Op.appendToVector(NewOps);
1408   }
1409 
1410   NewOps.append(Ops.begin(), Ops.end());
1411   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1412   assert(result->isValid() && "concatenated expression is not valid");
1413   return result;
1414 }
1415 
1416 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1417                                           ArrayRef<uint64_t> Ops) {
1418   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1419   assert(none_of(Ops,
1420                  [](uint64_t Op) {
1421                    return Op == dwarf::DW_OP_stack_value ||
1422                           Op == dwarf::DW_OP_LLVM_fragment;
1423                  }) &&
1424          "Can't append this op");
1425 
1426   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1427   // has no DW_OP_stack_value.
1428   //
1429   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1430   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1431   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1432   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1433       Expr->getElements().drop_back(DropUntilStackValue);
1434   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1435                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1436   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1437 
1438   // Append a DW_OP_deref after Expr's current op list if needed, then append
1439   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1440   SmallVector<uint64_t, 16> NewOps;
1441   if (NeedsDeref)
1442     NewOps.push_back(dwarf::DW_OP_deref);
1443   NewOps.append(Ops.begin(), Ops.end());
1444   if (NeedsStackValue)
1445     NewOps.push_back(dwarf::DW_OP_stack_value);
1446   return DIExpression::append(Expr, NewOps);
1447 }
1448 
1449 Optional<DIExpression *> DIExpression::createFragmentExpression(
1450     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1451   SmallVector<uint64_t, 8> Ops;
1452   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1453   if (Expr) {
1454     for (auto Op : Expr->expr_ops()) {
1455       switch (Op.getOp()) {
1456       default: break;
1457       case dwarf::DW_OP_shr:
1458       case dwarf::DW_OP_shra:
1459       case dwarf::DW_OP_shl:
1460       case dwarf::DW_OP_plus:
1461       case dwarf::DW_OP_plus_uconst:
1462       case dwarf::DW_OP_minus:
1463         // We can't safely split arithmetic or shift operations into multiple
1464         // fragments because we can't express carry-over between fragments.
1465         //
1466         // FIXME: We *could* preserve the lowest fragment of a constant offset
1467         // operation if the offset fits into SizeInBits.
1468         return None;
1469       case dwarf::DW_OP_LLVM_fragment: {
1470         // Make the new offset point into the existing fragment.
1471         uint64_t FragmentOffsetInBits = Op.getArg(0);
1472         uint64_t FragmentSizeInBits = Op.getArg(1);
1473         (void)FragmentSizeInBits;
1474         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1475                "new fragment outside of original fragment");
1476         OffsetInBits += FragmentOffsetInBits;
1477         continue;
1478       }
1479       }
1480       Op.appendToVector(Ops);
1481     }
1482   }
1483   assert(Expr && "Unknown DIExpression");
1484   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1485   Ops.push_back(OffsetInBits);
1486   Ops.push_back(SizeInBits);
1487   return DIExpression::get(Expr->getContext(), Ops);
1488 }
1489 
1490 std::pair<DIExpression *, const ConstantInt *>
1491 DIExpression::constantFold(const ConstantInt *CI) {
1492   // Copy the APInt so we can modify it.
1493   APInt NewInt = CI->getValue();
1494   SmallVector<uint64_t, 8> Ops;
1495 
1496   // Fold operators only at the beginning of the expression.
1497   bool First = true;
1498   bool Changed = false;
1499   for (auto Op : expr_ops()) {
1500     switch (Op.getOp()) {
1501     default:
1502       // We fold only the leading part of the expression; if we get to a part
1503       // that we're going to copy unchanged, and haven't done any folding,
1504       // then the entire expression is unchanged and we can return early.
1505       if (!Changed)
1506         return {this, CI};
1507       First = false;
1508       break;
1509     case dwarf::DW_OP_LLVM_convert:
1510       if (!First)
1511         break;
1512       Changed = true;
1513       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1514         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1515       else {
1516         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1517         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1518       }
1519       continue;
1520     }
1521     Op.appendToVector(Ops);
1522   }
1523   if (!Changed)
1524     return {this, CI};
1525   return {DIExpression::get(getContext(), Ops),
1526           ConstantInt::get(getContext(), NewInt)};
1527 }
1528 
1529 uint64_t DIExpression::getNumLocationOperands() const {
1530   uint64_t Result = 0;
1531   for (auto ExprOp : expr_ops())
1532     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1533       Result = std::max(Result, ExprOp.getArg(0) + 1);
1534   assert(hasAllLocationOps(Result) &&
1535          "Expression is missing one or more location operands.");
1536   return Result;
1537 }
1538 
1539 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1540 DIExpression::isConstant() const {
1541 
1542   // Recognize signed and unsigned constants.
1543   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1544   // (DW_OP_LLVM_fragment of Len).
1545   // An unsigned constant can be represented as
1546   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1547 
1548   if ((getNumElements() != 2 && getNumElements() != 3 &&
1549        getNumElements() != 6) ||
1550       (getElement(0) != dwarf::DW_OP_consts &&
1551        getElement(0) != dwarf::DW_OP_constu))
1552     return None;
1553 
1554   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1555     return SignedOrUnsignedConstant::SignedConstant;
1556 
1557   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1558       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1559                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1560     return None;
1561   return getElement(0) == dwarf::DW_OP_constu
1562              ? SignedOrUnsignedConstant::UnsignedConstant
1563              : SignedOrUnsignedConstant::SignedConstant;
1564 }
1565 
1566 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1567                                              bool Signed) {
1568   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1569   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1570                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1571   return Ops;
1572 }
1573 
1574 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1575                                       unsigned FromSize, unsigned ToSize,
1576                                       bool Signed) {
1577   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1578 }
1579 
1580 DIGlobalVariableExpression *
1581 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1582                                     Metadata *Expression, StorageType Storage,
1583                                     bool ShouldCreate) {
1584   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1585   Metadata *Ops[] = {Variable, Expression};
1586   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1587 }
1588 
1589 DIObjCProperty *DIObjCProperty::getImpl(
1590     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1591     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1592     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1593   assert(isCanonical(Name) && "Expected canonical MDString");
1594   assert(isCanonical(GetterName) && "Expected canonical MDString");
1595   assert(isCanonical(SetterName) && "Expected canonical MDString");
1596   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1597                                          SetterName, Attributes, Type));
1598   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1599   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1600 }
1601 
1602 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1603                                             Metadata *Scope, Metadata *Entity,
1604                                             Metadata *File, unsigned Line,
1605                                             MDString *Name, StorageType Storage,
1606                                             bool ShouldCreate) {
1607   assert(isCanonical(Name) && "Expected canonical MDString");
1608   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1609                         (Tag, Scope, Entity, File, Line, Name));
1610   Metadata *Ops[] = {Scope, Entity, Name, File};
1611   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1612 }
1613 
1614 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1615                           unsigned Line, MDString *Name, MDString *Value,
1616                           StorageType Storage, bool ShouldCreate) {
1617   assert(isCanonical(Name) && "Expected canonical MDString");
1618   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1619   Metadata *Ops[] = { Name, Value };
1620   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1621 }
1622 
1623 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1624                                   unsigned Line, Metadata *File,
1625                                   Metadata *Elements, StorageType Storage,
1626                                   bool ShouldCreate) {
1627   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1628                         (MIType, Line, File, Elements));
1629   Metadata *Ops[] = { File, Elements };
1630   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1631 }
1632 
1633 DIArgList *DIArgList::getImpl(LLVMContext &Context,
1634                               ArrayRef<ValueAsMetadata *> Args,
1635                               StorageType Storage, bool ShouldCreate) {
1636   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1637   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1638 }
1639 
1640 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1641   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1642   assert((!New || isa<ValueAsMetadata>(New)) &&
1643          "DIArgList must be passed a ValueAsMetadata");
1644   untrack();
1645   bool Uniq = isUniqued();
1646   if (Uniq) {
1647     // We need to update the uniqueness once the Args are updated since they
1648     // form the key to the DIArgLists store.
1649     eraseFromStore();
1650   }
1651   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1652   for (ValueAsMetadata *&VM : Args) {
1653     if (&VM == OldVMPtr) {
1654       if (NewVM)
1655         VM = NewVM;
1656       else
1657         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1658     }
1659   }
1660   if (Uniq) {
1661     if (uniquify() != this)
1662       storeDistinctInContext();
1663   }
1664   track();
1665 }
1666 void DIArgList::track() {
1667   for (ValueAsMetadata *&VAM : Args)
1668     if (VAM)
1669       MetadataTracking::track(&VAM, *VAM, *this);
1670 }
1671 void DIArgList::untrack() {
1672   for (ValueAsMetadata *&VAM : Args)
1673     if (VAM)
1674       MetadataTracking::untrack(&VAM, *VAM);
1675 }
1676 void DIArgList::dropAllReferences() {
1677   untrack();
1678   Args.clear();
1679   MDNode::dropAllReferences();
1680 }
1681