xref: /freebsd/contrib/llvm-project/llvm/lib/IR/DebugInfoMetadata.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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/SmallPtrSet.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/IR/DebugProgramInstruction.h"
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/IntrinsicInst.h"
22 #include "llvm/IR/Type.h"
23 #include "llvm/IR/Value.h"
24 
25 #include <numeric>
26 #include <optional>
27 
28 using namespace llvm;
29 
30 namespace llvm {
31 // Use FS-AFDO discriminator.
32 cl::opt<bool> EnableFSDiscriminator(
33     "enable-fs-discriminator", cl::Hidden,
34     cl::desc("Enable adding flow sensitive discriminators"));
35 } // namespace llvm
36 
getAlignInBits() const37 uint32_t DIType::getAlignInBits() const {
38   return (getTag() == dwarf::DW_TAG_LLVM_ptrauth_type ? 0 : SubclassData32);
39 }
40 
41 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
42     std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
43 
DebugVariable(const DbgVariableIntrinsic * DII)44 DebugVariable::DebugVariable(const DbgVariableIntrinsic *DII)
45     : Variable(DII->getVariable()),
46       Fragment(DII->getExpression()->getFragmentInfo()),
47       InlinedAt(DII->getDebugLoc().getInlinedAt()) {}
48 
DebugVariable(const DbgVariableRecord * DVR)49 DebugVariable::DebugVariable(const DbgVariableRecord *DVR)
50     : Variable(DVR->getVariable()),
51       Fragment(DVR->getExpression()->getFragmentInfo()),
52       InlinedAt(DVR->getDebugLoc().getInlinedAt()) {}
53 
DebugVariableAggregate(const DbgVariableIntrinsic * DVI)54 DebugVariableAggregate::DebugVariableAggregate(const DbgVariableIntrinsic *DVI)
55     : DebugVariable(DVI->getVariable(), std::nullopt,
56                     DVI->getDebugLoc()->getInlinedAt()) {}
57 
DILocation(LLVMContext & C,StorageType Storage,unsigned Line,unsigned Column,ArrayRef<Metadata * > MDs,bool ImplicitCode)58 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
59                        unsigned Column, ArrayRef<Metadata *> MDs,
60                        bool ImplicitCode)
61     : MDNode(C, DILocationKind, Storage, MDs) {
62   assert((MDs.size() == 1 || MDs.size() == 2) &&
63          "Expected a scope and optional inlined-at");
64 
65   // Set line and column.
66   assert(Column < (1u << 16) && "Expected 16-bit column");
67 
68   SubclassData32 = Line;
69   SubclassData16 = Column;
70 
71   setImplicitCode(ImplicitCode);
72 }
73 
adjustColumn(unsigned & Column)74 static void adjustColumn(unsigned &Column) {
75   // Set to unknown on overflow.  We only have 16 bits to play with here.
76   if (Column >= (1u << 16))
77     Column = 0;
78 }
79 
getImpl(LLVMContext & Context,unsigned Line,unsigned Column,Metadata * Scope,Metadata * InlinedAt,bool ImplicitCode,StorageType Storage,bool ShouldCreate)80 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
81                                 unsigned Column, Metadata *Scope,
82                                 Metadata *InlinedAt, bool ImplicitCode,
83                                 StorageType Storage, bool ShouldCreate) {
84   // Fixup column.
85   adjustColumn(Column);
86 
87   if (Storage == Uniqued) {
88     if (auto *N = getUniqued(Context.pImpl->DILocations,
89                              DILocationInfo::KeyTy(Line, Column, Scope,
90                                                    InlinedAt, ImplicitCode)))
91       return N;
92     if (!ShouldCreate)
93       return nullptr;
94   } else {
95     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
96   }
97 
98   SmallVector<Metadata *, 2> Ops;
99   Ops.push_back(Scope);
100   if (InlinedAt)
101     Ops.push_back(InlinedAt);
102   return storeImpl(new (Ops.size(), Storage) DILocation(
103                        Context, Storage, Line, Column, Ops, ImplicitCode),
104                    Storage, Context.pImpl->DILocations);
105 }
106 
getMergedLocations(ArrayRef<DILocation * > Locs)107 DILocation *DILocation::getMergedLocations(ArrayRef<DILocation *> Locs) {
108   if (Locs.empty())
109     return nullptr;
110   if (Locs.size() == 1)
111     return Locs[0];
112   auto *Merged = Locs[0];
113   for (DILocation *L : llvm::drop_begin(Locs)) {
114     Merged = getMergedLocation(Merged, L);
115     if (Merged == nullptr)
116       break;
117   }
118   return Merged;
119 }
120 
getMergedLocation(DILocation * LocA,DILocation * LocB)121 DILocation *DILocation::getMergedLocation(DILocation *LocA, DILocation *LocB) {
122   if (!LocA || !LocB)
123     return nullptr;
124 
125   if (LocA == LocB)
126     return LocA;
127 
128   LLVMContext &C = LocA->getContext();
129 
130   using LocVec = SmallVector<const DILocation *>;
131   LocVec ALocs;
132   LocVec BLocs;
133   SmallDenseMap<std::pair<const DISubprogram *, const DILocation *>, unsigned,
134                 4>
135       ALookup;
136 
137   // Walk through LocA and its inlined-at locations, populate them in ALocs and
138   // save the index for the subprogram and inlined-at pair, which we use to find
139   // a matching starting location in LocB's chain.
140   for (auto [L, I] = std::make_pair(LocA, 0U); L; L = L->getInlinedAt(), I++) {
141     ALocs.push_back(L);
142     auto Res = ALookup.try_emplace(
143         {L->getScope()->getSubprogram(), L->getInlinedAt()}, I);
144     assert(Res.second && "Multiple <SP, InlinedAt> pairs in a location chain?");
145     (void)Res;
146   }
147 
148   LocVec::reverse_iterator ARIt = ALocs.rend();
149   LocVec::reverse_iterator BRIt = BLocs.rend();
150 
151   // Populate BLocs and look for a matching starting location, the first
152   // location with the same subprogram and inlined-at location as in LocA's
153   // chain. Since the two locations have the same inlined-at location we do
154   // not need to look at those parts of the chains.
155   for (auto [L, I] = std::make_pair(LocB, 0U); L; L = L->getInlinedAt(), I++) {
156     BLocs.push_back(L);
157 
158     if (ARIt != ALocs.rend())
159       // We have already found a matching starting location.
160       continue;
161 
162     auto IT = ALookup.find({L->getScope()->getSubprogram(), L->getInlinedAt()});
163     if (IT == ALookup.end())
164       continue;
165 
166     // The + 1 is to account for the &*rev_it = &(it - 1) relationship.
167     ARIt = LocVec::reverse_iterator(ALocs.begin() + IT->second + 1);
168     BRIt = LocVec::reverse_iterator(BLocs.begin() + I + 1);
169 
170     // If we have found a matching starting location we do not need to add more
171     // locations to BLocs, since we will only look at location pairs preceding
172     // the matching starting location, and adding more elements to BLocs could
173     // invalidate the iterator that we initialized here.
174     break;
175   }
176 
177   // Merge the two locations if possible, using the supplied
178   // inlined-at location for the created location.
179   auto MergeLocPair = [&C](const DILocation *L1, const DILocation *L2,
180                            DILocation *InlinedAt) -> DILocation * {
181     if (L1 == L2)
182       return DILocation::get(C, L1->getLine(), L1->getColumn(), L1->getScope(),
183                              InlinedAt);
184 
185     // If the locations originate from different subprograms we can't produce
186     // a common location.
187     if (L1->getScope()->getSubprogram() != L2->getScope()->getSubprogram())
188       return nullptr;
189 
190     // Return the nearest common scope inside a subprogram.
191     auto GetNearestCommonScope = [](DIScope *S1, DIScope *S2) -> DIScope * {
192       SmallPtrSet<DIScope *, 8> Scopes;
193       for (; S1; S1 = S1->getScope()) {
194         Scopes.insert(S1);
195         if (isa<DISubprogram>(S1))
196           break;
197       }
198 
199       for (; S2; S2 = S2->getScope()) {
200         if (Scopes.count(S2))
201           return S2;
202         if (isa<DISubprogram>(S2))
203           break;
204       }
205 
206       return nullptr;
207     };
208 
209     auto Scope = GetNearestCommonScope(L1->getScope(), L2->getScope());
210     assert(Scope && "No common scope in the same subprogram?");
211 
212     bool SameLine = L1->getLine() == L2->getLine();
213     bool SameCol = L1->getColumn() == L2->getColumn();
214     unsigned Line = SameLine ? L1->getLine() : 0;
215     unsigned Col = SameLine && SameCol ? L1->getColumn() : 0;
216 
217     return DILocation::get(C, Line, Col, Scope, InlinedAt);
218   };
219 
220   DILocation *Result = ARIt != ALocs.rend() ? (*ARIt)->getInlinedAt() : nullptr;
221 
222   // If we have found a common starting location, walk up the inlined-at chains
223   // and try to produce common locations.
224   for (; ARIt != ALocs.rend() && BRIt != BLocs.rend(); ++ARIt, ++BRIt) {
225     DILocation *Tmp = MergeLocPair(*ARIt, *BRIt, Result);
226 
227     if (!Tmp)
228       // We have walked up to a point in the chains where the two locations
229       // are irreconsilable. At this point Result contains the nearest common
230       // location in the inlined-at chains of LocA and LocB, so we break here.
231       break;
232 
233     Result = Tmp;
234   }
235 
236   if (Result)
237     return Result;
238 
239   // We ended up with LocA and LocB as irreconsilable locations. Produce a
240   // location at 0:0 with one of the locations' scope. The function has
241   // historically picked A's scope, and a nullptr inlined-at location, so that
242   // behavior is mimicked here but I am not sure if this is always the correct
243   // way to handle this.
244   return DILocation::get(C, 0, 0, LocA->getScope(), nullptr);
245 }
246 
247 std::optional<unsigned>
encodeDiscriminator(unsigned BD,unsigned DF,unsigned CI)248 DILocation::encodeDiscriminator(unsigned BD, unsigned DF, unsigned CI) {
249   std::array<unsigned, 3> Components = {BD, DF, CI};
250   uint64_t RemainingWork = 0U;
251   // We use RemainingWork to figure out if we have no remaining components to
252   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
253   // encode anything for the latter 2.
254   // Since any of the input components is at most 32 bits, their sum will be
255   // less than 34 bits, and thus RemainingWork won't overflow.
256   RemainingWork =
257       std::accumulate(Components.begin(), Components.end(), RemainingWork);
258 
259   int I = 0;
260   unsigned Ret = 0;
261   unsigned NextBitInsertionIndex = 0;
262   while (RemainingWork > 0) {
263     unsigned C = Components[I++];
264     RemainingWork -= C;
265     unsigned EC = encodeComponent(C);
266     Ret |= (EC << NextBitInsertionIndex);
267     NextBitInsertionIndex += encodingBits(C);
268   }
269 
270   // Encoding may be unsuccessful because of overflow. We determine success by
271   // checking equivalence of components before & after encoding. Alternatively,
272   // we could determine Success during encoding, but the current alternative is
273   // simpler.
274   unsigned TBD, TDF, TCI = 0;
275   decodeDiscriminator(Ret, TBD, TDF, TCI);
276   if (TBD == BD && TDF == DF && TCI == CI)
277     return Ret;
278   return std::nullopt;
279 }
280 
decodeDiscriminator(unsigned D,unsigned & BD,unsigned & DF,unsigned & CI)281 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
282                                      unsigned &CI) {
283   BD = getUnsignedFromPrefixEncoding(D);
284   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
285   CI = getUnsignedFromPrefixEncoding(
286       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
287 }
getTag() const288 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; }
289 
getFlag(StringRef Flag)290 DINode::DIFlags DINode::getFlag(StringRef Flag) {
291   return StringSwitch<DIFlags>(Flag)
292 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
293 #include "llvm/IR/DebugInfoFlags.def"
294       .Default(DINode::FlagZero);
295 }
296 
getFlagString(DIFlags Flag)297 StringRef DINode::getFlagString(DIFlags Flag) {
298   switch (Flag) {
299 #define HANDLE_DI_FLAG(ID, NAME)                                               \
300   case Flag##NAME:                                                             \
301     return "DIFlag" #NAME;
302 #include "llvm/IR/DebugInfoFlags.def"
303   }
304   return "";
305 }
306 
splitFlags(DIFlags Flags,SmallVectorImpl<DIFlags> & SplitFlags)307 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
308                                    SmallVectorImpl<DIFlags> &SplitFlags) {
309   // Flags that are packed together need to be specially handled, so
310   // that, for example, we emit "DIFlagPublic" and not
311   // "DIFlagPrivate | DIFlagProtected".
312   if (DIFlags A = Flags & FlagAccessibility) {
313     if (A == FlagPrivate)
314       SplitFlags.push_back(FlagPrivate);
315     else if (A == FlagProtected)
316       SplitFlags.push_back(FlagProtected);
317     else
318       SplitFlags.push_back(FlagPublic);
319     Flags &= ~A;
320   }
321   if (DIFlags R = Flags & FlagPtrToMemberRep) {
322     if (R == FlagSingleInheritance)
323       SplitFlags.push_back(FlagSingleInheritance);
324     else if (R == FlagMultipleInheritance)
325       SplitFlags.push_back(FlagMultipleInheritance);
326     else
327       SplitFlags.push_back(FlagVirtualInheritance);
328     Flags &= ~R;
329   }
330   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
331     Flags &= ~FlagIndirectVirtualBase;
332     SplitFlags.push_back(FlagIndirectVirtualBase);
333   }
334 
335 #define HANDLE_DI_FLAG(ID, NAME)                                               \
336   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
337     SplitFlags.push_back(Bit);                                                 \
338     Flags &= ~Bit;                                                             \
339   }
340 #include "llvm/IR/DebugInfoFlags.def"
341   return Flags;
342 }
343 
getScope() const344 DIScope *DIScope::getScope() const {
345   if (auto *T = dyn_cast<DIType>(this))
346     return T->getScope();
347 
348   if (auto *SP = dyn_cast<DISubprogram>(this))
349     return SP->getScope();
350 
351   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
352     return LB->getScope();
353 
354   if (auto *NS = dyn_cast<DINamespace>(this))
355     return NS->getScope();
356 
357   if (auto *CB = dyn_cast<DICommonBlock>(this))
358     return CB->getScope();
359 
360   if (auto *M = dyn_cast<DIModule>(this))
361     return M->getScope();
362 
363   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
364          "Unhandled type of scope.");
365   return nullptr;
366 }
367 
getName() const368 StringRef DIScope::getName() const {
369   if (auto *T = dyn_cast<DIType>(this))
370     return T->getName();
371   if (auto *SP = dyn_cast<DISubprogram>(this))
372     return SP->getName();
373   if (auto *NS = dyn_cast<DINamespace>(this))
374     return NS->getName();
375   if (auto *CB = dyn_cast<DICommonBlock>(this))
376     return CB->getName();
377   if (auto *M = dyn_cast<DIModule>(this))
378     return M->getName();
379   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
380           isa<DICompileUnit>(this)) &&
381          "Unhandled type of scope.");
382   return "";
383 }
384 
385 #ifndef NDEBUG
isCanonical(const MDString * S)386 static bool isCanonical(const MDString *S) {
387   return !S || !S->getString().empty();
388 }
389 #endif
390 
getTag() const391 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; }
getImpl(LLVMContext & Context,unsigned Tag,MDString * Header,ArrayRef<Metadata * > DwarfOps,StorageType Storage,bool ShouldCreate)392 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
393                                       MDString *Header,
394                                       ArrayRef<Metadata *> DwarfOps,
395                                       StorageType Storage, bool ShouldCreate) {
396   unsigned Hash = 0;
397   if (Storage == Uniqued) {
398     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
399     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
400       return N;
401     if (!ShouldCreate)
402       return nullptr;
403     Hash = Key.getHash();
404   } else {
405     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
406   }
407 
408   // Use a nullptr for empty headers.
409   assert(isCanonical(Header) && "Expected canonical MDString");
410   Metadata *PreOps[] = {Header};
411   return storeImpl(new (DwarfOps.size() + 1, Storage) GenericDINode(
412                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
413                    Storage, Context.pImpl->GenericDINodes);
414 }
415 
recalculateHash()416 void GenericDINode::recalculateHash() {
417   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
418 }
419 
420 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
421 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
422 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
423   do {                                                                         \
424     if (Storage == Uniqued) {                                                  \
425       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
426                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
427         return N;                                                              \
428       if (!ShouldCreate)                                                       \
429         return nullptr;                                                        \
430     } else {                                                                   \
431       assert(ShouldCreate &&                                                   \
432              "Expected non-uniqued nodes to always be created");               \
433     }                                                                          \
434   } while (false)
435 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
436   return storeImpl(new (std::size(OPS), Storage)                               \
437                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
438                    Storage, Context.pImpl->CLASS##s)
439 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
440   return storeImpl(new (0u, Storage)                                           \
441                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),             \
442                    Storage, Context.pImpl->CLASS##s)
443 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
444   return storeImpl(new (std::size(OPS), Storage) CLASS(Context, Storage, OPS), \
445                    Storage, Context.pImpl->CLASS##s)
446 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
447   return storeImpl(new (NUM_OPS, Storage)                                      \
448                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
449                    Storage, Context.pImpl->CLASS##s)
450 
DISubrange(LLVMContext & C,StorageType Storage,ArrayRef<Metadata * > Ops)451 DISubrange::DISubrange(LLVMContext &C, StorageType Storage,
452                        ArrayRef<Metadata *> Ops)
453     : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
getImpl(LLVMContext & Context,int64_t Count,int64_t Lo,StorageType Storage,bool ShouldCreate)454 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
455                                 StorageType Storage, bool ShouldCreate) {
456   auto *CountNode = ConstantAsMetadata::get(
457       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
458   auto *LB = ConstantAsMetadata::get(
459       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
460   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
461                  ShouldCreate);
462 }
463 
getImpl(LLVMContext & Context,Metadata * CountNode,int64_t Lo,StorageType Storage,bool ShouldCreate)464 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
465                                 int64_t Lo, StorageType Storage,
466                                 bool ShouldCreate) {
467   auto *LB = ConstantAsMetadata::get(
468       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
469   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
470                  ShouldCreate);
471 }
472 
getImpl(LLVMContext & Context,Metadata * CountNode,Metadata * LB,Metadata * UB,Metadata * Stride,StorageType Storage,bool ShouldCreate)473 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
474                                 Metadata *LB, Metadata *UB, Metadata *Stride,
475                                 StorageType Storage, bool ShouldCreate) {
476   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
477   Metadata *Ops[] = {CountNode, LB, UB, Stride};
478   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
479 }
480 
getCount() const481 DISubrange::BoundType DISubrange::getCount() const {
482   Metadata *CB = getRawCountNode();
483   if (!CB)
484     return BoundType();
485 
486   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
487           isa<DIExpression>(CB)) &&
488          "Count must be signed constant or DIVariable or DIExpression");
489 
490   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
491     return BoundType(cast<ConstantInt>(MD->getValue()));
492 
493   if (auto *MD = dyn_cast<DIVariable>(CB))
494     return BoundType(MD);
495 
496   if (auto *MD = dyn_cast<DIExpression>(CB))
497     return BoundType(MD);
498 
499   return BoundType();
500 }
501 
getLowerBound() const502 DISubrange::BoundType DISubrange::getLowerBound() const {
503   Metadata *LB = getRawLowerBound();
504   if (!LB)
505     return BoundType();
506 
507   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
508           isa<DIExpression>(LB)) &&
509          "LowerBound must be signed constant or DIVariable or DIExpression");
510 
511   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
512     return BoundType(cast<ConstantInt>(MD->getValue()));
513 
514   if (auto *MD = dyn_cast<DIVariable>(LB))
515     return BoundType(MD);
516 
517   if (auto *MD = dyn_cast<DIExpression>(LB))
518     return BoundType(MD);
519 
520   return BoundType();
521 }
522 
getUpperBound() const523 DISubrange::BoundType DISubrange::getUpperBound() const {
524   Metadata *UB = getRawUpperBound();
525   if (!UB)
526     return BoundType();
527 
528   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
529           isa<DIExpression>(UB)) &&
530          "UpperBound must be signed constant or DIVariable or DIExpression");
531 
532   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
533     return BoundType(cast<ConstantInt>(MD->getValue()));
534 
535   if (auto *MD = dyn_cast<DIVariable>(UB))
536     return BoundType(MD);
537 
538   if (auto *MD = dyn_cast<DIExpression>(UB))
539     return BoundType(MD);
540 
541   return BoundType();
542 }
543 
getStride() const544 DISubrange::BoundType DISubrange::getStride() const {
545   Metadata *ST = getRawStride();
546   if (!ST)
547     return BoundType();
548 
549   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
550           isa<DIExpression>(ST)) &&
551          "Stride must be signed constant or DIVariable or DIExpression");
552 
553   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
554     return BoundType(cast<ConstantInt>(MD->getValue()));
555 
556   if (auto *MD = dyn_cast<DIVariable>(ST))
557     return BoundType(MD);
558 
559   if (auto *MD = dyn_cast<DIExpression>(ST))
560     return BoundType(MD);
561 
562   return BoundType();
563 }
DIGenericSubrange(LLVMContext & C,StorageType Storage,ArrayRef<Metadata * > Ops)564 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage,
565                                      ArrayRef<Metadata *> Ops)
566     : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange,
567              Ops) {}
568 
getImpl(LLVMContext & Context,Metadata * CountNode,Metadata * LB,Metadata * UB,Metadata * Stride,StorageType Storage,bool ShouldCreate)569 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
570                                               Metadata *CountNode, Metadata *LB,
571                                               Metadata *UB, Metadata *Stride,
572                                               StorageType Storage,
573                                               bool ShouldCreate) {
574   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
575   Metadata *Ops[] = {CountNode, LB, UB, Stride};
576   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
577 }
578 
getCount() const579 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
580   Metadata *CB = getRawCountNode();
581   if (!CB)
582     return BoundType();
583 
584   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
585          "Count must be signed constant or DIVariable or DIExpression");
586 
587   if (auto *MD = dyn_cast<DIVariable>(CB))
588     return BoundType(MD);
589 
590   if (auto *MD = dyn_cast<DIExpression>(CB))
591     return BoundType(MD);
592 
593   return BoundType();
594 }
595 
getLowerBound() const596 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
597   Metadata *LB = getRawLowerBound();
598   if (!LB)
599     return BoundType();
600 
601   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
602          "LowerBound must be signed constant or DIVariable or DIExpression");
603 
604   if (auto *MD = dyn_cast<DIVariable>(LB))
605     return BoundType(MD);
606 
607   if (auto *MD = dyn_cast<DIExpression>(LB))
608     return BoundType(MD);
609 
610   return BoundType();
611 }
612 
getUpperBound() const613 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
614   Metadata *UB = getRawUpperBound();
615   if (!UB)
616     return BoundType();
617 
618   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
619          "UpperBound must be signed constant or DIVariable or DIExpression");
620 
621   if (auto *MD = dyn_cast<DIVariable>(UB))
622     return BoundType(MD);
623 
624   if (auto *MD = dyn_cast<DIExpression>(UB))
625     return BoundType(MD);
626 
627   return BoundType();
628 }
629 
getStride() const630 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
631   Metadata *ST = getRawStride();
632   if (!ST)
633     return BoundType();
634 
635   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
636          "Stride must be signed constant or DIVariable or DIExpression");
637 
638   if (auto *MD = dyn_cast<DIVariable>(ST))
639     return BoundType(MD);
640 
641   if (auto *MD = dyn_cast<DIExpression>(ST))
642     return BoundType(MD);
643 
644   return BoundType();
645 }
646 
DIEnumerator(LLVMContext & C,StorageType Storage,const APInt & Value,bool IsUnsigned,ArrayRef<Metadata * > Ops)647 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage,
648                            const APInt &Value, bool IsUnsigned,
649                            ArrayRef<Metadata *> Ops)
650     : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
651       Value(Value) {
652   SubclassData32 = IsUnsigned;
653 }
getImpl(LLVMContext & Context,const APInt & Value,bool IsUnsigned,MDString * Name,StorageType Storage,bool ShouldCreate)654 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
655                                     bool IsUnsigned, MDString *Name,
656                                     StorageType Storage, bool ShouldCreate) {
657   assert(isCanonical(Name) && "Expected canonical MDString");
658   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
659   Metadata *Ops[] = {Name};
660   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
661 }
662 
getImpl(LLVMContext & Context,unsigned Tag,MDString * Name,uint64_t SizeInBits,uint32_t AlignInBits,unsigned Encoding,DIFlags Flags,StorageType Storage,bool ShouldCreate)663 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
664                                   MDString *Name, uint64_t SizeInBits,
665                                   uint32_t AlignInBits, unsigned Encoding,
666                                   DIFlags Flags, StorageType Storage,
667                                   bool ShouldCreate) {
668   assert(isCanonical(Name) && "Expected canonical MDString");
669   DEFINE_GETIMPL_LOOKUP(DIBasicType,
670                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
671   Metadata *Ops[] = {nullptr, nullptr, Name};
672   DEFINE_GETIMPL_STORE(DIBasicType,
673                        (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops);
674 }
675 
getSignedness() const676 std::optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
677   switch (getEncoding()) {
678   case dwarf::DW_ATE_signed:
679   case dwarf::DW_ATE_signed_char:
680     return Signedness::Signed;
681   case dwarf::DW_ATE_unsigned:
682   case dwarf::DW_ATE_unsigned_char:
683     return Signedness::Unsigned;
684   default:
685     return std::nullopt;
686   }
687 }
688 
getImpl(LLVMContext & Context,unsigned Tag,MDString * Name,Metadata * StringLength,Metadata * StringLengthExp,Metadata * StringLocationExp,uint64_t SizeInBits,uint32_t AlignInBits,unsigned Encoding,StorageType Storage,bool ShouldCreate)689 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
690                                     MDString *Name, Metadata *StringLength,
691                                     Metadata *StringLengthExp,
692                                     Metadata *StringLocationExp,
693                                     uint64_t SizeInBits, uint32_t AlignInBits,
694                                     unsigned Encoding, StorageType Storage,
695                                     bool ShouldCreate) {
696   assert(isCanonical(Name) && "Expected canonical MDString");
697   DEFINE_GETIMPL_LOOKUP(DIStringType,
698                         (Tag, Name, StringLength, StringLengthExp,
699                          StringLocationExp, SizeInBits, AlignInBits, Encoding));
700   Metadata *Ops[] = {nullptr,      nullptr,         Name,
701                      StringLength, StringLengthExp, StringLocationExp};
702   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
703                        Ops);
704 }
getClassType() const705 DIType *DIDerivedType::getClassType() const {
706   assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
707   return cast_or_null<DIType>(getExtraData());
708 }
getVBPtrOffset() const709 uint32_t DIDerivedType::getVBPtrOffset() const {
710   assert(getTag() == dwarf::DW_TAG_inheritance);
711   if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
712     if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
713       return static_cast<uint32_t>(CI->getZExtValue());
714   return 0;
715 }
getStorageOffsetInBits() const716 Constant *DIDerivedType::getStorageOffsetInBits() const {
717   assert(getTag() == dwarf::DW_TAG_member && isBitField());
718   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
719     return C->getValue();
720   return nullptr;
721 }
722 
getConstant() const723 Constant *DIDerivedType::getConstant() const {
724   assert((getTag() == dwarf::DW_TAG_member ||
725           getTag() == dwarf::DW_TAG_variable) &&
726          isStaticMember());
727   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
728     return C->getValue();
729   return nullptr;
730 }
getDiscriminantValue() const731 Constant *DIDerivedType::getDiscriminantValue() const {
732   assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
733   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
734     return C->getValue();
735   return nullptr;
736 }
737 
getImpl(LLVMContext & Context,unsigned Tag,MDString * Name,Metadata * File,unsigned Line,Metadata * Scope,Metadata * BaseType,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,std::optional<unsigned> DWARFAddressSpace,std::optional<PtrAuthData> PtrAuthData,DIFlags Flags,Metadata * ExtraData,Metadata * Annotations,StorageType Storage,bool ShouldCreate)738 DIDerivedType *DIDerivedType::getImpl(
739     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
740     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
741     uint32_t AlignInBits, uint64_t OffsetInBits,
742     std::optional<unsigned> DWARFAddressSpace,
743     std::optional<PtrAuthData> PtrAuthData, DIFlags Flags, Metadata *ExtraData,
744     Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
745   assert(isCanonical(Name) && "Expected canonical MDString");
746   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
747                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
748                          AlignInBits, OffsetInBits, DWARFAddressSpace,
749                          PtrAuthData, Flags, ExtraData, Annotations));
750   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
751   DEFINE_GETIMPL_STORE(DIDerivedType,
752                        (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
753                         DWARFAddressSpace, PtrAuthData, Flags),
754                        Ops);
755 }
756 
757 std::optional<DIDerivedType::PtrAuthData>
getPtrAuthData() const758 DIDerivedType::getPtrAuthData() const {
759   return getTag() == dwarf::DW_TAG_LLVM_ptrauth_type
760              ? std::optional<PtrAuthData>(PtrAuthData(SubclassData32))
761              : std::nullopt;
762 }
763 
getImpl(LLVMContext & Context,unsigned Tag,MDString * Name,Metadata * File,unsigned Line,Metadata * Scope,Metadata * BaseType,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags,Metadata * Elements,unsigned RuntimeLang,Metadata * VTableHolder,Metadata * TemplateParams,MDString * Identifier,Metadata * Discriminator,Metadata * DataLocation,Metadata * Associated,Metadata * Allocated,Metadata * Rank,Metadata * Annotations,StorageType Storage,bool ShouldCreate)764 DICompositeType *DICompositeType::getImpl(
765     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
766     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
767     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
768     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
769     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
770     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
771     Metadata *Rank, Metadata *Annotations, StorageType Storage,
772     bool ShouldCreate) {
773   assert(isCanonical(Name) && "Expected canonical MDString");
774 
775   // Keep this in sync with buildODRType.
776   DEFINE_GETIMPL_LOOKUP(DICompositeType,
777                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
778                          AlignInBits, OffsetInBits, Flags, Elements,
779                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
780                          Discriminator, DataLocation, Associated, Allocated,
781                          Rank, Annotations));
782   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
783                      Elements,      VTableHolder, TemplateParams, Identifier,
784                      Discriminator, DataLocation, Associated,     Allocated,
785                      Rank,          Annotations};
786   DEFINE_GETIMPL_STORE(
787       DICompositeType,
788       (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags),
789       Ops);
790 }
791 
buildODRType(LLVMContext & Context,MDString & Identifier,unsigned Tag,MDString * Name,Metadata * File,unsigned Line,Metadata * Scope,Metadata * BaseType,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags,Metadata * Elements,unsigned RuntimeLang,Metadata * VTableHolder,Metadata * TemplateParams,Metadata * Discriminator,Metadata * DataLocation,Metadata * Associated,Metadata * Allocated,Metadata * Rank,Metadata * Annotations)792 DICompositeType *DICompositeType::buildODRType(
793     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
794     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
795     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
796     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
797     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
798     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
799     Metadata *Rank, Metadata *Annotations) {
800   assert(!Identifier.getString().empty() && "Expected valid identifier");
801   if (!Context.isODRUniquingDebugTypes())
802     return nullptr;
803   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
804   if (!CT)
805     return CT = DICompositeType::getDistinct(
806                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
807                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
808                VTableHolder, TemplateParams, &Identifier, Discriminator,
809                DataLocation, Associated, Allocated, Rank, Annotations);
810 
811   if (CT->getTag() != Tag)
812     return nullptr;
813 
814   // Only mutate CT if it's a forward declaration and the new operands aren't.
815   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
816   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
817     return CT;
818 
819   // Mutate CT in place.  Keep this in sync with getImpl.
820   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
821              Flags);
822   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
823                      Elements,      VTableHolder, TemplateParams, &Identifier,
824                      Discriminator, DataLocation, Associated,     Allocated,
825                      Rank,          Annotations};
826   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
827          "Mismatched number of operands");
828   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
829     if (Ops[I] != CT->getOperand(I))
830       CT->setOperand(I, Ops[I]);
831   return CT;
832 }
833 
getODRType(LLVMContext & Context,MDString & Identifier,unsigned Tag,MDString * Name,Metadata * File,unsigned Line,Metadata * Scope,Metadata * BaseType,uint64_t SizeInBits,uint32_t AlignInBits,uint64_t OffsetInBits,DIFlags Flags,Metadata * Elements,unsigned RuntimeLang,Metadata * VTableHolder,Metadata * TemplateParams,Metadata * Discriminator,Metadata * DataLocation,Metadata * Associated,Metadata * Allocated,Metadata * Rank,Metadata * Annotations)834 DICompositeType *DICompositeType::getODRType(
835     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
836     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
837     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
838     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
839     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
840     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
841     Metadata *Rank, Metadata *Annotations) {
842   assert(!Identifier.getString().empty() && "Expected valid identifier");
843   if (!Context.isODRUniquingDebugTypes())
844     return nullptr;
845   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
846   if (!CT) {
847     CT = DICompositeType::getDistinct(
848         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
849         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
850         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
851         Allocated, Rank, Annotations);
852   } else {
853     if (CT->getTag() != Tag)
854       return nullptr;
855   }
856   return CT;
857 }
858 
getODRTypeIfExists(LLVMContext & Context,MDString & Identifier)859 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
860                                                      MDString &Identifier) {
861   assert(!Identifier.getString().empty() && "Expected valid identifier");
862   if (!Context.isODRUniquingDebugTypes())
863     return nullptr;
864   return Context.pImpl->DITypeMap->lookup(&Identifier);
865 }
DISubroutineType(LLVMContext & C,StorageType Storage,DIFlags Flags,uint8_t CC,ArrayRef<Metadata * > Ops)866 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage,
867                                    DIFlags Flags, uint8_t CC,
868                                    ArrayRef<Metadata *> Ops)
869     : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0,
870              0, 0, 0, Flags, Ops),
871       CC(CC) {}
872 
getImpl(LLVMContext & Context,DIFlags Flags,uint8_t CC,Metadata * TypeArray,StorageType Storage,bool ShouldCreate)873 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
874                                             uint8_t CC, Metadata *TypeArray,
875                                             StorageType Storage,
876                                             bool ShouldCreate) {
877   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
878   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
879   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
880 }
881 
DIFile(LLVMContext & C,StorageType Storage,std::optional<ChecksumInfo<MDString * >> CS,MDString * Src,ArrayRef<Metadata * > Ops)882 DIFile::DIFile(LLVMContext &C, StorageType Storage,
883                std::optional<ChecksumInfo<MDString *>> CS, MDString *Src,
884                ArrayRef<Metadata *> Ops)
885     : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
886       Checksum(CS), Source(Src) {}
887 
888 // FIXME: Implement this string-enum correspondence with a .def file and macros,
889 // so that the association is explicit rather than implied.
890 static const char *ChecksumKindName[DIFile::CSK_Last] = {
891     "CSK_MD5",
892     "CSK_SHA1",
893     "CSK_SHA256",
894 };
895 
getChecksumKindAsString(ChecksumKind CSKind)896 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
897   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
898   // The first space was originally the CSK_None variant, which is now
899   // obsolete, but the space is still reserved in ChecksumKind, so we account
900   // for it here.
901   return ChecksumKindName[CSKind - 1];
902 }
903 
904 std::optional<DIFile::ChecksumKind>
getChecksumKind(StringRef CSKindStr)905 DIFile::getChecksumKind(StringRef CSKindStr) {
906   return StringSwitch<std::optional<DIFile::ChecksumKind>>(CSKindStr)
907       .Case("CSK_MD5", DIFile::CSK_MD5)
908       .Case("CSK_SHA1", DIFile::CSK_SHA1)
909       .Case("CSK_SHA256", DIFile::CSK_SHA256)
910       .Default(std::nullopt);
911 }
912 
getImpl(LLVMContext & Context,MDString * Filename,MDString * Directory,std::optional<DIFile::ChecksumInfo<MDString * >> CS,MDString * Source,StorageType Storage,bool ShouldCreate)913 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
914                         MDString *Directory,
915                         std::optional<DIFile::ChecksumInfo<MDString *>> CS,
916                         MDString *Source, StorageType Storage,
917                         bool ShouldCreate) {
918   assert(isCanonical(Filename) && "Expected canonical MDString");
919   assert(isCanonical(Directory) && "Expected canonical MDString");
920   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
921   // We do *NOT* expect Source to be a canonical MDString because nullptr
922   // means none, so we need something to represent the empty file.
923   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
924   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr, Source};
925   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
926 }
DICompileUnit(LLVMContext & C,StorageType Storage,unsigned SourceLanguage,bool IsOptimized,unsigned RuntimeVersion,unsigned EmissionKind,uint64_t DWOId,bool SplitDebugInlining,bool DebugInfoForProfiling,unsigned NameTableKind,bool RangesBaseAddress,ArrayRef<Metadata * > Ops)927 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage,
928                              unsigned SourceLanguage, bool IsOptimized,
929                              unsigned RuntimeVersion, unsigned EmissionKind,
930                              uint64_t DWOId, bool SplitDebugInlining,
931                              bool DebugInfoForProfiling, unsigned NameTableKind,
932                              bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
933     : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
934       SourceLanguage(SourceLanguage), RuntimeVersion(RuntimeVersion),
935       DWOId(DWOId), EmissionKind(EmissionKind), NameTableKind(NameTableKind),
936       IsOptimized(IsOptimized), SplitDebugInlining(SplitDebugInlining),
937       DebugInfoForProfiling(DebugInfoForProfiling),
938       RangesBaseAddress(RangesBaseAddress) {
939   assert(Storage != Uniqued);
940 }
941 
getImpl(LLVMContext & Context,unsigned SourceLanguage,Metadata * File,MDString * Producer,bool IsOptimized,MDString * Flags,unsigned RuntimeVersion,MDString * SplitDebugFilename,unsigned EmissionKind,Metadata * EnumTypes,Metadata * RetainedTypes,Metadata * GlobalVariables,Metadata * ImportedEntities,Metadata * Macros,uint64_t DWOId,bool SplitDebugInlining,bool DebugInfoForProfiling,unsigned NameTableKind,bool RangesBaseAddress,MDString * SysRoot,MDString * SDK,StorageType Storage,bool ShouldCreate)942 DICompileUnit *DICompileUnit::getImpl(
943     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
944     MDString *Producer, bool IsOptimized, MDString *Flags,
945     unsigned RuntimeVersion, MDString *SplitDebugFilename,
946     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
947     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
948     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
949     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
950     MDString *SDK, StorageType Storage, bool ShouldCreate) {
951   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
952   assert(isCanonical(Producer) && "Expected canonical MDString");
953   assert(isCanonical(Flags) && "Expected canonical MDString");
954   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
955 
956   Metadata *Ops[] = {File,
957                      Producer,
958                      Flags,
959                      SplitDebugFilename,
960                      EnumTypes,
961                      RetainedTypes,
962                      GlobalVariables,
963                      ImportedEntities,
964                      Macros,
965                      SysRoot,
966                      SDK};
967   return storeImpl(new (std::size(Ops), Storage) DICompileUnit(
968                        Context, Storage, SourceLanguage, IsOptimized,
969                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
970                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
971                        Ops),
972                    Storage);
973 }
974 
975 std::optional<DICompileUnit::DebugEmissionKind>
getEmissionKind(StringRef Str)976 DICompileUnit::getEmissionKind(StringRef Str) {
977   return StringSwitch<std::optional<DebugEmissionKind>>(Str)
978       .Case("NoDebug", NoDebug)
979       .Case("FullDebug", FullDebug)
980       .Case("LineTablesOnly", LineTablesOnly)
981       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
982       .Default(std::nullopt);
983 }
984 
985 std::optional<DICompileUnit::DebugNameTableKind>
getNameTableKind(StringRef Str)986 DICompileUnit::getNameTableKind(StringRef Str) {
987   return StringSwitch<std::optional<DebugNameTableKind>>(Str)
988       .Case("Default", DebugNameTableKind::Default)
989       .Case("GNU", DebugNameTableKind::GNU)
990       .Case("Apple", DebugNameTableKind::Apple)
991       .Case("None", DebugNameTableKind::None)
992       .Default(std::nullopt);
993 }
994 
emissionKindString(DebugEmissionKind EK)995 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
996   switch (EK) {
997   case NoDebug:
998     return "NoDebug";
999   case FullDebug:
1000     return "FullDebug";
1001   case LineTablesOnly:
1002     return "LineTablesOnly";
1003   case DebugDirectivesOnly:
1004     return "DebugDirectivesOnly";
1005   }
1006   return nullptr;
1007 }
1008 
nameTableKindString(DebugNameTableKind NTK)1009 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
1010   switch (NTK) {
1011   case DebugNameTableKind::Default:
1012     return nullptr;
1013   case DebugNameTableKind::GNU:
1014     return "GNU";
1015   case DebugNameTableKind::Apple:
1016     return "Apple";
1017   case DebugNameTableKind::None:
1018     return "None";
1019   }
1020   return nullptr;
1021 }
DISubprogram(LLVMContext & C,StorageType Storage,unsigned Line,unsigned ScopeLine,unsigned VirtualIndex,int ThisAdjustment,DIFlags Flags,DISPFlags SPFlags,ArrayRef<Metadata * > Ops)1022 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
1023                            unsigned ScopeLine, unsigned VirtualIndex,
1024                            int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags,
1025                            ArrayRef<Metadata *> Ops)
1026     : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops),
1027       Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
1028       ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
1029   static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
1030 }
1031 DISubprogram::DISPFlags
toSPFlags(bool IsLocalToUnit,bool IsDefinition,bool IsOptimized,unsigned Virtuality,bool IsMainSubprogram)1032 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized,
1033                         unsigned Virtuality, bool IsMainSubprogram) {
1034   // We're assuming virtuality is the low-order field.
1035   static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
1036                     int(SPFlagPureVirtual) ==
1037                         int(dwarf::DW_VIRTUALITY_pure_virtual),
1038                 "Virtuality constant mismatch");
1039   return static_cast<DISPFlags>(
1040       (Virtuality & SPFlagVirtuality) |
1041       (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
1042       (IsDefinition ? SPFlagDefinition : SPFlagZero) |
1043       (IsOptimized ? SPFlagOptimized : SPFlagZero) |
1044       (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
1045 }
1046 
getSubprogram() const1047 DISubprogram *DILocalScope::getSubprogram() const {
1048   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
1049     return Block->getScope()->getSubprogram();
1050   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
1051 }
1052 
getNonLexicalBlockFileScope() const1053 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
1054   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
1055     return File->getScope()->getNonLexicalBlockFileScope();
1056   return const_cast<DILocalScope *>(this);
1057 }
1058 
cloneScopeForSubprogram(DILocalScope & RootScope,DISubprogram & NewSP,LLVMContext & Ctx,DenseMap<const MDNode *,MDNode * > & Cache)1059 DILocalScope *DILocalScope::cloneScopeForSubprogram(
1060     DILocalScope &RootScope, DISubprogram &NewSP, LLVMContext &Ctx,
1061     DenseMap<const MDNode *, MDNode *> &Cache) {
1062   SmallVector<DIScope *> ScopeChain;
1063   DIScope *CachedResult = nullptr;
1064 
1065   for (DIScope *Scope = &RootScope; !isa<DISubprogram>(Scope);
1066        Scope = Scope->getScope()) {
1067     if (auto It = Cache.find(Scope); It != Cache.end()) {
1068       CachedResult = cast<DIScope>(It->second);
1069       break;
1070     }
1071     ScopeChain.push_back(Scope);
1072   }
1073 
1074   // Recreate the scope chain, bottom-up, starting at the new subprogram (or a
1075   // cached result).
1076   DIScope *UpdatedScope = CachedResult ? CachedResult : &NewSP;
1077   for (DIScope *ScopeToUpdate : reverse(ScopeChain)) {
1078     TempMDNode ClonedScope = ScopeToUpdate->clone();
1079     cast<DILexicalBlockBase>(*ClonedScope).replaceScope(UpdatedScope);
1080     UpdatedScope =
1081         cast<DIScope>(MDNode::replaceWithUniqued(std::move(ClonedScope)));
1082     Cache[ScopeToUpdate] = UpdatedScope;
1083   }
1084 
1085   return cast<DILocalScope>(UpdatedScope);
1086 }
1087 
getFlag(StringRef Flag)1088 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
1089   return StringSwitch<DISPFlags>(Flag)
1090 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
1091 #include "llvm/IR/DebugInfoFlags.def"
1092       .Default(SPFlagZero);
1093 }
1094 
getFlagString(DISPFlags Flag)1095 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
1096   switch (Flag) {
1097   // Appease a warning.
1098   case SPFlagVirtuality:
1099     return "";
1100 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
1101   case SPFlag##NAME:                                                           \
1102     return "DISPFlag" #NAME;
1103 #include "llvm/IR/DebugInfoFlags.def"
1104   }
1105   return "";
1106 }
1107 
1108 DISubprogram::DISPFlags
splitFlags(DISPFlags Flags,SmallVectorImpl<DISPFlags> & SplitFlags)1109 DISubprogram::splitFlags(DISPFlags Flags,
1110                          SmallVectorImpl<DISPFlags> &SplitFlags) {
1111   // Multi-bit fields can require special handling. In our case, however, the
1112   // only multi-bit field is virtuality, and all its values happen to be
1113   // single-bit values, so the right behavior just falls out.
1114 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
1115   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
1116     SplitFlags.push_back(Bit);                                                 \
1117     Flags &= ~Bit;                                                             \
1118   }
1119 #include "llvm/IR/DebugInfoFlags.def"
1120   return Flags;
1121 }
1122 
getImpl(LLVMContext & Context,Metadata * Scope,MDString * Name,MDString * LinkageName,Metadata * File,unsigned Line,Metadata * Type,unsigned ScopeLine,Metadata * ContainingType,unsigned VirtualIndex,int ThisAdjustment,DIFlags Flags,DISPFlags SPFlags,Metadata * Unit,Metadata * TemplateParams,Metadata * Declaration,Metadata * RetainedNodes,Metadata * ThrownTypes,Metadata * Annotations,MDString * TargetFuncName,StorageType Storage,bool ShouldCreate)1123 DISubprogram *DISubprogram::getImpl(
1124     LLVMContext &Context, Metadata *Scope, MDString *Name,
1125     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
1126     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
1127     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
1128     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
1129     Metadata *ThrownTypes, Metadata *Annotations, MDString *TargetFuncName,
1130     StorageType Storage, bool ShouldCreate) {
1131   assert(isCanonical(Name) && "Expected canonical MDString");
1132   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1133   assert(isCanonical(TargetFuncName) && "Expected canonical MDString");
1134   DEFINE_GETIMPL_LOOKUP(DISubprogram,
1135                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
1136                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
1137                          SPFlags, Unit, TemplateParams, Declaration,
1138                          RetainedNodes, ThrownTypes, Annotations,
1139                          TargetFuncName));
1140   SmallVector<Metadata *, 13> Ops = {
1141       File,           Scope,          Name,        LinkageName,
1142       Type,           Unit,           Declaration, RetainedNodes,
1143       ContainingType, TemplateParams, ThrownTypes, Annotations,
1144       TargetFuncName};
1145   if (!TargetFuncName) {
1146     Ops.pop_back();
1147     if (!Annotations) {
1148       Ops.pop_back();
1149       if (!ThrownTypes) {
1150         Ops.pop_back();
1151         if (!TemplateParams) {
1152           Ops.pop_back();
1153           if (!ContainingType)
1154             Ops.pop_back();
1155         }
1156       }
1157     }
1158   }
1159   DEFINE_GETIMPL_STORE_N(
1160       DISubprogram,
1161       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
1162       Ops.size());
1163 }
1164 
describes(const Function * F) const1165 bool DISubprogram::describes(const Function *F) const {
1166   assert(F && "Invalid function");
1167   return F->getSubprogram() == this;
1168 }
DILexicalBlockBase(LLVMContext & C,unsigned ID,StorageType Storage,ArrayRef<Metadata * > Ops)1169 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID,
1170                                        StorageType Storage,
1171                                        ArrayRef<Metadata *> Ops)
1172     : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1173 
getImpl(LLVMContext & Context,Metadata * Scope,Metadata * File,unsigned Line,unsigned Column,StorageType Storage,bool ShouldCreate)1174 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1175                                         Metadata *File, unsigned Line,
1176                                         unsigned Column, StorageType Storage,
1177                                         bool ShouldCreate) {
1178   // Fixup column.
1179   adjustColumn(Column);
1180 
1181   assert(Scope && "Expected scope");
1182   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
1183   Metadata *Ops[] = {File, Scope};
1184   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
1185 }
1186 
getImpl(LLVMContext & Context,Metadata * Scope,Metadata * File,unsigned Discriminator,StorageType Storage,bool ShouldCreate)1187 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
1188                                                 Metadata *Scope, Metadata *File,
1189                                                 unsigned Discriminator,
1190                                                 StorageType Storage,
1191                                                 bool ShouldCreate) {
1192   assert(Scope && "Expected scope");
1193   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
1194   Metadata *Ops[] = {File, Scope};
1195   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
1196 }
1197 
DINamespace(LLVMContext & Context,StorageType Storage,bool ExportSymbols,ArrayRef<Metadata * > Ops)1198 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage,
1199                          bool ExportSymbols, ArrayRef<Metadata *> Ops)
1200     : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops) {
1201   SubclassData1 = ExportSymbols;
1202 }
getImpl(LLVMContext & Context,Metadata * Scope,MDString * Name,bool ExportSymbols,StorageType Storage,bool ShouldCreate)1203 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
1204                                   MDString *Name, bool ExportSymbols,
1205                                   StorageType Storage, bool ShouldCreate) {
1206   assert(isCanonical(Name) && "Expected canonical MDString");
1207   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
1208   // The nullptr is for DIScope's File operand. This should be refactored.
1209   Metadata *Ops[] = {nullptr, Scope, Name};
1210   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
1211 }
1212 
DICommonBlock(LLVMContext & Context,StorageType Storage,unsigned LineNo,ArrayRef<Metadata * > Ops)1213 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage,
1214                              unsigned LineNo, ArrayRef<Metadata *> Ops)
1215     : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
1216               Ops) {
1217   SubclassData32 = LineNo;
1218 }
getImpl(LLVMContext & Context,Metadata * Scope,Metadata * Decl,MDString * Name,Metadata * File,unsigned LineNo,StorageType Storage,bool ShouldCreate)1219 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1220                                       Metadata *Decl, MDString *Name,
1221                                       Metadata *File, unsigned LineNo,
1222                                       StorageType Storage, bool ShouldCreate) {
1223   assert(isCanonical(Name) && "Expected canonical MDString");
1224   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
1225   // The nullptr is for DIScope's File operand. This should be refactored.
1226   Metadata *Ops[] = {Scope, Decl, Name, File};
1227   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
1228 }
1229 
DIModule(LLVMContext & Context,StorageType Storage,unsigned LineNo,bool IsDecl,ArrayRef<Metadata * > Ops)1230 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
1231                    bool IsDecl, ArrayRef<Metadata *> Ops)
1232     : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops) {
1233   SubclassData1 = IsDecl;
1234   SubclassData32 = LineNo;
1235 }
getImpl(LLVMContext & Context,Metadata * File,Metadata * Scope,MDString * Name,MDString * ConfigurationMacros,MDString * IncludePath,MDString * APINotesFile,unsigned LineNo,bool IsDecl,StorageType Storage,bool ShouldCreate)1236 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
1237                             Metadata *Scope, MDString *Name,
1238                             MDString *ConfigurationMacros,
1239                             MDString *IncludePath, MDString *APINotesFile,
1240                             unsigned LineNo, bool IsDecl, StorageType Storage,
1241                             bool ShouldCreate) {
1242   assert(isCanonical(Name) && "Expected canonical MDString");
1243   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
1244                                    IncludePath, APINotesFile, LineNo, IsDecl));
1245   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
1246                      IncludePath, APINotesFile};
1247   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
1248 }
DITemplateTypeParameter(LLVMContext & Context,StorageType Storage,bool IsDefault,ArrayRef<Metadata * > Ops)1249 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context,
1250                                                  StorageType Storage,
1251                                                  bool IsDefault,
1252                                                  ArrayRef<Metadata *> Ops)
1253     : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
1254                           dwarf::DW_TAG_template_type_parameter, IsDefault,
1255                           Ops) {}
1256 
1257 DITemplateTypeParameter *
getImpl(LLVMContext & Context,MDString * Name,Metadata * Type,bool isDefault,StorageType Storage,bool ShouldCreate)1258 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
1259                                  Metadata *Type, bool isDefault,
1260                                  StorageType Storage, bool ShouldCreate) {
1261   assert(isCanonical(Name) && "Expected canonical MDString");
1262   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
1263   Metadata *Ops[] = {Name, Type};
1264   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
1265 }
1266 
getImpl(LLVMContext & Context,unsigned Tag,MDString * Name,Metadata * Type,bool isDefault,Metadata * Value,StorageType Storage,bool ShouldCreate)1267 DITemplateValueParameter *DITemplateValueParameter::getImpl(
1268     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
1269     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
1270   assert(isCanonical(Name) && "Expected canonical MDString");
1271   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
1272                         (Tag, Name, Type, isDefault, Value));
1273   Metadata *Ops[] = {Name, Type, Value};
1274   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
1275 }
1276 
1277 DIGlobalVariable *
getImpl(LLVMContext & Context,Metadata * Scope,MDString * Name,MDString * LinkageName,Metadata * File,unsigned Line,Metadata * Type,bool IsLocalToUnit,bool IsDefinition,Metadata * StaticDataMemberDeclaration,Metadata * TemplateParams,uint32_t AlignInBits,Metadata * Annotations,StorageType Storage,bool ShouldCreate)1278 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1279                           MDString *LinkageName, Metadata *File, unsigned Line,
1280                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1281                           Metadata *StaticDataMemberDeclaration,
1282                           Metadata *TemplateParams, uint32_t AlignInBits,
1283                           Metadata *Annotations, StorageType Storage,
1284                           bool ShouldCreate) {
1285   assert(isCanonical(Name) && "Expected canonical MDString");
1286   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1287   DEFINE_GETIMPL_LOOKUP(
1288       DIGlobalVariable,
1289       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1290        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations));
1291   Metadata *Ops[] = {Scope,
1292                      Name,
1293                      File,
1294                      Type,
1295                      Name,
1296                      LinkageName,
1297                      StaticDataMemberDeclaration,
1298                      TemplateParams,
1299                      Annotations};
1300   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1301                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1302 }
1303 
1304 DILocalVariable *
getImpl(LLVMContext & Context,Metadata * Scope,MDString * Name,Metadata * File,unsigned Line,Metadata * Type,unsigned Arg,DIFlags Flags,uint32_t AlignInBits,Metadata * Annotations,StorageType Storage,bool ShouldCreate)1305 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1306                          Metadata *File, unsigned Line, Metadata *Type,
1307                          unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
1308                          Metadata *Annotations, StorageType Storage,
1309                          bool ShouldCreate) {
1310   // 64K ought to be enough for any frontend.
1311   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1312 
1313   assert(Scope && "Expected scope");
1314   assert(isCanonical(Name) && "Expected canonical MDString");
1315   DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg,
1316                                           Flags, AlignInBits, Annotations));
1317   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1318   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1319 }
1320 
DIVariable(LLVMContext & C,unsigned ID,StorageType Storage,signed Line,ArrayRef<Metadata * > Ops,uint32_t AlignInBits)1321 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage,
1322                        signed Line, ArrayRef<Metadata *> Ops,
1323                        uint32_t AlignInBits)
1324     : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line) {
1325   SubclassData32 = AlignInBits;
1326 }
getSizeInBits() const1327 std::optional<uint64_t> DIVariable::getSizeInBits() const {
1328   // This is used by the Verifier so be mindful of broken types.
1329   const Metadata *RawType = getRawType();
1330   while (RawType) {
1331     // Try to get the size directly.
1332     if (auto *T = dyn_cast<DIType>(RawType))
1333       if (uint64_t Size = T->getSizeInBits())
1334         return Size;
1335 
1336     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1337       // Look at the base type.
1338       RawType = DT->getRawBaseType();
1339       continue;
1340     }
1341 
1342     // Missing type or size.
1343     break;
1344   }
1345 
1346   // Fail gracefully.
1347   return std::nullopt;
1348 }
1349 
DILabel(LLVMContext & C,StorageType Storage,unsigned Line,ArrayRef<Metadata * > Ops)1350 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
1351                  ArrayRef<Metadata *> Ops)
1352     : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops) {
1353   SubclassData32 = Line;
1354 }
getImpl(LLVMContext & Context,Metadata * Scope,MDString * Name,Metadata * File,unsigned Line,StorageType Storage,bool ShouldCreate)1355 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1356                           Metadata *File, unsigned Line, StorageType Storage,
1357                           bool ShouldCreate) {
1358   assert(Scope && "Expected scope");
1359   assert(isCanonical(Name) && "Expected canonical MDString");
1360   DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line));
1361   Metadata *Ops[] = {Scope, Name, File};
1362   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1363 }
1364 
getImpl(LLVMContext & Context,ArrayRef<uint64_t> Elements,StorageType Storage,bool ShouldCreate)1365 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1366                                     ArrayRef<uint64_t> Elements,
1367                                     StorageType Storage, bool ShouldCreate) {
1368   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1369   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1370 }
isEntryValue() const1371 bool DIExpression::isEntryValue() const {
1372   if (auto singleLocElts = getSingleLocationExpressionElements()) {
1373     return singleLocElts->size() > 0 &&
1374            (*singleLocElts)[0] == dwarf::DW_OP_LLVM_entry_value;
1375   }
1376   return false;
1377 }
startsWithDeref() const1378 bool DIExpression::startsWithDeref() const {
1379   if (auto singleLocElts = getSingleLocationExpressionElements())
1380     return singleLocElts->size() > 0 &&
1381            (*singleLocElts)[0] == dwarf::DW_OP_deref;
1382   return false;
1383 }
isDeref() const1384 bool DIExpression::isDeref() const {
1385   if (auto singleLocElts = getSingleLocationExpressionElements())
1386     return singleLocElts->size() == 1 &&
1387            (*singleLocElts)[0] == dwarf::DW_OP_deref;
1388   return false;
1389 }
1390 
getImpl(LLVMContext & Context,StorageType Storage,bool ShouldCreate)1391 DIAssignID *DIAssignID::getImpl(LLVMContext &Context, StorageType Storage,
1392                                 bool ShouldCreate) {
1393   // Uniqued DIAssignID are not supported as the instance address *is* the ID.
1394   assert(Storage != StorageType::Uniqued && "uniqued DIAssignID unsupported");
1395   return storeImpl(new (0u, Storage) DIAssignID(Context, Storage), Storage);
1396 }
1397 
getSize() const1398 unsigned DIExpression::ExprOperand::getSize() const {
1399   uint64_t Op = getOp();
1400 
1401   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1402     return 2;
1403 
1404   switch (Op) {
1405   case dwarf::DW_OP_LLVM_convert:
1406   case dwarf::DW_OP_LLVM_fragment:
1407   case dwarf::DW_OP_LLVM_extract_bits_sext:
1408   case dwarf::DW_OP_LLVM_extract_bits_zext:
1409   case dwarf::DW_OP_bregx:
1410     return 3;
1411   case dwarf::DW_OP_constu:
1412   case dwarf::DW_OP_consts:
1413   case dwarf::DW_OP_deref_size:
1414   case dwarf::DW_OP_plus_uconst:
1415   case dwarf::DW_OP_LLVM_tag_offset:
1416   case dwarf::DW_OP_LLVM_entry_value:
1417   case dwarf::DW_OP_LLVM_arg:
1418   case dwarf::DW_OP_regx:
1419     return 2;
1420   default:
1421     return 1;
1422   }
1423 }
1424 
isValid() const1425 bool DIExpression::isValid() const {
1426   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1427     // Check that there's space for the operand.
1428     if (I->get() + I->getSize() > E->get())
1429       return false;
1430 
1431     uint64_t Op = I->getOp();
1432     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1433         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1434       return true;
1435 
1436     // Check that the operand is valid.
1437     switch (Op) {
1438     default:
1439       return false;
1440     case dwarf::DW_OP_LLVM_fragment:
1441       // A fragment operator must appear at the end.
1442       return I->get() + I->getSize() == E->get();
1443     case dwarf::DW_OP_stack_value: {
1444       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1445       if (I->get() + I->getSize() == E->get())
1446         break;
1447       auto J = I;
1448       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1449         return false;
1450       break;
1451     }
1452     case dwarf::DW_OP_swap: {
1453       // Must be more than one implicit element on the stack.
1454 
1455       // FIXME: A better way to implement this would be to add a local variable
1456       // that keeps track of the stack depth and introduce something like a
1457       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1458       // DIExpression is attached to, or else pass the number of implicit stack
1459       // elements into isValid.
1460       if (getNumElements() == 1)
1461         return false;
1462       break;
1463     }
1464     case dwarf::DW_OP_LLVM_entry_value: {
1465       // An entry value operator must appear at the beginning or immediately
1466       // following `DW_OP_LLVM_arg 0`, and the number of operations it cover can
1467       // currently only be 1, because we support only entry values of a simple
1468       // register location. One reason for this is that we currently can't
1469       // calculate the size of the resulting DWARF block for other expressions.
1470       auto FirstOp = expr_op_begin();
1471       if (FirstOp->getOp() == dwarf::DW_OP_LLVM_arg && FirstOp->getArg(0) == 0)
1472         ++FirstOp;
1473       return I->get() == FirstOp->get() && I->getArg(0) == 1;
1474     }
1475     case dwarf::DW_OP_LLVM_implicit_pointer:
1476     case dwarf::DW_OP_LLVM_convert:
1477     case dwarf::DW_OP_LLVM_arg:
1478     case dwarf::DW_OP_LLVM_tag_offset:
1479     case dwarf::DW_OP_LLVM_extract_bits_sext:
1480     case dwarf::DW_OP_LLVM_extract_bits_zext:
1481     case dwarf::DW_OP_constu:
1482     case dwarf::DW_OP_plus_uconst:
1483     case dwarf::DW_OP_plus:
1484     case dwarf::DW_OP_minus:
1485     case dwarf::DW_OP_mul:
1486     case dwarf::DW_OP_div:
1487     case dwarf::DW_OP_mod:
1488     case dwarf::DW_OP_or:
1489     case dwarf::DW_OP_and:
1490     case dwarf::DW_OP_xor:
1491     case dwarf::DW_OP_shl:
1492     case dwarf::DW_OP_shr:
1493     case dwarf::DW_OP_shra:
1494     case dwarf::DW_OP_deref:
1495     case dwarf::DW_OP_deref_size:
1496     case dwarf::DW_OP_xderef:
1497     case dwarf::DW_OP_lit0:
1498     case dwarf::DW_OP_not:
1499     case dwarf::DW_OP_dup:
1500     case dwarf::DW_OP_regx:
1501     case dwarf::DW_OP_bregx:
1502     case dwarf::DW_OP_push_object_address:
1503     case dwarf::DW_OP_over:
1504     case dwarf::DW_OP_consts:
1505     case dwarf::DW_OP_eq:
1506     case dwarf::DW_OP_ne:
1507     case dwarf::DW_OP_gt:
1508     case dwarf::DW_OP_ge:
1509     case dwarf::DW_OP_lt:
1510     case dwarf::DW_OP_le:
1511       break;
1512     }
1513   }
1514   return true;
1515 }
1516 
isImplicit() const1517 bool DIExpression::isImplicit() const {
1518   if (!isValid())
1519     return false;
1520 
1521   if (getNumElements() == 0)
1522     return false;
1523 
1524   for (const auto &It : expr_ops()) {
1525     switch (It.getOp()) {
1526     default:
1527       break;
1528     case dwarf::DW_OP_stack_value:
1529       return true;
1530     }
1531   }
1532 
1533   return false;
1534 }
1535 
isComplex() const1536 bool DIExpression::isComplex() const {
1537   if (!isValid())
1538     return false;
1539 
1540   if (getNumElements() == 0)
1541     return false;
1542 
1543   // If there are any elements other than fragment or tag_offset, then some
1544   // kind of complex computation occurs.
1545   for (const auto &It : expr_ops()) {
1546     switch (It.getOp()) {
1547     case dwarf::DW_OP_LLVM_tag_offset:
1548     case dwarf::DW_OP_LLVM_fragment:
1549     case dwarf::DW_OP_LLVM_arg:
1550       continue;
1551     default:
1552       return true;
1553     }
1554   }
1555 
1556   return false;
1557 }
1558 
isSingleLocationExpression() const1559 bool DIExpression::isSingleLocationExpression() const {
1560   if (!isValid())
1561     return false;
1562 
1563   if (getNumElements() == 0)
1564     return true;
1565 
1566   auto ExprOpBegin = expr_ops().begin();
1567   auto ExprOpEnd = expr_ops().end();
1568   if (ExprOpBegin->getOp() == dwarf::DW_OP_LLVM_arg) {
1569     if (ExprOpBegin->getArg(0) != 0)
1570       return false;
1571     ++ExprOpBegin;
1572   }
1573 
1574   return !std::any_of(ExprOpBegin, ExprOpEnd, [](auto Op) {
1575     return Op.getOp() == dwarf::DW_OP_LLVM_arg;
1576   });
1577 }
1578 
1579 std::optional<ArrayRef<uint64_t>>
getSingleLocationExpressionElements() const1580 DIExpression::getSingleLocationExpressionElements() const {
1581   // Check for `isValid` covered by `isSingleLocationExpression`.
1582   if (!isSingleLocationExpression())
1583     return std::nullopt;
1584 
1585   // An empty expression is already non-variadic.
1586   if (!getNumElements())
1587     return ArrayRef<uint64_t>();
1588 
1589   // If Expr does not have a leading DW_OP_LLVM_arg then we don't need to do
1590   // anything.
1591   if (getElements()[0] == dwarf::DW_OP_LLVM_arg)
1592     return getElements().drop_front(2);
1593   return getElements();
1594 }
1595 
1596 const DIExpression *
convertToUndefExpression(const DIExpression * Expr)1597 DIExpression::convertToUndefExpression(const DIExpression *Expr) {
1598   SmallVector<uint64_t, 3> UndefOps;
1599   if (auto FragmentInfo = Expr->getFragmentInfo()) {
1600     UndefOps.append({dwarf::DW_OP_LLVM_fragment, FragmentInfo->OffsetInBits,
1601                      FragmentInfo->SizeInBits});
1602   }
1603   return DIExpression::get(Expr->getContext(), UndefOps);
1604 }
1605 
1606 const DIExpression *
convertToVariadicExpression(const DIExpression * Expr)1607 DIExpression::convertToVariadicExpression(const DIExpression *Expr) {
1608   if (any_of(Expr->expr_ops(), [](auto ExprOp) {
1609         return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg;
1610       }))
1611     return Expr;
1612   SmallVector<uint64_t> NewOps;
1613   NewOps.reserve(Expr->getNumElements() + 2);
1614   NewOps.append({dwarf::DW_OP_LLVM_arg, 0});
1615   NewOps.append(Expr->elements_begin(), Expr->elements_end());
1616   return DIExpression::get(Expr->getContext(), NewOps);
1617 }
1618 
1619 std::optional<const DIExpression *>
convertToNonVariadicExpression(const DIExpression * Expr)1620 DIExpression::convertToNonVariadicExpression(const DIExpression *Expr) {
1621   if (!Expr)
1622     return std::nullopt;
1623 
1624   if (auto Elts = Expr->getSingleLocationExpressionElements())
1625     return DIExpression::get(Expr->getContext(), *Elts);
1626 
1627   return std::nullopt;
1628 }
1629 
canonicalizeExpressionOps(SmallVectorImpl<uint64_t> & Ops,const DIExpression * Expr,bool IsIndirect)1630 void DIExpression::canonicalizeExpressionOps(SmallVectorImpl<uint64_t> &Ops,
1631                                              const DIExpression *Expr,
1632                                              bool IsIndirect) {
1633   // If Expr is not already variadic, insert the implied `DW_OP_LLVM_arg 0`
1634   // to the existing expression ops.
1635   if (none_of(Expr->expr_ops(), [](auto ExprOp) {
1636         return ExprOp.getOp() == dwarf::DW_OP_LLVM_arg;
1637       }))
1638     Ops.append({dwarf::DW_OP_LLVM_arg, 0});
1639   // If Expr is not indirect, we only need to insert the expression elements and
1640   // we're done.
1641   if (!IsIndirect) {
1642     Ops.append(Expr->elements_begin(), Expr->elements_end());
1643     return;
1644   }
1645   // If Expr is indirect, insert the implied DW_OP_deref at the end of the
1646   // expression but before DW_OP_{stack_value, LLVM_fragment} if they are
1647   // present.
1648   for (auto Op : Expr->expr_ops()) {
1649     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1650         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1651       Ops.push_back(dwarf::DW_OP_deref);
1652       IsIndirect = false;
1653     }
1654     Op.appendToVector(Ops);
1655   }
1656   if (IsIndirect)
1657     Ops.push_back(dwarf::DW_OP_deref);
1658 }
1659 
isEqualExpression(const DIExpression * FirstExpr,bool FirstIndirect,const DIExpression * SecondExpr,bool SecondIndirect)1660 bool DIExpression::isEqualExpression(const DIExpression *FirstExpr,
1661                                      bool FirstIndirect,
1662                                      const DIExpression *SecondExpr,
1663                                      bool SecondIndirect) {
1664   SmallVector<uint64_t> FirstOps;
1665   DIExpression::canonicalizeExpressionOps(FirstOps, FirstExpr, FirstIndirect);
1666   SmallVector<uint64_t> SecondOps;
1667   DIExpression::canonicalizeExpressionOps(SecondOps, SecondExpr,
1668                                           SecondIndirect);
1669   return FirstOps == SecondOps;
1670 }
1671 
1672 std::optional<DIExpression::FragmentInfo>
getFragmentInfo(expr_op_iterator Start,expr_op_iterator End)1673 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1674   for (auto I = Start; I != End; ++I)
1675     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1676       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1677       return Info;
1678     }
1679   return std::nullopt;
1680 }
1681 
getActiveBits(DIVariable * Var)1682 std::optional<uint64_t> DIExpression::getActiveBits(DIVariable *Var) {
1683   std::optional<uint64_t> InitialActiveBits = Var->getSizeInBits();
1684   std::optional<uint64_t> ActiveBits = InitialActiveBits;
1685   for (auto Op : expr_ops()) {
1686     switch (Op.getOp()) {
1687     default:
1688       // We assume the worst case for anything we don't currently handle and
1689       // revert to the initial active bits.
1690       ActiveBits = InitialActiveBits;
1691       break;
1692     case dwarf::DW_OP_LLVM_extract_bits_zext:
1693     case dwarf::DW_OP_LLVM_extract_bits_sext: {
1694       // We can't handle an extract whose sign doesn't match that of the
1695       // variable.
1696       std::optional<DIBasicType::Signedness> VarSign = Var->getSignedness();
1697       bool VarSigned = (VarSign == DIBasicType::Signedness::Signed);
1698       bool OpSigned = (Op.getOp() == dwarf::DW_OP_LLVM_extract_bits_sext);
1699       if (!VarSign || VarSigned != OpSigned) {
1700         ActiveBits = InitialActiveBits;
1701         break;
1702       }
1703       [[fallthrough]];
1704     }
1705     case dwarf::DW_OP_LLVM_fragment:
1706       // Extract or fragment narrows the active bits
1707       if (ActiveBits)
1708         ActiveBits = std::min(*ActiveBits, Op.getArg(1));
1709       else
1710         ActiveBits = Op.getArg(1);
1711       break;
1712     }
1713   }
1714   return ActiveBits;
1715 }
1716 
appendOffset(SmallVectorImpl<uint64_t> & Ops,int64_t Offset)1717 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1718                                 int64_t Offset) {
1719   if (Offset > 0) {
1720     Ops.push_back(dwarf::DW_OP_plus_uconst);
1721     Ops.push_back(Offset);
1722   } else if (Offset < 0) {
1723     Ops.push_back(dwarf::DW_OP_constu);
1724     // Avoid UB when encountering LLONG_MIN, because in 2's complement
1725     // abs(LLONG_MIN) is LLONG_MAX+1.
1726     uint64_t AbsMinusOne = -(Offset+1);
1727     Ops.push_back(AbsMinusOne + 1);
1728     Ops.push_back(dwarf::DW_OP_minus);
1729   }
1730 }
1731 
extractIfOffset(int64_t & Offset) const1732 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1733   auto SingleLocEltsOpt = getSingleLocationExpressionElements();
1734   if (!SingleLocEltsOpt)
1735     return false;
1736   auto SingleLocElts = *SingleLocEltsOpt;
1737 
1738   if (SingleLocElts.size() == 0) {
1739     Offset = 0;
1740     return true;
1741   }
1742 
1743   if (SingleLocElts.size() == 2 &&
1744       SingleLocElts[0] == dwarf::DW_OP_plus_uconst) {
1745     Offset = SingleLocElts[1];
1746     return true;
1747   }
1748 
1749   if (SingleLocElts.size() == 3 && SingleLocElts[0] == dwarf::DW_OP_constu) {
1750     if (SingleLocElts[2] == dwarf::DW_OP_plus) {
1751       Offset = SingleLocElts[1];
1752       return true;
1753     }
1754     if (SingleLocElts[2] == dwarf::DW_OP_minus) {
1755       Offset = -SingleLocElts[1];
1756       return true;
1757     }
1758   }
1759 
1760   return false;
1761 }
1762 
extractLeadingOffset(int64_t & OffsetInBytes,SmallVectorImpl<uint64_t> & RemainingOps) const1763 bool DIExpression::extractLeadingOffset(
1764     int64_t &OffsetInBytes, SmallVectorImpl<uint64_t> &RemainingOps) const {
1765   OffsetInBytes = 0;
1766   RemainingOps.clear();
1767 
1768   auto SingleLocEltsOpt = getSingleLocationExpressionElements();
1769   if (!SingleLocEltsOpt)
1770     return false;
1771 
1772   auto ExprOpEnd = expr_op_iterator(SingleLocEltsOpt->end());
1773   auto ExprOpIt = expr_op_iterator(SingleLocEltsOpt->begin());
1774   while (ExprOpIt != ExprOpEnd) {
1775     uint64_t Op = ExprOpIt->getOp();
1776     if (Op == dwarf::DW_OP_deref || Op == dwarf::DW_OP_deref_size ||
1777         Op == dwarf::DW_OP_deref_type || Op == dwarf::DW_OP_LLVM_fragment ||
1778         Op == dwarf::DW_OP_LLVM_extract_bits_zext ||
1779         Op == dwarf::DW_OP_LLVM_extract_bits_sext) {
1780       break;
1781     } else if (Op == dwarf::DW_OP_plus_uconst) {
1782       OffsetInBytes += ExprOpIt->getArg(0);
1783     } else if (Op == dwarf::DW_OP_constu) {
1784       uint64_t Value = ExprOpIt->getArg(0);
1785       ++ExprOpIt;
1786       if (ExprOpIt->getOp() == dwarf::DW_OP_plus)
1787         OffsetInBytes += Value;
1788       else if (ExprOpIt->getOp() == dwarf::DW_OP_minus)
1789         OffsetInBytes -= Value;
1790       else
1791         return false;
1792     } else {
1793       // Not a const plus/minus operation or deref.
1794       return false;
1795     }
1796     ++ExprOpIt;
1797   }
1798   RemainingOps.append(ExprOpIt.getBase(), ExprOpEnd.getBase());
1799   return true;
1800 }
1801 
hasAllLocationOps(unsigned N) const1802 bool DIExpression::hasAllLocationOps(unsigned N) const {
1803   SmallDenseSet<uint64_t, 4> SeenOps;
1804   for (auto ExprOp : expr_ops())
1805     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1806       SeenOps.insert(ExprOp.getArg(0));
1807   for (uint64_t Idx = 0; Idx < N; ++Idx)
1808     if (!SeenOps.contains(Idx))
1809       return false;
1810   return true;
1811 }
1812 
extractAddressClass(const DIExpression * Expr,unsigned & AddrClass)1813 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1814                                                       unsigned &AddrClass) {
1815   // FIXME: This seems fragile. Nothing that verifies that these elements
1816   // actually map to ops and not operands.
1817   auto SingleLocEltsOpt = Expr->getSingleLocationExpressionElements();
1818   if (!SingleLocEltsOpt)
1819     return nullptr;
1820   auto SingleLocElts = *SingleLocEltsOpt;
1821 
1822   const unsigned PatternSize = 4;
1823   if (SingleLocElts.size() >= PatternSize &&
1824       SingleLocElts[PatternSize - 4] == dwarf::DW_OP_constu &&
1825       SingleLocElts[PatternSize - 2] == dwarf::DW_OP_swap &&
1826       SingleLocElts[PatternSize - 1] == dwarf::DW_OP_xderef) {
1827     AddrClass = SingleLocElts[PatternSize - 3];
1828 
1829     if (SingleLocElts.size() == PatternSize)
1830       return nullptr;
1831     return DIExpression::get(
1832         Expr->getContext(),
1833         ArrayRef(&*SingleLocElts.begin(), SingleLocElts.size() - PatternSize));
1834   }
1835   return Expr;
1836 }
1837 
prepend(const DIExpression * Expr,uint8_t Flags,int64_t Offset)1838 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1839                                     int64_t Offset) {
1840   SmallVector<uint64_t, 8> Ops;
1841   if (Flags & DIExpression::DerefBefore)
1842     Ops.push_back(dwarf::DW_OP_deref);
1843 
1844   appendOffset(Ops, Offset);
1845   if (Flags & DIExpression::DerefAfter)
1846     Ops.push_back(dwarf::DW_OP_deref);
1847 
1848   bool StackValue = Flags & DIExpression::StackValue;
1849   bool EntryValue = Flags & DIExpression::EntryValue;
1850 
1851   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1852 }
1853 
appendOpsToArg(const DIExpression * Expr,ArrayRef<uint64_t> Ops,unsigned ArgNo,bool StackValue)1854 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1855                                            ArrayRef<uint64_t> Ops,
1856                                            unsigned ArgNo, bool StackValue) {
1857   assert(Expr && "Can't add ops to this expression");
1858 
1859   // Handle non-variadic intrinsics by prepending the opcodes.
1860   if (!any_of(Expr->expr_ops(),
1861               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1862     assert(ArgNo == 0 &&
1863            "Location Index must be 0 for a non-variadic expression.");
1864     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1865     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1866   }
1867 
1868   SmallVector<uint64_t, 8> NewOps;
1869   for (auto Op : Expr->expr_ops()) {
1870     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1871     if (StackValue) {
1872       if (Op.getOp() == dwarf::DW_OP_stack_value)
1873         StackValue = false;
1874       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1875         NewOps.push_back(dwarf::DW_OP_stack_value);
1876         StackValue = false;
1877       }
1878     }
1879     Op.appendToVector(NewOps);
1880     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1881       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1882   }
1883   if (StackValue)
1884     NewOps.push_back(dwarf::DW_OP_stack_value);
1885 
1886   return DIExpression::get(Expr->getContext(), NewOps);
1887 }
1888 
replaceArg(const DIExpression * Expr,uint64_t OldArg,uint64_t NewArg)1889 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1890                                        uint64_t OldArg, uint64_t NewArg) {
1891   assert(Expr && "Can't replace args in this expression");
1892 
1893   SmallVector<uint64_t, 8> NewOps;
1894 
1895   for (auto Op : Expr->expr_ops()) {
1896     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1897       Op.appendToVector(NewOps);
1898       continue;
1899     }
1900     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1901     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1902     // OldArg has been deleted from the Op list, so decrement all indices
1903     // greater than it.
1904     if (Arg > OldArg)
1905       --Arg;
1906     NewOps.push_back(Arg);
1907   }
1908   return DIExpression::get(Expr->getContext(), NewOps);
1909 }
1910 
prependOpcodes(const DIExpression * Expr,SmallVectorImpl<uint64_t> & Ops,bool StackValue,bool EntryValue)1911 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1912                                            SmallVectorImpl<uint64_t> &Ops,
1913                                            bool StackValue, bool EntryValue) {
1914   assert(Expr && "Can't prepend ops to this expression");
1915 
1916   if (EntryValue) {
1917     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1918     // Use a block size of 1 for the target register operand.  The
1919     // DWARF backend currently cannot emit entry values with a block
1920     // size > 1.
1921     Ops.push_back(1);
1922   }
1923 
1924   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1925   if (Ops.empty())
1926     StackValue = false;
1927   for (auto Op : Expr->expr_ops()) {
1928     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1929     if (StackValue) {
1930       if (Op.getOp() == dwarf::DW_OP_stack_value)
1931         StackValue = false;
1932       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1933         Ops.push_back(dwarf::DW_OP_stack_value);
1934         StackValue = false;
1935       }
1936     }
1937     Op.appendToVector(Ops);
1938   }
1939   if (StackValue)
1940     Ops.push_back(dwarf::DW_OP_stack_value);
1941   return DIExpression::get(Expr->getContext(), Ops);
1942 }
1943 
append(const DIExpression * Expr,ArrayRef<uint64_t> Ops)1944 DIExpression *DIExpression::append(const DIExpression *Expr,
1945                                    ArrayRef<uint64_t> Ops) {
1946   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1947 
1948   // Copy Expr's current op list.
1949   SmallVector<uint64_t, 16> NewOps;
1950   for (auto Op : Expr->expr_ops()) {
1951     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1952     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1953         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1954       NewOps.append(Ops.begin(), Ops.end());
1955 
1956       // Ensure that the new opcodes are only appended once.
1957       Ops = std::nullopt;
1958     }
1959     Op.appendToVector(NewOps);
1960   }
1961   NewOps.append(Ops.begin(), Ops.end());
1962   auto *result =
1963       DIExpression::get(Expr->getContext(), NewOps)->foldConstantMath();
1964   assert(result->isValid() && "concatenated expression is not valid");
1965   return result;
1966 }
1967 
appendToStack(const DIExpression * Expr,ArrayRef<uint64_t> Ops)1968 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1969                                           ArrayRef<uint64_t> Ops) {
1970   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1971   assert(std::none_of(expr_op_iterator(Ops.begin()),
1972                       expr_op_iterator(Ops.end()),
1973                       [](auto Op) {
1974                         return Op.getOp() == dwarf::DW_OP_stack_value ||
1975                                Op.getOp() == dwarf::DW_OP_LLVM_fragment;
1976                       }) &&
1977          "Can't append this op");
1978 
1979   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1980   // has no DW_OP_stack_value.
1981   //
1982   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1983   std::optional<FragmentInfo> FI = Expr->getFragmentInfo();
1984   unsigned DropUntilStackValue = FI ? 3 : 0;
1985   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1986       Expr->getElements().drop_back(DropUntilStackValue);
1987   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1988                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1989   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1990 
1991   // Append a DW_OP_deref after Expr's current op list if needed, then append
1992   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1993   SmallVector<uint64_t, 16> NewOps;
1994   if (NeedsDeref)
1995     NewOps.push_back(dwarf::DW_OP_deref);
1996   NewOps.append(Ops.begin(), Ops.end());
1997   if (NeedsStackValue)
1998     NewOps.push_back(dwarf::DW_OP_stack_value);
1999   return DIExpression::append(Expr, NewOps);
2000 }
2001 
createFragmentExpression(const DIExpression * Expr,unsigned OffsetInBits,unsigned SizeInBits)2002 std::optional<DIExpression *> DIExpression::createFragmentExpression(
2003     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
2004   SmallVector<uint64_t, 8> Ops;
2005   // Track whether it's safe to split the value at the top of the DWARF stack,
2006   // assuming that it'll be used as an implicit location value.
2007   bool CanSplitValue = true;
2008   // Track whether we need to add a fragment expression to the end of Expr.
2009   bool EmitFragment = true;
2010   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
2011   if (Expr) {
2012     for (auto Op : Expr->expr_ops()) {
2013       switch (Op.getOp()) {
2014       default:
2015         break;
2016       case dwarf::DW_OP_shr:
2017       case dwarf::DW_OP_shra:
2018       case dwarf::DW_OP_shl:
2019       case dwarf::DW_OP_plus:
2020       case dwarf::DW_OP_plus_uconst:
2021       case dwarf::DW_OP_minus:
2022         // We can't safely split arithmetic or shift operations into multiple
2023         // fragments because we can't express carry-over between fragments.
2024         //
2025         // FIXME: We *could* preserve the lowest fragment of a constant offset
2026         // operation if the offset fits into SizeInBits.
2027         CanSplitValue = false;
2028         break;
2029       case dwarf::DW_OP_deref:
2030       case dwarf::DW_OP_deref_size:
2031       case dwarf::DW_OP_deref_type:
2032       case dwarf::DW_OP_xderef:
2033       case dwarf::DW_OP_xderef_size:
2034       case dwarf::DW_OP_xderef_type:
2035         // Preceeding arithmetic operations have been applied to compute an
2036         // address. It's okay to split the value loaded from that address.
2037         CanSplitValue = true;
2038         break;
2039       case dwarf::DW_OP_stack_value:
2040         // Bail if this expression computes a value that cannot be split.
2041         if (!CanSplitValue)
2042           return std::nullopt;
2043         break;
2044       case dwarf::DW_OP_LLVM_fragment: {
2045         // If we've decided we don't need a fragment then give up if we see that
2046         // there's already a fragment expression.
2047         // FIXME: We could probably do better here
2048         if (!EmitFragment)
2049           return std::nullopt;
2050         // Make the new offset point into the existing fragment.
2051         uint64_t FragmentOffsetInBits = Op.getArg(0);
2052         uint64_t FragmentSizeInBits = Op.getArg(1);
2053         (void)FragmentSizeInBits;
2054         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
2055                "new fragment outside of original fragment");
2056         OffsetInBits += FragmentOffsetInBits;
2057         continue;
2058       }
2059       case dwarf::DW_OP_LLVM_extract_bits_zext:
2060       case dwarf::DW_OP_LLVM_extract_bits_sext: {
2061         // If we're extracting bits from inside of the fragment that we're
2062         // creating then we don't have a fragment after all, and just need to
2063         // adjust the offset that we're extracting from.
2064         uint64_t ExtractOffsetInBits = Op.getArg(0);
2065         uint64_t ExtractSizeInBits = Op.getArg(1);
2066         if (ExtractOffsetInBits >= OffsetInBits &&
2067             ExtractOffsetInBits + ExtractSizeInBits <=
2068                 OffsetInBits + SizeInBits) {
2069           Ops.push_back(Op.getOp());
2070           Ops.push_back(ExtractOffsetInBits - OffsetInBits);
2071           Ops.push_back(ExtractSizeInBits);
2072           EmitFragment = false;
2073           continue;
2074         }
2075         // If the extracted bits aren't fully contained within the fragment then
2076         // give up.
2077         // FIXME: We could probably do better here
2078         return std::nullopt;
2079       }
2080       }
2081       Op.appendToVector(Ops);
2082     }
2083   }
2084   assert((!Expr->isImplicit() || CanSplitValue) && "Expr can't be split");
2085   assert(Expr && "Unknown DIExpression");
2086   if (EmitFragment) {
2087     Ops.push_back(dwarf::DW_OP_LLVM_fragment);
2088     Ops.push_back(OffsetInBits);
2089     Ops.push_back(SizeInBits);
2090   }
2091   return DIExpression::get(Expr->getContext(), Ops);
2092 }
2093 
2094 /// See declaration for more info.
calculateFragmentIntersect(const DataLayout & DL,const Value * SliceStart,uint64_t SliceOffsetInBits,uint64_t SliceSizeInBits,const Value * DbgPtr,int64_t DbgPtrOffsetInBits,int64_t DbgExtractOffsetInBits,DIExpression::FragmentInfo VarFrag,std::optional<DIExpression::FragmentInfo> & Result,int64_t & OffsetFromLocationInBits)2095 bool DIExpression::calculateFragmentIntersect(
2096     const DataLayout &DL, const Value *SliceStart, uint64_t SliceOffsetInBits,
2097     uint64_t SliceSizeInBits, const Value *DbgPtr, int64_t DbgPtrOffsetInBits,
2098     int64_t DbgExtractOffsetInBits, DIExpression::FragmentInfo VarFrag,
2099     std::optional<DIExpression::FragmentInfo> &Result,
2100     int64_t &OffsetFromLocationInBits) {
2101 
2102   if (VarFrag.SizeInBits == 0)
2103     return false; // Variable size is unknown.
2104 
2105   // Difference between mem slice start and the dbg location start.
2106   // 0   4   8   12   16 ...
2107   // |       |
2108   // dbg location start
2109   //         |
2110   //         mem slice start
2111   // Here MemStartRelToDbgStartInBits is 8. Note this can be negative.
2112   int64_t MemStartRelToDbgStartInBits;
2113   {
2114     auto MemOffsetFromDbgInBytes = SliceStart->getPointerOffsetFrom(DbgPtr, DL);
2115     if (!MemOffsetFromDbgInBytes)
2116       return false; // Can't calculate difference in addresses.
2117     // Difference between the pointers.
2118     MemStartRelToDbgStartInBits = *MemOffsetFromDbgInBytes * 8;
2119     // Add the difference of the offsets.
2120     MemStartRelToDbgStartInBits +=
2121         SliceOffsetInBits - (DbgPtrOffsetInBits + DbgExtractOffsetInBits);
2122   }
2123 
2124   // Out-param. Invert offset to get offset from debug location.
2125   OffsetFromLocationInBits = -MemStartRelToDbgStartInBits;
2126 
2127   // Check if the variable fragment sits outside (before) this memory slice.
2128   int64_t MemEndRelToDbgStart = MemStartRelToDbgStartInBits + SliceSizeInBits;
2129   if (MemEndRelToDbgStart < 0) {
2130     Result = {0, 0}; // Out-param.
2131     return true;
2132   }
2133 
2134   // Work towards creating SliceOfVariable which is the bits of the variable
2135   // that the memory region covers.
2136   // 0   4   8   12   16 ...
2137   // |       |
2138   // dbg location start with VarFrag offset=32
2139   //         |
2140   //         mem slice start: SliceOfVariable offset=40
2141   int64_t MemStartRelToVarInBits =
2142       MemStartRelToDbgStartInBits + VarFrag.OffsetInBits;
2143   int64_t MemEndRelToVarInBits = MemStartRelToVarInBits + SliceSizeInBits;
2144   // If the memory region starts before the debug location the fragment
2145   // offset would be negative, which we can't encode. Limit those to 0. This
2146   // is fine because those bits necessarily don't overlap with the existing
2147   // variable fragment.
2148   int64_t MemFragStart = std::max<int64_t>(0, MemStartRelToVarInBits);
2149   int64_t MemFragSize =
2150       std::max<int64_t>(0, MemEndRelToVarInBits - MemFragStart);
2151   DIExpression::FragmentInfo SliceOfVariable(MemFragSize, MemFragStart);
2152 
2153   // Intersect the memory region fragment with the variable location fragment.
2154   DIExpression::FragmentInfo TrimmedSliceOfVariable =
2155       DIExpression::FragmentInfo::intersect(SliceOfVariable, VarFrag);
2156   if (TrimmedSliceOfVariable == VarFrag)
2157     Result = std::nullopt; // Out-param.
2158   else
2159     Result = TrimmedSliceOfVariable; // Out-param.
2160   return true;
2161 }
2162 
2163 std::pair<DIExpression *, const ConstantInt *>
constantFold(const ConstantInt * CI)2164 DIExpression::constantFold(const ConstantInt *CI) {
2165   // Copy the APInt so we can modify it.
2166   APInt NewInt = CI->getValue();
2167   SmallVector<uint64_t, 8> Ops;
2168 
2169   // Fold operators only at the beginning of the expression.
2170   bool First = true;
2171   bool Changed = false;
2172   for (auto Op : expr_ops()) {
2173     switch (Op.getOp()) {
2174     default:
2175       // We fold only the leading part of the expression; if we get to a part
2176       // that we're going to copy unchanged, and haven't done any folding,
2177       // then the entire expression is unchanged and we can return early.
2178       if (!Changed)
2179         return {this, CI};
2180       First = false;
2181       break;
2182     case dwarf::DW_OP_LLVM_convert:
2183       if (!First)
2184         break;
2185       Changed = true;
2186       if (Op.getArg(1) == dwarf::DW_ATE_signed)
2187         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
2188       else {
2189         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
2190         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
2191       }
2192       continue;
2193     }
2194     Op.appendToVector(Ops);
2195   }
2196   if (!Changed)
2197     return {this, CI};
2198   return {DIExpression::get(getContext(), Ops),
2199           ConstantInt::get(getContext(), NewInt)};
2200 }
2201 
getNumLocationOperands() const2202 uint64_t DIExpression::getNumLocationOperands() const {
2203   uint64_t Result = 0;
2204   for (auto ExprOp : expr_ops())
2205     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
2206       Result = std::max(Result, ExprOp.getArg(0) + 1);
2207   assert(hasAllLocationOps(Result) &&
2208          "Expression is missing one or more location operands.");
2209   return Result;
2210 }
2211 
2212 std::optional<DIExpression::SignedOrUnsignedConstant>
isConstant() const2213 DIExpression::isConstant() const {
2214 
2215   // Recognize signed and unsigned constants.
2216   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
2217   // (DW_OP_LLVM_fragment of Len).
2218   // An unsigned constant can be represented as
2219   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
2220 
2221   if ((getNumElements() != 2 && getNumElements() != 3 &&
2222        getNumElements() != 6) ||
2223       (getElement(0) != dwarf::DW_OP_consts &&
2224        getElement(0) != dwarf::DW_OP_constu))
2225     return std::nullopt;
2226 
2227   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
2228     return SignedOrUnsignedConstant::SignedConstant;
2229 
2230   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
2231       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
2232                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
2233     return std::nullopt;
2234   return getElement(0) == dwarf::DW_OP_constu
2235              ? SignedOrUnsignedConstant::UnsignedConstant
2236              : SignedOrUnsignedConstant::SignedConstant;
2237 }
2238 
getExtOps(unsigned FromSize,unsigned ToSize,bool Signed)2239 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
2240                                              bool Signed) {
2241   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
2242   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
2243                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
2244   return Ops;
2245 }
2246 
appendExt(const DIExpression * Expr,unsigned FromSize,unsigned ToSize,bool Signed)2247 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
2248                                       unsigned FromSize, unsigned ToSize,
2249                                       bool Signed) {
2250   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
2251 }
2252 
2253 DIGlobalVariableExpression *
getImpl(LLVMContext & Context,Metadata * Variable,Metadata * Expression,StorageType Storage,bool ShouldCreate)2254 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
2255                                     Metadata *Expression, StorageType Storage,
2256                                     bool ShouldCreate) {
2257   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
2258   Metadata *Ops[] = {Variable, Expression};
2259   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
2260 }
DIObjCProperty(LLVMContext & C,StorageType Storage,unsigned Line,unsigned Attributes,ArrayRef<Metadata * > Ops)2261 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage,
2262                                unsigned Line, unsigned Attributes,
2263                                ArrayRef<Metadata *> Ops)
2264     : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops),
2265       Line(Line), Attributes(Attributes) {}
2266 
getImpl(LLVMContext & Context,MDString * Name,Metadata * File,unsigned Line,MDString * GetterName,MDString * SetterName,unsigned Attributes,Metadata * Type,StorageType Storage,bool ShouldCreate)2267 DIObjCProperty *DIObjCProperty::getImpl(
2268     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
2269     MDString *GetterName, MDString *SetterName, unsigned Attributes,
2270     Metadata *Type, StorageType Storage, bool ShouldCreate) {
2271   assert(isCanonical(Name) && "Expected canonical MDString");
2272   assert(isCanonical(GetterName) && "Expected canonical MDString");
2273   assert(isCanonical(SetterName) && "Expected canonical MDString");
2274   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
2275                                          SetterName, Attributes, Type));
2276   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
2277   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
2278 }
2279 
getImpl(LLVMContext & Context,unsigned Tag,Metadata * Scope,Metadata * Entity,Metadata * File,unsigned Line,MDString * Name,Metadata * Elements,StorageType Storage,bool ShouldCreate)2280 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
2281                                             Metadata *Scope, Metadata *Entity,
2282                                             Metadata *File, unsigned Line,
2283                                             MDString *Name, Metadata *Elements,
2284                                             StorageType Storage,
2285                                             bool ShouldCreate) {
2286   assert(isCanonical(Name) && "Expected canonical MDString");
2287   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
2288                         (Tag, Scope, Entity, File, Line, Name, Elements));
2289   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
2290   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
2291 }
2292 
getImpl(LLVMContext & Context,unsigned MIType,unsigned Line,MDString * Name,MDString * Value,StorageType Storage,bool ShouldCreate)2293 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
2294                           MDString *Name, MDString *Value, StorageType Storage,
2295                           bool ShouldCreate) {
2296   assert(isCanonical(Name) && "Expected canonical MDString");
2297   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
2298   Metadata *Ops[] = {Name, Value};
2299   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
2300 }
2301 
getImpl(LLVMContext & Context,unsigned MIType,unsigned Line,Metadata * File,Metadata * Elements,StorageType Storage,bool ShouldCreate)2302 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
2303                                   unsigned Line, Metadata *File,
2304                                   Metadata *Elements, StorageType Storage,
2305                                   bool ShouldCreate) {
2306   DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements));
2307   Metadata *Ops[] = {File, Elements};
2308   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
2309 }
2310 
get(LLVMContext & Context,ArrayRef<ValueAsMetadata * > Args)2311 DIArgList *DIArgList::get(LLVMContext &Context,
2312                           ArrayRef<ValueAsMetadata *> Args) {
2313   auto ExistingIt = Context.pImpl->DIArgLists.find_as(DIArgListKeyInfo(Args));
2314   if (ExistingIt != Context.pImpl->DIArgLists.end())
2315     return *ExistingIt;
2316   DIArgList *NewArgList = new DIArgList(Context, Args);
2317   Context.pImpl->DIArgLists.insert(NewArgList);
2318   return NewArgList;
2319 }
2320 
handleChangedOperand(void * Ref,Metadata * New)2321 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
2322   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
2323   assert((!New || isa<ValueAsMetadata>(New)) &&
2324          "DIArgList must be passed a ValueAsMetadata");
2325   untrack();
2326   // We need to update the set storage once the Args are updated since they
2327   // form the key to the DIArgLists store.
2328   getContext().pImpl->DIArgLists.erase(this);
2329   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
2330   for (ValueAsMetadata *&VM : Args) {
2331     if (&VM == OldVMPtr) {
2332       if (NewVM)
2333         VM = NewVM;
2334       else
2335         VM = ValueAsMetadata::get(PoisonValue::get(VM->getValue()->getType()));
2336     }
2337   }
2338   // We've changed the contents of this DIArgList, and the set storage may
2339   // already contain a DIArgList with our new set of args; if it does, then we
2340   // must RAUW this with the existing DIArgList, otherwise we simply insert this
2341   // back into the set storage.
2342   DIArgList *ExistingArgList = getUniqued(getContext().pImpl->DIArgLists, this);
2343   if (ExistingArgList) {
2344     replaceAllUsesWith(ExistingArgList);
2345     // Clear this here so we don't try to untrack in the destructor.
2346     Args.clear();
2347     delete this;
2348     return;
2349   }
2350   getContext().pImpl->DIArgLists.insert(this);
2351   track();
2352 }
track()2353 void DIArgList::track() {
2354   for (ValueAsMetadata *&VAM : Args)
2355     if (VAM)
2356       MetadataTracking::track(&VAM, *VAM, *this);
2357 }
untrack()2358 void DIArgList::untrack() {
2359   for (ValueAsMetadata *&VAM : Args)
2360     if (VAM)
2361       MetadataTracking::untrack(&VAM, *VAM);
2362 }
dropAllReferences(bool Untrack)2363 void DIArgList::dropAllReferences(bool Untrack) {
2364   if (Untrack)
2365     untrack();
2366   Args.clear();
2367   ReplaceableMetadataImpl::resolveAllUses(/* ResolveUsers */ false);
2368 }
2369