1 //===- DebugInfoMetadata.cpp - Implement debug info metadata --------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the debug info Metadata classes.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "LLVMContextImpl.h"
15 #include "MetadataImpl.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/BinaryFormat/Dwarf.h"
19 #include "llvm/IR/Function.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/IR/Value.h"
22 
23 #include <numeric>
24 
25 using namespace llvm;
26 
27 namespace llvm {
28 // Use FS-AFDO discriminator.
29 cl::opt<bool> EnableFSDiscriminator(
30     "enable-fs-discriminator", cl::Hidden, cl::init(false), cl::ZeroOrMore,
31     cl::desc("Enable adding flow sensitive discriminators"));
32 } // namespace llvm
33 
34 const DIExpression::FragmentInfo DebugVariable::DefaultFragment = {
35     std::numeric_limits<uint64_t>::max(), std::numeric_limits<uint64_t>::min()};
36 
37 DILocation::DILocation(LLVMContext &C, StorageType Storage, unsigned Line,
38                        unsigned Column, ArrayRef<Metadata *> MDs,
39                        bool ImplicitCode)
40     : MDNode(C, DILocationKind, Storage, MDs) {
41   assert((MDs.size() == 1 || MDs.size() == 2) &&
42          "Expected a scope and optional inlined-at");
43 
44   // Set line and column.
45   assert(Column < (1u << 16) && "Expected 16-bit column");
46 
47   SubclassData32 = Line;
48   SubclassData16 = Column;
49 
50   setImplicitCode(ImplicitCode);
51 }
52 
53 static void adjustColumn(unsigned &Column) {
54   // Set to unknown on overflow.  We only have 16 bits to play with here.
55   if (Column >= (1u << 16))
56     Column = 0;
57 }
58 
59 DILocation *DILocation::getImpl(LLVMContext &Context, unsigned Line,
60                                 unsigned Column, Metadata *Scope,
61                                 Metadata *InlinedAt, bool ImplicitCode,
62                                 StorageType Storage, bool ShouldCreate) {
63   // Fixup column.
64   adjustColumn(Column);
65 
66   if (Storage == Uniqued) {
67     if (auto *N = getUniqued(Context.pImpl->DILocations,
68                              DILocationInfo::KeyTy(Line, Column, Scope,
69                                                    InlinedAt, ImplicitCode)))
70       return N;
71     if (!ShouldCreate)
72       return nullptr;
73   } else {
74     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
75   }
76 
77   SmallVector<Metadata *, 2> Ops;
78   Ops.push_back(Scope);
79   if (InlinedAt)
80     Ops.push_back(InlinedAt);
81   return storeImpl(new (Ops.size()) DILocation(Context, Storage, Line, Column,
82                                                Ops, ImplicitCode),
83                    Storage, Context.pImpl->DILocations);
84 }
85 
86 const DILocation *
87 DILocation::getMergedLocations(ArrayRef<const DILocation *> Locs) {
88   if (Locs.empty())
89     return nullptr;
90   if (Locs.size() == 1)
91     return Locs[0];
92   auto *Merged = Locs[0];
93   for (const DILocation *L : llvm::drop_begin(Locs)) {
94     Merged = getMergedLocation(Merged, L);
95     if (Merged == nullptr)
96       break;
97   }
98   return Merged;
99 }
100 
101 const DILocation *DILocation::getMergedLocation(const DILocation *LocA,
102                                                 const DILocation *LocB) {
103   if (!LocA || !LocB)
104     return nullptr;
105 
106   if (LocA == LocB)
107     return LocA;
108 
109   SmallPtrSet<DILocation *, 5> InlinedLocationsA;
110   for (DILocation *L = LocA->getInlinedAt(); L; L = L->getInlinedAt())
111     InlinedLocationsA.insert(L);
112   SmallSet<std::pair<DIScope *, DILocation *>, 5> Locations;
113   DIScope *S = LocA->getScope();
114   DILocation *L = LocA->getInlinedAt();
115   while (S) {
116     Locations.insert(std::make_pair(S, L));
117     S = S->getScope();
118     if (!S && L) {
119       S = L->getScope();
120       L = L->getInlinedAt();
121     }
122   }
123   const DILocation *Result = LocB;
124   S = LocB->getScope();
125   L = LocB->getInlinedAt();
126   while (S) {
127     if (Locations.count(std::make_pair(S, L)))
128       break;
129     S = S->getScope();
130     if (!S && L) {
131       S = L->getScope();
132       L = L->getInlinedAt();
133     }
134   }
135 
136   // If the two locations are irreconsilable, just pick one. This is misleading,
137   // but on the other hand, it's a "line 0" location.
138   if (!S || !isa<DILocalScope>(S))
139     S = LocA->getScope();
140   return DILocation::get(Result->getContext(), 0, 0, S, L);
141 }
142 
143 Optional<unsigned> DILocation::encodeDiscriminator(unsigned BD, unsigned DF,
144                                                    unsigned CI) {
145   std::array<unsigned, 3> Components = {BD, DF, CI};
146   uint64_t RemainingWork = 0U;
147   // We use RemainingWork to figure out if we have no remaining components to
148   // encode. For example: if BD != 0 but DF == 0 && CI == 0, we don't need to
149   // encode anything for the latter 2.
150   // Since any of the input components is at most 32 bits, their sum will be
151   // less than 34 bits, and thus RemainingWork won't overflow.
152   RemainingWork =
153       std::accumulate(Components.begin(), Components.end(), RemainingWork);
154 
155   int I = 0;
156   unsigned Ret = 0;
157   unsigned NextBitInsertionIndex = 0;
158   while (RemainingWork > 0) {
159     unsigned C = Components[I++];
160     RemainingWork -= C;
161     unsigned EC = encodeComponent(C);
162     Ret |= (EC << NextBitInsertionIndex);
163     NextBitInsertionIndex += encodingBits(C);
164   }
165 
166   // Encoding may be unsuccessful because of overflow. We determine success by
167   // checking equivalence of components before & after encoding. Alternatively,
168   // we could determine Success during encoding, but the current alternative is
169   // simpler.
170   unsigned TBD, TDF, TCI = 0;
171   decodeDiscriminator(Ret, TBD, TDF, TCI);
172   if (TBD == BD && TDF == DF && TCI == CI)
173     return Ret;
174   return None;
175 }
176 
177 void DILocation::decodeDiscriminator(unsigned D, unsigned &BD, unsigned &DF,
178                                      unsigned &CI) {
179   BD = getUnsignedFromPrefixEncoding(D);
180   DF = getUnsignedFromPrefixEncoding(getNextComponentInDiscriminator(D));
181   CI = getUnsignedFromPrefixEncoding(
182       getNextComponentInDiscriminator(getNextComponentInDiscriminator(D)));
183 }
184 dwarf::Tag DINode::getTag() const { return (dwarf::Tag)SubclassData16; }
185 
186 DINode::DIFlags DINode::getFlag(StringRef Flag) {
187   return StringSwitch<DIFlags>(Flag)
188 #define HANDLE_DI_FLAG(ID, NAME) .Case("DIFlag" #NAME, Flag##NAME)
189 #include "llvm/IR/DebugInfoFlags.def"
190       .Default(DINode::FlagZero);
191 }
192 
193 StringRef DINode::getFlagString(DIFlags Flag) {
194   switch (Flag) {
195 #define HANDLE_DI_FLAG(ID, NAME)                                               \
196   case Flag##NAME:                                                             \
197     return "DIFlag" #NAME;
198 #include "llvm/IR/DebugInfoFlags.def"
199   }
200   return "";
201 }
202 
203 DINode::DIFlags DINode::splitFlags(DIFlags Flags,
204                                    SmallVectorImpl<DIFlags> &SplitFlags) {
205   // Flags that are packed together need to be specially handled, so
206   // that, for example, we emit "DIFlagPublic" and not
207   // "DIFlagPrivate | DIFlagProtected".
208   if (DIFlags A = Flags & FlagAccessibility) {
209     if (A == FlagPrivate)
210       SplitFlags.push_back(FlagPrivate);
211     else if (A == FlagProtected)
212       SplitFlags.push_back(FlagProtected);
213     else
214       SplitFlags.push_back(FlagPublic);
215     Flags &= ~A;
216   }
217   if (DIFlags R = Flags & FlagPtrToMemberRep) {
218     if (R == FlagSingleInheritance)
219       SplitFlags.push_back(FlagSingleInheritance);
220     else if (R == FlagMultipleInheritance)
221       SplitFlags.push_back(FlagMultipleInheritance);
222     else
223       SplitFlags.push_back(FlagVirtualInheritance);
224     Flags &= ~R;
225   }
226   if ((Flags & FlagIndirectVirtualBase) == FlagIndirectVirtualBase) {
227     Flags &= ~FlagIndirectVirtualBase;
228     SplitFlags.push_back(FlagIndirectVirtualBase);
229   }
230 
231 #define HANDLE_DI_FLAG(ID, NAME)                                               \
232   if (DIFlags Bit = Flags & Flag##NAME) {                                      \
233     SplitFlags.push_back(Bit);                                                 \
234     Flags &= ~Bit;                                                             \
235   }
236 #include "llvm/IR/DebugInfoFlags.def"
237   return Flags;
238 }
239 
240 DIScope *DIScope::getScope() const {
241   if (auto *T = dyn_cast<DIType>(this))
242     return T->getScope();
243 
244   if (auto *SP = dyn_cast<DISubprogram>(this))
245     return SP->getScope();
246 
247   if (auto *LB = dyn_cast<DILexicalBlockBase>(this))
248     return LB->getScope();
249 
250   if (auto *NS = dyn_cast<DINamespace>(this))
251     return NS->getScope();
252 
253   if (auto *CB = dyn_cast<DICommonBlock>(this))
254     return CB->getScope();
255 
256   if (auto *M = dyn_cast<DIModule>(this))
257     return M->getScope();
258 
259   assert((isa<DIFile>(this) || isa<DICompileUnit>(this)) &&
260          "Unhandled type of scope.");
261   return nullptr;
262 }
263 
264 StringRef DIScope::getName() const {
265   if (auto *T = dyn_cast<DIType>(this))
266     return T->getName();
267   if (auto *SP = dyn_cast<DISubprogram>(this))
268     return SP->getName();
269   if (auto *NS = dyn_cast<DINamespace>(this))
270     return NS->getName();
271   if (auto *CB = dyn_cast<DICommonBlock>(this))
272     return CB->getName();
273   if (auto *M = dyn_cast<DIModule>(this))
274     return M->getName();
275   assert((isa<DILexicalBlockBase>(this) || isa<DIFile>(this) ||
276           isa<DICompileUnit>(this)) &&
277          "Unhandled type of scope.");
278   return "";
279 }
280 
281 #ifndef NDEBUG
282 static bool isCanonical(const MDString *S) {
283   return !S || !S->getString().empty();
284 }
285 #endif
286 
287 dwarf::Tag GenericDINode::getTag() const { return (dwarf::Tag)SubclassData16; }
288 GenericDINode *GenericDINode::getImpl(LLVMContext &Context, unsigned Tag,
289                                       MDString *Header,
290                                       ArrayRef<Metadata *> DwarfOps,
291                                       StorageType Storage, bool ShouldCreate) {
292   unsigned Hash = 0;
293   if (Storage == Uniqued) {
294     GenericDINodeInfo::KeyTy Key(Tag, Header, DwarfOps);
295     if (auto *N = getUniqued(Context.pImpl->GenericDINodes, Key))
296       return N;
297     if (!ShouldCreate)
298       return nullptr;
299     Hash = Key.getHash();
300   } else {
301     assert(ShouldCreate && "Expected non-uniqued nodes to always be created");
302   }
303 
304   // Use a nullptr for empty headers.
305   assert(isCanonical(Header) && "Expected canonical MDString");
306   Metadata *PreOps[] = {Header};
307   return storeImpl(new (DwarfOps.size() + 1) GenericDINode(
308                        Context, Storage, Hash, Tag, PreOps, DwarfOps),
309                    Storage, Context.pImpl->GenericDINodes);
310 }
311 
312 void GenericDINode::recalculateHash() {
313   setHash(GenericDINodeInfo::KeyTy::calculateHash(this));
314 }
315 
316 #define UNWRAP_ARGS_IMPL(...) __VA_ARGS__
317 #define UNWRAP_ARGS(ARGS) UNWRAP_ARGS_IMPL ARGS
318 #define DEFINE_GETIMPL_LOOKUP(CLASS, ARGS)                                     \
319   do {                                                                         \
320     if (Storage == Uniqued) {                                                  \
321       if (auto *N = getUniqued(Context.pImpl->CLASS##s,                        \
322                                CLASS##Info::KeyTy(UNWRAP_ARGS(ARGS))))         \
323         return N;                                                              \
324       if (!ShouldCreate)                                                       \
325         return nullptr;                                                        \
326     } else {                                                                   \
327       assert(ShouldCreate &&                                                   \
328              "Expected non-uniqued nodes to always be created");               \
329     }                                                                          \
330   } while (false)
331 #define DEFINE_GETIMPL_STORE(CLASS, ARGS, OPS)                                 \
332   return storeImpl(new (array_lengthof(OPS))                                   \
333                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
334                    Storage, Context.pImpl->CLASS##s)
335 #define DEFINE_GETIMPL_STORE_NO_OPS(CLASS, ARGS)                               \
336   return storeImpl(new (0u) CLASS(Context, Storage, UNWRAP_ARGS(ARGS)),        \
337                    Storage, Context.pImpl->CLASS##s)
338 #define DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(CLASS, OPS)                   \
339   return storeImpl(new (array_lengthof(OPS)) CLASS(Context, Storage, OPS),     \
340                    Storage, Context.pImpl->CLASS##s)
341 #define DEFINE_GETIMPL_STORE_N(CLASS, ARGS, OPS, NUM_OPS)                      \
342   return storeImpl(new (NUM_OPS)                                               \
343                        CLASS(Context, Storage, UNWRAP_ARGS(ARGS), OPS),        \
344                    Storage, Context.pImpl->CLASS##s)
345 
346 DISubrange::DISubrange(LLVMContext &C, StorageType Storage,
347                        ArrayRef<Metadata *> Ops)
348     : DINode(C, DISubrangeKind, Storage, dwarf::DW_TAG_subrange_type, Ops) {}
349 DISubrange *DISubrange::getImpl(LLVMContext &Context, int64_t Count, int64_t Lo,
350                                 StorageType Storage, bool ShouldCreate) {
351   auto *CountNode = ConstantAsMetadata::get(
352       ConstantInt::getSigned(Type::getInt64Ty(Context), Count));
353   auto *LB = ConstantAsMetadata::get(
354       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
355   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
356                  ShouldCreate);
357 }
358 
359 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
360                                 int64_t Lo, StorageType Storage,
361                                 bool ShouldCreate) {
362   auto *LB = ConstantAsMetadata::get(
363       ConstantInt::getSigned(Type::getInt64Ty(Context), Lo));
364   return getImpl(Context, CountNode, LB, nullptr, nullptr, Storage,
365                  ShouldCreate);
366 }
367 
368 DISubrange *DISubrange::getImpl(LLVMContext &Context, Metadata *CountNode,
369                                 Metadata *LB, Metadata *UB, Metadata *Stride,
370                                 StorageType Storage, bool ShouldCreate) {
371   DEFINE_GETIMPL_LOOKUP(DISubrange, (CountNode, LB, UB, Stride));
372   Metadata *Ops[] = {CountNode, LB, UB, Stride};
373   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DISubrange, Ops);
374 }
375 
376 DISubrange::BoundType DISubrange::getCount() const {
377   Metadata *CB = getRawCountNode();
378   if (!CB)
379     return BoundType();
380 
381   assert((isa<ConstantAsMetadata>(CB) || isa<DIVariable>(CB) ||
382           isa<DIExpression>(CB)) &&
383          "Count must be signed constant or DIVariable or DIExpression");
384 
385   if (auto *MD = dyn_cast<ConstantAsMetadata>(CB))
386     return BoundType(cast<ConstantInt>(MD->getValue()));
387 
388   if (auto *MD = dyn_cast<DIVariable>(CB))
389     return BoundType(MD);
390 
391   if (auto *MD = dyn_cast<DIExpression>(CB))
392     return BoundType(MD);
393 
394   return BoundType();
395 }
396 
397 DISubrange::BoundType DISubrange::getLowerBound() const {
398   Metadata *LB = getRawLowerBound();
399   if (!LB)
400     return BoundType();
401 
402   assert((isa<ConstantAsMetadata>(LB) || isa<DIVariable>(LB) ||
403           isa<DIExpression>(LB)) &&
404          "LowerBound must be signed constant or DIVariable or DIExpression");
405 
406   if (auto *MD = dyn_cast<ConstantAsMetadata>(LB))
407     return BoundType(cast<ConstantInt>(MD->getValue()));
408 
409   if (auto *MD = dyn_cast<DIVariable>(LB))
410     return BoundType(MD);
411 
412   if (auto *MD = dyn_cast<DIExpression>(LB))
413     return BoundType(MD);
414 
415   return BoundType();
416 }
417 
418 DISubrange::BoundType DISubrange::getUpperBound() const {
419   Metadata *UB = getRawUpperBound();
420   if (!UB)
421     return BoundType();
422 
423   assert((isa<ConstantAsMetadata>(UB) || isa<DIVariable>(UB) ||
424           isa<DIExpression>(UB)) &&
425          "UpperBound must be signed constant or DIVariable or DIExpression");
426 
427   if (auto *MD = dyn_cast<ConstantAsMetadata>(UB))
428     return BoundType(cast<ConstantInt>(MD->getValue()));
429 
430   if (auto *MD = dyn_cast<DIVariable>(UB))
431     return BoundType(MD);
432 
433   if (auto *MD = dyn_cast<DIExpression>(UB))
434     return BoundType(MD);
435 
436   return BoundType();
437 }
438 
439 DISubrange::BoundType DISubrange::getStride() const {
440   Metadata *ST = getRawStride();
441   if (!ST)
442     return BoundType();
443 
444   assert((isa<ConstantAsMetadata>(ST) || isa<DIVariable>(ST) ||
445           isa<DIExpression>(ST)) &&
446          "Stride must be signed constant or DIVariable or DIExpression");
447 
448   if (auto *MD = dyn_cast<ConstantAsMetadata>(ST))
449     return BoundType(cast<ConstantInt>(MD->getValue()));
450 
451   if (auto *MD = dyn_cast<DIVariable>(ST))
452     return BoundType(MD);
453 
454   if (auto *MD = dyn_cast<DIExpression>(ST))
455     return BoundType(MD);
456 
457   return BoundType();
458 }
459 DIGenericSubrange::DIGenericSubrange(LLVMContext &C, StorageType Storage,
460                                      ArrayRef<Metadata *> Ops)
461     : DINode(C, DIGenericSubrangeKind, Storage, dwarf::DW_TAG_generic_subrange,
462              Ops) {}
463 
464 DIGenericSubrange *DIGenericSubrange::getImpl(LLVMContext &Context,
465                                               Metadata *CountNode, Metadata *LB,
466                                               Metadata *UB, Metadata *Stride,
467                                               StorageType Storage,
468                                               bool ShouldCreate) {
469   DEFINE_GETIMPL_LOOKUP(DIGenericSubrange, (CountNode, LB, UB, Stride));
470   Metadata *Ops[] = {CountNode, LB, UB, Stride};
471   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGenericSubrange, Ops);
472 }
473 
474 DIGenericSubrange::BoundType DIGenericSubrange::getCount() const {
475   Metadata *CB = getRawCountNode();
476   if (!CB)
477     return BoundType();
478 
479   assert((isa<DIVariable>(CB) || isa<DIExpression>(CB)) &&
480          "Count must be signed constant or DIVariable or DIExpression");
481 
482   if (auto *MD = dyn_cast<DIVariable>(CB))
483     return BoundType(MD);
484 
485   if (auto *MD = dyn_cast<DIExpression>(CB))
486     return BoundType(MD);
487 
488   return BoundType();
489 }
490 
491 DIGenericSubrange::BoundType DIGenericSubrange::getLowerBound() const {
492   Metadata *LB = getRawLowerBound();
493   if (!LB)
494     return BoundType();
495 
496   assert((isa<DIVariable>(LB) || isa<DIExpression>(LB)) &&
497          "LowerBound must be signed constant or DIVariable or DIExpression");
498 
499   if (auto *MD = dyn_cast<DIVariable>(LB))
500     return BoundType(MD);
501 
502   if (auto *MD = dyn_cast<DIExpression>(LB))
503     return BoundType(MD);
504 
505   return BoundType();
506 }
507 
508 DIGenericSubrange::BoundType DIGenericSubrange::getUpperBound() const {
509   Metadata *UB = getRawUpperBound();
510   if (!UB)
511     return BoundType();
512 
513   assert((isa<DIVariable>(UB) || isa<DIExpression>(UB)) &&
514          "UpperBound must be signed constant or DIVariable or DIExpression");
515 
516   if (auto *MD = dyn_cast<DIVariable>(UB))
517     return BoundType(MD);
518 
519   if (auto *MD = dyn_cast<DIExpression>(UB))
520     return BoundType(MD);
521 
522   return BoundType();
523 }
524 
525 DIGenericSubrange::BoundType DIGenericSubrange::getStride() const {
526   Metadata *ST = getRawStride();
527   if (!ST)
528     return BoundType();
529 
530   assert((isa<DIVariable>(ST) || isa<DIExpression>(ST)) &&
531          "Stride must be signed constant or DIVariable or DIExpression");
532 
533   if (auto *MD = dyn_cast<DIVariable>(ST))
534     return BoundType(MD);
535 
536   if (auto *MD = dyn_cast<DIExpression>(ST))
537     return BoundType(MD);
538 
539   return BoundType();
540 }
541 
542 DIEnumerator::DIEnumerator(LLVMContext &C, StorageType Storage,
543                            const APInt &Value, bool IsUnsigned,
544                            ArrayRef<Metadata *> Ops)
545     : DINode(C, DIEnumeratorKind, Storage, dwarf::DW_TAG_enumerator, Ops),
546       Value(Value) {
547   SubclassData32 = IsUnsigned;
548 }
549 DIEnumerator *DIEnumerator::getImpl(LLVMContext &Context, const APInt &Value,
550                                     bool IsUnsigned, MDString *Name,
551                                     StorageType Storage, bool ShouldCreate) {
552   assert(isCanonical(Name) && "Expected canonical MDString");
553   DEFINE_GETIMPL_LOOKUP(DIEnumerator, (Value, IsUnsigned, Name));
554   Metadata *Ops[] = {Name};
555   DEFINE_GETIMPL_STORE(DIEnumerator, (Value, IsUnsigned), Ops);
556 }
557 
558 DIBasicType *DIBasicType::getImpl(LLVMContext &Context, unsigned Tag,
559                                   MDString *Name, uint64_t SizeInBits,
560                                   uint32_t AlignInBits, unsigned Encoding,
561                                   DIFlags Flags, StorageType Storage,
562                                   bool ShouldCreate) {
563   assert(isCanonical(Name) && "Expected canonical MDString");
564   DEFINE_GETIMPL_LOOKUP(DIBasicType,
565                         (Tag, Name, SizeInBits, AlignInBits, Encoding, Flags));
566   Metadata *Ops[] = {nullptr, nullptr, Name};
567   DEFINE_GETIMPL_STORE(DIBasicType,
568                        (Tag, SizeInBits, AlignInBits, Encoding, Flags), Ops);
569 }
570 
571 Optional<DIBasicType::Signedness> DIBasicType::getSignedness() const {
572   switch (getEncoding()) {
573   case dwarf::DW_ATE_signed:
574   case dwarf::DW_ATE_signed_char:
575     return Signedness::Signed;
576   case dwarf::DW_ATE_unsigned:
577   case dwarf::DW_ATE_unsigned_char:
578     return Signedness::Unsigned;
579   default:
580     return None;
581   }
582 }
583 
584 DIStringType *DIStringType::getImpl(LLVMContext &Context, unsigned Tag,
585                                     MDString *Name, Metadata *StringLength,
586                                     Metadata *StringLengthExp,
587                                     Metadata *StringLocationExp,
588                                     uint64_t SizeInBits, uint32_t AlignInBits,
589                                     unsigned Encoding, StorageType Storage,
590                                     bool ShouldCreate) {
591   assert(isCanonical(Name) && "Expected canonical MDString");
592   DEFINE_GETIMPL_LOOKUP(DIStringType,
593                         (Tag, Name, StringLength, StringLengthExp,
594                          StringLocationExp, SizeInBits, AlignInBits, Encoding));
595   Metadata *Ops[] = {nullptr,      nullptr,         Name,
596                      StringLength, StringLengthExp, StringLocationExp};
597   DEFINE_GETIMPL_STORE(DIStringType, (Tag, SizeInBits, AlignInBits, Encoding),
598                        Ops);
599 }
600 DIType *DIDerivedType::getClassType() const {
601   assert(getTag() == dwarf::DW_TAG_ptr_to_member_type);
602   return cast_or_null<DIType>(getExtraData());
603 }
604 uint32_t DIDerivedType::getVBPtrOffset() const {
605   assert(getTag() == dwarf::DW_TAG_inheritance);
606   if (auto *CM = cast_or_null<ConstantAsMetadata>(getExtraData()))
607     if (auto *CI = dyn_cast_or_null<ConstantInt>(CM->getValue()))
608       return static_cast<uint32_t>(CI->getZExtValue());
609   return 0;
610 }
611 Constant *DIDerivedType::getStorageOffsetInBits() const {
612   assert(getTag() == dwarf::DW_TAG_member && isBitField());
613   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
614     return C->getValue();
615   return nullptr;
616 }
617 
618 Constant *DIDerivedType::getConstant() const {
619   assert(getTag() == dwarf::DW_TAG_member && isStaticMember());
620   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
621     return C->getValue();
622   return nullptr;
623 }
624 Constant *DIDerivedType::getDiscriminantValue() const {
625   assert(getTag() == dwarf::DW_TAG_member && !isStaticMember());
626   if (auto *C = cast_or_null<ConstantAsMetadata>(getExtraData()))
627     return C->getValue();
628   return nullptr;
629 }
630 
631 DIDerivedType *DIDerivedType::getImpl(
632     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
633     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
634     uint32_t AlignInBits, uint64_t OffsetInBits,
635     Optional<unsigned> DWARFAddressSpace, DIFlags Flags, Metadata *ExtraData,
636     Metadata *Annotations, StorageType Storage, bool ShouldCreate) {
637   assert(isCanonical(Name) && "Expected canonical MDString");
638   DEFINE_GETIMPL_LOOKUP(DIDerivedType,
639                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
640                          AlignInBits, OffsetInBits, DWARFAddressSpace, Flags,
641                          ExtraData, Annotations));
642   Metadata *Ops[] = {File, Scope, Name, BaseType, ExtraData, Annotations};
643   DEFINE_GETIMPL_STORE(DIDerivedType,
644                        (Tag, Line, SizeInBits, AlignInBits, OffsetInBits,
645                         DWARFAddressSpace, Flags),
646                        Ops);
647 }
648 
649 DICompositeType *DICompositeType::getImpl(
650     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *File,
651     unsigned Line, Metadata *Scope, Metadata *BaseType, uint64_t SizeInBits,
652     uint32_t AlignInBits, uint64_t OffsetInBits, DIFlags Flags,
653     Metadata *Elements, unsigned RuntimeLang, Metadata *VTableHolder,
654     Metadata *TemplateParams, MDString *Identifier, Metadata *Discriminator,
655     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
656     Metadata *Rank, Metadata *Annotations, StorageType Storage,
657     bool ShouldCreate) {
658   assert(isCanonical(Name) && "Expected canonical MDString");
659 
660   // Keep this in sync with buildODRType.
661   DEFINE_GETIMPL_LOOKUP(DICompositeType,
662                         (Tag, Name, File, Line, Scope, BaseType, SizeInBits,
663                          AlignInBits, OffsetInBits, Flags, Elements,
664                          RuntimeLang, VTableHolder, TemplateParams, Identifier,
665                          Discriminator, DataLocation, Associated, Allocated,
666                          Rank, Annotations));
667   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
668                      Elements,      VTableHolder, TemplateParams, Identifier,
669                      Discriminator, DataLocation, Associated,     Allocated,
670                      Rank,          Annotations};
671   DEFINE_GETIMPL_STORE(
672       DICompositeType,
673       (Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits, Flags),
674       Ops);
675 }
676 
677 DICompositeType *DICompositeType::buildODRType(
678     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
679     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
680     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
681     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
682     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
683     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
684     Metadata *Rank, Metadata *Annotations) {
685   assert(!Identifier.getString().empty() && "Expected valid identifier");
686   if (!Context.isODRUniquingDebugTypes())
687     return nullptr;
688   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
689   if (!CT)
690     return CT = DICompositeType::getDistinct(
691                Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
692                AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
693                VTableHolder, TemplateParams, &Identifier, Discriminator,
694                DataLocation, Associated, Allocated, Rank, Annotations);
695 
696   if (CT->getTag() != Tag)
697     return nullptr;
698 
699   // Only mutate CT if it's a forward declaration and the new operands aren't.
700   assert(CT->getRawIdentifier() == &Identifier && "Wrong ODR identifier?");
701   if (!CT->isForwardDecl() || (Flags & DINode::FlagFwdDecl))
702     return CT;
703 
704   // Mutate CT in place.  Keep this in sync with getImpl.
705   CT->mutate(Tag, Line, RuntimeLang, SizeInBits, AlignInBits, OffsetInBits,
706              Flags);
707   Metadata *Ops[] = {File,          Scope,        Name,           BaseType,
708                      Elements,      VTableHolder, TemplateParams, &Identifier,
709                      Discriminator, DataLocation, Associated,     Allocated,
710                      Rank,          Annotations};
711   assert((std::end(Ops) - std::begin(Ops)) == (int)CT->getNumOperands() &&
712          "Mismatched number of operands");
713   for (unsigned I = 0, E = CT->getNumOperands(); I != E; ++I)
714     if (Ops[I] != CT->getOperand(I))
715       CT->setOperand(I, Ops[I]);
716   return CT;
717 }
718 
719 DICompositeType *DICompositeType::getODRType(
720     LLVMContext &Context, MDString &Identifier, unsigned Tag, MDString *Name,
721     Metadata *File, unsigned Line, Metadata *Scope, Metadata *BaseType,
722     uint64_t SizeInBits, uint32_t AlignInBits, uint64_t OffsetInBits,
723     DIFlags Flags, Metadata *Elements, unsigned RuntimeLang,
724     Metadata *VTableHolder, Metadata *TemplateParams, Metadata *Discriminator,
725     Metadata *DataLocation, Metadata *Associated, Metadata *Allocated,
726     Metadata *Rank, Metadata *Annotations) {
727   assert(!Identifier.getString().empty() && "Expected valid identifier");
728   if (!Context.isODRUniquingDebugTypes())
729     return nullptr;
730   auto *&CT = (*Context.pImpl->DITypeMap)[&Identifier];
731   if (!CT) {
732     CT = DICompositeType::getDistinct(
733         Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
734         AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, VTableHolder,
735         TemplateParams, &Identifier, Discriminator, DataLocation, Associated,
736         Allocated, Rank, Annotations);
737   } else {
738     if (CT->getTag() != Tag)
739       return nullptr;
740   }
741   return CT;
742 }
743 
744 DICompositeType *DICompositeType::getODRTypeIfExists(LLVMContext &Context,
745                                                      MDString &Identifier) {
746   assert(!Identifier.getString().empty() && "Expected valid identifier");
747   if (!Context.isODRUniquingDebugTypes())
748     return nullptr;
749   return Context.pImpl->DITypeMap->lookup(&Identifier);
750 }
751 DISubroutineType::DISubroutineType(LLVMContext &C, StorageType Storage,
752                                    DIFlags Flags, uint8_t CC,
753                                    ArrayRef<Metadata *> Ops)
754     : DIType(C, DISubroutineTypeKind, Storage, dwarf::DW_TAG_subroutine_type, 0,
755              0, 0, 0, Flags, Ops),
756       CC(CC) {}
757 
758 DISubroutineType *DISubroutineType::getImpl(LLVMContext &Context, DIFlags Flags,
759                                             uint8_t CC, Metadata *TypeArray,
760                                             StorageType Storage,
761                                             bool ShouldCreate) {
762   DEFINE_GETIMPL_LOOKUP(DISubroutineType, (Flags, CC, TypeArray));
763   Metadata *Ops[] = {nullptr, nullptr, nullptr, TypeArray};
764   DEFINE_GETIMPL_STORE(DISubroutineType, (Flags, CC), Ops);
765 }
766 
767 DIFile::DIFile(LLVMContext &C, StorageType Storage,
768                Optional<ChecksumInfo<MDString *>> CS, Optional<MDString *> Src,
769                ArrayRef<Metadata *> Ops)
770     : DIScope(C, DIFileKind, Storage, dwarf::DW_TAG_file_type, Ops),
771       Checksum(CS), Source(Src) {}
772 
773 // FIXME: Implement this string-enum correspondence with a .def file and macros,
774 // so that the association is explicit rather than implied.
775 static const char *ChecksumKindName[DIFile::CSK_Last] = {
776     "CSK_MD5",
777     "CSK_SHA1",
778     "CSK_SHA256",
779 };
780 
781 StringRef DIFile::getChecksumKindAsString(ChecksumKind CSKind) {
782   assert(CSKind <= DIFile::CSK_Last && "Invalid checksum kind");
783   // The first space was originally the CSK_None variant, which is now
784   // obsolete, but the space is still reserved in ChecksumKind, so we account
785   // for it here.
786   return ChecksumKindName[CSKind - 1];
787 }
788 
789 Optional<DIFile::ChecksumKind> DIFile::getChecksumKind(StringRef CSKindStr) {
790   return StringSwitch<Optional<DIFile::ChecksumKind>>(CSKindStr)
791       .Case("CSK_MD5", DIFile::CSK_MD5)
792       .Case("CSK_SHA1", DIFile::CSK_SHA1)
793       .Case("CSK_SHA256", DIFile::CSK_SHA256)
794       .Default(None);
795 }
796 
797 DIFile *DIFile::getImpl(LLVMContext &Context, MDString *Filename,
798                         MDString *Directory,
799                         Optional<DIFile::ChecksumInfo<MDString *>> CS,
800                         Optional<MDString *> Source, StorageType Storage,
801                         bool ShouldCreate) {
802   assert(isCanonical(Filename) && "Expected canonical MDString");
803   assert(isCanonical(Directory) && "Expected canonical MDString");
804   assert((!CS || isCanonical(CS->Value)) && "Expected canonical MDString");
805   assert((!Source || isCanonical(*Source)) && "Expected canonical MDString");
806   DEFINE_GETIMPL_LOOKUP(DIFile, (Filename, Directory, CS, Source));
807   Metadata *Ops[] = {Filename, Directory, CS ? CS->Value : nullptr,
808                      Source.getValueOr(nullptr)};
809   DEFINE_GETIMPL_STORE(DIFile, (CS, Source), Ops);
810 }
811 DICompileUnit::DICompileUnit(LLVMContext &C, StorageType Storage,
812                              unsigned SourceLanguage, bool IsOptimized,
813                              unsigned RuntimeVersion, unsigned EmissionKind,
814                              uint64_t DWOId, bool SplitDebugInlining,
815                              bool DebugInfoForProfiling, unsigned NameTableKind,
816                              bool RangesBaseAddress, ArrayRef<Metadata *> Ops)
817     : DIScope(C, DICompileUnitKind, Storage, dwarf::DW_TAG_compile_unit, Ops),
818       SourceLanguage(SourceLanguage), IsOptimized(IsOptimized),
819       RuntimeVersion(RuntimeVersion), EmissionKind(EmissionKind), DWOId(DWOId),
820       SplitDebugInlining(SplitDebugInlining),
821       DebugInfoForProfiling(DebugInfoForProfiling),
822       NameTableKind(NameTableKind), RangesBaseAddress(RangesBaseAddress) {
823   assert(Storage != Uniqued);
824 }
825 
826 DICompileUnit *DICompileUnit::getImpl(
827     LLVMContext &Context, unsigned SourceLanguage, Metadata *File,
828     MDString *Producer, bool IsOptimized, MDString *Flags,
829     unsigned RuntimeVersion, MDString *SplitDebugFilename,
830     unsigned EmissionKind, Metadata *EnumTypes, Metadata *RetainedTypes,
831     Metadata *GlobalVariables, Metadata *ImportedEntities, Metadata *Macros,
832     uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling,
833     unsigned NameTableKind, bool RangesBaseAddress, MDString *SysRoot,
834     MDString *SDK, StorageType Storage, bool ShouldCreate) {
835   assert(Storage != Uniqued && "Cannot unique DICompileUnit");
836   assert(isCanonical(Producer) && "Expected canonical MDString");
837   assert(isCanonical(Flags) && "Expected canonical MDString");
838   assert(isCanonical(SplitDebugFilename) && "Expected canonical MDString");
839 
840   Metadata *Ops[] = {File,
841                      Producer,
842                      Flags,
843                      SplitDebugFilename,
844                      EnumTypes,
845                      RetainedTypes,
846                      GlobalVariables,
847                      ImportedEntities,
848                      Macros,
849                      SysRoot,
850                      SDK};
851   return storeImpl(new (array_lengthof(Ops)) DICompileUnit(
852                        Context, Storage, SourceLanguage, IsOptimized,
853                        RuntimeVersion, EmissionKind, DWOId, SplitDebugInlining,
854                        DebugInfoForProfiling, NameTableKind, RangesBaseAddress,
855                        Ops),
856                    Storage);
857 }
858 
859 Optional<DICompileUnit::DebugEmissionKind>
860 DICompileUnit::getEmissionKind(StringRef Str) {
861   return StringSwitch<Optional<DebugEmissionKind>>(Str)
862       .Case("NoDebug", NoDebug)
863       .Case("FullDebug", FullDebug)
864       .Case("LineTablesOnly", LineTablesOnly)
865       .Case("DebugDirectivesOnly", DebugDirectivesOnly)
866       .Default(None);
867 }
868 
869 Optional<DICompileUnit::DebugNameTableKind>
870 DICompileUnit::getNameTableKind(StringRef Str) {
871   return StringSwitch<Optional<DebugNameTableKind>>(Str)
872       .Case("Default", DebugNameTableKind::Default)
873       .Case("GNU", DebugNameTableKind::GNU)
874       .Case("None", DebugNameTableKind::None)
875       .Default(None);
876 }
877 
878 const char *DICompileUnit::emissionKindString(DebugEmissionKind EK) {
879   switch (EK) {
880   case NoDebug:
881     return "NoDebug";
882   case FullDebug:
883     return "FullDebug";
884   case LineTablesOnly:
885     return "LineTablesOnly";
886   case DebugDirectivesOnly:
887     return "DebugDirectivesOnly";
888   }
889   return nullptr;
890 }
891 
892 const char *DICompileUnit::nameTableKindString(DebugNameTableKind NTK) {
893   switch (NTK) {
894   case DebugNameTableKind::Default:
895     return nullptr;
896   case DebugNameTableKind::GNU:
897     return "GNU";
898   case DebugNameTableKind::None:
899     return "None";
900   }
901   return nullptr;
902 }
903 DISubprogram::DISubprogram(LLVMContext &C, StorageType Storage, unsigned Line,
904                            unsigned ScopeLine, unsigned VirtualIndex,
905                            int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags,
906                            ArrayRef<Metadata *> Ops)
907     : DILocalScope(C, DISubprogramKind, Storage, dwarf::DW_TAG_subprogram, Ops),
908       Line(Line), ScopeLine(ScopeLine), VirtualIndex(VirtualIndex),
909       ThisAdjustment(ThisAdjustment), Flags(Flags), SPFlags(SPFlags) {
910   static_assert(dwarf::DW_VIRTUALITY_max < 4, "Virtuality out of range");
911 }
912 DISubprogram::DISPFlags
913 DISubprogram::toSPFlags(bool IsLocalToUnit, bool IsDefinition, bool IsOptimized,
914                         unsigned Virtuality, bool IsMainSubprogram) {
915   // We're assuming virtuality is the low-order field.
916   static_assert(int(SPFlagVirtual) == int(dwarf::DW_VIRTUALITY_virtual) &&
917                     int(SPFlagPureVirtual) ==
918                         int(dwarf::DW_VIRTUALITY_pure_virtual),
919                 "Virtuality constant mismatch");
920   return static_cast<DISPFlags>(
921       (Virtuality & SPFlagVirtuality) |
922       (IsLocalToUnit ? SPFlagLocalToUnit : SPFlagZero) |
923       (IsDefinition ? SPFlagDefinition : SPFlagZero) |
924       (IsOptimized ? SPFlagOptimized : SPFlagZero) |
925       (IsMainSubprogram ? SPFlagMainSubprogram : SPFlagZero));
926 }
927 
928 DISubprogram *DILocalScope::getSubprogram() const {
929   if (auto *Block = dyn_cast<DILexicalBlockBase>(this))
930     return Block->getScope()->getSubprogram();
931   return const_cast<DISubprogram *>(cast<DISubprogram>(this));
932 }
933 
934 DILocalScope *DILocalScope::getNonLexicalBlockFileScope() const {
935   if (auto *File = dyn_cast<DILexicalBlockFile>(this))
936     return File->getScope()->getNonLexicalBlockFileScope();
937   return const_cast<DILocalScope *>(this);
938 }
939 
940 DISubprogram::DISPFlags DISubprogram::getFlag(StringRef Flag) {
941   return StringSwitch<DISPFlags>(Flag)
942 #define HANDLE_DISP_FLAG(ID, NAME) .Case("DISPFlag" #NAME, SPFlag##NAME)
943 #include "llvm/IR/DebugInfoFlags.def"
944       .Default(SPFlagZero);
945 }
946 
947 StringRef DISubprogram::getFlagString(DISPFlags Flag) {
948   switch (Flag) {
949   // Appease a warning.
950   case SPFlagVirtuality:
951     return "";
952 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
953   case SPFlag##NAME:                                                           \
954     return "DISPFlag" #NAME;
955 #include "llvm/IR/DebugInfoFlags.def"
956   }
957   return "";
958 }
959 
960 DISubprogram::DISPFlags
961 DISubprogram::splitFlags(DISPFlags Flags,
962                          SmallVectorImpl<DISPFlags> &SplitFlags) {
963   // Multi-bit fields can require special handling. In our case, however, the
964   // only multi-bit field is virtuality, and all its values happen to be
965   // single-bit values, so the right behavior just falls out.
966 #define HANDLE_DISP_FLAG(ID, NAME)                                             \
967   if (DISPFlags Bit = Flags & SPFlag##NAME) {                                  \
968     SplitFlags.push_back(Bit);                                                 \
969     Flags &= ~Bit;                                                             \
970   }
971 #include "llvm/IR/DebugInfoFlags.def"
972   return Flags;
973 }
974 
975 DISubprogram *DISubprogram::getImpl(
976     LLVMContext &Context, Metadata *Scope, MDString *Name,
977     MDString *LinkageName, Metadata *File, unsigned Line, Metadata *Type,
978     unsigned ScopeLine, Metadata *ContainingType, unsigned VirtualIndex,
979     int ThisAdjustment, DIFlags Flags, DISPFlags SPFlags, Metadata *Unit,
980     Metadata *TemplateParams, Metadata *Declaration, Metadata *RetainedNodes,
981     Metadata *ThrownTypes, Metadata *Annotations, MDString *TargetFuncName,
982     StorageType Storage, bool ShouldCreate) {
983   assert(isCanonical(Name) && "Expected canonical MDString");
984   assert(isCanonical(LinkageName) && "Expected canonical MDString");
985   assert(isCanonical(TargetFuncName) && "Expected canonical MDString");
986   DEFINE_GETIMPL_LOOKUP(DISubprogram,
987                         (Scope, Name, LinkageName, File, Line, Type, ScopeLine,
988                          ContainingType, VirtualIndex, ThisAdjustment, Flags,
989                          SPFlags, Unit, TemplateParams, Declaration,
990                          RetainedNodes, ThrownTypes, Annotations,
991                          TargetFuncName));
992   SmallVector<Metadata *, 13> Ops = {
993       File,           Scope,          Name,        LinkageName,
994       Type,           Unit,           Declaration, RetainedNodes,
995       ContainingType, TemplateParams, ThrownTypes, Annotations,
996       TargetFuncName};
997   if (!TargetFuncName) {
998     Ops.pop_back();
999     if (!Annotations) {
1000       Ops.pop_back();
1001       if (!ThrownTypes) {
1002         Ops.pop_back();
1003         if (!TemplateParams) {
1004           Ops.pop_back();
1005           if (!ContainingType)
1006             Ops.pop_back();
1007         }
1008       }
1009     }
1010   }
1011   DEFINE_GETIMPL_STORE_N(
1012       DISubprogram,
1013       (Line, ScopeLine, VirtualIndex, ThisAdjustment, Flags, SPFlags), Ops,
1014       Ops.size());
1015 }
1016 
1017 bool DISubprogram::describes(const Function *F) const {
1018   assert(F && "Invalid function");
1019   return F->getSubprogram() == this;
1020 }
1021 DILexicalBlockBase::DILexicalBlockBase(LLVMContext &C, unsigned ID,
1022                                        StorageType Storage,
1023                                        ArrayRef<Metadata *> Ops)
1024     : DILocalScope(C, ID, Storage, dwarf::DW_TAG_lexical_block, Ops) {}
1025 
1026 DILexicalBlock *DILexicalBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1027                                         Metadata *File, unsigned Line,
1028                                         unsigned Column, StorageType Storage,
1029                                         bool ShouldCreate) {
1030   // Fixup column.
1031   adjustColumn(Column);
1032 
1033   assert(Scope && "Expected scope");
1034   DEFINE_GETIMPL_LOOKUP(DILexicalBlock, (Scope, File, Line, Column));
1035   Metadata *Ops[] = {File, Scope};
1036   DEFINE_GETIMPL_STORE(DILexicalBlock, (Line, Column), Ops);
1037 }
1038 
1039 DILexicalBlockFile *DILexicalBlockFile::getImpl(LLVMContext &Context,
1040                                                 Metadata *Scope, Metadata *File,
1041                                                 unsigned Discriminator,
1042                                                 StorageType Storage,
1043                                                 bool ShouldCreate) {
1044   assert(Scope && "Expected scope");
1045   DEFINE_GETIMPL_LOOKUP(DILexicalBlockFile, (Scope, File, Discriminator));
1046   Metadata *Ops[] = {File, Scope};
1047   DEFINE_GETIMPL_STORE(DILexicalBlockFile, (Discriminator), Ops);
1048 }
1049 
1050 DINamespace::DINamespace(LLVMContext &Context, StorageType Storage,
1051                          bool ExportSymbols, ArrayRef<Metadata *> Ops)
1052     : DIScope(Context, DINamespaceKind, Storage, dwarf::DW_TAG_namespace, Ops),
1053       ExportSymbols(ExportSymbols) {}
1054 DINamespace *DINamespace::getImpl(LLVMContext &Context, Metadata *Scope,
1055                                   MDString *Name, bool ExportSymbols,
1056                                   StorageType Storage, bool ShouldCreate) {
1057   assert(isCanonical(Name) && "Expected canonical MDString");
1058   DEFINE_GETIMPL_LOOKUP(DINamespace, (Scope, Name, ExportSymbols));
1059   // The nullptr is for DIScope's File operand. This should be refactored.
1060   Metadata *Ops[] = {nullptr, Scope, Name};
1061   DEFINE_GETIMPL_STORE(DINamespace, (ExportSymbols), Ops);
1062 }
1063 
1064 DICommonBlock::DICommonBlock(LLVMContext &Context, StorageType Storage,
1065                              unsigned LineNo, ArrayRef<Metadata *> Ops)
1066     : DIScope(Context, DICommonBlockKind, Storage, dwarf::DW_TAG_common_block,
1067               Ops),
1068       LineNo(LineNo) {}
1069 DICommonBlock *DICommonBlock::getImpl(LLVMContext &Context, Metadata *Scope,
1070                                       Metadata *Decl, MDString *Name,
1071                                       Metadata *File, unsigned LineNo,
1072                                       StorageType Storage, bool ShouldCreate) {
1073   assert(isCanonical(Name) && "Expected canonical MDString");
1074   DEFINE_GETIMPL_LOOKUP(DICommonBlock, (Scope, Decl, Name, File, LineNo));
1075   // The nullptr is for DIScope's File operand. This should be refactored.
1076   Metadata *Ops[] = {Scope, Decl, Name, File};
1077   DEFINE_GETIMPL_STORE(DICommonBlock, (LineNo), Ops);
1078 }
1079 
1080 DIModule::DIModule(LLVMContext &Context, StorageType Storage, unsigned LineNo,
1081                    bool IsDecl, ArrayRef<Metadata *> Ops)
1082     : DIScope(Context, DIModuleKind, Storage, dwarf::DW_TAG_module, Ops),
1083       LineNo(LineNo), IsDecl(IsDecl) {}
1084 DIModule *DIModule::getImpl(LLVMContext &Context, Metadata *File,
1085                             Metadata *Scope, MDString *Name,
1086                             MDString *ConfigurationMacros,
1087                             MDString *IncludePath, MDString *APINotesFile,
1088                             unsigned LineNo, bool IsDecl, StorageType Storage,
1089                             bool ShouldCreate) {
1090   assert(isCanonical(Name) && "Expected canonical MDString");
1091   DEFINE_GETIMPL_LOOKUP(DIModule, (File, Scope, Name, ConfigurationMacros,
1092                                    IncludePath, APINotesFile, LineNo, IsDecl));
1093   Metadata *Ops[] = {File,        Scope,       Name, ConfigurationMacros,
1094                      IncludePath, APINotesFile};
1095   DEFINE_GETIMPL_STORE(DIModule, (LineNo, IsDecl), Ops);
1096 }
1097 DITemplateTypeParameter::DITemplateTypeParameter(LLVMContext &Context,
1098                                                  StorageType Storage,
1099                                                  bool IsDefault,
1100                                                  ArrayRef<Metadata *> Ops)
1101     : DITemplateParameter(Context, DITemplateTypeParameterKind, Storage,
1102                           dwarf::DW_TAG_template_type_parameter, IsDefault,
1103                           Ops) {}
1104 
1105 DITemplateTypeParameter *
1106 DITemplateTypeParameter::getImpl(LLVMContext &Context, MDString *Name,
1107                                  Metadata *Type, bool isDefault,
1108                                  StorageType Storage, bool ShouldCreate) {
1109   assert(isCanonical(Name) && "Expected canonical MDString");
1110   DEFINE_GETIMPL_LOOKUP(DITemplateTypeParameter, (Name, Type, isDefault));
1111   Metadata *Ops[] = {Name, Type};
1112   DEFINE_GETIMPL_STORE(DITemplateTypeParameter, (isDefault), Ops);
1113 }
1114 
1115 DITemplateValueParameter *DITemplateValueParameter::getImpl(
1116     LLVMContext &Context, unsigned Tag, MDString *Name, Metadata *Type,
1117     bool isDefault, Metadata *Value, StorageType Storage, bool ShouldCreate) {
1118   assert(isCanonical(Name) && "Expected canonical MDString");
1119   DEFINE_GETIMPL_LOOKUP(DITemplateValueParameter,
1120                         (Tag, Name, Type, isDefault, Value));
1121   Metadata *Ops[] = {Name, Type, Value};
1122   DEFINE_GETIMPL_STORE(DITemplateValueParameter, (Tag, isDefault), Ops);
1123 }
1124 
1125 DIGlobalVariable *
1126 DIGlobalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1127                           MDString *LinkageName, Metadata *File, unsigned Line,
1128                           Metadata *Type, bool IsLocalToUnit, bool IsDefinition,
1129                           Metadata *StaticDataMemberDeclaration,
1130                           Metadata *TemplateParams, uint32_t AlignInBits,
1131                           Metadata *Annotations, StorageType Storage,
1132                           bool ShouldCreate) {
1133   assert(isCanonical(Name) && "Expected canonical MDString");
1134   assert(isCanonical(LinkageName) && "Expected canonical MDString");
1135   DEFINE_GETIMPL_LOOKUP(
1136       DIGlobalVariable,
1137       (Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit, IsDefinition,
1138        StaticDataMemberDeclaration, TemplateParams, AlignInBits, Annotations));
1139   Metadata *Ops[] = {Scope,
1140                      Name,
1141                      File,
1142                      Type,
1143                      Name,
1144                      LinkageName,
1145                      StaticDataMemberDeclaration,
1146                      TemplateParams,
1147                      Annotations};
1148   DEFINE_GETIMPL_STORE(DIGlobalVariable,
1149                        (Line, IsLocalToUnit, IsDefinition, AlignInBits), Ops);
1150 }
1151 
1152 DILocalVariable *
1153 DILocalVariable::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1154                          Metadata *File, unsigned Line, Metadata *Type,
1155                          unsigned Arg, DIFlags Flags, uint32_t AlignInBits,
1156                          Metadata *Annotations, StorageType Storage,
1157                          bool ShouldCreate) {
1158   // 64K ought to be enough for any frontend.
1159   assert(Arg <= UINT16_MAX && "Expected argument number to fit in 16-bits");
1160 
1161   assert(Scope && "Expected scope");
1162   assert(isCanonical(Name) && "Expected canonical MDString");
1163   DEFINE_GETIMPL_LOOKUP(DILocalVariable, (Scope, Name, File, Line, Type, Arg,
1164                                           Flags, AlignInBits, Annotations));
1165   Metadata *Ops[] = {Scope, Name, File, Type, Annotations};
1166   DEFINE_GETIMPL_STORE(DILocalVariable, (Line, Arg, Flags, AlignInBits), Ops);
1167 }
1168 
1169 DIVariable::DIVariable(LLVMContext &C, unsigned ID, StorageType Storage,
1170                        signed Line, ArrayRef<Metadata *> Ops,
1171                        uint32_t AlignInBits)
1172     : DINode(C, ID, Storage, dwarf::DW_TAG_variable, Ops), Line(Line),
1173       AlignInBits(AlignInBits) {}
1174 Optional<uint64_t> DIVariable::getSizeInBits() const {
1175   // This is used by the Verifier so be mindful of broken types.
1176   const Metadata *RawType = getRawType();
1177   while (RawType) {
1178     // Try to get the size directly.
1179     if (auto *T = dyn_cast<DIType>(RawType))
1180       if (uint64_t Size = T->getSizeInBits())
1181         return Size;
1182 
1183     if (auto *DT = dyn_cast<DIDerivedType>(RawType)) {
1184       // Look at the base type.
1185       RawType = DT->getRawBaseType();
1186       continue;
1187     }
1188 
1189     // Missing type or size.
1190     break;
1191   }
1192 
1193   // Fail gracefully.
1194   return None;
1195 }
1196 
1197 DILabel::DILabel(LLVMContext &C, StorageType Storage, unsigned Line,
1198                  ArrayRef<Metadata *> Ops)
1199     : DINode(C, DILabelKind, Storage, dwarf::DW_TAG_label, Ops), Line(Line) {}
1200 DILabel *DILabel::getImpl(LLVMContext &Context, Metadata *Scope, MDString *Name,
1201                           Metadata *File, unsigned Line, StorageType Storage,
1202                           bool ShouldCreate) {
1203   assert(Scope && "Expected scope");
1204   assert(isCanonical(Name) && "Expected canonical MDString");
1205   DEFINE_GETIMPL_LOOKUP(DILabel, (Scope, Name, File, Line));
1206   Metadata *Ops[] = {Scope, Name, File};
1207   DEFINE_GETIMPL_STORE(DILabel, (Line), Ops);
1208 }
1209 
1210 DIExpression *DIExpression::getImpl(LLVMContext &Context,
1211                                     ArrayRef<uint64_t> Elements,
1212                                     StorageType Storage, bool ShouldCreate) {
1213   DEFINE_GETIMPL_LOOKUP(DIExpression, (Elements));
1214   DEFINE_GETIMPL_STORE_NO_OPS(DIExpression, (Elements));
1215 }
1216 bool DIExpression::isEntryValue() const {
1217   return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_LLVM_entry_value;
1218 }
1219 bool DIExpression::startsWithDeref() const {
1220   return getNumElements() > 0 && getElement(0) == dwarf::DW_OP_deref;
1221 }
1222 
1223 unsigned DIExpression::ExprOperand::getSize() const {
1224   uint64_t Op = getOp();
1225 
1226   if (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31)
1227     return 2;
1228 
1229   switch (Op) {
1230   case dwarf::DW_OP_LLVM_convert:
1231   case dwarf::DW_OP_LLVM_fragment:
1232   case dwarf::DW_OP_bregx:
1233     return 3;
1234   case dwarf::DW_OP_constu:
1235   case dwarf::DW_OP_consts:
1236   case dwarf::DW_OP_deref_size:
1237   case dwarf::DW_OP_plus_uconst:
1238   case dwarf::DW_OP_LLVM_tag_offset:
1239   case dwarf::DW_OP_LLVM_entry_value:
1240   case dwarf::DW_OP_LLVM_arg:
1241   case dwarf::DW_OP_regx:
1242     return 2;
1243   default:
1244     return 1;
1245   }
1246 }
1247 
1248 bool DIExpression::isValid() const {
1249   for (auto I = expr_op_begin(), E = expr_op_end(); I != E; ++I) {
1250     // Check that there's space for the operand.
1251     if (I->get() + I->getSize() > E->get())
1252       return false;
1253 
1254     uint64_t Op = I->getOp();
1255     if ((Op >= dwarf::DW_OP_reg0 && Op <= dwarf::DW_OP_reg31) ||
1256         (Op >= dwarf::DW_OP_breg0 && Op <= dwarf::DW_OP_breg31))
1257       return true;
1258 
1259     // Check that the operand is valid.
1260     switch (Op) {
1261     default:
1262       return false;
1263     case dwarf::DW_OP_LLVM_fragment:
1264       // A fragment operator must appear at the end.
1265       return I->get() + I->getSize() == E->get();
1266     case dwarf::DW_OP_stack_value: {
1267       // Must be the last one or followed by a DW_OP_LLVM_fragment.
1268       if (I->get() + I->getSize() == E->get())
1269         break;
1270       auto J = I;
1271       if ((++J)->getOp() != dwarf::DW_OP_LLVM_fragment)
1272         return false;
1273       break;
1274     }
1275     case dwarf::DW_OP_swap: {
1276       // Must be more than one implicit element on the stack.
1277 
1278       // FIXME: A better way to implement this would be to add a local variable
1279       // that keeps track of the stack depth and introduce something like a
1280       // DW_LLVM_OP_implicit_location as a placeholder for the location this
1281       // DIExpression is attached to, or else pass the number of implicit stack
1282       // elements into isValid.
1283       if (getNumElements() == 1)
1284         return false;
1285       break;
1286     }
1287     case dwarf::DW_OP_LLVM_entry_value: {
1288       // An entry value operator must appear at the beginning and the number of
1289       // operations it cover can currently only be 1, because we support only
1290       // entry values of a simple register location. One reason for this is that
1291       // we currently can't calculate the size of the resulting DWARF block for
1292       // other expressions.
1293       return I->get() == expr_op_begin()->get() && I->getArg(0) == 1;
1294     }
1295     case dwarf::DW_OP_LLVM_implicit_pointer:
1296     case dwarf::DW_OP_LLVM_convert:
1297     case dwarf::DW_OP_LLVM_arg:
1298     case dwarf::DW_OP_LLVM_tag_offset:
1299     case dwarf::DW_OP_constu:
1300     case dwarf::DW_OP_plus_uconst:
1301     case dwarf::DW_OP_plus:
1302     case dwarf::DW_OP_minus:
1303     case dwarf::DW_OP_mul:
1304     case dwarf::DW_OP_div:
1305     case dwarf::DW_OP_mod:
1306     case dwarf::DW_OP_or:
1307     case dwarf::DW_OP_and:
1308     case dwarf::DW_OP_xor:
1309     case dwarf::DW_OP_shl:
1310     case dwarf::DW_OP_shr:
1311     case dwarf::DW_OP_shra:
1312     case dwarf::DW_OP_deref:
1313     case dwarf::DW_OP_deref_size:
1314     case dwarf::DW_OP_xderef:
1315     case dwarf::DW_OP_lit0:
1316     case dwarf::DW_OP_not:
1317     case dwarf::DW_OP_dup:
1318     case dwarf::DW_OP_regx:
1319     case dwarf::DW_OP_bregx:
1320     case dwarf::DW_OP_push_object_address:
1321     case dwarf::DW_OP_over:
1322     case dwarf::DW_OP_consts:
1323       break;
1324     }
1325   }
1326   return true;
1327 }
1328 
1329 bool DIExpression::isImplicit() const {
1330   if (!isValid())
1331     return false;
1332 
1333   if (getNumElements() == 0)
1334     return false;
1335 
1336   for (const auto &It : expr_ops()) {
1337     switch (It.getOp()) {
1338     default:
1339       break;
1340     case dwarf::DW_OP_stack_value:
1341     case dwarf::DW_OP_LLVM_tag_offset:
1342       return true;
1343     }
1344   }
1345 
1346   return false;
1347 }
1348 
1349 bool DIExpression::isComplex() const {
1350   if (!isValid())
1351     return false;
1352 
1353   if (getNumElements() == 0)
1354     return false;
1355 
1356   // If there are any elements other than fragment or tag_offset, then some
1357   // kind of complex computation occurs.
1358   for (const auto &It : expr_ops()) {
1359     switch (It.getOp()) {
1360     case dwarf::DW_OP_LLVM_tag_offset:
1361     case dwarf::DW_OP_LLVM_fragment:
1362       continue;
1363     default:
1364       return true;
1365     }
1366   }
1367 
1368   return false;
1369 }
1370 
1371 Optional<DIExpression::FragmentInfo>
1372 DIExpression::getFragmentInfo(expr_op_iterator Start, expr_op_iterator End) {
1373   for (auto I = Start; I != End; ++I)
1374     if (I->getOp() == dwarf::DW_OP_LLVM_fragment) {
1375       DIExpression::FragmentInfo Info = {I->getArg(1), I->getArg(0)};
1376       return Info;
1377     }
1378   return None;
1379 }
1380 
1381 void DIExpression::appendOffset(SmallVectorImpl<uint64_t> &Ops,
1382                                 int64_t Offset) {
1383   if (Offset > 0) {
1384     Ops.push_back(dwarf::DW_OP_plus_uconst);
1385     Ops.push_back(Offset);
1386   } else if (Offset < 0) {
1387     Ops.push_back(dwarf::DW_OP_constu);
1388     Ops.push_back(-Offset);
1389     Ops.push_back(dwarf::DW_OP_minus);
1390   }
1391 }
1392 
1393 bool DIExpression::extractIfOffset(int64_t &Offset) const {
1394   if (getNumElements() == 0) {
1395     Offset = 0;
1396     return true;
1397   }
1398 
1399   if (getNumElements() == 2 && Elements[0] == dwarf::DW_OP_plus_uconst) {
1400     Offset = Elements[1];
1401     return true;
1402   }
1403 
1404   if (getNumElements() == 3 && Elements[0] == dwarf::DW_OP_constu) {
1405     if (Elements[2] == dwarf::DW_OP_plus) {
1406       Offset = Elements[1];
1407       return true;
1408     }
1409     if (Elements[2] == dwarf::DW_OP_minus) {
1410       Offset = -Elements[1];
1411       return true;
1412     }
1413   }
1414 
1415   return false;
1416 }
1417 
1418 bool DIExpression::hasAllLocationOps(unsigned N) const {
1419   SmallDenseSet<uint64_t, 4> SeenOps;
1420   for (auto ExprOp : expr_ops())
1421     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1422       SeenOps.insert(ExprOp.getArg(0));
1423   for (uint64_t Idx = 0; Idx < N; ++Idx)
1424     if (!is_contained(SeenOps, Idx))
1425       return false;
1426   return true;
1427 }
1428 
1429 const DIExpression *DIExpression::extractAddressClass(const DIExpression *Expr,
1430                                                       unsigned &AddrClass) {
1431   // FIXME: This seems fragile. Nothing that verifies that these elements
1432   // actually map to ops and not operands.
1433   const unsigned PatternSize = 4;
1434   if (Expr->Elements.size() >= PatternSize &&
1435       Expr->Elements[PatternSize - 4] == dwarf::DW_OP_constu &&
1436       Expr->Elements[PatternSize - 2] == dwarf::DW_OP_swap &&
1437       Expr->Elements[PatternSize - 1] == dwarf::DW_OP_xderef) {
1438     AddrClass = Expr->Elements[PatternSize - 3];
1439 
1440     if (Expr->Elements.size() == PatternSize)
1441       return nullptr;
1442     return DIExpression::get(Expr->getContext(),
1443                              makeArrayRef(&*Expr->Elements.begin(),
1444                                           Expr->Elements.size() - PatternSize));
1445   }
1446   return Expr;
1447 }
1448 
1449 DIExpression *DIExpression::prepend(const DIExpression *Expr, uint8_t Flags,
1450                                     int64_t Offset) {
1451   SmallVector<uint64_t, 8> Ops;
1452   if (Flags & DIExpression::DerefBefore)
1453     Ops.push_back(dwarf::DW_OP_deref);
1454 
1455   appendOffset(Ops, Offset);
1456   if (Flags & DIExpression::DerefAfter)
1457     Ops.push_back(dwarf::DW_OP_deref);
1458 
1459   bool StackValue = Flags & DIExpression::StackValue;
1460   bool EntryValue = Flags & DIExpression::EntryValue;
1461 
1462   return prependOpcodes(Expr, Ops, StackValue, EntryValue);
1463 }
1464 
1465 DIExpression *DIExpression::appendOpsToArg(const DIExpression *Expr,
1466                                            ArrayRef<uint64_t> Ops,
1467                                            unsigned ArgNo, bool StackValue) {
1468   assert(Expr && "Can't add ops to this expression");
1469 
1470   // Handle non-variadic intrinsics by prepending the opcodes.
1471   if (!any_of(Expr->expr_ops(),
1472               [](auto Op) { return Op.getOp() == dwarf::DW_OP_LLVM_arg; })) {
1473     assert(ArgNo == 0 &&
1474            "Location Index must be 0 for a non-variadic expression.");
1475     SmallVector<uint64_t, 8> NewOps(Ops.begin(), Ops.end());
1476     return DIExpression::prependOpcodes(Expr, NewOps, StackValue);
1477   }
1478 
1479   SmallVector<uint64_t, 8> NewOps;
1480   for (auto Op : Expr->expr_ops()) {
1481     Op.appendToVector(NewOps);
1482     if (Op.getOp() == dwarf::DW_OP_LLVM_arg && Op.getArg(0) == ArgNo)
1483       NewOps.insert(NewOps.end(), Ops.begin(), Ops.end());
1484   }
1485 
1486   return DIExpression::get(Expr->getContext(), NewOps);
1487 }
1488 
1489 DIExpression *DIExpression::replaceArg(const DIExpression *Expr,
1490                                        uint64_t OldArg, uint64_t NewArg) {
1491   assert(Expr && "Can't replace args in this expression");
1492 
1493   SmallVector<uint64_t, 8> NewOps;
1494 
1495   for (auto Op : Expr->expr_ops()) {
1496     if (Op.getOp() != dwarf::DW_OP_LLVM_arg || Op.getArg(0) < OldArg) {
1497       Op.appendToVector(NewOps);
1498       continue;
1499     }
1500     NewOps.push_back(dwarf::DW_OP_LLVM_arg);
1501     uint64_t Arg = Op.getArg(0) == OldArg ? NewArg : Op.getArg(0);
1502     // OldArg has been deleted from the Op list, so decrement all indices
1503     // greater than it.
1504     if (Arg > OldArg)
1505       --Arg;
1506     NewOps.push_back(Arg);
1507   }
1508   return DIExpression::get(Expr->getContext(), NewOps);
1509 }
1510 
1511 DIExpression *DIExpression::prependOpcodes(const DIExpression *Expr,
1512                                            SmallVectorImpl<uint64_t> &Ops,
1513                                            bool StackValue, bool EntryValue) {
1514   assert(Expr && "Can't prepend ops to this expression");
1515 
1516   if (EntryValue) {
1517     Ops.push_back(dwarf::DW_OP_LLVM_entry_value);
1518     // Use a block size of 1 for the target register operand.  The
1519     // DWARF backend currently cannot emit entry values with a block
1520     // size > 1.
1521     Ops.push_back(1);
1522   }
1523 
1524   // If there are no ops to prepend, do not even add the DW_OP_stack_value.
1525   if (Ops.empty())
1526     StackValue = false;
1527   for (auto Op : Expr->expr_ops()) {
1528     // A DW_OP_stack_value comes at the end, but before a DW_OP_LLVM_fragment.
1529     if (StackValue) {
1530       if (Op.getOp() == dwarf::DW_OP_stack_value)
1531         StackValue = false;
1532       else if (Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1533         Ops.push_back(dwarf::DW_OP_stack_value);
1534         StackValue = false;
1535       }
1536     }
1537     Op.appendToVector(Ops);
1538   }
1539   if (StackValue)
1540     Ops.push_back(dwarf::DW_OP_stack_value);
1541   return DIExpression::get(Expr->getContext(), Ops);
1542 }
1543 
1544 DIExpression *DIExpression::append(const DIExpression *Expr,
1545                                    ArrayRef<uint64_t> Ops) {
1546   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1547 
1548   // Copy Expr's current op list.
1549   SmallVector<uint64_t, 16> NewOps;
1550   for (auto Op : Expr->expr_ops()) {
1551     // Append new opcodes before DW_OP_{stack_value, LLVM_fragment}.
1552     if (Op.getOp() == dwarf::DW_OP_stack_value ||
1553         Op.getOp() == dwarf::DW_OP_LLVM_fragment) {
1554       NewOps.append(Ops.begin(), Ops.end());
1555 
1556       // Ensure that the new opcodes are only appended once.
1557       Ops = None;
1558     }
1559     Op.appendToVector(NewOps);
1560   }
1561 
1562   NewOps.append(Ops.begin(), Ops.end());
1563   auto *result = DIExpression::get(Expr->getContext(), NewOps);
1564   assert(result->isValid() && "concatenated expression is not valid");
1565   return result;
1566 }
1567 
1568 DIExpression *DIExpression::appendToStack(const DIExpression *Expr,
1569                                           ArrayRef<uint64_t> Ops) {
1570   assert(Expr && !Ops.empty() && "Can't append ops to this expression");
1571   assert(none_of(Ops,
1572                  [](uint64_t Op) {
1573                    return Op == dwarf::DW_OP_stack_value ||
1574                           Op == dwarf::DW_OP_LLVM_fragment;
1575                  }) &&
1576          "Can't append this op");
1577 
1578   // Append a DW_OP_deref after Expr's current op list if it's non-empty and
1579   // has no DW_OP_stack_value.
1580   //
1581   // Match .* DW_OP_stack_value (DW_OP_LLVM_fragment A B)?.
1582   Optional<FragmentInfo> FI = Expr->getFragmentInfo();
1583   unsigned DropUntilStackValue = FI.hasValue() ? 3 : 0;
1584   ArrayRef<uint64_t> ExprOpsBeforeFragment =
1585       Expr->getElements().drop_back(DropUntilStackValue);
1586   bool NeedsDeref = (Expr->getNumElements() > DropUntilStackValue) &&
1587                     (ExprOpsBeforeFragment.back() != dwarf::DW_OP_stack_value);
1588   bool NeedsStackValue = NeedsDeref || ExprOpsBeforeFragment.empty();
1589 
1590   // Append a DW_OP_deref after Expr's current op list if needed, then append
1591   // the new ops, and finally ensure that a single DW_OP_stack_value is present.
1592   SmallVector<uint64_t, 16> NewOps;
1593   if (NeedsDeref)
1594     NewOps.push_back(dwarf::DW_OP_deref);
1595   NewOps.append(Ops.begin(), Ops.end());
1596   if (NeedsStackValue)
1597     NewOps.push_back(dwarf::DW_OP_stack_value);
1598   return DIExpression::append(Expr, NewOps);
1599 }
1600 
1601 Optional<DIExpression *> DIExpression::createFragmentExpression(
1602     const DIExpression *Expr, unsigned OffsetInBits, unsigned SizeInBits) {
1603   SmallVector<uint64_t, 8> Ops;
1604   // Copy over the expression, but leave off any trailing DW_OP_LLVM_fragment.
1605   if (Expr) {
1606     for (auto Op : Expr->expr_ops()) {
1607       switch (Op.getOp()) {
1608       default:
1609         break;
1610       case dwarf::DW_OP_shr:
1611       case dwarf::DW_OP_shra:
1612       case dwarf::DW_OP_shl:
1613       case dwarf::DW_OP_plus:
1614       case dwarf::DW_OP_plus_uconst:
1615       case dwarf::DW_OP_minus:
1616         // We can't safely split arithmetic or shift operations into multiple
1617         // fragments because we can't express carry-over between fragments.
1618         //
1619         // FIXME: We *could* preserve the lowest fragment of a constant offset
1620         // operation if the offset fits into SizeInBits.
1621         return None;
1622       case dwarf::DW_OP_LLVM_fragment: {
1623         // Make the new offset point into the existing fragment.
1624         uint64_t FragmentOffsetInBits = Op.getArg(0);
1625         uint64_t FragmentSizeInBits = Op.getArg(1);
1626         (void)FragmentSizeInBits;
1627         assert((OffsetInBits + SizeInBits <= FragmentSizeInBits) &&
1628                "new fragment outside of original fragment");
1629         OffsetInBits += FragmentOffsetInBits;
1630         continue;
1631       }
1632       }
1633       Op.appendToVector(Ops);
1634     }
1635   }
1636   assert(Expr && "Unknown DIExpression");
1637   Ops.push_back(dwarf::DW_OP_LLVM_fragment);
1638   Ops.push_back(OffsetInBits);
1639   Ops.push_back(SizeInBits);
1640   return DIExpression::get(Expr->getContext(), Ops);
1641 }
1642 
1643 std::pair<DIExpression *, const ConstantInt *>
1644 DIExpression::constantFold(const ConstantInt *CI) {
1645   // Copy the APInt so we can modify it.
1646   APInt NewInt = CI->getValue();
1647   SmallVector<uint64_t, 8> Ops;
1648 
1649   // Fold operators only at the beginning of the expression.
1650   bool First = true;
1651   bool Changed = false;
1652   for (auto Op : expr_ops()) {
1653     switch (Op.getOp()) {
1654     default:
1655       // We fold only the leading part of the expression; if we get to a part
1656       // that we're going to copy unchanged, and haven't done any folding,
1657       // then the entire expression is unchanged and we can return early.
1658       if (!Changed)
1659         return {this, CI};
1660       First = false;
1661       break;
1662     case dwarf::DW_OP_LLVM_convert:
1663       if (!First)
1664         break;
1665       Changed = true;
1666       if (Op.getArg(1) == dwarf::DW_ATE_signed)
1667         NewInt = NewInt.sextOrTrunc(Op.getArg(0));
1668       else {
1669         assert(Op.getArg(1) == dwarf::DW_ATE_unsigned && "Unexpected operand");
1670         NewInt = NewInt.zextOrTrunc(Op.getArg(0));
1671       }
1672       continue;
1673     }
1674     Op.appendToVector(Ops);
1675   }
1676   if (!Changed)
1677     return {this, CI};
1678   return {DIExpression::get(getContext(), Ops),
1679           ConstantInt::get(getContext(), NewInt)};
1680 }
1681 
1682 uint64_t DIExpression::getNumLocationOperands() const {
1683   uint64_t Result = 0;
1684   for (auto ExprOp : expr_ops())
1685     if (ExprOp.getOp() == dwarf::DW_OP_LLVM_arg)
1686       Result = std::max(Result, ExprOp.getArg(0) + 1);
1687   assert(hasAllLocationOps(Result) &&
1688          "Expression is missing one or more location operands.");
1689   return Result;
1690 }
1691 
1692 llvm::Optional<DIExpression::SignedOrUnsignedConstant>
1693 DIExpression::isConstant() const {
1694 
1695   // Recognize signed and unsigned constants.
1696   // An signed constants can be represented as DW_OP_consts C DW_OP_stack_value
1697   // (DW_OP_LLVM_fragment of Len).
1698   // An unsigned constant can be represented as
1699   // DW_OP_constu C DW_OP_stack_value (DW_OP_LLVM_fragment of Len).
1700 
1701   if ((getNumElements() != 2 && getNumElements() != 3 &&
1702        getNumElements() != 6) ||
1703       (getElement(0) != dwarf::DW_OP_consts &&
1704        getElement(0) != dwarf::DW_OP_constu))
1705     return None;
1706 
1707   if (getNumElements() == 2 && getElement(0) == dwarf::DW_OP_consts)
1708     return SignedOrUnsignedConstant::SignedConstant;
1709 
1710   if ((getNumElements() == 3 && getElement(2) != dwarf::DW_OP_stack_value) ||
1711       (getNumElements() == 6 && (getElement(2) != dwarf::DW_OP_stack_value ||
1712                                  getElement(3) != dwarf::DW_OP_LLVM_fragment)))
1713     return None;
1714   return getElement(0) == dwarf::DW_OP_constu
1715              ? SignedOrUnsignedConstant::UnsignedConstant
1716              : SignedOrUnsignedConstant::SignedConstant;
1717 }
1718 
1719 DIExpression::ExtOps DIExpression::getExtOps(unsigned FromSize, unsigned ToSize,
1720                                              bool Signed) {
1721   dwarf::TypeKind TK = Signed ? dwarf::DW_ATE_signed : dwarf::DW_ATE_unsigned;
1722   DIExpression::ExtOps Ops{{dwarf::DW_OP_LLVM_convert, FromSize, TK,
1723                             dwarf::DW_OP_LLVM_convert, ToSize, TK}};
1724   return Ops;
1725 }
1726 
1727 DIExpression *DIExpression::appendExt(const DIExpression *Expr,
1728                                       unsigned FromSize, unsigned ToSize,
1729                                       bool Signed) {
1730   return appendToStack(Expr, getExtOps(FromSize, ToSize, Signed));
1731 }
1732 
1733 DIGlobalVariableExpression *
1734 DIGlobalVariableExpression::getImpl(LLVMContext &Context, Metadata *Variable,
1735                                     Metadata *Expression, StorageType Storage,
1736                                     bool ShouldCreate) {
1737   DEFINE_GETIMPL_LOOKUP(DIGlobalVariableExpression, (Variable, Expression));
1738   Metadata *Ops[] = {Variable, Expression};
1739   DEFINE_GETIMPL_STORE_NO_CONSTRUCTOR_ARGS(DIGlobalVariableExpression, Ops);
1740 }
1741 DIObjCProperty::DIObjCProperty(LLVMContext &C, StorageType Storage,
1742                                unsigned Line, unsigned Attributes,
1743                                ArrayRef<Metadata *> Ops)
1744     : DINode(C, DIObjCPropertyKind, Storage, dwarf::DW_TAG_APPLE_property, Ops),
1745       Line(Line), Attributes(Attributes) {}
1746 
1747 DIObjCProperty *DIObjCProperty::getImpl(
1748     LLVMContext &Context, MDString *Name, Metadata *File, unsigned Line,
1749     MDString *GetterName, MDString *SetterName, unsigned Attributes,
1750     Metadata *Type, StorageType Storage, bool ShouldCreate) {
1751   assert(isCanonical(Name) && "Expected canonical MDString");
1752   assert(isCanonical(GetterName) && "Expected canonical MDString");
1753   assert(isCanonical(SetterName) && "Expected canonical MDString");
1754   DEFINE_GETIMPL_LOOKUP(DIObjCProperty, (Name, File, Line, GetterName,
1755                                          SetterName, Attributes, Type));
1756   Metadata *Ops[] = {Name, File, GetterName, SetterName, Type};
1757   DEFINE_GETIMPL_STORE(DIObjCProperty, (Line, Attributes), Ops);
1758 }
1759 
1760 DIImportedEntity *DIImportedEntity::getImpl(LLVMContext &Context, unsigned Tag,
1761                                             Metadata *Scope, Metadata *Entity,
1762                                             Metadata *File, unsigned Line,
1763                                             MDString *Name, Metadata *Elements,
1764                                             StorageType Storage,
1765                                             bool ShouldCreate) {
1766   assert(isCanonical(Name) && "Expected canonical MDString");
1767   DEFINE_GETIMPL_LOOKUP(DIImportedEntity,
1768                         (Tag, Scope, Entity, File, Line, Name, Elements));
1769   Metadata *Ops[] = {Scope, Entity, Name, File, Elements};
1770   DEFINE_GETIMPL_STORE(DIImportedEntity, (Tag, Line), Ops);
1771 }
1772 
1773 DIMacro *DIMacro::getImpl(LLVMContext &Context, unsigned MIType, unsigned Line,
1774                           MDString *Name, MDString *Value, StorageType Storage,
1775                           bool ShouldCreate) {
1776   assert(isCanonical(Name) && "Expected canonical MDString");
1777   DEFINE_GETIMPL_LOOKUP(DIMacro, (MIType, Line, Name, Value));
1778   Metadata *Ops[] = {Name, Value};
1779   DEFINE_GETIMPL_STORE(DIMacro, (MIType, Line), Ops);
1780 }
1781 
1782 DIMacroFile *DIMacroFile::getImpl(LLVMContext &Context, unsigned MIType,
1783                                   unsigned Line, Metadata *File,
1784                                   Metadata *Elements, StorageType Storage,
1785                                   bool ShouldCreate) {
1786   DEFINE_GETIMPL_LOOKUP(DIMacroFile, (MIType, Line, File, Elements));
1787   Metadata *Ops[] = {File, Elements};
1788   DEFINE_GETIMPL_STORE(DIMacroFile, (MIType, Line), Ops);
1789 }
1790 
1791 DIArgList *DIArgList::getImpl(LLVMContext &Context,
1792                               ArrayRef<ValueAsMetadata *> Args,
1793                               StorageType Storage, bool ShouldCreate) {
1794   DEFINE_GETIMPL_LOOKUP(DIArgList, (Args));
1795   DEFINE_GETIMPL_STORE_NO_OPS(DIArgList, (Args));
1796 }
1797 
1798 void DIArgList::handleChangedOperand(void *Ref, Metadata *New) {
1799   ValueAsMetadata **OldVMPtr = static_cast<ValueAsMetadata **>(Ref);
1800   assert((!New || isa<ValueAsMetadata>(New)) &&
1801          "DIArgList must be passed a ValueAsMetadata");
1802   untrack();
1803   bool Uniq = isUniqued();
1804   if (Uniq) {
1805     // We need to update the uniqueness once the Args are updated since they
1806     // form the key to the DIArgLists store.
1807     eraseFromStore();
1808   }
1809   ValueAsMetadata *NewVM = cast_or_null<ValueAsMetadata>(New);
1810   for (ValueAsMetadata *&VM : Args) {
1811     if (&VM == OldVMPtr) {
1812       if (NewVM)
1813         VM = NewVM;
1814       else
1815         VM = ValueAsMetadata::get(UndefValue::get(VM->getValue()->getType()));
1816     }
1817   }
1818   if (Uniq) {
1819     if (uniquify() != this)
1820       storeDistinctInContext();
1821   }
1822   track();
1823 }
1824 void DIArgList::track() {
1825   for (ValueAsMetadata *&VAM : Args)
1826     if (VAM)
1827       MetadataTracking::track(&VAM, *VAM, *this);
1828 }
1829 void DIArgList::untrack() {
1830   for (ValueAsMetadata *&VAM : Args)
1831     if (VAM)
1832       MetadataTracking::untrack(&VAM, *VAM);
1833 }
1834 void DIArgList::dropAllReferences() {
1835   untrack();
1836   Args.clear();
1837   MDNode::dropAllReferences();
1838 }
1839