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