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