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     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));
591   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData};
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, StorageType Storage, bool ShouldCreate) {
868   assert(isCanonical(Name) && "Expected canonical MDString");
869   assert(isCanonical(LinkageName) && "Expected canonical MDString");
870   DEFINE_GETIMPL_LOOKUP(DISubprogram,
871                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
872                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
873                          SPFlags, Unit, TemplateParams, Declaration,
874                          RetainedNodes, ThrownTypes));
875   SmallVector<Metadata *, 11> Ops = {
876       File,        Scope,         Name,           LinkageName,    Type,       Unit,
877       Declaration, RetainedNodes, ContainingType, TemplateParams, ThrownTypes};
878   if (!ThrownTypes) {
879     Ops.pop_back();
880     if (!TemplateParams) {
881       Ops.pop_back();
882       if (!ContainingType)
883         Ops.pop_back();
884     }
885   }
886   DEFINE_GETIMPL_STORE_N(
887       DISubprogram,
888       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
889       Ops.size());
890 }
891 
892 bool DISubprogram::describes(const Function *F) const {
893   assert(F && "Invalid function");
894   return F->getSubprogram() == this;
895 }
896 
897 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
898                                         Metadata *File, unsigned Line,
899                                         unsigned Column, StorageType Storage,
900                                         bool ShouldCreate) {
901   // Fixup column.
902   adjustColumn(Column);
903 
904   assert(Scope && "Expected scope");
905   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
906   Metadata *Ops[] = {File, Scope};
907   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
908 }
909 
910 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
911                                                 Metadata *Scope, Metadata *File,
912                                                 unsigned Discriminator,
913                                                 StorageType Storage,
914                                                 bool ShouldCreate) {
915   assert(Scope && "Expected scope");
916   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
917   Metadata *Ops[] = {File, Scope};
918   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
919 }
920 
921 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
922                                   MDString *Name, bool ExportSymbols,
923                                   StorageType Storage, bool ShouldCreate) {
924   assert(isCanonical(Name) && "Expected canonical MDString");
925   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
926   // The nullptr is for DIScope's File operand. This should be refactored.
927   Metadata *Ops[] = {nullptr, Scope, Name};
928   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
929 }
930 
931 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
932                                       Metadata *Decl, MDString *Name,
933                                       Metadata *File, unsigned LineNo,
934                                       StorageType Storage, bool ShouldCreate) {
935   assert(isCanonical(Name) && "Expected canonical MDString");
936   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
937   // The nullptr is for DIScope's File operand. This should be refactored.
938   Metadata *Ops[] = {Scope, Decl, Name, File};
939   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
940 }
941 
942 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
943                             Metadata *Scope, MDString *Name,
944                             MDString *ConfigurationMacros,
945                             MDString *IncludePath, MDString *APINotesFile,
946                             unsigned LineNo, bool IsDecl, StorageType Storage,
947                             bool ShouldCreate) {
948   assert(isCanonical(Name) && "Expected canonical MDString");
949   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
950                                    IncludePath, APINotesFile, LineNo, IsDecl));
951   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
952                      IncludePath, APINotesFile};
953   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
954 }
955 
956 DITemplateTypeParameter *
957 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
958                                  Metadata *Type, bool isDefault,
959                                  StorageType Storage, bool ShouldCreate) {
960   assert(isCanonical(Name) && "Expected canonical MDString");
961   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
962   Metadata *Ops[] = {Name, Type};
963   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
964 }
965 
966 DITemplateValueParameter *DITemplateValueParameter::getImpl(
967     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
968     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
969   assert(isCanonical(Name) && "Expected canonical MDString");
970   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
971                         (Tag, Name, Type, isDefault, Value));
972   Metadata *Ops[] = {Name, Type, Value};
973   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
974 }
975 
976 DIGlobalVariable *
977 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
978                           MDString *LinkageName, Metadata *File, unsigned Line,
979                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
980                           Metadata *StaticDataMemberDeclaration,
981                           Metadata *TemplateParams, uint32_t AlignInBits,
982                           StorageType Storage, bool ShouldCreate) {
983   assert(isCanonical(Name) && "Expected canonical MDString");
984   assert(isCanonical(LinkageName) && "Expected canonical MDString");
985   DEFINE_GETIMPL_LOOKUP(DIGlobalVariable, (Scope, Name, LinkageName, File, Line,
986                                            Type, IsLocalToUnit, IsDefinition,
987                                            StaticDataMemberDeclaration,
988                                            TemplateParams, AlignInBits));
989   Metadata *Ops[] = {Scope,
990                      Name,
991                      File,
992                      Type,
993                      Name,
994                      LinkageName,
995                      StaticDataMemberDeclaration,
996                      TemplateParams};
997   DEFINE_GETIMPL_STORE(DIGlobalVariable,
998                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
999 }
1000 
1001 DILocalVariable *DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope,
1002                                           MDString *Name, Metadata *File,
1003                                           unsigned Line, Metadata *Type,
1004                                           unsigned Arg, DIFlags Flags,
1005                                           uint32_t AlignInBits,
1006                                           StorageType Storage,
1007                                           bool ShouldCreate) {
1008   // 64K ought to be enough for any frontend.
1009   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1010 
1011   assert(Scope && "Expected scope");
1012   assert(isCanonical(Name) && "Expected canonical MDString");
1013   DEFINE_GETIMPL_LOOKUP(DILocalVariable,
1014                         (Scope, Name, File, Line, Type, Arg, Flags,
1015                          AlignInBits));
1016   Metadata *Ops[] = {Scope, Name, File, Type};
1017   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1018 }
1019 
1020 Optional<uint64_t> DIVariable::getSizeInBits() const {
1021   // This is used by the Verifier so be mindful of broken types.
1022   const Metadata *RawType = getRawType();
1023   while (RawType) {
1024     // Try to get the size directly.
1025     if (auto *T = dyn_cast<DIType>(RawType))
1026       if (uint64_t Size = T->getSizeInBits())
1027         return Size;
1028 
1029     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1030       // Look at the base type.
1031       RawType = DT->getRawBaseType();
1032       continue;
1033     }
1034 
1035     // Missing type or size.
1036     break;
1037   }
1038 
1039   // Fail gracefully.
1040   return None;
1041 }
1042 
1043 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope,
1044                           MDString *Name, Metadata *File, unsigned Line,
1045                           StorageType Storage,
1046                           bool ShouldCreate) {
1047   assert(Scope && "Expected scope");
1048   assert(isCanonical(Name) && "Expected canonical MDString");
1049   DEFINE_GETIMPL_LOOKUP(DILabel,
1050                         (Scope, Name, File, Line));
1051   Metadata *Ops[] = {Scope, Name, File};
1052   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1053 }
1054 
1055 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1056                                     ArrayRef<uint64_t> Elements,
1057                                     StorageType Storage, bool ShouldCreate) {
1058   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1059   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1060 }
1061 
1062 unsigned DIExpression::ExprOperand::getSize() const {
1063   uint64_t Op = getOp();
1064 
1065   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1066     return 2;
1067 
1068   switch (Op) {
1069   case dwarf::DW_OP_LLVM_convert:
1070   case dwarf::DW_OP_LLVM_fragment:
1071   case dwarf::DW_OP_bregx:
1072     return 3;
1073   case dwarf::DW_OP_constu:
1074   case dwarf::DW_OP_consts:
1075   case dwarf::DW_OP_deref_size:
1076   case dwarf::DW_OP_plus_uconst:
1077   case dwarf::DW_OP_LLVM_tag_offset:
1078   case dwarf::DW_OP_LLVM_entry_value:
1079   case dwarf::DW_OP_LLVM_arg:
1080   case dwarf::DW_OP_regx:
1081     return 2;
1082   default:
1083     return 1;
1084   }
1085 }
1086 
1087 bool DIExpression::isValid() const {
1088   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1089     // Check that there's space for the operand.
1090     if (I->get() + I->getSize() > E->get())
1091       return false;
1092 
1093     uint64_t Op = I->getOp();
1094     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1095         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1096       return true;
1097 
1098     // Check that the operand is valid.
1099     switch (Op) {
1100     default:
1101       return false;
1102     case dwarf::DW_OP_LLVM_fragment:
1103       // A fragment operator must appear at the end.
1104       return I->get() + I->getSize() == E->get();
1105     case dwarf::DW_OP_stack_value: {
1106       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1107       if (I->get() + I->getSize() == E->get())
1108         break;
1109       auto J = I;
1110       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1111         return false;
1112       break;
1113     }
1114     case dwarf::DW_OP_swap: {
1115       // Must be more than one implicit element on the stack.
1116 
1117       // FIXME: A better way to implement this would be to add a local variable
1118       // that keeps track of the stack depth and introduce something like a
1119       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1120       // DIExpression is attached to, or else pass the number of implicit stack
1121       // elements into isValid.
1122       if (getNumElements() == 1)
1123         return false;
1124       break;
1125     }
1126     case dwarf::DW_OP_LLVM_entry_value: {
1127       // An entry value operator must appear at the beginning and the number of
1128       // operations it cover can currently only be 1, because we support only
1129       // entry values of a simple register location. One reason for this is that
1130       // we currently can't calculate the size of the resulting DWARF block for
1131       // other expressions.
1132       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
1133     }
1134     case dwarf::DW_OP_LLVM_implicit_pointer:
1135     case dwarf::DW_OP_LLVM_convert:
1136     case dwarf::DW_OP_LLVM_arg:
1137     case dwarf::DW_OP_LLVM_tag_offset:
1138     case dwarf::DW_OP_constu:
1139     case dwarf::DW_OP_plus_uconst:
1140     case dwarf::DW_OP_plus:
1141     case dwarf::DW_OP_minus:
1142     case dwarf::DW_OP_mul:
1143     case dwarf::DW_OP_div:
1144     case dwarf::DW_OP_mod:
1145     case dwarf::DW_OP_or:
1146     case dwarf::DW_OP_and:
1147     case dwarf::DW_OP_xor:
1148     case dwarf::DW_OP_shl:
1149     case dwarf::DW_OP_shr:
1150     case dwarf::DW_OP_shra:
1151     case dwarf::DW_OP_deref:
1152     case dwarf::DW_OP_deref_size:
1153     case dwarf::DW_OP_xderef:
1154     case dwarf::DW_OP_lit0:
1155     case dwarf::DW_OP_not:
1156     case dwarf::DW_OP_dup:
1157     case dwarf::DW_OP_regx:
1158     case dwarf::DW_OP_bregx:
1159     case dwarf::DW_OP_push_object_address:
1160     case dwarf::DW_OP_over:
1161     case dwarf::DW_OP_consts:
1162       break;
1163     }
1164   }
1165   return true;
1166 }
1167 
1168 bool DIExpression::isImplicit() const {
1169   if (!isValid())
1170     return false;
1171 
1172   if (getNumElements() == 0)
1173     return false;
1174 
1175   for (const auto &It : expr_ops()) {
1176     switch (It.getOp()) {
1177     default:
1178       break;
1179     case dwarf::DW_OP_stack_value:
1180     case dwarf::DW_OP_LLVM_tag_offset:
1181       return true;
1182     }
1183   }
1184 
1185   return false;
1186 }
1187 
1188 bool DIExpression::isComplex() const {
1189   if (!isValid())
1190     return false;
1191 
1192   if (getNumElements() == 0)
1193     return false;
1194 
1195   // If there are any elements other than fragment or tag_offset, then some
1196   // kind of complex computation occurs.
1197   for (const auto &It : expr_ops()) {
1198     switch (It.getOp()) {
1199       case dwarf::DW_OP_LLVM_tag_offset:
1200       case dwarf::DW_OP_LLVM_fragment:
1201         continue;
1202       default: return true;
1203     }
1204   }
1205 
1206   return false;
1207 }
1208 
1209 Optional<DIExpression::FragmentInfo>
1210 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1211   for (auto I = Start; I != End; ++I)
1212     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1213       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1214       return Info;
1215     }
1216   return None;
1217 }
1218 
1219 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1220                                 int64_t Offset) {
1221   if (Offset > 0) {
1222     Ops.push_back(dwarf::DW_OP_plus_uconst);
1223     Ops.push_back(Offset);
1224   } else if (Offset < 0) {
1225     Ops.push_back(dwarf::DW_OP_constu);
1226     Ops.push_back(-Offset);
1227     Ops.push_back(dwarf::DW_OP_minus);
1228   }
1229 }
1230 
1231 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1232   if (getNumElements() == 0) {
1233     Offset = 0;
1234     return true;
1235   }
1236 
1237   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1238     Offset = Elements[1];
1239     return true;
1240   }
1241 
1242   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1243     if (Elements[2] == dwarf::DW_OP_plus) {
1244       Offset = Elements[1];
1245       return true;
1246     }
1247     if (Elements[2] == dwarf::DW_OP_minus) {
1248       Offset = -Elements[1];
1249       return true;
1250     }
1251   }
1252 
1253   return false;
1254 }
1255 
1256 bool DIExpression::hasAllLocationOps(unsigned N) const {
1257   SmallDenseSet<uint64_t, 4> SeenOps;
1258   for (auto ExprOp : expr_ops())
1259     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1260       SeenOps.insert(ExprOp.getArg(0));
1261   for (uint64_t Idx = 0; Idx < N; ++Idx)
1262     if (!is_contained(SeenOps, Idx))
1263       return false;
1264   return true;
1265 }
1266 
1267 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1268                                                       unsigned &AddrClass) {
1269   // FIXME: This seems fragile. Nothing that verifies that these elements
1270   // actually map to ops and not operands.
1271   const unsigned PatternSize = 4;
1272   if (Expr->Elements.size() >= PatternSize &&
1273       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1274       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1275       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1276     AddrClass = Expr->Elements[PatternSize - 3];
1277 
1278     if (Expr->Elements.size() == PatternSize)
1279       return nullptr;
1280     return DIExpression::get(Expr->getContext(),
1281                              makeArrayRef(&*Expr->Elements.begin(),
1282                                           Expr->Elements.size() - PatternSize));
1283   }
1284   return Expr;
1285 }
1286 
1287 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1288                                     int64_t Offset) {
1289   SmallVector<uint64_t, 8> Ops;
1290   if (Flags & DIExpression::DerefBefore)
1291     Ops.push_back(dwarf::DW_OP_deref);
1292 
1293   appendOffset(Ops, Offset);
1294   if (Flags & DIExpression::DerefAfter)
1295     Ops.push_back(dwarf::DW_OP_deref);
1296 
1297   bool StackValue = Flags & DIExpression::StackValue;
1298   bool EntryValue = Flags & DIExpression::EntryValue;
1299 
1300   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1301 }
1302 
1303 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1304                                            ArrayRef<uint64_t> Ops,
1305                                            unsigned ArgNo, bool StackValue) {
1306   assert(Expr && "Can't add ops to this expression");
1307 
1308   // Handle non-variadic intrinsics by prepending the opcodes.
1309   if (!any_of(Expr->expr_ops(),
1310               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1311     assert(ArgNo == 0 &&
1312            "Location Index must be 0 for a non-variadic expression.");
1313     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1314     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1315   }
1316 
1317   SmallVector<uint64_t, 8> NewOps;
1318   for (auto Op : Expr->expr_ops()) {
1319     Op.appendToVector(NewOps);
1320     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1321       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1322   }
1323 
1324   return DIExpression::get(Expr->getContext(), NewOps);
1325 }
1326 
1327 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1328                                        uint64_t OldArg, uint64_t NewArg) {
1329   assert(Expr && "Can't replace args in this expression");
1330 
1331   SmallVector<uint64_t, 8> NewOps;
1332 
1333   for (auto Op : Expr->expr_ops()) {
1334     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1335       Op.appendToVector(NewOps);
1336       continue;
1337     }
1338     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1339     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1340     // OldArg has been deleted from the Op list, so decrement all indices
1341     // greater than it.
1342     if (Arg > OldArg)
1343       --Arg;
1344     NewOps.push_back(Arg);
1345   }
1346   return DIExpression::get(Expr->getContext(), NewOps);
1347 }
1348 
1349 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1350                                            SmallVectorImpl<uint64_t> &Ops,
1351                                            bool StackValue,
1352                                            bool EntryValue) {
1353   assert(Expr && "Can't prepend ops to this expression");
1354 
1355   if (EntryValue) {
1356     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1357     // Use a block size of 1 for the target register operand.  The
1358     // DWARF backend currently cannot emit entry values with a block
1359     // size > 1.
1360     Ops.push_back(1);
1361   }
1362 
1363   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1364   if (Ops.empty())
1365     StackValue = false;
1366   for (auto Op : Expr->expr_ops()) {
1367     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1368     if (StackValue) {
1369       if (Op.getOp() == dwarf::DW_OP_stack_value)
1370         StackValue = false;
1371       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1372         Ops.push_back(dwarf::DW_OP_stack_value);
1373         StackValue = false;
1374       }
1375     }
1376     Op.appendToVector(Ops);
1377   }
1378   if (StackValue)
1379     Ops.push_back(dwarf::DW_OP_stack_value);
1380   return DIExpression::get(Expr->getContext(), Ops);
1381 }
1382 
1383 DIExpression *DIExpression::append(const DIExpression *Expr,
1384                                    ArrayRef<uint64_t> Ops) {
1385   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1386 
1387   // Copy Expr's current op list.
1388   SmallVector<uint64_t, 16> NewOps;
1389   for (auto Op : Expr->expr_ops()) {
1390     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1391     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1392         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1393       NewOps.append(Ops.begin(), Ops.end());
1394 
1395       // Ensure that the new opcodes are only appended once.
1396       Ops = None;
1397     }
1398     Op.appendToVector(NewOps);
1399   }
1400 
1401   NewOps.append(Ops.begin(), Ops.end());
1402   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1403   assert(result->isValid() && "concatenated expression is not valid");
1404   return result;
1405 }
1406 
1407 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1408                                           ArrayRef<uint64_t> Ops) {
1409   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1410   assert(none_of(Ops,
1411                  [](uint64_t Op) {
1412                    return Op == dwarf::DW_OP_stack_value ||
1413                           Op == dwarf::DW_OP_LLVM_fragment;
1414                  }) &&
1415          "Can't append this op");
1416 
1417   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1418   // has no DW_OP_stack_value.
1419   //
1420   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1421   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1422   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1423   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1424       Expr->getElements().drop_back(DropUntilStackValue);
1425   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1426                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1427   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1428 
1429   // Append a DW_OP_deref after Expr's current op list if needed, then append
1430   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1431   SmallVector<uint64_t, 16> NewOps;
1432   if (NeedsDeref)
1433     NewOps.push_back(dwarf::DW_OP_deref);
1434   NewOps.append(Ops.begin(), Ops.end());
1435   if (NeedsStackValue)
1436     NewOps.push_back(dwarf::DW_OP_stack_value);
1437   return DIExpression::append(Expr, NewOps);
1438 }
1439 
1440 Optional<DIExpression *> DIExpression::createFragmentExpression(
1441     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1442   SmallVector<uint64_t, 8> Ops;
1443   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1444   if (Expr) {
1445     for (auto Op : Expr->expr_ops()) {
1446       switch (Op.getOp()) {
1447       default: break;
1448       case dwarf::DW_OP_shr:
1449       case dwarf::DW_OP_shra:
1450       case dwarf::DW_OP_shl:
1451       case dwarf::DW_OP_plus:
1452       case dwarf::DW_OP_plus_uconst:
1453       case dwarf::DW_OP_minus:
1454         // We can't safely split arithmetic or shift operations into multiple
1455         // fragments because we can't express carry-over between fragments.
1456         //
1457         // FIXME: We *could* preserve the lowest fragment of a constant offset
1458         // operation if the offset fits into SizeInBits.
1459         return None;
1460       case dwarf::DW_OP_LLVM_fragment: {
1461         // Make the new offset point into the existing fragment.
1462         uint64_t FragmentOffsetInBits = Op.getArg(0);
1463         uint64_t FragmentSizeInBits = Op.getArg(1);
1464         (void)FragmentSizeInBits;
1465         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1466                "new fragment outside of original fragment");
1467         OffsetInBits += FragmentOffsetInBits;
1468         continue;
1469       }
1470       }
1471       Op.appendToVector(Ops);
1472     }
1473   }
1474   assert(Expr && "Unknown DIExpression");
1475   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1476   Ops.push_back(OffsetInBits);
1477   Ops.push_back(SizeInBits);
1478   return DIExpression::get(Expr->getContext(), Ops);
1479 }
1480 
1481 std::pair<DIExpression *, const ConstantInt *>
1482 DIExpression::constantFold(const ConstantInt *CI) {
1483   // Copy the APInt so we can modify it.
1484   APInt NewInt = CI->getValue();
1485   SmallVector<uint64_t, 8> Ops;
1486 
1487   // Fold operators only at the beginning of the expression.
1488   bool First = true;
1489   bool Changed = false;
1490   for (auto Op : expr_ops()) {
1491     switch (Op.getOp()) {
1492     default:
1493       // We fold only the leading part of the expression; if we get to a part
1494       // that we're going to copy unchanged, and haven't done any folding,
1495       // then the entire expression is unchanged and we can return early.
1496       if (!Changed)
1497         return {this, CI};
1498       First = false;
1499       break;
1500     case dwarf::DW_OP_LLVM_convert:
1501       if (!First)
1502         break;
1503       Changed = true;
1504       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1505         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1506       else {
1507         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1508         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1509       }
1510       continue;
1511     }
1512     Op.appendToVector(Ops);
1513   }
1514   if (!Changed)
1515     return {this, CI};
1516   return {DIExpression::get(getContext(), Ops),
1517           ConstantInt::get(getContext(), NewInt)};
1518 }
1519 
1520 uint64_t DIExpression::getNumLocationOperands() const {
1521   uint64_t Result = 0;
1522   for (auto ExprOp : expr_ops())
1523     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1524       Result = std::max(Result, ExprOp.getArg(0) + 1);
1525   assert(hasAllLocationOps(Result) &&
1526          "Expression is missing one or more location operands.");
1527   return Result;
1528 }
1529 
1530 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1531 DIExpression::isConstant() const {
1532 
1533   // Recognize signed and unsigned constants.
1534   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1535   // (DW_OP_LLVM_fragment of Len).
1536   // An unsigned constant can be represented as
1537   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1538 
1539   if ((getNumElements() != 2 && getNumElements() != 3 &&
1540        getNumElements() != 6) ||
1541       (getElement(0) != dwarf::DW_OP_consts &&
1542        getElement(0) != dwarf::DW_OP_constu))
1543     return None;
1544 
1545   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1546     return SignedOrUnsignedConstant::SignedConstant;
1547 
1548   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1549       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1550                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1551     return None;
1552   return getElement(0) == dwarf::DW_OP_constu
1553              ? SignedOrUnsignedConstant::UnsignedConstant
1554              : SignedOrUnsignedConstant::SignedConstant;
1555 }
1556 
1557 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1558                                              bool Signed) {
1559   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1560   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1561                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1562   return Ops;
1563 }
1564 
1565 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1566                                       unsigned FromSize, unsigned ToSize,
1567                                       bool Signed) {
1568   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1569 }
1570 
1571 DIGlobalVariableExpression *
1572 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1573                                     Metadata *Expression, StorageType Storage,
1574                                     bool ShouldCreate) {
1575   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1576   Metadata *Ops[] = {Variable, Expression};
1577   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1578 }
1579 
1580 DIObjCProperty *DIObjCProperty::getImpl(
1581     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1582     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1583     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1584   assert(isCanonical(Name) && "Expected canonical MDString");
1585   assert(isCanonical(GetterName) && "Expected canonical MDString");
1586   assert(isCanonical(SetterName) && "Expected canonical MDString");
1587   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1588                                          SetterName, Attributes, Type));
1589   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1590   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1591 }
1592 
1593 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1594                                             Metadata *Scope, Metadata *Entity,
1595                                             Metadata *File, unsigned Line,
1596                                             MDString *Name, StorageType Storage,
1597                                             bool ShouldCreate) {
1598   assert(isCanonical(Name) && "Expected canonical MDString");
1599   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1600                         (Tag, Scope, Entity, File, Line, Name));
1601   Metadata *Ops[] = {Scope, Entity, Name, File};
1602   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1603 }
1604 
1605 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType,
1606                           unsigned Line, MDString *Name, MDString *Value,
1607                           StorageType Storage, bool ShouldCreate) {
1608   assert(isCanonical(Name) && "Expected canonical MDString");
1609   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1610   Metadata *Ops[] = { Name, Value };
1611   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1612 }
1613 
1614 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1615                                   unsigned Line, Metadata *File,
1616                                   Metadata *Elements, StorageType Storage,
1617                                   bool ShouldCreate) {
1618   DEFINE_GETIMPL_LOOKUP(DIMacroFile,
1619                         (MIType, Line, File, Elements));
1620   Metadata *Ops[] = { File, Elements };
1621   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1622 }
1623 
1624 DIArgList *DIArgList::getImpl(LLVMContext &Context,
1625                               ArrayRef<ValueAsMetadata *> Args,
1626                               StorageType Storage, bool ShouldCreate) {
1627   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1628   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1629 }
1630 
1631 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1632   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1633   assert((!New || isa<ValueAsMetadata>(New)) &&
1634          "DIArgList must be passed a ValueAsMetadata");
1635   untrack();
1636   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1637   for (ValueAsMetadata *&VM : Args) {
1638     if (&VM == OldVMPtr) {
1639       if (NewVM)
1640         VM = NewVM;
1641       else
1642         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1643     }
1644   }
1645   track();
1646 }
1647 void DIArgList::track() {
1648   for (ValueAsMetadata *&VAM : Args)
1649     if (VAM)
1650       MetadataTracking::track(&VAM, *VAM, *this);
1651 }
1652 void DIArgList::untrack() {
1653   for (ValueAsMetadata *&VAM : Args)
1654     if (VAM)
1655       MetadataTracking::untrack(&VAM, *VAM);
1656 }
1657 void DIArgList::dropAllReferences() {
1658   untrack();
1659   Args.clear();
1660   MDNode::dropAllReferences();
1661 }
1662