Debian Codegraph @

clang/lib/CodeGen/CGDebugInfo.cpp

raw
1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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 coordinates the debug information generation while generating code.
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CGDebugInfo.h"
14 #include "CGBlocks.h"
15 #include "CGCXXABI.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "TargetInfo.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/Attr.h"
24 #include "clang/AST/DeclCXX.h"
25 #include "clang/AST/DeclFriend.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/LambdaCapture.h"
30 #include "clang/AST/RecordLayout.h"
31 #include "clang/AST/RecursiveASTVisitor.h"
32 #include "clang/AST/VTableBuilder.h"
33 #include "clang/Basic/CodeGenOptions.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/Version.h"
36 #include "clang/CodeGen/ModuleBuilder.h"
37 #include "clang/Frontend/FrontendOptions.h"
38 #include "clang/Lex/HeaderSearchOptions.h"
39 #include "clang/Lex/ModuleMap.h"
40 #include "clang/Lex/PreprocessorOptions.h"
41 #include "llvm/ADT/DenseSet.h"
42 #include "llvm/ADT/SmallVector.h"
43 #include "llvm/ADT/StringExtras.h"
44 #include "llvm/IR/Constants.h"
45 #include "llvm/IR/DataLayout.h"
46 #include "llvm/IR/DerivedTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/Metadata.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/Support/MD5.h"
53 #include "llvm/Support/Path.h"
54 #include "llvm/Support/SHA1.h"
55 #include "llvm/Support/SHA256.h"
56 #include "llvm/Support/TimeProfiler.h"
57 #include <cstdint>
58 #include <optional>
59 using namespace clang;
60 using namespace clang::CodeGen;
61
62 static SourceLocation getMacroDebugLoc(const CodeGenModule &CGM,
63 SourceLocation Loc) {
64 if (CGM.getCodeGenOpts().DebugInfoMacroExpansionLoc)
65 return Loc;
66 return CGM.getContext().getSourceManager().getFileLoc(Loc);
67 }
68
69 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
70 auto TI = Ctx.getTypeInfo(Ty);
71 if (TI.isAlignRequired())
72 return TI.Align;
73
74 // MaxFieldAlignmentAttr is the attribute added to types
75 // declared after #pragma pack(n).
76 if (auto *Decl = Ty->getAsRecordDecl())
77 if (Decl->hasAttr<MaxFieldAlignmentAttr>())
78 return TI.Align;
79
80 return 0;
81 }
82
83 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
84 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
85 }
86
87 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
88 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
89 }
90
91 /// Returns true if \ref VD is a a holding variable (aka a
92 /// VarDecl retrieved using \ref BindingDecl::getHoldingVar).
93 static bool IsDecomposedVarDecl(VarDecl const *VD) {
94 auto const *Init = VD->getInit();
95 if (!Init)
96 return false;
97
98 auto const *RefExpr =
99 llvm::dyn_cast_or_null<DeclRefExpr>(Init->IgnoreUnlessSpelledInSource());
100 if (!RefExpr)
101 return false;
102
103 return llvm::dyn_cast_or_null<DecompositionDecl>(RefExpr->getDecl());
104 }
105
106 /// Returns true if \ref VD is a compiler-generated variable
107 /// and should be treated as artificial for the purposes
108 /// of debug-info generation.
109 static bool IsArtificial(VarDecl const *VD) {
110 // Tuple-like bindings are marked as implicit despite
111 // being spelled out in source. Don't treat them as artificial
112 // variables.
113 if (IsDecomposedVarDecl(VD))
114 return false;
115
116 return VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
117 cast<Decl>(VD->getDeclContext())->isImplicit());
118 }
119
120 /// Returns \c true if the specified variable \c VD is an explicit parameter of
121 /// a synthesized Objective-C property accessor. E.g., a synthesized property
122 /// setter method will have a single explicit parameter which is the property to
123 /// set.
124 static bool IsObjCSynthesizedPropertyExplicitParameter(VarDecl const *VD) {
125 assert(VD);
126
127 if (!llvm::isa<ParmVarDecl>(VD))
128 return false;
129
130 // Not a property method.
131 const auto *Method =
132 llvm::dyn_cast_or_null<ObjCMethodDecl>(VD->getDeclContext());
133 if (!Method)
134 return false;
135
136 // Not a synthesized property accessor.
137 if (!Method->isImplicit() || !Method->isPropertyAccessor())
138 return false;
139
140 // Not an explicit parameter.
141 if (VD->isImplicit())
142 return false;
143
144 return true;
145 }
146
147 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
148 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
149 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
150 DBuilder(CGM.getModule()) {
151 CreateCompileUnit();
152 }
153
154 CGDebugInfo::~CGDebugInfo() {
155 assert(LexicalBlockStack.empty() &&
156 "Region stack mismatch, stack not empty!");
157 }
158
159 void CGDebugInfo::addInstSourceAtomMetadata(llvm::Instruction *I,
160 uint64_t Group, uint8_t Rank) {
161 if (!I->getDebugLoc() || Group == 0 || !I->getDebugLoc()->getLine())
162 return;
163
164 // Saturate the 3-bit rank.
165 Rank = std::min<uint8_t>(Rank, 7);
166
167 const llvm::DebugLoc &DL = I->getDebugLoc();
168
169 // Each instruction can only be attributed to one source atom (a limitation of
170 // the implementation). If this instruction is already part of a source atom,
171 // pick the group in which it has highest precedence (lowest rank).
172 if (DL->getAtomGroup() && DL->getAtomRank() && DL->getAtomRank() < Rank) {
173 Group = DL->getAtomGroup();
174 Rank = DL->getAtomRank();
175 }
176
177 // Update the function-local watermark so we don't reuse this number for
178 // another atom.
179 KeyInstructionsInfo.HighestEmittedAtom =
180 std::max(Group, KeyInstructionsInfo.HighestEmittedAtom);
181
182 // Apply the new DILocation to the instruction.
183 llvm::DILocation *NewDL = llvm::DILocation::get(
184 I->getContext(), DL.getLine(), DL.getCol(), DL.getScope(),
185 DL.getInlinedAt(), DL.isImplicitCode(), Group, Rank);
186 I->setDebugLoc(NewDL);
187 }
188
189 void CGDebugInfo::addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction,
190 llvm::Value *Backup) {
191 addInstToSpecificSourceAtom(KeyInstruction, Backup,
192 KeyInstructionsInfo.CurrentAtom);
193 }
194
195 void CGDebugInfo::addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction,
196 llvm::Value *Backup,
197 uint64_t Group) {
198 if (!Group || !CGM.getCodeGenOpts().DebugKeyInstructions)
199 return;
200
201 llvm::DISubprogram *SP = KeyInstruction->getFunction()->getSubprogram();
202 if (!SP || !SP->getKeyInstructionsEnabled())
203 return;
204
205 addInstSourceAtomMetadata(KeyInstruction, Group, /*Rank=*/1);
206
207 llvm::Instruction *BackupI =
208 llvm::dyn_cast_or_null<llvm::Instruction>(Backup);
209 if (!BackupI)
210 return;
211
212 // Add the backup instruction to the group.
213 addInstSourceAtomMetadata(BackupI, Group, /*Rank=*/2);
214
215 // Look through chains of casts too, as they're probably going to evaporate.
216 // FIXME: And other nops like zero length geps?
217 // FIXME: Should use Cast->isNoopCast()?
218 uint8_t Rank = 3;
219 while (auto *Cast = dyn_cast<llvm::CastInst>(BackupI)) {
220 BackupI = dyn_cast<llvm::Instruction>(Cast->getOperand(0));
221 if (!BackupI)
222 break;
223 addInstSourceAtomMetadata(BackupI, Group, Rank++);
224 }
225 }
226
227 void CGDebugInfo::completeFunction() {
228 // Reset the atom group number tracker as the numbers are function-local.
229 KeyInstructionsInfo.NextAtom = 1;
230 KeyInstructionsInfo.HighestEmittedAtom = 0;
231 KeyInstructionsInfo.CurrentAtom = 0;
232 }
233
234 ApplyAtomGroup::ApplyAtomGroup(CGDebugInfo *DI) : DI(DI) {
235 if (!DI)
236 return;
237 OriginalAtom = DI->KeyInstructionsInfo.CurrentAtom;
238 DI->KeyInstructionsInfo.CurrentAtom = DI->KeyInstructionsInfo.NextAtom++;
239 }
240
241 ApplyAtomGroup::~ApplyAtomGroup() {
242 if (!DI)
243 return;
244
245 // We may not have used the group number at all.
246 DI->KeyInstructionsInfo.NextAtom =
247 std::min(DI->KeyInstructionsInfo.HighestEmittedAtom + 1,
248 DI->KeyInstructionsInfo.NextAtom);
249
250 DI->KeyInstructionsInfo.CurrentAtom = OriginalAtom;
251 }
252
253 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
254 SourceLocation TemporaryLocation)
255 : CGF(&CGF) {
256 init(TemporaryLocation);
257 }
258
259 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
260 bool DefaultToEmpty,
261 SourceLocation TemporaryLocation)
262 : CGF(&CGF) {
263 init(TemporaryLocation, DefaultToEmpty);
264 }
265
266 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
267 bool DefaultToEmpty) {
268 auto *DI = CGF->getDebugInfo();
269 if (!DI) {
270 CGF = nullptr;
271 return;
272 }
273
274 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
275
276 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
277 return;
278
279 if (TemporaryLocation.isValid()) {
280 DI->EmitLocation(CGF->Builder, TemporaryLocation);
281 return;
282 }
283
284 if (DefaultToEmpty) {
285 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
286 return;
287 }
288
289 // Construct a location that has a valid scope, but no line info.
290 assert(!DI->LexicalBlockStack.empty());
291 CGF->Builder.SetCurrentDebugLocation(
292 llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
293 DI->LexicalBlockStack.back(), DI->getInlinedAt()));
294 }
295
296 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
297 : CGF(&CGF) {
298 init(E->getExprLoc());
299 }
300
301 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
302 : CGF(&CGF) {
303 if (!CGF.getDebugInfo()) {
304 this->CGF = nullptr;
305 return;
306 }
307 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
308 if (Loc) {
309 // Key Instructions: drop the atom group and rank to avoid accidentally
310 // propagating it around.
311 if (Loc->getAtomGroup())
312 Loc = llvm::DILocation::get(Loc->getContext(), Loc.getLine(),
313 Loc->getColumn(), Loc->getScope(),
314 Loc->getInlinedAt(), Loc.isImplicitCode());
315 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
316 }
317 }
318
319 ApplyDebugLocation::~ApplyDebugLocation() {
320 // Query CGF so the location isn't overwritten when location updates are
321 // temporarily disabled (for C++ default function arguments)
322 if (CGF)
323 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
324 }
325
326 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
327 GlobalDecl InlinedFn)
328 : CGF(&CGF) {
329 if (!CGF.getDebugInfo()) {
330 this->CGF = nullptr;
331 return;
332 }
333 auto &DI = *CGF.getDebugInfo();
334 SavedLocation = DI.getLocation();
335 assert((DI.getInlinedAt() ==
336 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
337 "CGDebugInfo and IRBuilder are out of sync");
338
339 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
340 }
341
342 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
343 if (!CGF)
344 return;
345 auto &DI = *CGF->getDebugInfo();
346 DI.EmitInlineFunctionEnd(CGF->Builder);
347 DI.EmitLocation(CGF->Builder, SavedLocation);
348 }
349
350 void CGDebugInfo::setLocation(SourceLocation Loc) {
351 // If the new location isn't valid return.
352 if (Loc.isInvalid())
353 return;
354
355 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(
356 getMacroDebugLoc(CGM, Loc));
357
358 // If we've changed files in the middle of a lexical scope go ahead
359 // and create a new lexical scope with file node if it's different
360 // from the one in the scope.
361 if (LexicalBlockStack.empty())
362 return;
363
364 SourceManager &SM = CGM.getContext().getSourceManager();
365 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
366 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
367 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
368 return;
369
370 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
371 LexicalBlockStack.pop_back();
372 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
373 LBF->getScope(), getOrCreateFile(CurLoc)));
374 } else if (isa<llvm::DILexicalBlock>(Scope) ||
375 isa<llvm::DISubprogram>(Scope)) {
376 LexicalBlockStack.pop_back();
377 LexicalBlockStack.emplace_back(
378 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
379 }
380 }
381
382 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
383 llvm::DIScope *Mod = getParentModuleOrNull(D);
384 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
385 Mod ? Mod : TheCU);
386 }
387
388 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
389 llvm::DIScope *Default) {
390 if (!Context)
391 return Default;
392
393 auto I = RegionMap.find(Context);
394 if (I != RegionMap.end()) {
395 llvm::Metadata *V = I->second;
396 return dyn_cast_or_null<llvm::DIScope>(V);
397 }
398
399 // Check namespace.
400 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
401 return getOrCreateNamespace(NSDecl);
402
403 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
404 if (!RDecl->isDependentType())
405 return getOrCreateType(CGM.getContext().getCanonicalTagType(RDecl),
406 TheCU->getFile());
407 return Default;
408 }
409
410 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
411 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
412
413 // If we're emitting codeview, it's important to try to match MSVC's naming so
414 // that visualizers written for MSVC will trigger for our class names. In
415 // particular, we can't have spaces between arguments of standard templates
416 // like basic_string and vector, but we must have spaces between consecutive
417 // angle brackets that close nested template argument lists.
418 if (CGM.getCodeGenOpts().EmitCodeView) {
419 PP.MSVCFormatting = true;
420 PP.SplitTemplateClosers = true;
421 } else {
422 // For DWARF, printing rules are underspecified.
423 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
424 PP.SplitTemplateClosers = true;
425 }
426
427 PP.SuppressInlineNamespace =
428 llvm::to_underlying(PrintingPolicy::SuppressInlineNamespaceMode::None);
429 PP.PrintAsCanonical = true;
430 PP.UsePreferredNames = false;
431 PP.AlwaysIncludeTypeForTemplateArgument = true;
432 PP.UseEnumerators = false;
433
434 // Apply -fdebug-prefix-map.
435 PP.Callbacks = &PrintCB;
436 return PP;
437 }
438
439 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
440 return internString(GetName(FD));
441 }
442
443 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
444 SmallString<256> MethodName;
445 llvm::raw_svector_ostream OS(MethodName);
446 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
447 const DeclContext *DC = OMD->getDeclContext();
448 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
449 OS << OID->getName();
450 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
451 OS << OID->getName();
452 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
453 if (OC->IsClassExtension()) {
454 OS << OC->getClassInterface()->getName();
455 } else {
456 OS << OC->getIdentifier()->getNameStart() << '('
457 << OC->getIdentifier()->getNameStart() << ')';
458 }
459 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
460 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
461 }
462 OS << ' ' << OMD->getSelector().getAsString() << ']';
463
464 return internString(OS.str());
465 }
466
467 StringRef CGDebugInfo::getSelectorName(Selector S) {
468 return internString(S.getAsString());
469 }
470
471 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
472 if (isa<ClassTemplateSpecializationDecl>(RD)) {
473 // Copy this name on the side and use its reference.
474 return internString(GetName(RD));
475 }
476
477 // quick optimization to avoid having to intern strings that are already
478 // stored reliably elsewhere
479 if (const IdentifierInfo *II = RD->getIdentifier())
480 return II->getName();
481
482 // The CodeView printer in LLVM wants to see the names of unnamed types
483 // because they need to have a unique identifier.
484 // These names are used to reconstruct the fully qualified type names.
485 if (CGM.getCodeGenOpts().EmitCodeView) {
486 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
487 assert(RD->getDeclContext() == D->getDeclContext() &&
488 "Typedef should not be in another decl context!");
489 assert(D->getDeclName().getAsIdentifierInfo() &&
490 "Typedef was not named!");
491 return D->getDeclName().getAsIdentifierInfo()->getName();
492 }
493
494 if (CGM.getLangOpts().CPlusPlus) {
495 StringRef Name;
496
497 ASTContext &Context = CGM.getContext();
498 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
499 // Anonymous types without a name for linkage purposes have their
500 // declarator mangled in if they have one.
501 Name = DD->getName();
502 else if (const TypedefNameDecl *TND =
503 Context.getTypedefNameForUnnamedTagDecl(RD))
504 // Anonymous types without a name for linkage purposes have their
505 // associate typedef mangled in if they have one.
506 Name = TND->getName();
507
508 // Give lambdas a display name based on their name mangling.
509 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
510 if (CXXRD->isLambda())
511 return internString(
512 CGM.getCXXABI().getMangleContext().getLambdaString(CXXRD));
513
514 if (!Name.empty()) {
515 SmallString<256> UnnamedType("<unnamed-type-");
516 UnnamedType += Name;
517 UnnamedType += '>';
518 return internString(UnnamedType);
519 }
520 }
521 }
522
523 return StringRef();
524 }
525
526 std::optional<llvm::DIFile::ChecksumKind>
527 CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
528 Checksum.clear();
529
530 if (!CGM.getCodeGenOpts().EmitCodeView &&
531 CGM.getCodeGenOpts().DwarfVersion < 5)
532 return std::nullopt;
533
534 SourceManager &SM = CGM.getContext().getSourceManager();
535 std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
536 if (!MemBuffer)
537 return std::nullopt;
538
539 auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());
540 switch (CGM.getCodeGenOpts().getDebugSrcHash()) {
541 case clang::CodeGenOptions::DSH_MD5:
542 llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);
543 return llvm::DIFile::CSK_MD5;
544 case clang::CodeGenOptions::DSH_SHA1:
545 llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);
546 return llvm::DIFile::CSK_SHA1;
547 case clang::CodeGenOptions::DSH_SHA256:
548 llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);
549 return llvm::DIFile::CSK_SHA256;
550 case clang::CodeGenOptions::DSH_NONE:
551 return std::nullopt;
552 }
553 llvm_unreachable("Unhandled DebugSrcHashKind enum");
554 }
555
556 std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
557 FileID FID) {
558 if (!CGM.getCodeGenOpts().EmbedSource)
559 return std::nullopt;
560
561 bool SourceInvalid = false;
562 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
563
564 if (SourceInvalid)
565 return std::nullopt;
566
567 return Source;
568 }
569
570 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
571 SourceManager &SM = CGM.getContext().getSourceManager();
572 StringRef FileName;
573 FileID FID;
574 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
575
576 if (Loc.isInvalid()) {
577 // The DIFile used by the CU is distinct from the main source file. Call
578 // createFile() below for canonicalization if the source file was specified
579 // with an absolute path.
580 FileName = TheCU->getFile()->getFilename();
581 CSInfo = TheCU->getFile()->getChecksum();
582 } else {
583 PresumedLoc PLoc = SM.getPresumedLoc(getMacroDebugLoc(CGM, Loc));
584 FileName = PLoc.getFilename();
585
586 if (FileName.empty()) {
587 FileName = TheCU->getFile()->getFilename();
588 } else {
589 FileName = PLoc.getFilename();
590 }
591 FID = PLoc.getFileID();
592 }
593
594 // Cache the results.
595 auto It = DIFileCache.find(FileName.data());
596 if (It != DIFileCache.end()) {
597 // Verify that the information still exists.
598 if (llvm::Metadata *V = It->second)
599 return cast<llvm::DIFile>(V);
600 }
601
602 // Put Checksum at a scope where it will persist past the createFile call.
603 SmallString<64> Checksum;
604 if (!CSInfo) {
605 std::optional<llvm::DIFile::ChecksumKind> CSKind =
606 computeChecksum(FID, Checksum);
607 if (CSKind)
608 CSInfo.emplace(*CSKind, Checksum);
609 }
610 return createFile(FileName, CSInfo,
611 getSource(SM, SM.getFileID(getMacroDebugLoc(CGM, Loc))));
612 }
613
614 llvm::DIFile *CGDebugInfo::createFile(
615 StringRef FileName,
616 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
617 std::optional<StringRef> Source) {
618 StringRef Dir;
619 StringRef File;
620 std::string RemappedFile = remapDIPath(FileName);
621 std::string CurDir = remapDIPath(getCurrentDirname());
622 SmallString<128> DirBuf;
623 SmallString<128> FileBuf;
624 if (llvm::sys::path::is_absolute(RemappedFile)) {
625 // Strip the common prefix (if it is more than just "/" or "C:\") from
626 // current directory and FileName for a more space-efficient encoding.
627 auto FileIt = llvm::sys::path::begin(RemappedFile);
628 auto FileE = llvm::sys::path::end(RemappedFile);
629 auto CurDirIt = llvm::sys::path::begin(CurDir);
630 auto CurDirE = llvm::sys::path::end(CurDir);
631 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
632 llvm::sys::path::append(DirBuf, *CurDirIt);
633 if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
634 // Don't strip the common prefix if it is only the root ("/" or "C:\")
635 // since that would make LLVM diagnostic locations confusing.
636 Dir = {};
637 File = RemappedFile;
638 } else {
639 for (; FileIt != FileE; ++FileIt)
640 llvm::sys::path::append(FileBuf, *FileIt);
641 Dir = DirBuf;
642 File = FileBuf;
643 }
644 } else {
645 if (!llvm::sys::path::is_absolute(FileName))
646 Dir = CurDir;
647 File = RemappedFile;
648 }
649 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
650 DIFileCache[FileName.data()].reset(F);
651 return F;
652 }
653
654 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
655 SmallString<256> P = Path;
656 for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))
657 if (llvm::sys::path::replace_path_prefix(P, From, To))
658 break;
659 return P.str().str();
660 }
661
662 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
663 if (Loc.isInvalid())
664 return 0;
665 SourceManager &SM = CGM.getContext().getSourceManager();
666 return SM.getPresumedLoc(getMacroDebugLoc(CGM, Loc)).getLine();
667 }
668
669 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
670 // We may not want column information at all.
671 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
672 return 0;
673
674 // If the location is invalid then use the current column.
675 if (Loc.isInvalid() && CurLoc.isInvalid())
676 return 0;
677 SourceManager &SM = CGM.getContext().getSourceManager();
678 PresumedLoc PLoc =
679 SM.getPresumedLoc(Loc.isValid() ? getMacroDebugLoc(CGM, Loc) : CurLoc);
680 return PLoc.isValid() ? PLoc.getColumn() : 0;
681 }
682
683 StringRef CGDebugInfo::getCurrentDirname() {
684 return CGM.getCodeGenOpts().DebugCompilationDir;
685 }
686
687 static llvm::dwarf::SourceLanguage GetSourceLanguage(const CodeGenModule &CGM) {
688 const CodeGenOptions &CGO = CGM.getCodeGenOpts();
689 const LangOptions &LO = CGM.getLangOpts();
690
691 assert(CGO.DwarfVersion <= 5);
692
693 llvm::dwarf::SourceLanguage LangTag;
694 if (LO.CPlusPlus) {
695 if (LO.ObjC)
696 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
697 else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
698 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
699 else if (LO.CPlusPlus14)
700 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
701 else if (LO.CPlusPlus11)
702 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
703 else
704 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
705 } else if (LO.ObjC) {
706 LangTag = llvm::dwarf::DW_LANG_ObjC;
707 } else if (LO.OpenCL && (!CGO.DebugStrictDwarf || CGO.DwarfVersion >= 5)) {
708 LangTag = llvm::dwarf::DW_LANG_OpenCL;
709 } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
710 LangTag = llvm::dwarf::DW_LANG_C11;
711 } else if (LO.C99) {
712 LangTag = llvm::dwarf::DW_LANG_C99;
713 } else {
714 LangTag = llvm::dwarf::DW_LANG_C89;
715 }
716
717 return LangTag;
718 }
719
720 static llvm::DISourceLanguageName
721 GetDISourceLanguageName(const CodeGenModule &CGM) {
722 // Emit pre-DWARFv6 language codes.
723 if (CGM.getCodeGenOpts().DwarfVersion < 6)
724 return llvm::DISourceLanguageName(GetSourceLanguage(CGM));
725
726 const LangOptions &LO = CGM.getLangOpts();
727
728 uint32_t LangVersion = 0;
729 llvm::dwarf::SourceLanguageName LangTag;
730 if (LO.CPlusPlus) {
731 if (LO.ObjC) {
732 LangTag = llvm::dwarf::DW_LNAME_ObjC_plus_plus;
733 } else {
734 LangTag = llvm::dwarf::DW_LNAME_C_plus_plus;
735 LangVersion = LO.getCPlusPlusLangStd().value_or(0);
736 }
737 } else if (LO.ObjC) {
738 LangTag = llvm::dwarf::DW_LNAME_ObjC;
739 } else if (LO.OpenCL) {
740 LangTag = llvm::dwarf::DW_LNAME_OpenCL_C;
741 } else {
742 LangTag = llvm::dwarf::DW_LNAME_C;
743 LangVersion = LO.getCLangStd().value_or(0);
744 }
745
746 return llvm::DISourceLanguageName(LangTag, LangVersion);
747 }
748
749 void CGDebugInfo::CreateCompileUnit() {
750 SmallString<64> Checksum;
751 std::optional<llvm::DIFile::ChecksumKind> CSKind;
752 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
753
754 // Should we be asking the SourceManager for the main file name, instead of
755 // accepting it as an argument? This just causes the main file name to
756 // mismatch with source locations and create extra lexical scopes or
757 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
758 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
759 // because that's what the SourceManager says)
760
761 // Get absolute path name.
762 SourceManager &SM = CGM.getContext().getSourceManager();
763 auto &CGO = CGM.getCodeGenOpts();
764 const LangOptions &LO = CGM.getLangOpts();
765 std::string MainFileName = CGO.MainFileName;
766 if (MainFileName.empty())
767 MainFileName = "<stdin>";
768
769 // The main file name provided via the "-main-file-name" option contains just
770 // the file name itself with no path information. This file name may have had
771 // a relative path, so we look into the actual file entry for the main
772 // file to determine the real absolute path for the file.
773 std::string MainFileDir;
774 if (OptionalFileEntryRef MainFile =
775 SM.getFileEntryRefForID(SM.getMainFileID())) {
776 MainFileDir = std::string(MainFile->getDir().getName());
777 if (!llvm::sys::path::is_absolute(MainFileName)) {
778 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
779 llvm::sys::path::Style Style =
780 LO.UseTargetPathSeparator
781 ? (CGM.getTarget().getTriple().isOSWindows()
782 ? llvm::sys::path::Style::windows_backslash
783 : llvm::sys::path::Style::posix)
784 : llvm::sys::path::Style::native;
785 llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
786 MainFileName = std::string(
787 llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
788 }
789 // If the main file name provided is identical to the input file name, and
790 // if the input file is a preprocessed source, use the module name for
791 // debug info. The module name comes from the name specified in the first
792 // linemarker if the input is a preprocessed source. In this case we don't
793 // know the content to compute a checksum.
794 if (MainFile->getName() == MainFileName &&
795 FrontendOptions::getInputKindForExtension(
796 MainFile->getName().rsplit('.').second)
797 .isPreprocessed()) {
798 MainFileName = CGM.getModule().getName().str();
799 } else {
800 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
801 }
802 }
803
804 std::string Producer = getClangFullVersion();
805
806 // Figure out which version of the ObjC runtime we have.
807 unsigned RuntimeVers = 0;
808 if (LO.ObjC)
809 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
810
811 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
812 switch (DebugKind) {
813 case llvm::codegenoptions::NoDebugInfo:
814 case llvm::codegenoptions::LocTrackingOnly:
815 EmissionKind = llvm::DICompileUnit::NoDebug;
816 break;
817 case llvm::codegenoptions::DebugLineTablesOnly:
818 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
819 break;
820 case llvm::codegenoptions::DebugDirectivesOnly:
821 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
822 break;
823 case llvm::codegenoptions::DebugInfoConstructor:
824 case llvm::codegenoptions::LimitedDebugInfo:
825 case llvm::codegenoptions::FullDebugInfo:
826 case llvm::codegenoptions::UnusedTypeInfo:
827 EmissionKind = llvm::DICompileUnit::FullDebug;
828 break;
829 }
830
831 uint64_t DwoId = 0;
832 auto &CGOpts = CGM.getCodeGenOpts();
833 // The DIFile used by the CU is distinct from the main source
834 // file. Its directory part specifies what becomes the
835 // DW_AT_comp_dir (the compilation directory), even if the source
836 // file was specified with an absolute path.
837 if (CSKind)
838 CSInfo.emplace(*CSKind, Checksum);
839 llvm::DIFile *CUFile = DBuilder.createFile(
840 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
841 getSource(SM, SM.getMainFileID()));
842
843 StringRef Sysroot, SDK;
844 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
845 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
846 auto B = llvm::sys::path::rbegin(Sysroot);
847 auto E = llvm::sys::path::rend(Sysroot);
848 auto It =
849 std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });
850 if (It != E)
851 SDK = *It;
852 }
853
854 llvm::DICompileUnit::DebugNameTableKind NameTableKind =
855 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
856 CGOpts.DebugNameTable);
857 if (CGM.getTarget().getTriple().isNVPTX())
858 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;
859 else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
860 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;
861
862 // Create new compile unit.
863 TheCU = DBuilder.createCompileUnit(
864 GetDISourceLanguageName(CGM), CUFile,
865 CGOpts.EmitVersionIdentMetadata ? Producer : "",
866 CGOpts.OptimizationLevel != 0 || CGOpts.PrepareForLTO ||
867 CGOpts.PrepareForThinLTO,
868 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
869 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
870 NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
871 }
872
873 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
874 llvm::dwarf::TypeKind Encoding;
875 StringRef BTName;
876 switch (BT->getKind()) {
877 #define BUILTIN_TYPE(Id, SingletonId)
878 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
879 #include "clang/AST/BuiltinTypes.def"
880 case BuiltinType::Dependent:
881 llvm_unreachable("Unexpected builtin type");
882 case BuiltinType::NullPtr:
883 return DBuilder.createNullPtrType();
884 case BuiltinType::Void:
885 return nullptr;
886 case BuiltinType::ObjCClass:
887 if (!ClassTy)
888 ClassTy =
889 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
890 "objc_class", TheCU, TheCU->getFile(), 0);
891 return ClassTy;
892 case BuiltinType::ObjCId: {
893 // typedef struct objc_class *Class;
894 // typedef struct objc_object {
895 // Class isa;
896 // } *id;
897
898 if (ObjTy)
899 return ObjTy;
900
901 if (!ClassTy)
902 ClassTy =
903 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
904 "objc_class", TheCU, TheCU->getFile(), 0);
905
906 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
907
908 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
909
910 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
911 (uint64_t)0, 0, llvm::DINode::FlagZero,
912 nullptr, llvm::DINodeArray());
913
914 DBuilder.replaceArrays(
915 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
916 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
917 llvm::DINode::FlagZero, ISATy)));
918 return ObjTy;
919 }
920 case BuiltinType::ObjCSel: {
921 if (!SelTy)
922 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
923 "objc_selector", TheCU,
924 TheCU->getFile(), 0);
925 return SelTy;
926 }
927
928 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
929 case BuiltinType::Id: \
930 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
931 SingletonId);
932 #include "clang/Basic/OpenCLImageTypes.def"
933 case BuiltinType::OCLSampler:
934 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
935 case BuiltinType::OCLEvent:
936 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
937 case BuiltinType::OCLClkEvent:
938 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
939 case BuiltinType::OCLQueue:
940 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
941 case BuiltinType::OCLReserveID:
942 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
943 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
944 case BuiltinType::Id: \
945 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
946 #include "clang/Basic/OpenCLExtensionTypes.def"
947 #define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
948 case BuiltinType::Id: \
949 return getOrCreateStructPtrType(#Name, SingletonId);
950 #include "clang/Basic/HLSLIntangibleTypes.def"
951
952 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
953 #include "clang/Basic/AArch64ACLETypes.def"
954 {
955 if (BT->getKind() == BuiltinType::MFloat8) {
956 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
957 BTName = BT->getName(CGM.getLangOpts());
958 // Bit size and offset of the type.
959 uint64_t Size = CGM.getContext().getTypeSize(BT);
960 return DBuilder.createBasicType(BTName, Size, Encoding);
961 }
962 ASTContext::BuiltinVectorTypeInfo Info =
963 // For svcount_t, only the lower 2 bytes are relevant.
964 BT->getKind() == BuiltinType::SveCount
965 ? ASTContext::BuiltinVectorTypeInfo(
966 CGM.getContext().BoolTy, llvm::ElementCount::getFixed(16),
967 1)
968 : CGM.getContext().getBuiltinVectorTypeInfo(BT);
969
970 // A single vector of bytes may not suffice as the representation of
971 // svcount_t tuples because of the gap between the active 16bits of
972 // successive tuple members. Currently no such tuples are defined for
973 // svcount_t, so assert that NumVectors is 1.
974 assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) &&
975 "Unsupported number of vectors for svcount_t");
976
977 unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors;
978 llvm::Metadata *BitStride = nullptr;
979 if (BT->getKind() == BuiltinType::SveBool) {
980 Info.ElementType = CGM.getContext().UnsignedCharTy;
981 BitStride = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
982 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 1));
983 } else if (BT->getKind() == BuiltinType::SveCount) {
984 NumElems /= 8;
985 Info.ElementType = CGM.getContext().UnsignedCharTy;
986 }
987
988 llvm::Metadata *LowerBound, *UpperBound;
989 LowerBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
990 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
991 if (Info.EC.isScalable()) {
992 unsigned NumElemsPerVG = NumElems / 2;
993 SmallVector<uint64_t, 9> Expr(
994 {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
995 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
996 llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
997 UpperBound = DBuilder.createExpression(Expr);
998 } else
999 UpperBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
1000 llvm::Type::getInt64Ty(CGM.getLLVMContext()), NumElems - 1));
1001
1002 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
1003 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
1004 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1005 llvm::DIType *ElemTy =
1006 getOrCreateType(Info.ElementType, TheCU->getFile());
1007 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
1008 return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
1009 SubscriptArray, BitStride);
1010 }
1011 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
1012 // So we return a safe type here to avoid generating an error.
1013 #define PPC_VECTOR_TYPE(Name, Id, size) \
1014 case BuiltinType::Id:
1015 #include "clang/Basic/PPCTypes.def"
1016 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
1017
1018 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
1019 #include "clang/Basic/RISCVVTypes.def"
1020 {
1021 ASTContext::BuiltinVectorTypeInfo Info =
1022 CGM.getContext().getBuiltinVectorTypeInfo(BT);
1023
1024 unsigned ElementCount = Info.EC.getKnownMinValue();
1025 unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
1026
1027 bool Fractional = false;
1028 unsigned LMUL;
1029 unsigned NFIELDS = Info.NumVectors;
1030 unsigned FixedSize = ElementCount * SEW;
1031 if (Info.ElementType == CGM.getContext().BoolTy) {
1032 // Mask type only occupies one vector register.
1033 LMUL = 1;
1034 } else if (FixedSize < 64) {
1035 // In RVV scalable vector types, we encode 64 bits in the fixed part.
1036 Fractional = true;
1037 LMUL = 64 / FixedSize;
1038 } else {
1039 LMUL = FixedSize / 64;
1040 }
1041
1042 // Element count = (VLENB / SEW) x LMUL x NFIELDS
1043 SmallVector<uint64_t, 12> Expr(
1044 // The DW_OP_bregx operation has two operands: a register which is
1045 // specified by an unsigned LEB128 number, followed by a signed LEB128
1046 // offset.
1047 {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
1048 4096 + 0xC22, // RISC-V VLENB CSR register.
1049 0, // Offset for DW_OP_bregx. It is dummy here.
1050 llvm::dwarf::DW_OP_constu,
1051 SEW / 8, // SEW is in bits.
1052 llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
1053 if (Fractional)
1054 Expr.push_back(llvm::dwarf::DW_OP_div);
1055 else
1056 Expr.push_back(llvm::dwarf::DW_OP_mul);
1057 // NFIELDS multiplier
1058 if (NFIELDS > 1)
1059 Expr.append({llvm::dwarf::DW_OP_constu, NFIELDS, llvm::dwarf::DW_OP_mul});
1060 // Element max index = count - 1
1061 Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
1062
1063 auto *LowerBound =
1064 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
1065 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
1066 auto *UpperBound = DBuilder.createExpression(Expr);
1067 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
1068 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
1069 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1070 llvm::DIType *ElemTy =
1071 getOrCreateType(Info.ElementType, TheCU->getFile());
1072
1073 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
1074 return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
1075 SubscriptArray);
1076 }
1077
1078 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
1079 case BuiltinType::Id: { \
1080 if (!SingletonId) \
1081 SingletonId = \
1082 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
1083 MangledName, TheCU, TheCU->getFile(), 0); \
1084 return SingletonId; \
1085 }
1086 #include "clang/Basic/WebAssemblyReferenceTypes.def"
1087 #define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
1088 case BuiltinType::Id: { \
1089 if (!SingletonId) \
1090 SingletonId = \
1091 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, \
1092 TheCU, TheCU->getFile(), 0); \
1093 return SingletonId; \
1094 }
1095 #define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
1096 case BuiltinType::Id: { \
1097 if (!SingletonId) \
1098 SingletonId = \
1099 DBuilder.createBasicType(Name, Width, llvm::dwarf::DW_ATE_unsigned); \
1100 return SingletonId; \
1101 }
1102 #include "clang/Basic/AMDGPUTypes.def"
1103 case BuiltinType::UChar:
1104 case BuiltinType::Char_U:
1105 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
1106 break;
1107 case BuiltinType::Char_S:
1108 case BuiltinType::SChar:
1109 Encoding = llvm::dwarf::DW_ATE_signed_char;
1110 break;
1111 case BuiltinType::Char8:
1112 case BuiltinType::Char16:
1113 case BuiltinType::Char32:
1114 Encoding = llvm::dwarf::DW_ATE_UTF;
1115 break;
1116 case BuiltinType::UShort:
1117 case BuiltinType::UInt:
1118 case BuiltinType::UInt128:
1119 case BuiltinType::ULong:
1120 case BuiltinType::WChar_U:
1121 case BuiltinType::ULongLong:
1122 Encoding = llvm::dwarf::DW_ATE_unsigned;
1123 break;
1124 case BuiltinType::Short:
1125 case BuiltinType::Int:
1126 case BuiltinType::Int128:
1127 case BuiltinType::Long:
1128 case BuiltinType::WChar_S:
1129 case BuiltinType::LongLong:
1130 Encoding = llvm::dwarf::DW_ATE_signed;
1131 break;
1132 case BuiltinType::Bool:
1133 Encoding = llvm::dwarf::DW_ATE_boolean;
1134 break;
1135 case BuiltinType::Half:
1136 case BuiltinType::Float:
1137 case BuiltinType::LongDouble:
1138 case BuiltinType::Float16:
1139 case BuiltinType::BFloat16:
1140 case BuiltinType::Float128:
1141 case BuiltinType::Double:
1142 case BuiltinType::Ibm128:
1143 // FIXME: For targets where long double, __ibm128 and __float128 have the
1144 // same size, they are currently indistinguishable in the debugger without
1145 // some special treatment. However, there is currently no consensus on
1146 // encoding and this should be updated once a DWARF encoding exists for
1147 // distinct floating point types of the same size.
1148 Encoding = llvm::dwarf::DW_ATE_float;
1149 break;
1150 case BuiltinType::ShortAccum:
1151 case BuiltinType::Accum:
1152 case BuiltinType::LongAccum:
1153 case BuiltinType::ShortFract:
1154 case BuiltinType::Fract:
1155 case BuiltinType::LongFract:
1156 case BuiltinType::SatShortFract:
1157 case BuiltinType::SatFract:
1158 case BuiltinType::SatLongFract:
1159 case BuiltinType::SatShortAccum:
1160 case BuiltinType::SatAccum:
1161 case BuiltinType::SatLongAccum:
1162 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
1163 break;
1164 case BuiltinType::UShortAccum:
1165 case BuiltinType::UAccum:
1166 case BuiltinType::ULongAccum:
1167 case BuiltinType::UShortFract:
1168 case BuiltinType::UFract:
1169 case BuiltinType::ULongFract:
1170 case BuiltinType::SatUShortAccum:
1171 case BuiltinType::SatUAccum:
1172 case BuiltinType::SatULongAccum:
1173 case BuiltinType::SatUShortFract:
1174 case BuiltinType::SatUFract:
1175 case BuiltinType::SatULongFract:
1176 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
1177 break;
1178 }
1179
1180 BTName = BT->getName(CGM.getLangOpts());
1181 // Bit size and offset of the type.
1182 uint64_t Size = CGM.getContext().getTypeSize(BT);
1183 return DBuilder.createBasicType(BTName, Size, Encoding);
1184 }
1185
1186 llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
1187 SmallString<32> Name;
1188 llvm::raw_svector_ostream OS(Name);
1189 OS << (Ty->isUnsigned() ? "unsigned _BitInt(" : "_BitInt(")
1190 << Ty->getNumBits() << ")";
1191 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
1192 ? llvm::dwarf::DW_ATE_unsigned
1193 : llvm::dwarf::DW_ATE_signed;
1194 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
1195 Encoding, llvm::DINode::FlagZero, 0,
1196 Ty->getNumBits());
1197 }
1198
1199 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
1200 // Bit size and offset of the type.
1201 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
1202 if (Ty->isComplexIntegerType())
1203 Encoding = llvm::dwarf::DW_ATE_lo_user;
1204
1205 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1206 return DBuilder.createBasicType("complex", Size, Encoding);
1207 }
1208
1209 static void stripUnusedQualifiers(Qualifiers &Q) {
1210 // Ignore these qualifiers for now.
1211 Q.removeObjCGCAttr();
1212 Q.removeAddressSpace();
1213 Q.removeObjCLifetime();
1214 Q.removeUnaligned();
1215 }
1216
1217 static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
1218 if (Q.hasConst()) {
1219 Q.removeConst();
1220 return llvm::dwarf::DW_TAG_const_type;
1221 }
1222 if (Q.hasVolatile()) {
1223 Q.removeVolatile();
1224 return llvm::dwarf::DW_TAG_volatile_type;
1225 }
1226 if (Q.hasRestrict()) {
1227 Q.removeRestrict();
1228 return llvm::dwarf::DW_TAG_restrict_type;
1229 }
1230 return (llvm::dwarf::Tag)0;
1231 }
1232
1233 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
1234 llvm::DIFile *Unit) {
1235 QualifierCollector Qc;
1236 const Type *T = Qc.strip(Ty);
1237
1238 stripUnusedQualifiers(Qc);
1239
1240 // We will create one Derived type for one qualifier and recurse to handle any
1241 // additional ones.
1242 llvm::dwarf::Tag Tag = getNextQualifier(Qc);
1243 if (!Tag) {
1244 if (Qc.getPointerAuth()) {
1245 unsigned Key = Qc.getPointerAuth().getKey();
1246 bool IsDiscr = Qc.getPointerAuth().isAddressDiscriminated();
1247 unsigned ExtraDiscr = Qc.getPointerAuth().getExtraDiscriminator();
1248 bool IsaPointer = Qc.getPointerAuth().isIsaPointer();
1249 bool AuthenticatesNullValues =
1250 Qc.getPointerAuth().authenticatesNullValues();
1251 Qc.removePointerAuth();
1252 assert(Qc.empty() && "Unknown type qualifier for debug info");
1253 llvm::DIType *FromTy = getOrCreateType(QualType(T, 0), Unit);
1254 return DBuilder.createPtrAuthQualifiedType(FromTy, Key, IsDiscr,
1255 ExtraDiscr, IsaPointer,
1256 AuthenticatesNullValues);
1257 } else {
1258 assert(Qc.empty() && "Unknown type qualifier for debug info");
1259 return getOrCreateType(QualType(T, 0), Unit);
1260 }
1261 }
1262
1263 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
1264
1265 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1266 // CVR derived types.
1267 return DBuilder.createQualifiedType(Tag, FromTy);
1268 }
1269
1270 llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
1271 llvm::DIFile *Unit) {
1272 FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();
1273 Qualifiers &Q = EPI.TypeQuals;
1274 stripUnusedQualifiers(Q);
1275
1276 // We will create one Derived type for one qualifier and recurse to handle any
1277 // additional ones.
1278 llvm::dwarf::Tag Tag = getNextQualifier(Q);
1279 if (!Tag) {
1280 assert(Q.empty() && "Unknown type qualifier for debug info");
1281 return nullptr;
1282 }
1283
1284 auto *FromTy =
1285 getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
1286 F->getParamTypes(), EPI),
1287 Unit);
1288
1289 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1290 // CVR derived types.
1291 return DBuilder.createQualifiedType(Tag, FromTy);
1292 }
1293
1294 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1295 llvm::DIFile *Unit) {
1296
1297 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1298 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1299 // debug info, we want to emit 'id' in both cases.
1300 if (Ty->isObjCQualifiedIdType())
1301 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1302
1303 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1304 Ty->getPointeeType(), Unit);
1305 }
1306
1307 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
1308 llvm::DIFile *Unit) {
1309 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1310 Ty->getPointeeType(), Unit);
1311 }
1312
1313 static bool hasCXXMangling(llvm::dwarf::SourceLanguage Lang, bool IsTagDecl) {
1314 switch (Lang) {
1315 case llvm::dwarf::DW_LANG_C_plus_plus:
1316 case llvm::dwarf::DW_LANG_C_plus_plus_11:
1317 case llvm::dwarf::DW_LANG_C_plus_plus_14:
1318 return true;
1319 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1320 return IsTagDecl;
1321 default:
1322 return false;
1323 }
1324 }
1325
1326 static bool hasCXXMangling(llvm::dwarf::SourceLanguageName Lang,
1327 bool IsTagDecl) {
1328 switch (Lang) {
1329 case llvm::dwarf::DW_LNAME_C_plus_plus:
1330 return true;
1331 case llvm::dwarf::DW_LNAME_ObjC_plus_plus:
1332 return IsTagDecl;
1333 default:
1334 return false;
1335 }
1336 }
1337
1338 /// \return whether a C++ mangling exists for the type defined by TD.
1339 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1340 const bool IsTagDecl = isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1341
1342 if (llvm::DISourceLanguageName SourceLang = TheCU->getSourceLanguage();
1343 SourceLang.hasVersionedName())
1344 return hasCXXMangling(
1345 static_cast<llvm::dwarf::SourceLanguageName>(SourceLang.getName()),
1346 IsTagDecl);
1347 else
1348 return hasCXXMangling(
1349 static_cast<llvm::dwarf::SourceLanguage>(SourceLang.getName()),
1350 IsTagDecl);
1351 }
1352
1353 // Determines if the debug info for this tag declaration needs a type
1354 // identifier. The purpose of the unique identifier is to deduplicate type
1355 // information for identical types across TUs. Because of the C++ one definition
1356 // rule (ODR), it is valid to assume that the type is defined the same way in
1357 // every TU and its debug info is equivalent.
1358 //
1359 // C does not have the ODR, and it is common for codebases to contain multiple
1360 // different definitions of a struct with the same name in different TUs.
1361 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1362 // identifer. Type information in C is smaller and simpler than C++ type
1363 // information, so the increase in debug info size is negligible.
1364 //
1365 // If the type is not externally visible, it should be unique to the current TU,
1366 // and should not need an identifier to participate in type deduplication.
1367 // However, when emitting CodeView, the format internally uses these
1368 // unique type name identifers for references between debug info. For example,
1369 // the method of a class in an anonymous namespace uses the identifer to refer
1370 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1371 // for such types, so when emitting CodeView, always use identifiers for C++
1372 // types. This may create problems when attempting to emit CodeView when the MS
1373 // C++ ABI is not in use.
1374 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1375 llvm::DICompileUnit *TheCU) {
1376 // We only add a type identifier for types with C++ name mangling.
1377 if (!hasCXXMangling(TD, TheCU))
1378 return false;
1379
1380 // Externally visible types with C++ mangling need a type identifier.
1381 if (TD->isExternallyVisible())
1382 return true;
1383
1384 // CodeView types with C++ mangling need a type identifier.
1385 if (CGM.getCodeGenOpts().EmitCodeView)
1386 return true;
1387
1388 return false;
1389 }
1390
1391 // Returns a unique type identifier string if one exists, or an empty string.
1392 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1393 llvm::DICompileUnit *TheCU) {
1394 SmallString<256> Identifier;
1395 const TagDecl *TD = Ty->getDecl()->getDefinitionOrSelf();
1396
1397 if (!needsTypeIdentifier(TD, CGM, TheCU))
1398 return Identifier;
1399 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1400 if (RD->getDefinition())
1401 if (RD->isDynamicClass() &&
1402 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1403 return Identifier;
1404
1405 // TODO: This is using the RTTI name. Is there a better way to get
1406 // a unique string for a type?
1407 llvm::raw_svector_ostream Out(Identifier);
1408 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
1409 return Identifier;
1410 }
1411
1412 /// \return the appropriate DWARF tag for a composite type.
1413 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1414 llvm::dwarf::Tag Tag;
1415 if (RD->isStruct() || RD->isInterface())
1416 Tag = llvm::dwarf::DW_TAG_structure_type;
1417 else if (RD->isUnion())
1418 Tag = llvm::dwarf::DW_TAG_union_type;
1419 else {
1420 // FIXME: This could be a struct type giving a default visibility different
1421 // than C++ class type, but needs llvm metadata changes first.
1422 assert(RD->isClass());
1423 Tag = llvm::dwarf::DW_TAG_class_type;
1424 }
1425 return Tag;
1426 }
1427
1428 llvm::DICompositeType *
1429 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1430 llvm::DIScope *Ctx) {
1431 const RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
1432 if (llvm::DIType *T = getTypeOrNull(QualType(Ty, 0)))
1433 return cast<llvm::DICompositeType>(T);
1434 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1435 const unsigned Line =
1436 getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1437 StringRef RDName = getClassName(RD);
1438
1439 uint64_t Size = 0;
1440 uint32_t Align = 0;
1441
1442 const RecordDecl *D = RD->getDefinition();
1443 if (D && D->isCompleteDefinition())
1444 Size = CGM.getContext().getTypeSize(Ty);
1445
1446 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1447
1448 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1449 // add the flag if a record has no definition because we don't know whether
1450 // it will be trivial or not.
1451 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1452 if (!CXXRD->hasDefinition() ||
1453 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1454 Flags |= llvm::DINode::FlagNonTrivial;
1455
1456 // Create the type.
1457 SmallString<256> Identifier;
1458 // Don't include a linkage name in line tables only.
1459 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1460 Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1461 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1462 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1463 Identifier);
1464 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1465 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1466 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1467 CollectCXXTemplateParams(TSpecial, DefUnit));
1468 ReplaceMap.emplace_back(
1469 std::piecewise_construct, std::make_tuple(Ty),
1470 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1471 return RetTy;
1472 }
1473
1474 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1475 const Type *Ty,
1476 QualType PointeeTy,
1477 llvm::DIFile *Unit) {
1478 // Bit size, align and offset of the type.
1479 // Size is always the size of a pointer.
1480 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1481 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1482 std::optional<unsigned> DWARFAddressSpace =
1483 CGM.getTarget().getDWARFAddressSpace(
1484 CGM.getTypes().getTargetAddressSpace(PointeeTy));
1485
1486 const BTFTagAttributedType *BTFAttrTy;
1487 if (auto *Atomic = PointeeTy->getAs<AtomicType>())
1488 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Atomic->getValueType());
1489 else
1490 BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1491 SmallVector<llvm::Metadata *, 4> Annots;
1492 while (BTFAttrTy) {
1493 StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1494 if (!Tag.empty()) {
1495 llvm::Metadata *Ops[2] = {
1496 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1497 llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1498 Annots.insert(Annots.begin(),
1499 llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1500 }
1501 BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1502 }
1503
1504 llvm::DINodeArray Annotations = nullptr;
1505 if (Annots.size() > 0)
1506 Annotations = DBuilder.getOrCreateArray(Annots);
1507
1508 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1509 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1510 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1511 Size, Align, DWARFAddressSpace);
1512 else
1513 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1514 Align, DWARFAddressSpace, StringRef(),
1515 Annotations);
1516 }
1517
1518 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1519 llvm::DIType *&Cache) {
1520 if (Cache)
1521 return Cache;
1522 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1523 TheCU, TheCU->getFile(), 0);
1524 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1525 Cache = DBuilder.createPointerType(Cache, Size);
1526 return Cache;
1527 }
1528
1529 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1530 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1531 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1532 QualType FType;
1533
1534 // Advanced by calls to CreateMemberType in increments of FType, then
1535 // returned as the overall size of the default elements.
1536 uint64_t FieldOffset = 0;
1537
1538 // Blocks in OpenCL have unique constraints which make the standard fields
1539 // redundant while requiring size and align fields for enqueue_kernel. See
1540 // initializeForBlockHeader in CGBlocks.cpp
1541 if (CGM.getLangOpts().OpenCL) {
1542 FType = CGM.getContext().IntTy;
1543 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1544 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1545 } else {
1546 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1547 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1548 FType = CGM.getContext().IntTy;
1549 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1550 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1551 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1552 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1553 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1554 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1555 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1556 EltTys.push_back(DBuilder.createMemberType(
1557 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1558 FieldOffset, llvm::DINode::FlagZero, DescTy));
1559 FieldOffset += FieldSize;
1560 }
1561
1562 return FieldOffset;
1563 }
1564
1565 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1566 llvm::DIFile *Unit) {
1567 SmallVector<llvm::Metadata *, 8> EltTys;
1568 QualType FType;
1569 uint64_t FieldOffset;
1570 llvm::DINodeArray Elements;
1571
1572 FieldOffset = 0;
1573 FType = CGM.getContext().UnsignedLongTy;
1574 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1575 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1576
1577 Elements = DBuilder.getOrCreateArray(EltTys);
1578 EltTys.clear();
1579
1580 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1581
1582 auto *EltTy =
1583 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1584 FieldOffset, 0, Flags, nullptr, Elements);
1585
1586 // Bit size, align and offset of the type.
1587 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1588
1589 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1590
1591 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1592 0, EltTys);
1593
1594 Elements = DBuilder.getOrCreateArray(EltTys);
1595
1596 // The __block_literal_generic structs are marked with a special
1597 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1598 // the debugger needs to know about. To allow type uniquing, emit
1599 // them without a name or a location.
1600 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1601 Flags, nullptr, Elements);
1602
1603 return DBuilder.createPointerType(EltTy, Size);
1604 }
1605
1606 static llvm::SmallVector<TemplateArgument>
1607 GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) {
1608 assert(Ty->isTypeAlias());
1609 // TemplateSpecializationType doesn't know if its template args are
1610 // being substituted into a parameter pack. We can find out if that's
1611 // the case now by inspecting the TypeAliasTemplateDecl template
1612 // parameters. Insert Ty's template args into SpecArgs, bundling args
1613 // passed to a parameter pack into a TemplateArgument::Pack. It also
1614 // doesn't know the value of any defaulted args, so collect those now
1615 // too.
1616 SmallVector<TemplateArgument> SpecArgs;
1617 ArrayRef SubstArgs = Ty->template_arguments();
1618 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1619 // If Param is a parameter pack, pack the remaining arguments.
1620 if (Param->isParameterPack()) {
1621 SpecArgs.push_back(TemplateArgument(SubstArgs));
1622 break;
1623 }
1624
1625 // Skip defaulted args.
1626 // FIXME: Ideally, we wouldn't do this. We can read the default values
1627 // for each parameter. However, defaulted arguments which are dependent
1628 // values or dependent types can't (easily?) be resolved here.
1629 if (SubstArgs.empty()) {
1630 // If SubstArgs is now empty (we're taking from it each iteration) and
1631 // this template parameter isn't a pack, then that should mean we're
1632 // using default values for the remaining template parameters (after
1633 // which there may be an empty pack too which we will ignore).
1634 break;
1635 }
1636
1637 // Take the next argument.
1638 SpecArgs.push_back(SubstArgs.front());
1639 SubstArgs = SubstArgs.drop_front();
1640 }
1641 return SpecArgs;
1642 }
1643
1644 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1645 llvm::DIFile *Unit) {
1646 assert(Ty->isTypeAlias());
1647 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1648
1649 const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl();
1650 if (isa<BuiltinTemplateDecl>(TD))
1651 return Src;
1652
1653 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1654 if (AliasDecl->hasAttr<NoDebugAttr>())
1655 return Src;
1656
1657 SmallString<128> NS;
1658 llvm::raw_svector_ostream OS(NS);
1659
1660 auto PP = getPrintingPolicy();
1661 Ty->getTemplateName().print(OS, PP, TemplateName::Qualified::None);
1662
1663 SourceLocation Loc = AliasDecl->getLocation();
1664
1665 if (CGM.getCodeGenOpts().DebugTemplateAlias) {
1666 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1667 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1668
1669 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1670 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1671 // doesn't have instantiation information, so
1672 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1673 // template args.
1674 std::string Name;
1675 llvm::raw_string_ostream OS(Name);
1676 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1677 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1678 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1679 !HasReconstitutableArgs(Args.Args))
1680 printTemplateArgumentList(OS, Args.Args, PP);
1681
1682 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1683 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1684 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1685 return AliasTy;
1686 }
1687
1688 printTemplateArgumentList(OS, Ty->template_arguments(), PP,
1689 TD->getTemplateParameters());
1690 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1691 getLineNumber(Loc),
1692 getDeclContextDescriptor(AliasDecl));
1693 }
1694
1695 /// Convert an AccessSpecifier into the corresponding DINode flag.
1696 /// As an optimization, return 0 if the access specifier equals the
1697 /// default for the containing type.
1698 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1699 const RecordDecl *RD) {
1700 AccessSpecifier Default = clang::AS_none;
1701 if (RD && RD->isClass())
1702 Default = clang::AS_private;
1703 else if (RD && (RD->isStruct() || RD->isUnion()))
1704 Default = clang::AS_public;
1705
1706 if (Access == Default)
1707 return llvm::DINode::FlagZero;
1708
1709 switch (Access) {
1710 case clang::AS_private:
1711 return llvm::DINode::FlagPrivate;
1712 case clang::AS_protected:
1713 return llvm::DINode::FlagProtected;
1714 case clang::AS_public:
1715 return llvm::DINode::FlagPublic;
1716 case clang::AS_none:
1717 return llvm::DINode::FlagZero;
1718 }
1719 llvm_unreachable("unexpected access enumerator");
1720 }
1721
1722 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1723 llvm::DIFile *Unit) {
1724 llvm::DIType *Underlying =
1725 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1726
1727 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1728 return Underlying;
1729
1730 // We don't set size information, but do specify where the typedef was
1731 // declared.
1732 SourceLocation Loc = Ty->getDecl()->getLocation();
1733
1734 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1735 // Typedefs are derived from some other type.
1736 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1737
1738 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1739 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1740 if (isa<RecordDecl>(DC))
1741 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1742
1743 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1744 getOrCreateFile(Loc), getLineNumber(Loc),
1745 getDeclContextDescriptor(Ty->getDecl()), Align,
1746 Flags, Annotations);
1747 }
1748
1749 static unsigned getDwarfCC(CallingConv CC) {
1750 switch (CC) {
1751 case CC_C:
1752 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1753 return 0;
1754
1755 case CC_X86StdCall:
1756 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1757 case CC_X86FastCall:
1758 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1759 case CC_X86ThisCall:
1760 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1761 case CC_X86VectorCall:
1762 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1763 case CC_X86Pascal:
1764 return llvm::dwarf::DW_CC_BORLAND_pascal;
1765 case CC_Win64:
1766 return llvm::dwarf::DW_CC_LLVM_Win64;
1767 case CC_X86_64SysV:
1768 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1769 case CC_AAPCS:
1770 case CC_AArch64VectorCall:
1771 case CC_AArch64SVEPCS:
1772 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1773 case CC_AAPCS_VFP:
1774 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1775 case CC_IntelOclBicc:
1776 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1777 case CC_SpirFunction:
1778 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1779 case CC_DeviceKernel:
1780 return llvm::dwarf::DW_CC_LLVM_DeviceKernel;
1781 case CC_Swift:
1782 return llvm::dwarf::DW_CC_LLVM_Swift;
1783 case CC_SwiftAsync:
1784 return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1785 case CC_PreserveMost:
1786 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1787 case CC_PreserveAll:
1788 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1789 case CC_X86RegCall:
1790 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1791 case CC_M68kRTD:
1792 return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1793 case CC_PreserveNone:
1794 return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1795 case CC_RISCVVectorCall:
1796 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1797 #define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN:
1798 CC_VLS_CASE(32)
1799 CC_VLS_CASE(64)
1800 CC_VLS_CASE(128)
1801 CC_VLS_CASE(256)
1802 CC_VLS_CASE(512)
1803 CC_VLS_CASE(1024)
1804 CC_VLS_CASE(2048)
1805 CC_VLS_CASE(4096)
1806 CC_VLS_CASE(8192)
1807 CC_VLS_CASE(16384)
1808 CC_VLS_CASE(32768)
1809 CC_VLS_CASE(65536)
1810 #undef CC_VLS_CASE
1811 return llvm::dwarf::DW_CC_LLVM_RISCVVLSCall;
1812 }
1813 return 0;
1814 }
1815
1816 static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1817 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1818 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1819 Flags |= llvm::DINode::FlagLValueReference;
1820 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1821 Flags |= llvm::DINode::FlagRValueReference;
1822 return Flags;
1823 }
1824
1825 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1826 llvm::DIFile *Unit) {
1827 const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1828 if (FPT) {
1829 if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1830 return QTy;
1831 }
1832
1833 // Create the type without any qualifiers
1834
1835 SmallVector<llvm::Metadata *, 16> EltTys;
1836
1837 // Add the result type at least.
1838 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1839
1840 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1841 // Set up remainder of arguments if there is a prototype.
1842 // otherwise emit it as a variadic function.
1843 if (!FPT) {
1844 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1845 } else {
1846 Flags = getRefFlags(FPT);
1847 for (const QualType &ParamType : FPT->param_types())
1848 EltTys.push_back(getOrCreateType(ParamType, Unit));
1849 if (FPT->isVariadic())
1850 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1851 }
1852
1853 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1854 llvm::DIType *F = DBuilder.createSubroutineType(
1855 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1856 return F;
1857 }
1858
1859 llvm::DIDerivedType *
1860 CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1861 llvm::DIScope *RecordTy, const RecordDecl *RD) {
1862 StringRef Name = BitFieldDecl->getName();
1863 QualType Ty = BitFieldDecl->getType();
1864 if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1865 Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1866 SourceLocation Loc = BitFieldDecl->getLocation();
1867 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1868 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1869
1870 // Get the location for the field.
1871 llvm::DIFile *File = getOrCreateFile(Loc);
1872 unsigned Line = getLineNumber(Loc);
1873
1874 const CGBitFieldInfo &BitFieldInfo =
1875 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1876 uint64_t SizeInBits = BitFieldInfo.Size;
1877 assert(SizeInBits > 0 && "found named 0-width bitfield");
1878 uint64_t StorageOffsetInBits =
1879 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1880 uint64_t Offset = BitFieldInfo.Offset;
1881 // The bit offsets for big endian machines are reversed for big
1882 // endian target, compensate for that as the DIDerivedType requires
1883 // un-reversed offsets.
1884 if (CGM.getDataLayout().isBigEndian())
1885 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1886 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1887 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1888 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1889 return DBuilder.createBitFieldMemberType(
1890 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1891 Flags, DebugType, Annotations);
1892 }
1893
1894 llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1895 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1896 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1897
1898 if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())
1899 return nullptr;
1900
1901 /*
1902 Add a *single* zero-bitfield separator between two non-zero bitfields
1903 separated by one or more zero-bitfields. This is used to distinguish between
1904 structures such the ones below, where the memory layout is the same, but how
1905 the ABI assigns fields to registers differs.
1906
1907 struct foo {
1908 int space[4];
1909 char a : 8; // on amdgpu, passed on v4
1910 char b : 8;
1911 char x : 8;
1912 char y : 8;
1913 };
1914 struct bar {
1915 int space[4];
1916 char a : 8; // on amdgpu, passed on v4
1917 char b : 8;
1918 char : 0;
1919 char x : 8; // passed on v5
1920 char y : 8;
1921 };
1922 */
1923 if (PreviousFieldsDI.empty())
1924 return nullptr;
1925
1926 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1927 auto *PreviousMDEntry =
1928 PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1929 auto *PreviousMDField =
1930 dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1931 if (!PreviousMDField || !PreviousMDField->isBitField() ||
1932 PreviousMDField->getSizeInBits() == 0)
1933 return nullptr;
1934
1935 auto PreviousBitfield = RD->field_begin();
1936 std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1937
1938 assert(PreviousBitfield->isBitField());
1939
1940 if (!PreviousBitfield->isZeroLengthBitField())
1941 return nullptr;
1942
1943 QualType Ty = PreviousBitfield->getType();
1944 SourceLocation Loc = PreviousBitfield->getLocation();
1945 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1946 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1947 llvm::DIScope *RecordTy = BitFieldDI->getScope();
1948
1949 llvm::DIFile *File = getOrCreateFile(Loc);
1950 unsigned Line = getLineNumber(Loc);
1951
1952 uint64_t StorageOffsetInBits =
1953 cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1954 ->getZExtValue();
1955
1956 llvm::DINode::DIFlags Flags =
1957 getAccessFlag(PreviousBitfield->getAccess(), RD);
1958 llvm::DINodeArray Annotations =
1959 CollectBTFDeclTagAnnotations(*PreviousBitfield);
1960 return DBuilder.createBitFieldMemberType(
1961 RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
1962 Flags, DebugType, Annotations);
1963 }
1964
1965 llvm::DIType *CGDebugInfo::createFieldType(
1966 StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1967 uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1968 llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1969 llvm::DIType *debugType = getOrCreateType(type, tunit);
1970
1971 // Get the location for the field.
1972 llvm::DIFile *file = getOrCreateFile(loc);
1973 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1974
1975 uint64_t SizeInBits = 0;
1976 auto Align = AlignInBits;
1977 if (!type->isIncompleteArrayType()) {
1978 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1979 SizeInBits = TI.Width;
1980 if (!Align)
1981 Align = getTypeAlignIfRequired(type, CGM.getContext());
1982 }
1983
1984 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1985 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1986 offsetInBits, flags, debugType, Annotations);
1987 }
1988
1989 llvm::DISubprogram *
1990 CGDebugInfo::createInlinedSubprogram(StringRef FuncName,
1991 llvm::DIFile *FileScope) {
1992 // We are caching the subprogram because we don't want to duplicate
1993 // subprograms with the same message. Note that `SPFlagDefinition` prevents
1994 // subprograms from being uniqued.
1995 llvm::DISubprogram *&SP = InlinedSubprogramMap[FuncName];
1996
1997 if (!SP) {
1998 llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(nullptr);
1999 SP = DBuilder.createFunction(
2000 /*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(),
2001 /*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy,
2002 /*ScopeLine=*/0,
2003 /*Flags=*/llvm::DINode::FlagArtificial,
2004 /*SPFlags=*/llvm::DISubprogram::SPFlagDefinition,
2005 /*TParams=*/nullptr, /*Decl=*/nullptr, /*ThrownTypes=*/nullptr,
2006 /*Annotations=*/nullptr, /*TargetFuncName=*/StringRef(),
2007 /*UseKeyInstructions=*/CGM.getCodeGenOpts().DebugKeyInstructions);
2008 }
2009
2010 return SP;
2011 }
2012
2013 llvm::StringRef
2014 CGDebugInfo::GetLambdaCaptureName(const LambdaCapture &Capture) {
2015 if (Capture.capturesThis())
2016 return CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
2017
2018 assert(Capture.capturesVariable());
2019
2020 const ValueDecl *CaptureDecl = Capture.getCapturedVar();
2021 assert(CaptureDecl && "Expected valid decl for captured variable.");
2022
2023 return CaptureDecl->getName();
2024 }
2025
2026 void CGDebugInfo::CollectRecordLambdaFields(
2027 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
2028 llvm::DIType *RecordTy) {
2029 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
2030 // has the name and the location of the variable so we should iterate over
2031 // both concurrently.
2032 RecordDecl::field_iterator Field = CXXDecl->field_begin();
2033 unsigned fieldno = 0;
2034 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
2035 E = CXXDecl->captures_end();
2036 I != E; ++I, ++Field, ++fieldno) {
2037 const LambdaCapture &Capture = *I;
2038 const uint64_t FieldOffset =
2039 CGM.getContext().getASTRecordLayout(CXXDecl).getFieldOffset(fieldno);
2040
2041 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
2042
2043 SourceLocation Loc;
2044 uint32_t Align = 0;
2045
2046 if (Capture.capturesThis()) {
2047 // TODO: Need to handle 'this' in some way by probably renaming the
2048 // this of the lambda class and having a field member of 'this' or
2049 // by using AT_object_pointer for the function and having that be
2050 // used as 'this' for semantic references.
2051 Loc = Field->getLocation();
2052 } else if (Capture.capturesVariable()) {
2053 Loc = Capture.getLocation();
2054
2055 const ValueDecl *CaptureDecl = Capture.getCapturedVar();
2056 assert(CaptureDecl && "Expected valid decl for captured variable.");
2057
2058 Align = getDeclAlignIfRequired(CaptureDecl, CGM.getContext());
2059 } else {
2060 continue;
2061 }
2062
2063 llvm::DIFile *VUnit = getOrCreateFile(Loc);
2064
2065 elements.push_back(createFieldType(
2066 GetLambdaCaptureName(Capture), Field->getType(), Loc,
2067 Field->getAccess(), FieldOffset, Align, VUnit, RecordTy, CXXDecl));
2068 }
2069 }
2070
2071 llvm::DIDerivedType *
2072 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
2073 const RecordDecl *RD) {
2074 // Create the descriptor for the static variable, with or without
2075 // constant initializers.
2076 Var = Var->getCanonicalDecl();
2077 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
2078 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
2079
2080 unsigned LineNumber = getLineNumber(Var->getLocation());
2081 StringRef VName = Var->getName();
2082
2083 // FIXME: to avoid complications with type merging we should
2084 // emit the constant on the definition instead of the declaration.
2085 llvm::Constant *C = nullptr;
2086 if (Var->getInit()) {
2087 const APValue *Value = Var->evaluateValue();
2088 if (Value) {
2089 if (Value->isInt())
2090 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
2091 if (Value->isFloat())
2092 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
2093 }
2094 }
2095
2096 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
2097 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
2098 ? llvm::dwarf::DW_TAG_variable
2099 : llvm::dwarf::DW_TAG_member;
2100 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
2101 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
2102 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
2103 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
2104 return GV;
2105 }
2106
2107 void CGDebugInfo::CollectRecordNormalField(
2108 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
2109 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
2110 const RecordDecl *RD) {
2111 StringRef name = field->getName();
2112 QualType type = field->getType();
2113
2114 // Ignore unnamed fields unless they're anonymous structs/unions.
2115 if (name.empty() && !type->isRecordType())
2116 return;
2117
2118 llvm::DIType *FieldType;
2119 if (field->isBitField()) {
2120 llvm::DIDerivedType *BitFieldType;
2121 FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
2122 if (llvm::DIType *Separator =
2123 createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
2124 elements.push_back(Separator);
2125 } else {
2126 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
2127 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
2128 FieldType =
2129 createFieldType(name, type, field->getLocation(), field->getAccess(),
2130 OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
2131 }
2132
2133 elements.push_back(FieldType);
2134 }
2135
2136 void CGDebugInfo::CollectRecordNestedType(
2137 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
2138 QualType Ty = CGM.getContext().getTypeDeclType(TD);
2139 // Injected class names are not considered nested records.
2140 // FIXME: Is this supposed to be testing for injected class name declarations
2141 // instead?
2142 if (isa<InjectedClassNameType>(Ty))
2143 return;
2144 SourceLocation Loc = TD->getLocation();
2145 if (llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc)))
2146 elements.push_back(nestedType);
2147 }
2148
2149 void CGDebugInfo::CollectRecordFields(
2150 const RecordDecl *record, llvm::DIFile *tunit,
2151 SmallVectorImpl<llvm::Metadata *> &elements,
2152 llvm::DICompositeType *RecordTy) {
2153 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
2154
2155 if (CXXDecl && CXXDecl->isLambda())
2156 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
2157 else {
2158 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
2159
2160 // Field number for non-static fields.
2161 unsigned fieldNo = 0;
2162
2163 // Static and non-static members should appear in the same order as
2164 // the corresponding declarations in the source program.
2165 for (const auto *I : record->decls())
2166 if (const auto *V = dyn_cast<VarDecl>(I)) {
2167 if (V->hasAttr<NoDebugAttr>())
2168 continue;
2169
2170 // Skip variable template specializations when emitting CodeView. MSVC
2171 // doesn't emit them.
2172 if (CGM.getCodeGenOpts().EmitCodeView &&
2173 isa<VarTemplateSpecializationDecl>(V))
2174 continue;
2175
2176 if (isa<VarTemplatePartialSpecializationDecl>(V))
2177 continue;
2178
2179 // Reuse the existing static member declaration if one exists
2180 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
2181 if (MI != StaticDataMemberCache.end()) {
2182 assert(MI->second &&
2183 "Static data member declaration should still exist");
2184 elements.push_back(MI->second);
2185 } else {
2186 auto Field = CreateRecordStaticField(V, RecordTy, record);
2187 elements.push_back(Field);
2188 }
2189 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
2190 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
2191 elements, RecordTy, record);
2192
2193 // Bump field number for next field.
2194 ++fieldNo;
2195 } else if (CGM.getCodeGenOpts().EmitCodeView) {
2196 // Debug info for nested types is included in the member list only for
2197 // CodeView.
2198 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
2199 // MSVC doesn't generate nested type for anonymous struct/union.
2200 if (isa<RecordDecl>(I) &&
2201 cast<RecordDecl>(I)->isAnonymousStructOrUnion())
2202 continue;
2203 if (!nestedType->isImplicit() &&
2204 nestedType->getDeclContext() == record)
2205 CollectRecordNestedType(nestedType, elements);
2206 }
2207 }
2208 }
2209 }
2210
2211 llvm::DISubroutineType *
2212 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
2213 llvm::DIFile *Unit) {
2214 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
2215 if (Method->isStatic())
2216 return cast_or_null<llvm::DISubroutineType>(
2217 getOrCreateType(QualType(Func, 0), Unit));
2218
2219 QualType ThisType;
2220 if (!Method->hasCXXExplicitFunctionObjectParameter())
2221 ThisType = Method->getThisType();
2222
2223 return getOrCreateInstanceMethodType(ThisType, Func, Unit);
2224 }
2225
2226 llvm::DISubroutineType *CGDebugInfo::getOrCreateMethodTypeForDestructor(
2227 const CXXMethodDecl *Method, llvm::DIFile *Unit, QualType FNType) {
2228 const FunctionProtoType *Func = FNType->getAs<FunctionProtoType>();
2229 // skip the first param since it is also this
2230 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, true);
2231 }
2232
2233 llvm::DISubroutineType *
2234 CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
2235 const FunctionProtoType *Func,
2236 llvm::DIFile *Unit, bool SkipFirst) {
2237 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
2238 Qualifiers &Qc = EPI.TypeQuals;
2239 Qc.removeConst();
2240 Qc.removeVolatile();
2241 Qc.removeRestrict();
2242 Qc.removeUnaligned();
2243 // Keep the removed qualifiers in sync with
2244 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
2245 // On a 'real' member function type, these qualifiers are carried on the type
2246 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
2247 // tags around them. (But, in the raw function types with qualifiers, they have
2248 // to use wrapper types.)
2249
2250 // Add "this" pointer.
2251 const auto *OriginalFunc = cast<llvm::DISubroutineType>(
2252 getOrCreateType(CGM.getContext().getFunctionType(
2253 Func->getReturnType(), Func->getParamTypes(), EPI),
2254 Unit));
2255 llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
2256 assert(Args.size() && "Invalid number of arguments!");
2257
2258 SmallVector<llvm::Metadata *, 16> Elts;
2259
2260 // First element is always return type. For 'void' functions it is NULL.
2261 Elts.push_back(Args[0]);
2262
2263 const bool HasExplicitObjectParameter = ThisPtr.isNull();
2264
2265 // "this" pointer is always first argument. For explicit "this"
2266 // parameters, it will already be in Args[1].
2267 if (!HasExplicitObjectParameter) {
2268 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
2269 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2270 ThisPtrType =
2271 DBuilder.createObjectPointerType(ThisPtrType, /*Implicit=*/true);
2272 Elts.push_back(ThisPtrType);
2273 }
2274
2275 // Copy rest of the arguments.
2276 for (unsigned i = (SkipFirst ? 2 : 1), e = Args.size(); i < e; ++i)
2277 Elts.push_back(Args[i]);
2278
2279 // Attach FlagObjectPointer to the explicit "this" parameter.
2280 if (HasExplicitObjectParameter) {
2281 assert(Elts.size() >= 2 && Args.size() >= 2 &&
2282 "Expected at least return type and object parameter.");
2283 Elts[1] = DBuilder.createObjectPointerType(Args[1], /*Implicit=*/false);
2284 }
2285
2286 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2287
2288 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
2289 getDwarfCC(Func->getCallConv()));
2290 }
2291
2292 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
2293 /// inside a function.
2294 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
2295 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
2296 return isFunctionLocalClass(NRD);
2297 if (isa<FunctionDecl>(RD->getDeclContext()))
2298 return true;
2299 return false;
2300 }
2301
2302 llvm::StringRef
2303 CGDebugInfo::GetMethodLinkageName(const CXXMethodDecl *Method) const {
2304 assert(Method);
2305
2306 const bool IsCtorOrDtor =
2307 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
2308
2309 if (IsCtorOrDtor && !CGM.getCodeGenOpts().DebugStructorDeclLinkageNames)
2310 return {};
2311
2312 // In some ABIs (particularly Itanium) a single ctor/dtor
2313 // corresponds to multiple functions. Attach a "unified"
2314 // linkage name for those (which is the convention GCC uses).
2315 // Otherwise, attach no linkage name.
2316 if (IsCtorOrDtor && !CGM.getTarget().getCXXABI().hasConstructorVariants())
2317 return {};
2318
2319 if (const auto *Ctor = llvm::dyn_cast<CXXConstructorDecl>(Method))
2320 return CGM.getMangledName(GlobalDecl(Ctor, CXXCtorType::Ctor_Unified));
2321
2322 if (const auto *Dtor = llvm::dyn_cast<CXXDestructorDecl>(Method))
2323 return CGM.getMangledName(GlobalDecl(Dtor, CXXDtorType::Dtor_Unified));
2324
2325 return CGM.getMangledName(Method);
2326 }
2327
2328 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
2329 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
2330 assert(Method);
2331
2332 StringRef MethodName = getFunctionName(Method);
2333 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
2334
2335 StringRef MethodLinkageName;
2336 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
2337 // property to use here. It may've been intended to model "is non-external
2338 // type" but misses cases of non-function-local but non-external classes such
2339 // as those in anonymous namespaces as well as the reverse - external types
2340 // that are function local, such as those in (non-local) inline functions.
2341 if (!isFunctionLocalClass(Method->getParent()))
2342 MethodLinkageName = GetMethodLinkageName(Method);
2343
2344 // Get the location for the method.
2345 llvm::DIFile *MethodDefUnit = nullptr;
2346 unsigned MethodLine = 0;
2347 if (!Method->isImplicit()) {
2348 MethodDefUnit = getOrCreateFile(Method->getLocation());
2349 MethodLine = getLineNumber(Method->getLocation());
2350 }
2351
2352 // Collect virtual method info.
2353 llvm::DIType *ContainingType = nullptr;
2354 unsigned VIndex = 0;
2355 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2356 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2357 int ThisAdjustment = 0;
2358
2359 if (VTableContextBase::hasVtableSlot(Method)) {
2360 if (Method->isPureVirtual())
2361 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2362 else
2363 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2364
2365 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2366 // It doesn't make sense to give a virtual destructor a vtable index,
2367 // since a single destructor has two entries in the vtable.
2368 if (!isa<CXXDestructorDecl>(Method))
2369 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2370 } else {
2371 // Emit MS ABI vftable information. There is only one entry for the
2372 // deleting dtor.
2373 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2374 GlobalDecl GD =
2375 DD ? GlobalDecl(
2376 DD, CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
2377 CGM.getContext().getLangOpts())
2378 ? Dtor_VectorDeleting
2379 : Dtor_Deleting)
2380 : GlobalDecl(Method);
2381 MethodVFTableLocation ML =
2382 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
2383 VIndex = ML.Index;
2384
2385 // CodeView only records the vftable offset in the class that introduces
2386 // the virtual method. This is possible because, unlike Itanium, the MS
2387 // C++ ABI does not include all virtual methods from non-primary bases in
2388 // the vtable for the most derived class. For example, if C inherits from
2389 // A and B, C's primary vftable will not include B's virtual methods.
2390 if (Method->size_overridden_methods() == 0)
2391 Flags |= llvm::DINode::FlagIntroducedVirtual;
2392
2393 // The 'this' adjustment accounts for both the virtual and non-virtual
2394 // portions of the adjustment. Presumably the debugger only uses it when
2395 // it knows the dynamic type of an object.
2396 ThisAdjustment = CGM.getCXXABI()
2397 .getVirtualFunctionPrologueThisAdjustment(GD)
2398 .getQuantity();
2399 }
2400 ContainingType = RecordTy;
2401 }
2402
2403 if (Method->getCanonicalDecl()->isDeleted())
2404 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2405
2406 if (Method->isNoReturn())
2407 Flags |= llvm::DINode::FlagNoReturn;
2408
2409 if (Method->isStatic())
2410 Flags |= llvm::DINode::FlagStaticMember;
2411 if (Method->isImplicit())
2412 Flags |= llvm::DINode::FlagArtificial;
2413 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2414 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2415 if (CXXC->isExplicit())
2416 Flags |= llvm::DINode::FlagExplicit;
2417 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2418 if (CXXC->isExplicit())
2419 Flags |= llvm::DINode::FlagExplicit;
2420 }
2421 if (Method->hasPrototype())
2422 Flags |= llvm::DINode::FlagPrototyped;
2423 if (Method->getRefQualifier() == RQ_LValue)
2424 Flags |= llvm::DINode::FlagLValueReference;
2425 if (Method->getRefQualifier() == RQ_RValue)
2426 Flags |= llvm::DINode::FlagRValueReference;
2427 if (!Method->isExternallyVisible())
2428 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2429 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
2430 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2431
2432 // In this debug mode, emit type info for a class when its constructor type
2433 // info is emitted.
2434 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2435 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2436 completeUnusedClass(*CD->getParent());
2437
2438 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2439 llvm::DISubprogram *SP = DBuilder.createMethod(
2440 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2441 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2442 TParamsArray.get(), /*ThrownTypes*/ nullptr,
2443 CGM.getCodeGenOpts().DebugKeyInstructions);
2444
2445 SPCache[Method->getCanonicalDecl()].reset(SP);
2446
2447 return SP;
2448 }
2449
2450 void CGDebugInfo::CollectCXXMemberFunctions(
2451 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2452 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2453
2454 // Since we want more than just the individual member decls if we
2455 // have templated functions iterate over every declaration to gather
2456 // the functions.
2457 for (const auto *I : RD->decls()) {
2458 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2459 // If the member is implicit, don't add it to the member list. This avoids
2460 // the member being added to type units by LLVM, while still allowing it
2461 // to be emitted into the type declaration/reference inside the compile
2462 // unit.
2463 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2464 // FIXME: Handle Using(Shadow?)Decls here to create
2465 // DW_TAG_imported_declarations inside the class for base decls brought into
2466 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2467 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2468 // referenced)
2469 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2470 continue;
2471
2472 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
2473 continue;
2474
2475 // Reuse the existing member function declaration if it exists.
2476 // It may be associated with the declaration of the type & should be
2477 // reused as we're building the definition.
2478 //
2479 // This situation can arise in the vtable-based debug info reduction where
2480 // implicit members are emitted in a non-vtable TU.
2481 auto MI = SPCache.find(Method->getCanonicalDecl());
2482 EltTys.push_back(MI == SPCache.end()
2483 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2484 : static_cast<llvm::Metadata *>(MI->second));
2485 }
2486 }
2487
2488 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2489 SmallVectorImpl<llvm::Metadata *> &EltTys,
2490 llvm::DIType *RecordTy) {
2491 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
2492 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2493 llvm::DINode::FlagZero);
2494
2495 // If we are generating CodeView debug info, we also need to emit records for
2496 // indirect virtual base classes.
2497 if (CGM.getCodeGenOpts().EmitCodeView) {
2498 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2499 llvm::DINode::FlagIndirectVirtualBase);
2500 }
2501 }
2502
2503 void CGDebugInfo::CollectCXXBasesAux(
2504 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2505 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2506 const CXXRecordDecl::base_class_const_range &Bases,
2507 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2508 llvm::DINode::DIFlags StartingFlags) {
2509 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2510 for (const auto &BI : Bases) {
2511 const auto *Base =
2512 cast<CXXRecordDecl>(
2513 BI.getType()->castAsCanonical<RecordType>()->getDecl())
2514 ->getDefinition();
2515 if (!SeenTypes.insert(Base).second)
2516 continue;
2517 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2518 llvm::DINode::DIFlags BFlags = StartingFlags;
2519 uint64_t BaseOffset;
2520 uint32_t VBPtrOffset = 0;
2521
2522 if (BI.isVirtual()) {
2523 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2524 // virtual base offset offset is -ve. The code generator emits dwarf
2525 // expression where it expects +ve number.
2526 BaseOffset = 0 - CGM.getItaniumVTableContext()
2527 .getVirtualBaseOffsetOffset(RD, Base)
2528 .getQuantity();
2529 } else {
2530 // In the MS ABI, store the vbtable offset, which is analogous to the
2531 // vbase offset offset in Itanium.
2532 BaseOffset =
2533 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
2534 VBPtrOffset = CGM.getContext()
2535 .getASTRecordLayout(RD)
2536 .getVBPtrOffset()
2537 .getQuantity();
2538 }
2539 BFlags |= llvm::DINode::FlagVirtual;
2540 } else
2541 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2542 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2543 // BI->isVirtual() and bits when not.
2544
2545 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2546 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2547 VBPtrOffset, BFlags);
2548 EltTys.push_back(DTy);
2549 }
2550 }
2551
2552 llvm::DINodeArray
2553 CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2554 llvm::DIFile *Unit) {
2555 if (!OArgs)
2556 return llvm::DINodeArray();
2557 TemplateArgs &Args = *OArgs;
2558 SmallVector<llvm::Metadata *, 16> TemplateParams;
2559 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2560 const TemplateArgument &TA = Args.Args[i];
2561 StringRef Name;
2562 const bool defaultParameter = TA.getIsDefaulted();
2563 if (Args.TList)
2564 Name = Args.TList->getParam(i)->getName();
2565
2566 switch (TA.getKind()) {
2567 case TemplateArgument::Type: {
2568 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2569 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2570 TheCU, Name, TTy, defaultParameter));
2571
2572 } break;
2573 case TemplateArgument::Integral: {
2574 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2575 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2576 TheCU, Name, TTy, defaultParameter,
2577 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2578 } break;
2579 case TemplateArgument::Declaration: {
2580 const ValueDecl *D = TA.getAsDecl();
2581 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2582 llvm::DIType *TTy = getOrCreateType(T, Unit);
2583 llvm::Constant *V = nullptr;
2584 // Skip retrieve the value if that template parameter has cuda device
2585 // attribute, i.e. that value is not available at the host side.
2586 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2587 !D->hasAttr<CUDADeviceAttr>()) {
2588 // Variable pointer template parameters have a value that is the address
2589 // of the variable.
2590 if (const auto *VD = dyn_cast<VarDecl>(D))
2591 V = CGM.GetAddrOfGlobalVar(VD);
2592 // Member function pointers have special support for building them,
2593 // though this is currently unsupported in LLVM CodeGen.
2594 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2595 MD && MD->isImplicitObjectMemberFunction())
2596 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2597 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2598 V = CGM.GetAddrOfFunction(FD);
2599 // Member data pointers have special handling too to compute the fixed
2600 // offset within the object.
2601 else if (const auto *MPT =
2602 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2603 // These five lines (& possibly the above member function pointer
2604 // handling) might be able to be refactored to use similar code in
2605 // CodeGenModule::getMemberPointerConstant
2606 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2607 CharUnits chars =
2608 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2609 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2610 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2611 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2612 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2613 if (T->isRecordType())
2614 V = ConstantEmitter(CGM).emitAbstract(
2615 SourceLocation(), TPO->getValue(), TPO->getType());
2616 else
2617 V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2618 }
2619 assert(V && "Failed to find template parameter pointer");
2620 V = V->stripPointerCasts();
2621 }
2622 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2623 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2624 } break;
2625 case TemplateArgument::NullPtr: {
2626 QualType T = TA.getNullPtrType();
2627 llvm::DIType *TTy = getOrCreateType(T, Unit);
2628 llvm::Constant *V = nullptr;
2629 // Special case member data pointer null values since they're actually -1
2630 // instead of zero.
2631 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2632 // But treat member function pointers as simple zero integers because
2633 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2634 // CodeGen grows handling for values of non-null member function
2635 // pointers then perhaps we could remove this special case and rely on
2636 // EmitNullMemberPointer for member function pointers.
2637 if (MPT->isMemberDataPointer())
2638 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2639 if (!V)
2640 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2641 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2642 TheCU, Name, TTy, defaultParameter, V));
2643 } break;
2644 case TemplateArgument::StructuralValue: {
2645 QualType T = TA.getStructuralValueType();
2646 llvm::DIType *TTy = getOrCreateType(T, Unit);
2647 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2648 SourceLocation(), TA.getAsStructuralValue(), T);
2649 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2650 TheCU, Name, TTy, defaultParameter, V));
2651 } break;
2652 case TemplateArgument::Template: {
2653 std::string QualName;
2654 llvm::raw_string_ostream OS(QualName);
2655 TA.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2656 OS, getPrintingPolicy());
2657 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2658 TheCU, Name, nullptr, QualName, defaultParameter));
2659 break;
2660 }
2661 case TemplateArgument::Pack:
2662 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2663 TheCU, Name, nullptr,
2664 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2665 break;
2666 case TemplateArgument::Expression: {
2667 const Expr *E = TA.getAsExpr();
2668 QualType T = E->getType();
2669 if (E->isGLValue())
2670 T = CGM.getContext().getLValueReferenceType(T);
2671 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2672 assert(V && "Expression in template argument isn't constant");
2673 llvm::DIType *TTy = getOrCreateType(T, Unit);
2674 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2675 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2676 } break;
2677 // And the following should never occur:
2678 case TemplateArgument::TemplateExpansion:
2679 case TemplateArgument::Null:
2680 llvm_unreachable(
2681 "These argument types shouldn't exist in concrete types");
2682 }
2683 }
2684 return DBuilder.getOrCreateArray(TemplateParams);
2685 }
2686
2687 std::optional<CGDebugInfo::TemplateArgs>
2688 CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2689 if (FD->getTemplatedKind() ==
2690 FunctionDecl::TK_FunctionTemplateSpecialization) {
2691 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2692 ->getTemplate()
2693 ->getTemplateParameters();
2694 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2695 }
2696 return std::nullopt;
2697 }
2698 std::optional<CGDebugInfo::TemplateArgs>
2699 CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2700 // Always get the full list of parameters, not just the ones from the
2701 // specialization. A partial specialization may have fewer parameters than
2702 // there are arguments.
2703 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2704 if (!TS)
2705 return std::nullopt;
2706 VarTemplateDecl *T = TS->getSpecializedTemplate();
2707 const TemplateParameterList *TList = T->getTemplateParameters();
2708 auto TA = TS->getTemplateArgs().asArray();
2709 return {{TList, TA}};
2710 }
2711 std::optional<CGDebugInfo::TemplateArgs>
2712 CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2713 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2714 // Always get the full list of parameters, not just the ones from the
2715 // specialization. A partial specialization may have fewer parameters than
2716 // there are arguments.
2717 TemplateParameterList *TPList =
2718 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2719 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2720 return {{TPList, TAList.asArray()}};
2721 }
2722 return std::nullopt;
2723 }
2724
2725 llvm::DINodeArray
2726 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2727 llvm::DIFile *Unit) {
2728 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2729 }
2730
2731 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2732 llvm::DIFile *Unit) {
2733 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2734 }
2735
2736 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2737 llvm::DIFile *Unit) {
2738 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2739 }
2740
2741 llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2742 if (!D->hasAttr<BTFDeclTagAttr>())
2743 return nullptr;
2744
2745 SmallVector<llvm::Metadata *, 4> Annotations;
2746 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2747 llvm::Metadata *Ops[2] = {
2748 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2749 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2750 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2751 }
2752 return DBuilder.getOrCreateArray(Annotations);
2753 }
2754
2755 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2756 if (VTablePtrType)
2757 return VTablePtrType;
2758
2759 ASTContext &Context = CGM.getContext();
2760
2761 /* Function type */
2762 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2763 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2764 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2765 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2766 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2767 std::optional<unsigned> DWARFAddressSpace =
2768 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2769
2770 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2771 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2772 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2773 return VTablePtrType;
2774 }
2775
2776 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2777 // Copy the gdb compatible name on the side and use its reference.
2778 return internString("_vptr$", RD->getNameAsString());
2779 }
2780
2781 // Emit symbol for the debugger that points to the vtable address for
2782 // the given class. The symbol is named as '_vtable$'.
2783 // The debugger does not need to know any details about the contents of the
2784 // vtable as it can work this out using its knowledge of the ABI and the
2785 // existing information in the DWARF. The type is assumed to be 'void *'.
2786 void CGDebugInfo::emitVTableSymbol(llvm::GlobalVariable *VTable,
2787 const CXXRecordDecl *RD) {
2788 if (!CGM.getTarget().getCXXABI().isItaniumFamily())
2789 return;
2790 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2791 return;
2792
2793 // On COFF platform, we shouldn't emit a reference to an external entity (i.e.
2794 // VTable) into debug info, which is constructed within a discardable section.
2795 // If that entity ends up implicitly dllimported from another DLL, the linker
2796 // may produce a runtime pseudo-relocation for it (BFD-ld only. LLD prohibits
2797 // to emit such relocation). If the debug section is stripped, the runtime
2798 // pseudo-relocation points to memory space outside of the module, causing an
2799 // access violation.
2800 if (CGM.getTarget().getTriple().isOSBinFormatCOFF() &&
2801 VTable->isDeclarationForLinker())
2802 return;
2803
2804 ASTContext &Context = CGM.getContext();
2805 StringRef SymbolName = "_vtable$";
2806 SourceLocation Loc;
2807 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2808
2809 // We deal with two different contexts:
2810 // - The type for the variable, which is part of the class that has the
2811 // vtable, is placed in the context of the DICompositeType metadata.
2812 // - The DIGlobalVariable for the vtable is put in the DICompileUnitScope.
2813
2814 // The created non-member should be mark as 'artificial'. It will be
2815 // placed inside the scope of the C++ class/structure.
2816 llvm::DIScope *DContext = getContextDescriptor(RD, TheCU);
2817 auto *Ctxt = cast<llvm::DICompositeType>(DContext);
2818 llvm::DIFile *Unit = getOrCreateFile(Loc);
2819 llvm::DIType *VTy = getOrCreateType(VoidPtr, Unit);
2820 llvm::DINode::DIFlags Flags = getAccessFlag(AccessSpecifier::AS_private, RD) |
2821 llvm::DINode::FlagArtificial;
2822 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
2823 ? llvm::dwarf::DW_TAG_variable
2824 : llvm::dwarf::DW_TAG_member;
2825 llvm::DIDerivedType *DT = DBuilder.createStaticMemberType(
2826 Ctxt, SymbolName, Unit, /*LineNumber=*/0, VTy, Flags,
2827 /*Val=*/nullptr, Tag);
2828
2829 // Use the same vtable pointer to global alignment for the symbol.
2830 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2831
2832 // The global variable is in the CU scope, and links back to the type it's
2833 // "within" via the declaration field.
2834 llvm::DIGlobalVariableExpression *GVE =
2835 DBuilder.createGlobalVariableExpression(
2836 TheCU, SymbolName, VTable->getName(), Unit, /*LineNo=*/0,
2837 getOrCreateType(VoidPtr, Unit), VTable->hasLocalLinkage(),
2838 /*isDefined=*/true, nullptr, DT, /*TemplateParameters=*/nullptr,
2839 PAlign);
2840 VTable->addDebugInfo(GVE);
2841 }
2842
2843 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2844 DynamicInitKind StubKind,
2845 llvm::Function *InitFn) {
2846 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2847 // arbitrary.
2848 if (!CGM.getCodeGenOpts().EmitCodeView ||
2849 StubKind == DynamicInitKind::GlobalArrayDestructor)
2850 return InitFn->getName();
2851
2852 // Print the normal qualified name for the variable, then break off the last
2853 // NNS, and add the appropriate other text. Clang always prints the global
2854 // variable name without template arguments, so we can use rsplit("::") and
2855 // then recombine the pieces.
2856 SmallString<128> QualifiedGV;
2857 StringRef Quals;
2858 StringRef GVName;
2859 {
2860 llvm::raw_svector_ostream OS(QualifiedGV);
2861 VD->printQualifiedName(OS, getPrintingPolicy());
2862 std::tie(Quals, GVName) = OS.str().rsplit("::");
2863 if (GVName.empty())
2864 std::swap(Quals, GVName);
2865 }
2866
2867 SmallString<128> InitName;
2868 llvm::raw_svector_ostream OS(InitName);
2869 if (!Quals.empty())
2870 OS << Quals << "::";
2871
2872 switch (StubKind) {
2873 case DynamicInitKind::NoStub:
2874 case DynamicInitKind::GlobalArrayDestructor:
2875 llvm_unreachable("not an initializer");
2876 case DynamicInitKind::Initializer:
2877 OS << "`dynamic initializer for '";
2878 break;
2879 case DynamicInitKind::AtExit:
2880 OS << "`dynamic atexit destructor for '";
2881 break;
2882 }
2883
2884 OS << GVName;
2885
2886 // Add any template specialization args.
2887 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2888 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2889 getPrintingPolicy());
2890 }
2891
2892 OS << '\'';
2893
2894 return internString(OS.str());
2895 }
2896
2897 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2898 SmallVectorImpl<llvm::Metadata *> &EltTys) {
2899 // If this class is not dynamic then there is not any vtable info to collect.
2900 if (!RD->isDynamicClass())
2901 return;
2902
2903 // Don't emit any vtable shape or vptr info if this class doesn't have an
2904 // extendable vfptr. This can happen if the class doesn't have virtual
2905 // methods, or in the MS ABI if those virtual methods only come from virtually
2906 // inherited bases.
2907 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2908 if (!RL.hasExtendableVFPtr())
2909 return;
2910
2911 // CodeView needs to know how large the vtable of every dynamic class is, so
2912 // emit a special named pointer type into the element list. The vptr type
2913 // points to this type as well.
2914 llvm::DIType *VPtrTy = nullptr;
2915 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2916 CGM.getTarget().getCXXABI().isMicrosoft();
2917 if (NeedVTableShape) {
2918 uint64_t PtrWidth =
2919 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2920 const VTableLayout &VFTLayout =
2921 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2922 unsigned VSlotCount =
2923 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2924 unsigned VTableWidth = PtrWidth * VSlotCount;
2925 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2926 std::optional<unsigned> DWARFAddressSpace =
2927 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2928
2929 // Create a very wide void* type and insert it directly in the element list.
2930 llvm::DIType *VTableType = DBuilder.createPointerType(
2931 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2932 EltTys.push_back(VTableType);
2933
2934 // The vptr is a pointer to this special vtable type.
2935 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2936 }
2937
2938 // If there is a primary base then the artificial vptr member lives there.
2939 if (RL.getPrimaryBase())
2940 return;
2941
2942 if (!VPtrTy)
2943 VPtrTy = getOrCreateVTablePtrType(Unit);
2944
2945 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2946 llvm::DIType *VPtrMember =
2947 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2948 llvm::DINode::FlagArtificial, VPtrTy);
2949 EltTys.push_back(VPtrMember);
2950 }
2951
2952 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2953 SourceLocation Loc) {
2954 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2955 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2956 return T;
2957 }
2958
2959 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2960 SourceLocation Loc) {
2961 return getOrCreateStandaloneType(D, Loc);
2962 }
2963
2964 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2965 SourceLocation Loc) {
2966 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2967 assert(!D.isNull() && "null type");
2968 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2969 assert(T && "could not create debug info for type");
2970
2971 RetainedTypes.push_back(D.getAsOpaquePtr());
2972 return T;
2973 }
2974
2975 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase *CI,
2976 QualType AllocatedTy,
2977 SourceLocation Loc) {
2978 if (CGM.getCodeGenOpts().getDebugInfo() <=
2979 llvm::codegenoptions::DebugLineTablesOnly)
2980 return;
2981 llvm::MDNode *node;
2982 if (AllocatedTy->isVoidType())
2983 node = llvm::MDNode::get(CGM.getLLVMContext(), {});
2984 else
2985 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2986
2987 CI->setMetadata("heapallocsite", node);
2988 }
2989
2990 void CGDebugInfo::completeType(const EnumDecl *ED) {
2991 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2992 return;
2993 CanQualType Ty = CGM.getContext().getCanonicalTagType(ED);
2994 void *TyPtr = Ty.getAsOpaquePtr();
2995 auto I = TypeCache.find(TyPtr);
2996 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2997 return;
2998 llvm::DIType *Res = CreateTypeDefinition(dyn_cast<EnumType>(Ty));
2999 assert(!Res->isForwardDecl());
3000 TypeCache[TyPtr].reset(Res);
3001 }
3002
3003 void CGDebugInfo::completeType(const RecordDecl *RD) {
3004 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3005 !CGM.getLangOpts().CPlusPlus)
3006 completeRequiredType(RD);
3007 }
3008
3009 /// Return true if the class or any of its methods are marked dllimport.
3010 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
3011 if (RD->hasAttr<DLLImportAttr>())
3012 return true;
3013 for (const CXXMethodDecl *MD : RD->methods())
3014 if (MD->hasAttr<DLLImportAttr>())
3015 return true;
3016 return false;
3017 }
3018
3019 /// Does a type definition exist in an imported clang module?
3020 static bool isDefinedInClangModule(const RecordDecl *RD) {
3021 // Only definitions that where imported from an AST file come from a module.
3022 if (!RD || !RD->isFromASTFile())
3023 return false;
3024 // Anonymous entities cannot be addressed. Treat them as not from module.
3025 if (!RD->isExternallyVisible() && RD->getName().empty())
3026 return false;
3027 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
3028 if (!CXXDecl->isCompleteDefinition())
3029 return false;
3030 // Check wether RD is a template.
3031 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
3032 if (TemplateKind != TSK_Undeclared) {
3033 // Unfortunately getOwningModule() isn't accurate enough to find the
3034 // owning module of a ClassTemplateSpecializationDecl that is inside a
3035 // namespace spanning multiple modules.
3036 bool Explicit = false;
3037 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
3038 Explicit = TD->isExplicitInstantiationOrSpecialization();
3039 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
3040 return false;
3041 // This is a template, check the origin of the first member.
3042 if (CXXDecl->fields().empty())
3043 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
3044 if (!CXXDecl->field_begin()->isFromASTFile())
3045 return false;
3046 }
3047 }
3048 return true;
3049 }
3050
3051 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
3052 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3053 if (CXXRD->isDynamicClass() &&
3054 CGM.getVTableLinkage(CXXRD) ==
3055 llvm::GlobalValue::AvailableExternallyLinkage &&
3056 !isClassOrMethodDLLImport(CXXRD))
3057 return;
3058
3059 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3060 return;
3061
3062 completeClass(RD);
3063 }
3064
3065 void CGDebugInfo::completeClass(const RecordDecl *RD) {
3066 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
3067 return;
3068 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3069 void *TyPtr = Ty.getAsOpaquePtr();
3070 auto I = TypeCache.find(TyPtr);
3071 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
3072 return;
3073
3074 // We want the canonical definition of the structure to not
3075 // be the typedef. Since that would lead to circular typedef
3076 // metadata.
3077 auto [Res, PrefRes] = CreateTypeDefinition(dyn_cast<RecordType>(Ty));
3078 assert(!Res->isForwardDecl());
3079 TypeCache[TyPtr].reset(Res);
3080 }
3081
3082 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
3083 CXXRecordDecl::method_iterator End) {
3084 for (CXXMethodDecl *MD : llvm::make_range(I, End))
3085 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
3086 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
3087 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
3088 return true;
3089 return false;
3090 }
3091
3092 static bool canUseCtorHoming(const CXXRecordDecl *RD) {
3093 // Constructor homing can be used for classes that cannnot be constructed
3094 // without emitting code for one of their constructors. This is classes that
3095 // don't have trivial or constexpr constructors, or can be created from
3096 // aggregate initialization. Also skip lambda objects because they don't call
3097 // constructors.
3098
3099 // Skip this optimization if the class or any of its methods are marked
3100 // dllimport.
3101 if (isClassOrMethodDLLImport(RD))
3102 return false;
3103
3104 if (RD->isLambda() || RD->isAggregate() ||
3105 RD->hasTrivialDefaultConstructor() ||
3106 RD->hasConstexprNonCopyMoveConstructor())
3107 return false;
3108
3109 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
3110 if (Ctor->isCopyOrMoveConstructor())
3111 continue;
3112 if (!Ctor->isDeleted())
3113 return true;
3114 }
3115 return false;
3116 }
3117
3118 static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
3119 bool DebugTypeExtRefs, const RecordDecl *RD,
3120 const LangOptions &LangOpts) {
3121 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3122 return true;
3123
3124 if (auto *ES = RD->getASTContext().getExternalSource())
3125 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
3126 return true;
3127
3128 // Only emit forward declarations in line tables only to keep debug info size
3129 // small. This only applies to CodeView, since we don't emit types in DWARF
3130 // line tables only.
3131 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
3132 return true;
3133
3134 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3135 RD->hasAttr<StandaloneDebugAttr>())
3136 return false;
3137
3138 if (!LangOpts.CPlusPlus)
3139 return false;
3140
3141 if (!RD->isCompleteDefinitionRequired())
3142 return true;
3143
3144 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3145
3146 if (!CXXDecl)
3147 return false;
3148
3149 // Only emit complete debug info for a dynamic class when its vtable is
3150 // emitted. However, Microsoft debuggers don't resolve type information
3151 // across DLL boundaries, so skip this optimization if the class or any of its
3152 // methods are marked dllimport. This isn't a complete solution, since objects
3153 // without any dllimport methods can be used in one DLL and constructed in
3154 // another, but it is the current behavior of LimitedDebugInfo.
3155 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
3156 !isClassOrMethodDLLImport(CXXDecl) && !CXXDecl->hasAttr<MSNoVTableAttr>())
3157 return true;
3158
3159 TemplateSpecializationKind Spec = TSK_Undeclared;
3160 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3161 Spec = SD->getSpecializationKind();
3162
3163 if (Spec == TSK_ExplicitInstantiationDeclaration &&
3164 hasExplicitMemberDefinition(CXXDecl->method_begin(),
3165 CXXDecl->method_end()))
3166 return true;
3167
3168 // In constructor homing mode, only emit complete debug info for a class
3169 // when its constructor is emitted.
3170 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
3171 canUseCtorHoming(CXXDecl))
3172 return true;
3173
3174 return false;
3175 }
3176
3177 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
3178 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
3179 return;
3180
3181 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3182 llvm::DIType *T = getTypeOrNull(Ty);
3183 if (T && T->isForwardDecl())
3184 completeClassData(RD);
3185 }
3186
3187 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
3188 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3189 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
3190 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
3191 CGM.getLangOpts())) {
3192 if (!T)
3193 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
3194 return T;
3195 }
3196
3197 auto [Def, Pref] = CreateTypeDefinition(Ty);
3198
3199 return Pref ? Pref : Def;
3200 }
3201
3202 llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
3203 llvm::DIFile *Unit) {
3204 if (!RD)
3205 return nullptr;
3206
3207 auto const *PNA = RD->getAttr<PreferredNameAttr>();
3208 if (!PNA)
3209 return nullptr;
3210
3211 return getOrCreateType(PNA->getTypedefType(), Unit);
3212 }
3213
3214 std::pair<llvm::DIType *, llvm::DIType *>
3215 CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
3216 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3217
3218 // Get overall information about the record type for the debug info.
3219 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3220
3221 // Records and classes and unions can all be recursive. To handle them, we
3222 // first generate a debug descriptor for the struct as a forward declaration.
3223 // Then (if it is a definition) we go through and get debug info for all of
3224 // its members. Finally, we create a descriptor for the complete type (which
3225 // may refer to the forward decl if the struct is recursive) and replace all
3226 // uses of the forward declaration with the final definition.
3227 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
3228
3229 const RecordDecl *D = RD->getDefinition();
3230 if (!D || !D->isCompleteDefinition())
3231 return {FwdDecl, nullptr};
3232
3233 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
3234 CollectContainingType(CXXDecl, FwdDecl);
3235
3236 // Push the struct on region stack.
3237 LexicalBlockStack.emplace_back(&*FwdDecl);
3238 RegionMap[RD].reset(FwdDecl);
3239
3240 // Convert all the elements.
3241 SmallVector<llvm::Metadata *, 16> EltTys;
3242 // what about nested types?
3243
3244 // Note: The split of CXXDecl information here is intentional, the
3245 // gdb tests will depend on a certain ordering at printout. The debug
3246 // information offsets are still correct if we merge them all together
3247 // though.
3248 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3249 if (CXXDecl) {
3250 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
3251 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
3252 }
3253
3254 // Collect data fields (including static variables and any initializers).
3255 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
3256 if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)
3257 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
3258
3259 LexicalBlockStack.pop_back();
3260 RegionMap.erase(RD);
3261
3262 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3263 DBuilder.replaceArrays(FwdDecl, Elements);
3264
3265 if (FwdDecl->isTemporary())
3266 FwdDecl =
3267 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
3268
3269 RegionMap[RD].reset(FwdDecl);
3270
3271 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
3272 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
3273 return {FwdDecl, PrefDI};
3274
3275 return {FwdDecl, nullptr};
3276 }
3277
3278 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
3279 llvm::DIFile *Unit) {
3280 // Ignore protocols.
3281 return getOrCreateType(Ty->getBaseType(), Unit);
3282 }
3283
3284 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
3285 llvm::DIFile *Unit) {
3286 // Ignore protocols.
3287 SourceLocation Loc = Ty->getDecl()->getLocation();
3288
3289 // Use Typedefs to represent ObjCTypeParamType.
3290 return DBuilder.createTypedef(
3291 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
3292 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
3293 getDeclContextDescriptor(Ty->getDecl()));
3294 }
3295
3296 /// \return true if Getter has the default name for the property PD.
3297 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
3298 const ObjCMethodDecl *Getter) {
3299 assert(PD);
3300 if (!Getter)
3301 return true;
3302
3303 assert(Getter->getDeclName().isObjCZeroArgSelector());
3304 return PD->getName() ==
3305 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
3306 }
3307
3308 /// \return true if Setter has the default name for the property PD.
3309 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
3310 const ObjCMethodDecl *Setter) {
3311 assert(PD);
3312 if (!Setter)
3313 return true;
3314
3315 assert(Setter->getDeclName().isObjCOneArgSelector());
3316 return SelectorTable::constructSetterName(PD->getName()) ==
3317 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
3318 }
3319
3320 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
3321 llvm::DIFile *Unit) {
3322 ObjCInterfaceDecl *ID = Ty->getDecl();
3323 if (!ID)
3324 return nullptr;
3325
3326 auto RuntimeLang = static_cast<llvm::dwarf::SourceLanguage>(
3327 TheCU->getSourceLanguage().getUnversionedName());
3328
3329 // Return a forward declaration if this type was imported from a clang module,
3330 // and this is not the compile unit with the implementation of the type (which
3331 // may contain hidden ivars).
3332 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
3333 !ID->getImplementation())
3334 return DBuilder.createForwardDecl(
3335 llvm::dwarf::DW_TAG_structure_type, ID->getName(),
3336 getDeclContextDescriptor(ID), Unit, 0, RuntimeLang);
3337
3338 // Get overall information about the record type for the debug info.
3339 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3340 unsigned Line = getLineNumber(ID->getLocation());
3341
3342 // If this is just a forward declaration return a special forward-declaration
3343 // debug type since we won't be able to lay out the entire type.
3344 ObjCInterfaceDecl *Def = ID->getDefinition();
3345 if (!Def || !Def->getImplementation()) {
3346 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3347 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
3348 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
3349 DefUnit, Line, RuntimeLang);
3350 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
3351 return FwdDecl;
3352 }
3353
3354 return CreateTypeDefinition(Ty, Unit);
3355 }
3356
3357 llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
3358 bool CreateSkeletonCU) {
3359 // Use the Module pointer as the key into the cache. This is a
3360 // nullptr if the "Module" is a PCH, which is safe because we don't
3361 // support chained PCH debug info, so there can only be a single PCH.
3362 const Module *M = Mod.getModuleOrNull();
3363 auto ModRef = ModuleCache.find(M);
3364 if (ModRef != ModuleCache.end())
3365 return cast<llvm::DIModule>(ModRef->second);
3366
3367 // Macro definitions that were defined with "-D" on the command line.
3368 SmallString<128> ConfigMacros;
3369 {
3370 llvm::raw_svector_ostream OS(ConfigMacros);
3371 const auto &PPOpts = CGM.getPreprocessorOpts();
3372 unsigned I = 0;
3373 // Translate the macro definitions back into a command line.
3374 for (auto &M : PPOpts.Macros) {
3375 if (++I > 1)
3376 OS << " ";
3377 const std::string &Macro = M.first;
3378 bool Undef = M.second;
3379 OS << "\"-" << (Undef ? 'U' : 'D');
3380 for (char c : Macro)
3381 switch (c) {
3382 case '\\':
3383 OS << "\\\\";
3384 break;
3385 case '"':
3386 OS << "\\\"";
3387 break;
3388 default:
3389 OS << c;
3390 }
3391 OS << '\"';
3392 }
3393 }
3394
3395 bool IsRootModule = M ? !M->Parent : true;
3396 // When a module name is specified as -fmodule-name, that module gets a
3397 // clang::Module object, but it won't actually be built or imported; it will
3398 // be textual.
3399 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3400 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3401 "clang module without ASTFile must be specified by -fmodule-name");
3402
3403 // Return a StringRef to the remapped Path.
3404 auto RemapPath = [this](StringRef Path) -> std::string {
3405 std::string Remapped = remapDIPath(Path);
3406 StringRef Relative(Remapped);
3407 StringRef CompDir = TheCU->getDirectory();
3408 if (CompDir.empty())
3409 return Remapped;
3410
3411 if (Relative.consume_front(CompDir))
3412 Relative.consume_front(llvm::sys::path::get_separator());
3413
3414 return Relative.str();
3415 };
3416
3417 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3418 // PCH files don't have a signature field in the control block,
3419 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3420 // We use the lower 64 bits for debug info.
3421
3422 uint64_t Signature = 0;
3423 if (const auto &ModSig = Mod.getSignature())
3424 Signature = ModSig.truncatedValue();
3425 else
3426 Signature = ~1ULL;
3427
3428 llvm::DIBuilder DIB(CGM.getModule());
3429 SmallString<0> PCM;
3430 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3431 if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd)
3432 PCM = getCurrentDirname();
3433 else
3434 PCM = Mod.getPath();
3435 }
3436 llvm::sys::path::append(PCM, Mod.getASTFile());
3437 DIB.createCompileUnit(
3438 TheCU->getSourceLanguage(),
3439 // TODO: Support "Source" from external AST providers?
3440 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3441 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3442 llvm::DICompileUnit::FullDebug, Signature);
3443 DIB.finalize();
3444 }
3445
3446 llvm::DIModule *Parent =
3447 IsRootModule ? nullptr
3448 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3449 CreateSkeletonCU);
3450 std::string IncludePath = Mod.getPath().str();
3451 llvm::DIModule *DIMod =
3452 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3453 RemapPath(IncludePath));
3454 ModuleCache[M].reset(DIMod);
3455 return DIMod;
3456 }
3457
3458 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3459 llvm::DIFile *Unit) {
3460 ObjCInterfaceDecl *ID = Ty->getDecl();
3461 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3462 unsigned Line = getLineNumber(ID->getLocation());
3463
3464 unsigned RuntimeLang = TheCU->getSourceLanguage().getUnversionedName();
3465
3466 // Bit size, align and offset of the type.
3467 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3468 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3469
3470 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3471 if (ID->getImplementation())
3472 Flags |= llvm::DINode::FlagObjcClassComplete;
3473
3474 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3475 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3476 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3477 nullptr, llvm::DINodeArray(), RuntimeLang);
3478
3479 QualType QTy(Ty, 0);
3480 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3481
3482 // Push the struct on region stack.
3483 LexicalBlockStack.emplace_back(RealDecl);
3484 RegionMap[Ty->getDecl()].reset(RealDecl);
3485
3486 // Convert all the elements.
3487 SmallVector<llvm::Metadata *, 16> EltTys;
3488
3489 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3490 if (SClass) {
3491 llvm::DIType *SClassTy =
3492 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3493 if (!SClassTy)
3494 return nullptr;
3495
3496 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3497 llvm::DINode::FlagZero);
3498 EltTys.push_back(InhTag);
3499 }
3500
3501 // Create entries for all of the properties.
3502 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3503 SourceLocation Loc = PD->getLocation();
3504 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3505 unsigned PLine = getLineNumber(Loc);
3506 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3507 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3508 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3509 PD->getName(), PUnit, PLine,
3510 hasDefaultGetterName(PD, Getter) ? ""
3511 : getSelectorName(PD->getGetterName()),
3512 hasDefaultSetterName(PD, Setter) ? ""
3513 : getSelectorName(PD->getSetterName()),
3514 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3515 EltTys.push_back(PropertyNode);
3516 };
3517 {
3518 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3519 // empty/tombstone keys in the data type (and bool is too small for that).
3520 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3521 /// List of already emitted properties. Two distinct class and instance
3522 /// properties can share the same identifier (but not two instance
3523 /// properties or two class properties).
3524 llvm::DenseSet<IsClassAndIdent> PropertySet;
3525 /// Returns the IsClassAndIdent key for the given property.
3526 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3527 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3528 };
3529 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3530 for (auto *PD : ClassExt->properties()) {
3531 PropertySet.insert(GetIsClassAndIdent(PD));
3532 AddProperty(PD);
3533 }
3534 for (const auto *PD : ID->properties()) {
3535 // Don't emit duplicate metadata for properties that were already in a
3536 // class extension.
3537 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3538 continue;
3539 AddProperty(PD);
3540 }
3541 }
3542
3543 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
3544 unsigned FieldNo = 0;
3545 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3546 Field = Field->getNextIvar(), ++FieldNo) {
3547 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3548 if (!FieldTy)
3549 return nullptr;
3550
3551 StringRef FieldName = Field->getName();
3552
3553 // Ignore unnamed fields.
3554 if (FieldName.empty())
3555 continue;
3556
3557 // Get the location for the field.
3558 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3559 unsigned FieldLine = getLineNumber(Field->getLocation());
3560 QualType FType = Field->getType();
3561 uint64_t FieldSize = 0;
3562 uint32_t FieldAlign = 0;
3563
3564 if (!FType->isIncompleteArrayType()) {
3565
3566 // Bit size, align and offset of the type.
3567 FieldSize = Field->isBitField() ? Field->getBitWidthValue()
3568 : CGM.getContext().getTypeSize(FType);
3569 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3570 }
3571
3572 uint64_t FieldOffset;
3573 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3574 // We don't know the runtime offset of an ivar if we're using the
3575 // non-fragile ABI. For bitfields, use the bit offset into the first
3576 // byte of storage of the bitfield. For other fields, use zero.
3577 if (Field->isBitField()) {
3578 FieldOffset =
3579 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3580 FieldOffset %= CGM.getContext().getCharWidth();
3581 } else {
3582 FieldOffset = 0;
3583 }
3584 } else {
3585 FieldOffset = RL.getFieldOffset(FieldNo);
3586 }
3587
3588 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3589 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3590 Flags = llvm::DINode::FlagProtected;
3591 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3592 Flags = llvm::DINode::FlagPrivate;
3593 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3594 Flags = llvm::DINode::FlagPublic;
3595
3596 if (Field->isBitField())
3597 Flags |= llvm::DINode::FlagBitField;
3598
3599 llvm::MDNode *PropertyNode = nullptr;
3600 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3601 if (ObjCPropertyImplDecl *PImpD =
3602 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3603 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3604 SourceLocation Loc = PD->getLocation();
3605 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3606 unsigned PLine = getLineNumber(Loc);
3607 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3608 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3609 PropertyNode = DBuilder.createObjCProperty(
3610 PD->getName(), PUnit, PLine,
3611 hasDefaultGetterName(PD, Getter)
3612 ? ""
3613 : getSelectorName(PD->getGetterName()),
3614 hasDefaultSetterName(PD, Setter)
3615 ? ""
3616 : getSelectorName(PD->getSetterName()),
3617 PD->getPropertyAttributes(),
3618 getOrCreateType(PD->getType(), PUnit));
3619 }
3620 }
3621 }
3622 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3623 FieldSize, FieldAlign, FieldOffset, Flags,
3624 FieldTy, PropertyNode);
3625 EltTys.push_back(FieldTy);
3626 }
3627
3628 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3629 DBuilder.replaceArrays(RealDecl, Elements);
3630
3631 LexicalBlockStack.pop_back();
3632 return RealDecl;
3633 }
3634
3635 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3636 llvm::DIFile *Unit) {
3637 if (Ty->isPackedVectorBoolType(CGM.getContext())) {
3638 // Boolean ext_vector_type(N) are special because their real element type
3639 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3640 // For now, we pretend the boolean vector were actually a vector of bytes
3641 // (where each byte represents 8 bits of the actual vector).
3642 // FIXME Debug info should actually represent this proper as a vector mask
3643 // type.
3644 auto &Ctx = CGM.getContext();
3645 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3646 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3647
3648 // Construct the vector of 'char' type.
3649 QualType CharVecTy =
3650 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3651 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3652 }
3653
3654 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3655 int64_t Count = Ty->getNumElements();
3656
3657 llvm::Metadata *Subscript;
3658 QualType QTy(Ty, 0);
3659 auto SizeExpr = SizeExprCache.find(QTy);
3660 if (SizeExpr != SizeExprCache.end())
3661 Subscript = DBuilder.getOrCreateSubrange(
3662 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3663 nullptr /*upperBound*/, nullptr /*stride*/);
3664 else {
3665 auto *CountNode =
3666 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3667 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3668 Subscript = DBuilder.getOrCreateSubrange(
3669 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3670 nullptr /*stride*/);
3671 }
3672 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3673
3674 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3675 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3676
3677 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3678 }
3679
3680 llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3681 llvm::DIFile *Unit) {
3682 // FIXME: Create another debug type for matrices
3683 // For the time being, it treats it like a nested ArrayType.
3684
3685 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3686 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3687 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3688
3689 // Create ranges for both dimensions.
3690 llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3691 auto *ColumnCountNode =
3692 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3693 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3694 auto *RowCountNode =
3695 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3696 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3697 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3698 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3699 nullptr /*stride*/));
3700 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3701 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3702 nullptr /*stride*/));
3703 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3704 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3705 }
3706
3707 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3708 uint64_t Size;
3709 uint32_t Align;
3710
3711 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3712 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3713 Size = 0;
3714 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3715 CGM.getContext());
3716 } else if (Ty->isIncompleteArrayType()) {
3717 Size = 0;
3718 if (Ty->getElementType()->isIncompleteType())
3719 Align = 0;
3720 else
3721 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3722 } else if (Ty->isIncompleteType()) {
3723 Size = 0;
3724 Align = 0;
3725 } else {
3726 // Size and align of the whole array, not the element type.
3727 Size = CGM.getContext().getTypeSize(Ty);
3728 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3729 }
3730
3731 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3732 // interior arrays, do we care? Why aren't nested arrays represented the
3733 // obvious/recursive way?
3734 SmallVector<llvm::Metadata *, 8> Subscripts;
3735 QualType EltTy(Ty, 0);
3736 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3737 // If the number of elements is known, then count is that number. Otherwise,
3738 // it's -1. This allows us to represent a subrange with an array of 0
3739 // elements, like this:
3740 //
3741 // struct foo {
3742 // int x[0];
3743 // };
3744 int64_t Count = -1; // Count == -1 is an unbounded array.
3745 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3746 Count = CAT->getZExtSize();
3747 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3748 if (Expr *Size = VAT->getSizeExpr()) {
3749 Expr::EvalResult Result;
3750 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3751 Count = Result.Val.getInt().getExtValue();
3752 }
3753 }
3754
3755 auto SizeNode = SizeExprCache.find(EltTy);
3756 if (SizeNode != SizeExprCache.end())
3757 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3758 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3759 nullptr /*upperBound*/, nullptr /*stride*/));
3760 else {
3761 auto *CountNode =
3762 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3763 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3764 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3765 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3766 nullptr /*stride*/));
3767 }
3768 EltTy = Ty->getElementType();
3769 }
3770
3771 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3772
3773 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3774 SubscriptArray);
3775 }
3776
3777 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3778 llvm::DIFile *Unit) {
3779 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3780 Ty->getPointeeType(), Unit);
3781 }
3782
3783 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3784 llvm::DIFile *Unit) {
3785 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3786 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3787 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3788 CGM.getCodeGenOpts().DwarfVersion < 4)
3789 Tag = llvm::dwarf::DW_TAG_reference_type;
3790
3791 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3792 }
3793
3794 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3795 llvm::DIFile *U) {
3796 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3797 uint64_t Size = 0;
3798
3799 if (!Ty->isIncompleteType()) {
3800 Size = CGM.getContext().getTypeSize(Ty);
3801
3802 // Set the MS inheritance model. There is no flag for the unspecified model.
3803 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3804 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3805 case MSInheritanceModel::Single:
3806 Flags |= llvm::DINode::FlagSingleInheritance;
3807 break;
3808 case MSInheritanceModel::Multiple:
3809 Flags |= llvm::DINode::FlagMultipleInheritance;
3810 break;
3811 case MSInheritanceModel::Virtual:
3812 Flags |= llvm::DINode::FlagVirtualInheritance;
3813 break;
3814 case MSInheritanceModel::Unspecified:
3815 break;
3816 }
3817 }
3818 }
3819
3820 CanQualType T =
3821 CGM.getContext().getCanonicalTagType(Ty->getMostRecentCXXRecordDecl());
3822 llvm::DIType *ClassType = getOrCreateType(T, U);
3823 if (Ty->isMemberDataPointerType())
3824 return DBuilder.createMemberPointerType(
3825 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3826 Flags);
3827
3828 const FunctionProtoType *FPT =
3829 Ty->getPointeeType()->castAs<FunctionProtoType>();
3830 return DBuilder.createMemberPointerType(
3831 getOrCreateInstanceMethodType(
3832 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
3833 FPT, U),
3834 ClassType, Size, /*Align=*/0, Flags);
3835 }
3836
3837 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3838 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3839 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3840 }
3841
3842 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3843 return getOrCreateType(Ty->getElementType(), U);
3844 }
3845
3846 llvm::DIType *CGDebugInfo::CreateType(const HLSLAttributedResourceType *Ty,
3847 llvm::DIFile *U) {
3848 return getOrCreateType(Ty->getWrappedType(), U);
3849 }
3850
3851 llvm::DIType *CGDebugInfo::CreateType(const HLSLInlineSpirvType *Ty,
3852 llvm::DIFile *U) {
3853 // Debug information unneeded.
3854 return nullptr;
3855 }
3856
3857 static auto getEnumInfo(CodeGenModule &CGM, llvm::DICompileUnit *TheCU,
3858 const EnumType *Ty) {
3859 const EnumDecl *ED = Ty->getDecl()->getDefinitionOrSelf();
3860
3861 uint64_t Size = 0;
3862 uint32_t Align = 0;
3863 if (ED->isComplete()) {
3864 Size = CGM.getContext().getTypeSize(QualType(Ty, 0));
3865 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3866 }
3867 return std::make_tuple(ED, Size, Align, getTypeIdentifier(Ty, CGM, TheCU));
3868 }
3869
3870 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3871 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
3872
3873 bool isImportedFromModule =
3874 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3875
3876 // If this is just a forward declaration, construct an appropriately
3877 // marked node and just return it.
3878 if (isImportedFromModule || !ED->getDefinition()) {
3879 // Note that it is possible for enums to be created as part of
3880 // their own declcontext. In this case a FwdDecl will be created
3881 // twice. This doesn't cause a problem because both FwdDecls are
3882 // entered into the ReplaceMap: finalize() will replace the first
3883 // FwdDecl with the second and then replace the second with
3884 // complete type.
3885 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3886 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3887 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3888 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3889
3890 unsigned Line = getLineNumber(ED->getLocation());
3891 StringRef EDName = ED->getName();
3892 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3893 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3894 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3895
3896 ReplaceMap.emplace_back(
3897 std::piecewise_construct, std::make_tuple(Ty),
3898 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3899 return RetTy;
3900 }
3901
3902 return CreateTypeDefinition(Ty);
3903 }
3904
3905 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3906 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
3907
3908 SmallVector<llvm::Metadata *, 16> Enumerators;
3909 ED = ED->getDefinition();
3910 assert(ED && "An enumeration definition is required");
3911 for (const auto *Enum : ED->enumerators()) {
3912 Enumerators.push_back(
3913 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3914 }
3915
3916 std::optional<EnumExtensibilityAttr::Kind> EnumKind;
3917 if (auto *Attr = ED->getAttr<EnumExtensibilityAttr>())
3918 EnumKind = Attr->getExtensibility();
3919
3920 // Return a CompositeType for the enum itself.
3921 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3922
3923 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3924 unsigned Line = getLineNumber(ED->getLocation());
3925 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3926 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3927 return DBuilder.createEnumerationType(
3928 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3929 /*RunTimeLang=*/0, Identifier, ED->isScoped(), EnumKind);
3930 }
3931
3932 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3933 unsigned MType, SourceLocation LineLoc,
3934 StringRef Name, StringRef Value) {
3935 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3936 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3937 }
3938
3939 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3940 SourceLocation LineLoc,
3941 SourceLocation FileLoc) {
3942 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3943 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3944 return DBuilder.createTempMacroFile(Parent, Line, FName);
3945 }
3946
3947 llvm::DILocation *CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc Location,
3948 StringRef FuncName) {
3949 llvm::DISubprogram *SP =
3950 createInlinedSubprogram(FuncName, Location->getFile());
3951 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
3952 /*Scope=*/SP, /*InlinedAt=*/Location);
3953 }
3954
3955 llvm::DILocation *CGDebugInfo::CreateTrapFailureMessageFor(
3956 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
3957 // Create a debug location from `TrapLocation` that adds an artificial inline
3958 // frame.
3959 SmallString<64> FuncName(ClangTrapPrefix);
3960
3961 FuncName += "$";
3962 FuncName += Category;
3963 FuncName += "$";
3964 FuncName += FailureMsg;
3965
3966 return CreateSyntheticInlineAt(TrapLocation, FuncName);
3967 }
3968
3969 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
3970 Qualifiers Quals;
3971 do {
3972 Qualifiers InnerQuals = T.getLocalQualifiers();
3973 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3974 // that is already there.
3975 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3976 Quals += InnerQuals;
3977 QualType LastT = T;
3978 switch (T->getTypeClass()) {
3979 default:
3980 return C.getQualifiedType(T.getTypePtr(), Quals);
3981 case Type::Enum:
3982 case Type::Record:
3983 case Type::InjectedClassName:
3984 return C.getQualifiedType(T->getCanonicalTypeUnqualified().getTypePtr(),
3985 Quals);
3986 case Type::TemplateSpecialization: {
3987 const auto *Spec = cast<TemplateSpecializationType>(T);
3988 if (Spec->isTypeAlias())
3989 return C.getQualifiedType(T.getTypePtr(), Quals);
3990 T = Spec->desugar();
3991 break;
3992 }
3993 case Type::TypeOfExpr:
3994 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3995 break;
3996 case Type::TypeOf:
3997 T = cast<TypeOfType>(T)->getUnmodifiedType();
3998 break;
3999 case Type::Decltype:
4000 T = cast<DecltypeType>(T)->getUnderlyingType();
4001 break;
4002 case Type::UnaryTransform:
4003 T = cast<UnaryTransformType>(T)->getUnderlyingType();
4004 break;
4005 case Type::Attributed:
4006 T = cast<AttributedType>(T)->getEquivalentType();
4007 break;
4008 case Type::BTFTagAttributed:
4009 T = cast<BTFTagAttributedType>(T)->getWrappedType();
4010 break;
4011 case Type::CountAttributed:
4012 T = cast<CountAttributedType>(T)->desugar();
4013 break;
4014 case Type::Using:
4015 T = cast<UsingType>(T)->desugar();
4016 break;
4017 case Type::Paren:
4018 T = cast<ParenType>(T)->getInnerType();
4019 break;
4020 case Type::MacroQualified:
4021 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
4022 break;
4023 case Type::SubstTemplateTypeParm:
4024 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
4025 break;
4026 case Type::Auto:
4027 case Type::DeducedTemplateSpecialization: {
4028 QualType DT = cast<DeducedType>(T)->getDeducedType();
4029 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
4030 T = DT;
4031 break;
4032 }
4033 case Type::PackIndexing: {
4034 T = cast<PackIndexingType>(T)->getSelectedType();
4035 break;
4036 }
4037 case Type::Adjusted:
4038 case Type::Decayed:
4039 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
4040 T = cast<AdjustedType>(T)->getAdjustedType();
4041 break;
4042 }
4043
4044 assert(T != LastT && "Type unwrapping failed to unwrap!");
4045 (void)LastT;
4046 } while (true);
4047 }
4048
4049 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
4050 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
4051 auto It = TypeCache.find(Ty.getAsOpaquePtr());
4052 if (It != TypeCache.end()) {
4053 // Verify that the debug info still exists.
4054 if (llvm::Metadata *V = It->second)
4055 return cast<llvm::DIType>(V);
4056 }
4057
4058 return nullptr;
4059 }
4060
4061 void CGDebugInfo::completeTemplateDefinition(
4062 const ClassTemplateSpecializationDecl &SD) {
4063 completeUnusedClass(SD);
4064 }
4065
4066 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
4067 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
4068 D.isDynamicClass())
4069 return;
4070
4071 completeClassData(&D);
4072 // In case this type has no member function definitions being emitted, ensure
4073 // it is retained
4074 RetainedTypes.push_back(
4075 CGM.getContext().getCanonicalTagType(&D).getAsOpaquePtr());
4076 }
4077
4078 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
4079 if (Ty.isNull())
4080 return nullptr;
4081
4082 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
4083 std::string Name;
4084 llvm::raw_string_ostream OS(Name);
4085 Ty.print(OS, getPrintingPolicy());
4086 return Name;
4087 });
4088
4089 // Unwrap the type as needed for debug information.
4090 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
4091
4092 if (auto *T = getTypeOrNull(Ty))
4093 return T;
4094
4095 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
4096 void *TyPtr = Ty.getAsOpaquePtr();
4097
4098 // And update the type cache.
4099 TypeCache[TyPtr].reset(Res);
4100
4101 return Res;
4102 }
4103
4104 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
4105 // A forward declaration inside a module header does not belong to the module.
4106 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
4107 return nullptr;
4108 if (DebugTypeExtRefs && D->isFromASTFile()) {
4109 // Record a reference to an imported clang module or precompiled header.
4110 auto *Reader = CGM.getContext().getExternalSource();
4111 auto Idx = D->getOwningModuleID();
4112 auto Info = Reader->getSourceDescriptor(Idx);
4113 if (Info)
4114 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
4115 } else if (ClangModuleMap) {
4116 // We are building a clang module or a precompiled header.
4117 //
4118 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
4119 // and it wouldn't be necessary to specify the parent scope
4120 // because the type is already unique by definition (it would look
4121 // like the output of -fno-standalone-debug). On the other hand,
4122 // the parent scope helps a consumer to quickly locate the object
4123 // file where the type's definition is located, so it might be
4124 // best to make this behavior a command line or debugger tuning
4125 // option.
4126 if (Module *M = D->getOwningModule()) {
4127 // This is a (sub-)module.
4128 auto Info = ASTSourceDescriptor(*M);
4129 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
4130 } else {
4131 // This the precompiled header being built.
4132 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
4133 }
4134 }
4135
4136 return nullptr;
4137 }
4138
4139 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
4140 // Handle qualifiers, which recursively handles what they refer to.
4141 if (Ty.hasLocalQualifiers())
4142 return CreateQualifiedType(Ty, Unit);
4143
4144 // Work out details of type.
4145 switch (Ty->getTypeClass()) {
4146 #define TYPE(Class, Base)
4147 #define ABSTRACT_TYPE(Class, Base)
4148 #define NON_CANONICAL_TYPE(Class, Base)
4149 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4150 #include "clang/AST/TypeNodes.inc"
4151 llvm_unreachable("Dependent types cannot show up in debug information");
4152
4153 case Type::ExtVector:
4154 case Type::Vector:
4155 return CreateType(cast<VectorType>(Ty), Unit);
4156 case Type::ConstantMatrix:
4157 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
4158 case Type::ObjCObjectPointer:
4159 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
4160 case Type::ObjCObject:
4161 return CreateType(cast<ObjCObjectType>(Ty), Unit);
4162 case Type::ObjCTypeParam:
4163 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
4164 case Type::ObjCInterface:
4165 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
4166 case Type::Builtin:
4167 return CreateType(cast<BuiltinType>(Ty));
4168 case Type::Complex:
4169 return CreateType(cast<ComplexType>(Ty));
4170 case Type::Pointer:
4171 return CreateType(cast<PointerType>(Ty), Unit);
4172 case Type::BlockPointer:
4173 return CreateType(cast<BlockPointerType>(Ty), Unit);
4174 case Type::Typedef:
4175 return CreateType(cast<TypedefType>(Ty), Unit);
4176 case Type::Record:
4177 return CreateType(cast<RecordType>(Ty));
4178 case Type::Enum:
4179 return CreateEnumType(cast<EnumType>(Ty));
4180 case Type::FunctionProto:
4181 case Type::FunctionNoProto:
4182 return CreateType(cast<FunctionType>(Ty), Unit);
4183 case Type::ConstantArray:
4184 case Type::VariableArray:
4185 case Type::IncompleteArray:
4186 case Type::ArrayParameter:
4187 return CreateType(cast<ArrayType>(Ty), Unit);
4188
4189 case Type::LValueReference:
4190 return CreateType(cast<LValueReferenceType>(Ty), Unit);
4191 case Type::RValueReference:
4192 return CreateType(cast<RValueReferenceType>(Ty), Unit);
4193
4194 case Type::MemberPointer:
4195 return CreateType(cast<MemberPointerType>(Ty), Unit);
4196
4197 case Type::Atomic:
4198 return CreateType(cast<AtomicType>(Ty), Unit);
4199
4200 case Type::BitInt:
4201 return CreateType(cast<BitIntType>(Ty));
4202 case Type::Pipe:
4203 return CreateType(cast<PipeType>(Ty), Unit);
4204
4205 case Type::TemplateSpecialization:
4206 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
4207 case Type::HLSLAttributedResource:
4208 return CreateType(cast<HLSLAttributedResourceType>(Ty), Unit);
4209 case Type::HLSLInlineSpirv:
4210 return CreateType(cast<HLSLInlineSpirvType>(Ty), Unit);
4211 case Type::PredefinedSugar:
4212 return getOrCreateType(cast<PredefinedSugarType>(Ty)->desugar(), Unit);
4213 case Type::CountAttributed:
4214 case Type::Auto:
4215 case Type::Attributed:
4216 case Type::BTFTagAttributed:
4217 case Type::Adjusted:
4218 case Type::Decayed:
4219 case Type::DeducedTemplateSpecialization:
4220 case Type::Using:
4221 case Type::Paren:
4222 case Type::MacroQualified:
4223 case Type::SubstTemplateTypeParm:
4224 case Type::TypeOfExpr:
4225 case Type::TypeOf:
4226 case Type::Decltype:
4227 case Type::PackIndexing:
4228 case Type::UnaryTransform:
4229 break;
4230 }
4231
4232 llvm_unreachable("type should have been unwrapped!");
4233 }
4234
4235 llvm::DICompositeType *
4236 CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
4237 QualType QTy(Ty, 0);
4238
4239 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
4240
4241 // We may have cached a forward decl when we could have created
4242 // a non-forward decl. Go ahead and create a non-forward decl
4243 // now.
4244 if (T && !T->isForwardDecl())
4245 return T;
4246
4247 // Otherwise create the type.
4248 llvm::DICompositeType *Res = CreateLimitedType(Ty);
4249
4250 // Propagate members from the declaration to the definition
4251 // CreateType(const RecordType*) will overwrite this with the members in the
4252 // correct order if the full type is needed.
4253 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
4254
4255 // And update the type cache.
4256 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
4257 return Res;
4258 }
4259
4260 // TODO: Currently used for context chains when limiting debug info.
4261 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
4262 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
4263
4264 // Get overall information about the record type for the debug info.
4265 StringRef RDName = getClassName(RD);
4266 const SourceLocation Loc = RD->getLocation();
4267 llvm::DIFile *DefUnit = nullptr;
4268 unsigned Line = 0;
4269 if (Loc.isValid()) {
4270 DefUnit = getOrCreateFile(Loc);
4271 Line = getLineNumber(Loc);
4272 }
4273
4274 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
4275
4276 // If we ended up creating the type during the context chain construction,
4277 // just return that.
4278 auto *T = cast_or_null<llvm::DICompositeType>(
4279 getTypeOrNull(CGM.getContext().getCanonicalTagType(RD)));
4280 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
4281 return T;
4282
4283 // If this is just a forward or incomplete declaration, construct an
4284 // appropriately marked node and just return it.
4285 const RecordDecl *D = RD->getDefinition();
4286 if (!D || !D->isCompleteDefinition())
4287 return getOrCreateRecordFwdDecl(Ty, RDContext);
4288
4289 uint64_t Size = CGM.getContext().getTypeSize(Ty);
4290 // __attribute__((aligned)) can increase or decrease alignment *except* on a
4291 // struct or struct member, where it only increases alignment unless 'packed'
4292 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
4293 // to be used.
4294 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
4295
4296 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
4297
4298 // Explicitly record the calling convention and export symbols for C++
4299 // records.
4300 auto Flags = llvm::DINode::FlagZero;
4301 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4302 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
4303 Flags |= llvm::DINode::FlagTypePassByReference;
4304 else
4305 Flags |= llvm::DINode::FlagTypePassByValue;
4306
4307 // Record if a C++ record is non-trivial type.
4308 if (!CXXRD->isTrivial())
4309 Flags |= llvm::DINode::FlagNonTrivial;
4310
4311 // Record exports it symbols to the containing structure.
4312 if (CXXRD->isAnonymousStructOrUnion())
4313 Flags |= llvm::DINode::FlagExportSymbols;
4314
4315 Flags |= getAccessFlag(CXXRD->getAccess(),
4316 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
4317 }
4318
4319 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4320 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
4321 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
4322 Flags, Identifier, Annotations);
4323
4324 // Elements of composite types usually have back to the type, creating
4325 // uniquing cycles. Distinct nodes are more efficient.
4326 switch (RealDecl->getTag()) {
4327 default:
4328 llvm_unreachable("invalid composite type tag");
4329
4330 case llvm::dwarf::DW_TAG_array_type:
4331 case llvm::dwarf::DW_TAG_enumeration_type:
4332 // Array elements and most enumeration elements don't have back references,
4333 // so they don't tend to be involved in uniquing cycles and there is some
4334 // chance of merging them when linking together two modules. Only make
4335 // them distinct if they are ODR-uniqued.
4336 if (Identifier.empty())
4337 break;
4338 [[fallthrough]];
4339
4340 case llvm::dwarf::DW_TAG_structure_type:
4341 case llvm::dwarf::DW_TAG_union_type:
4342 case llvm::dwarf::DW_TAG_class_type:
4343 // Immediately resolve to a distinct node.
4344 RealDecl =
4345 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
4346 break;
4347 }
4348
4349 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Ty->getDecl())) {
4350 CXXRecordDecl *TemplateDecl =
4351 CTSD->getSpecializedTemplate()->getTemplatedDecl();
4352 RegionMap[TemplateDecl].reset(RealDecl);
4353 } else {
4354 RegionMap[RD].reset(RealDecl);
4355 }
4356 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
4357
4358 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
4359 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
4360 CollectCXXTemplateParams(TSpecial, DefUnit));
4361 return RealDecl;
4362 }
4363
4364 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
4365 llvm::DICompositeType *RealDecl) {
4366 // A class's primary base or the class itself contains the vtable.
4367 llvm::DIType *ContainingType = nullptr;
4368 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
4369 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
4370 // Seek non-virtual primary base root.
4371 while (true) {
4372 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
4373 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
4374 if (PBT && !BRL.isPrimaryBaseVirtual())
4375 PBase = PBT;
4376 else
4377 break;
4378 }
4379 CanQualType T = CGM.getContext().getCanonicalTagType(PBase);
4380 ContainingType = getOrCreateType(T, getOrCreateFile(RD->getLocation()));
4381 } else if (RD->isDynamicClass())
4382 ContainingType = RealDecl;
4383
4384 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4385 }
4386
4387 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4388 StringRef Name, uint64_t *Offset) {
4389 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4390 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4391 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4392 llvm::DIType *Ty =
4393 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4394 *Offset, llvm::DINode::FlagZero, FieldTy);
4395 *Offset += FieldSize;
4396 return Ty;
4397 }
4398
4399 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4400 StringRef &Name,
4401 StringRef &LinkageName,
4402 llvm::DIScope *&FDContext,
4403 llvm::DINodeArray &TParamsArray,
4404 llvm::DINode::DIFlags &Flags) {
4405 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4406 Name = getFunctionName(FD);
4407 // Use mangled name as linkage name for C/C++ functions.
4408 if (FD->getType()->getAs<FunctionProtoType>())
4409 LinkageName = CGM.getMangledName(GD);
4410 if (FD->hasPrototype())
4411 Flags |= llvm::DINode::FlagPrototyped;
4412 // No need to replicate the linkage name if it isn't different from the
4413 // subprogram name, no need to have it at all unless coverage is enabled or
4414 // debug is set to more than just line tables or extra debug info is needed.
4415 if (LinkageName == Name ||
4416 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4417 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4418 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4419 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4420 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4421 LinkageName = StringRef();
4422
4423 // Emit the function scope in line tables only mode (if CodeView) to
4424 // differentiate between function names.
4425 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4426 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4427 CGM.getCodeGenOpts().EmitCodeView)) {
4428 if (const NamespaceDecl *NSDecl =
4429 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4430 FDContext = getOrCreateNamespace(NSDecl);
4431 else if (const RecordDecl *RDecl =
4432 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4433 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4434 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4435 }
4436 }
4437 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4438 // Check if it is a noreturn-marked function
4439 if (FD->isNoReturn())
4440 Flags |= llvm::DINode::FlagNoReturn;
4441 // Collect template parameters.
4442 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4443 }
4444 }
4445
4446 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4447 unsigned &LineNo, QualType &T,
4448 StringRef &Name, StringRef &LinkageName,
4449 llvm::MDTuple *&TemplateParameters,
4450 llvm::DIScope *&VDContext) {
4451 Unit = getOrCreateFile(VD->getLocation());
4452 LineNo = getLineNumber(VD->getLocation());
4453
4454 setLocation(VD->getLocation());
4455
4456 T = VD->getType();
4457 if (T->isIncompleteArrayType()) {
4458 // CodeGen turns int[] into int[1] so we'll do the same here.
4459 llvm::APInt ConstVal(32, 1);
4460 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
4461
4462 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4463 ArraySizeModifier::Normal, 0);
4464 }
4465
4466 Name = VD->getName();
4467 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4468 !isa<ObjCMethodDecl>(VD->getDeclContext()))
4469 LinkageName = CGM.getMangledName(VD);
4470 if (LinkageName == Name)
4471 LinkageName = StringRef();
4472
4473 if (isa<VarTemplateSpecializationDecl>(VD)) {
4474 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4475 TemplateParameters = parameterNodes.get();
4476 } else {
4477 TemplateParameters = nullptr;
4478 }
4479
4480 // Since we emit declarations (DW_AT_members) for static members, place the
4481 // definition of those static members in the namespace they were declared in
4482 // in the source code (the lexical decl context).
4483 // FIXME: Generalize this for even non-member global variables where the
4484 // declaration and definition may have different lexical decl contexts, once
4485 // we have support for emitting declarations of (non-member) global variables.
4486 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4487 : VD->getDeclContext();
4488 // When a record type contains an in-line initialization of a static data
4489 // member, and the record type is marked as __declspec(dllexport), an implicit
4490 // definition of the member will be created in the record context. DWARF
4491 // doesn't seem to have a nice way to describe this in a form that consumers
4492 // are likely to understand, so fake the "normal" situation of a definition
4493 // outside the class by putting it in the global scope.
4494 if (DC->isRecord())
4495 DC = CGM.getContext().getTranslationUnitDecl();
4496
4497 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4498 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4499 }
4500
4501 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4502 bool Stub) {
4503 llvm::DINodeArray TParamsArray;
4504 StringRef Name, LinkageName;
4505 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4506 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4507 SourceLocation Loc = GD.getDecl()->getLocation();
4508 llvm::DIFile *Unit = getOrCreateFile(Loc);
4509 llvm::DIScope *DContext = Unit;
4510 unsigned Line = getLineNumber(Loc);
4511 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4512 Flags);
4513 auto *FD = cast<FunctionDecl>(GD.getDecl());
4514
4515 // Build function type.
4516 SmallVector<QualType, 16> ArgTypes;
4517 for (const ParmVarDecl *Parm : FD->parameters())
4518 ArgTypes.push_back(Parm->getType());
4519
4520 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4521 QualType FnType = CGM.getContext().getFunctionType(
4522 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4523 if (!FD->isExternallyVisible())
4524 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4525 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
4526 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4527
4528 if (Stub) {
4529 Flags |= getCallSiteRelatedAttrs();
4530 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4531 return DBuilder.createFunction(
4532 DContext, Name, LinkageName, Unit, Line,
4533 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4534 TParamsArray.get(), getFunctionDeclaration(FD), /*ThrownTypes*/ nullptr,
4535 /*Annotations*/ nullptr, /*TargetFuncName*/ "",
4536 CGM.getCodeGenOpts().DebugKeyInstructions);
4537 }
4538
4539 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4540 DContext, Name, LinkageName, Unit, Line,
4541 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4542 TParamsArray.get(), getFunctionDeclaration(FD));
4543 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4544 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4545 std::make_tuple(CanonDecl),
4546 std::make_tuple(SP));
4547 return SP;
4548 }
4549
4550 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4551 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4552 }
4553
4554 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4555 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4556 }
4557
4558 llvm::DIGlobalVariable *
4559 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4560 QualType T;
4561 StringRef Name, LinkageName;
4562 SourceLocation Loc = VD->getLocation();
4563 llvm::DIFile *Unit = getOrCreateFile(Loc);
4564 llvm::DIScope *DContext = Unit;
4565 unsigned Line = getLineNumber(Loc);
4566 llvm::MDTuple *TemplateParameters = nullptr;
4567
4568 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4569 DContext);
4570 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4571 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4572 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4573 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4574 FwdDeclReplaceMap.emplace_back(
4575 std::piecewise_construct,
4576 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4577 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4578 return GV;
4579 }
4580
4581 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4582 // We only need a declaration (not a definition) of the type - so use whatever
4583 // we would otherwise do to get a type for a pointee. (forward declarations in
4584 // limited debug info, full definitions (if the type definition is available)
4585 // in unlimited debug info)
4586 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
4587 QualType Ty = CGM.getContext().getTypeDeclType(TD);
4588 return getOrCreateType(Ty, getOrCreateFile(TD->getLocation()));
4589 }
4590 auto I = DeclCache.find(D->getCanonicalDecl());
4591
4592 if (I != DeclCache.end()) {
4593 auto N = I->second;
4594 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4595 return GVE->getVariable();
4596 return cast<llvm::DINode>(N);
4597 }
4598
4599 // Search imported declaration cache if it is already defined
4600 // as imported declaration.
4601 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4602
4603 if (IE != ImportedDeclCache.end()) {
4604 auto N = IE->second;
4605 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4606 return cast<llvm::DINode>(GVE);
4607 return dyn_cast_or_null<llvm::DINode>(N);
4608 }
4609
4610 // No definition for now. Emit a forward definition that might be
4611 // merged with a potential upcoming definition.
4612 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4613 return getFunctionForwardDeclaration(FD);
4614 else if (const auto *VD = dyn_cast<VarDecl>(D))
4615 return getGlobalVariableForwardDeclaration(VD);
4616
4617 return nullptr;
4618 }
4619
4620 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4621 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4622 return nullptr;
4623
4624 const auto *FD = dyn_cast<FunctionDecl>(D);
4625 if (!FD)
4626 return nullptr;
4627
4628 // Setup context.
4629 auto *S = getDeclContextDescriptor(D);
4630
4631 auto MI = SPCache.find(FD->getCanonicalDecl());
4632 if (MI == SPCache.end()) {
4633 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4634 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4635 cast<llvm::DICompositeType>(S));
4636 }
4637 }
4638 if (MI != SPCache.end()) {
4639 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4640 if (SP && !SP->isDefinition())
4641 return SP;
4642 }
4643
4644 for (auto *NextFD : FD->redecls()) {
4645 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4646 if (MI != SPCache.end()) {
4647 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4648 if (SP && !SP->isDefinition())
4649 return SP;
4650 }
4651 }
4652 return nullptr;
4653 }
4654
4655 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4656 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4657 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4658 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4659 return nullptr;
4660
4661 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4662 if (!OMD)
4663 return nullptr;
4664
4665 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4666 return nullptr;
4667
4668 if (OMD->isDirectMethod())
4669 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4670
4671 // Starting with DWARF V5 method declarations are emitted as children of
4672 // the interface type.
4673 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4674 if (!ID)
4675 ID = OMD->getClassInterface();
4676 if (!ID)
4677 return nullptr;
4678 QualType QTy(ID->getTypeForDecl(), 0);
4679 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4680 if (It == TypeCache.end())
4681 return nullptr;
4682 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4683 llvm::DISubprogram *FD = DBuilder.createFunction(
4684 InterfaceType, getObjCMethodName(OMD), StringRef(),
4685 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4686 DBuilder.finalizeSubprogram(FD);
4687 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4688 return FD;
4689 }
4690
4691 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
4692 // implicit parameter "this".
4693 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4694 QualType FnType,
4695 llvm::DIFile *F) {
4696 // In CodeView, we emit the function types in line tables only because the
4697 // only way to distinguish between functions is by display name and type.
4698 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4699 !CGM.getCodeGenOpts().EmitCodeView))
4700 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4701 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4702 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4703
4704 if (const auto *Method = dyn_cast<CXXDestructorDecl>(D)) {
4705 // Read method type from 'FnType' because 'D.getType()' does not cover
4706 // implicit arguments for destructors.
4707 return getOrCreateMethodTypeForDestructor(Method, F, FnType);
4708 }
4709
4710 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4711 return getOrCreateMethodType(Method, F);
4712
4713 const auto *FTy = FnType->getAs<FunctionType>();
4714 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4715
4716 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4717 // Add "self" and "_cmd"
4718 SmallVector<llvm::Metadata *, 16> Elts;
4719
4720 // First element is always return type. For 'void' functions it is NULL.
4721 QualType ResultTy = OMethod->getReturnType();
4722
4723 // Replace the instancetype keyword with the actual type.
4724 if (ResultTy == CGM.getContext().getObjCInstanceType())
4725 ResultTy = CGM.getContext().getPointerType(
4726 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4727
4728 Elts.push_back(getOrCreateType(ResultTy, F));
4729 // "self" pointer is always first argument.
4730 QualType SelfDeclTy;
4731 if (auto *SelfDecl = OMethod->getSelfDecl())
4732 SelfDeclTy = SelfDecl->getType();
4733 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4734 if (FPT->getNumParams() > 1)
4735 SelfDeclTy = FPT->getParamType(0);
4736 if (!SelfDeclTy.isNull())
4737 Elts.push_back(
4738 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4739 // "_cmd" pointer is always second argument.
4740 Elts.push_back(DBuilder.createArtificialType(
4741 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4742 // Get rest of the arguments.
4743 for (const auto *PI : OMethod->parameters())
4744 Elts.push_back(getOrCreateType(PI->getType(), F));
4745 // Variadic methods need a special marker at the end of the type list.
4746 if (OMethod->isVariadic())
4747 Elts.push_back(DBuilder.createUnspecifiedParameter());
4748
4749 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4750 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4751 getDwarfCC(CC));
4752 }
4753
4754 // Handle variadic function types; they need an additional
4755 // unspecified parameter.
4756 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4757 if (FD->isVariadic()) {
4758 SmallVector<llvm::Metadata *, 16> EltTys;
4759 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4760 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4761 for (QualType ParamType : FPT->param_types())
4762 EltTys.push_back(getOrCreateType(ParamType, F));
4763 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4764 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4765 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4766 getDwarfCC(CC));
4767 }
4768
4769 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4770 }
4771
4772 QualType
4773 CGDebugInfo::getFunctionType(const FunctionDecl *FD, QualType RetTy,
4774 const SmallVectorImpl<const VarDecl *> &Args) {
4775 CallingConv CC = CallingConv::CC_C;
4776 if (FD)
4777 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4778 CC = SrcFnTy->getCallConv();
4779 SmallVector<QualType, 16> ArgTypes;
4780 for (const VarDecl *VD : Args)
4781 ArgTypes.push_back(VD->getType());
4782 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4783 FunctionProtoType::ExtProtoInfo(CC));
4784 }
4785
4786 void CGDebugInfo::emitFunctionStart(GlobalDecl GD, SourceLocation Loc,
4787 SourceLocation ScopeLoc, QualType FnType,
4788 llvm::Function *Fn, bool CurFuncIsThunk) {
4789 StringRef Name;
4790 StringRef LinkageName;
4791
4792 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4793
4794 const Decl *D = GD.getDecl();
4795 bool HasDecl = (D != nullptr);
4796
4797 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4798 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4799 llvm::DIFile *Unit = getOrCreateFile(Loc);
4800 llvm::DIScope *FDContext = Unit;
4801 llvm::DINodeArray TParamsArray;
4802 bool KeyInstructions = CGM.getCodeGenOpts().DebugKeyInstructions;
4803 if (!HasDecl) {
4804 // Use llvm function name.
4805 LinkageName = Fn->getName();
4806 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4807 // If there is a subprogram for this function available then use it.
4808 auto FI = SPCache.find(FD->getCanonicalDecl());
4809 if (FI != SPCache.end()) {
4810 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4811 if (SP && SP->isDefinition()) {
4812 LexicalBlockStack.emplace_back(SP);
4813 RegionMap[D].reset(SP);
4814 return;
4815 }
4816 }
4817 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4818 TParamsArray, Flags);
4819 // Disable KIs if this is a coroutine.
4820 KeyInstructions =
4821 KeyInstructions && !isa_and_present<CoroutineBodyStmt>(FD->getBody());
4822 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4823 Name = getObjCMethodName(OMD);
4824 Flags |= llvm::DINode::FlagPrototyped;
4825 } else if (isa<VarDecl>(D) &&
4826 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
4827 // This is a global initializer or atexit destructor for a global variable.
4828 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4829 Fn);
4830 } else {
4831 Name = Fn->getName();
4832
4833 if (isa<BlockDecl>(D))
4834 LinkageName = Name;
4835
4836 Flags |= llvm::DINode::FlagPrototyped;
4837 }
4838 Name.consume_front("\01");
4839
4840 assert((!D || !isa<VarDecl>(D) ||
4841 GD.getDynamicInitKind() != DynamicInitKind::NoStub) &&
4842 "Unexpected DynamicInitKind !");
4843
4844 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4845 isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4846 Flags |= llvm::DINode::FlagArtificial;
4847 // Artificial functions should not silently reuse CurLoc.
4848 CurLoc = SourceLocation();
4849 }
4850
4851 if (CurFuncIsThunk)
4852 Flags |= llvm::DINode::FlagThunk;
4853
4854 if (Fn->hasLocalLinkage())
4855 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4856 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
4857 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4858
4859 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4860 llvm::DISubprogram::DISPFlags SPFlagsForDef =
4861 SPFlags | llvm::DISubprogram::SPFlagDefinition;
4862
4863 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4864 unsigned ScopeLine = getLineNumber(ScopeLoc);
4865 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4866 llvm::DISubprogram *Decl = nullptr;
4867 llvm::DINodeArray Annotations = nullptr;
4868 if (D) {
4869 Decl = isa<ObjCMethodDecl>(D)
4870 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4871 : getFunctionDeclaration(D);
4872 Annotations = CollectBTFDeclTagAnnotations(D);
4873 }
4874
4875 // FIXME: The function declaration we're constructing here is mostly reusing
4876 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4877 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4878 // all subprograms instead of the actual context since subprogram definitions
4879 // are emitted as CU level entities by the backend.
4880 llvm::DISubprogram *SP = DBuilder.createFunction(
4881 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4882 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4883 Annotations, "", KeyInstructions);
4884 Fn->setSubprogram(SP);
4885
4886 // We might get here with a VarDecl in the case we're generating
4887 // code for the initialization of globals. Do not record these decls
4888 // as they will overwrite the actual VarDecl Decl in the cache.
4889 if (HasDecl && isa<FunctionDecl>(D))
4890 DeclCache[D->getCanonicalDecl()].reset(SP);
4891
4892 // Push the function onto the lexical block stack.
4893 LexicalBlockStack.emplace_back(SP);
4894
4895 if (HasDecl)
4896 RegionMap[D].reset(SP);
4897 }
4898
4899 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
4900 QualType FnType, llvm::Function *Fn) {
4901 StringRef Name;
4902 StringRef LinkageName;
4903
4904 const Decl *D = GD.getDecl();
4905 if (!D)
4906 return;
4907
4908 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4909 return GetName(D, true);
4910 });
4911
4912 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4913 llvm::DIFile *Unit = getOrCreateFile(Loc);
4914 bool IsDeclForCallSite = Fn ? true : false;
4915 llvm::DIScope *FDContext =
4916 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4917 llvm::DINodeArray TParamsArray;
4918 if (isa<FunctionDecl>(D)) {
4919 // If there is a DISubprogram for this function available then use it.
4920 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4921 TParamsArray, Flags);
4922 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4923 Name = getObjCMethodName(OMD);
4924 Flags |= llvm::DINode::FlagPrototyped;
4925 } else {
4926 llvm_unreachable("not a function or ObjC method");
4927 }
4928 Name.consume_front("\01");
4929
4930 if (D->isImplicit()) {
4931 Flags |= llvm::DINode::FlagArtificial;
4932 // Artificial functions without a location should not silently reuse CurLoc.
4933 if (Loc.isInvalid())
4934 CurLoc = SourceLocation();
4935 }
4936 unsigned LineNo = getLineNumber(Loc);
4937 unsigned ScopeLine = 0;
4938 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4939 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
4940 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4941
4942 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4943 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4944 // Key Instructions: Don't set flag on declarations.
4945 assert(~SPFlags & llvm::DISubprogram::SPFlagDefinition);
4946 llvm::DISubprogram *SP = DBuilder.createFunction(
4947 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4948 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations,
4949 /*TargetFunctionName*/ "", /*UseKeyInstructions*/ false);
4950
4951 // Preserve btf_decl_tag attributes for parameters of extern functions
4952 // for BPF target. The parameters created in this loop are attached as
4953 // DISubprogram's retainedNodes in the DIBuilder::finalize() call.
4954 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4955 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4956 llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4957 unsigned ArgNo = 1;
4958 for (ParmVarDecl *PD : FD->parameters()) {
4959 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4960 DBuilder.createParameterVariable(
4961 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4962 llvm::DINode::FlagZero, ParamAnnotations);
4963 ++ArgNo;
4964 }
4965 }
4966 }
4967
4968 if (IsDeclForCallSite)
4969 Fn->setSubprogram(SP);
4970 }
4971
4972 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4973 QualType CalleeType,
4974 GlobalDecl CalleeGlobalDecl) {
4975 if (!CallOrInvoke)
4976 return;
4977 auto *Func = dyn_cast<llvm::Function>(CallOrInvoke->getCalledOperand());
4978 if (!Func)
4979 return;
4980 if (Func->getSubprogram())
4981 return;
4982
4983 const FunctionDecl *CalleeDecl =
4984 cast<FunctionDecl>(CalleeGlobalDecl.getDecl());
4985
4986 // Do not emit a declaration subprogram for a function with nodebug
4987 // attribute, or if call site info isn't required.
4988 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4989 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4990 return;
4991
4992 // If there is no DISubprogram attached to the function being called,
4993 // create the one describing the function in order to have complete
4994 // call site debug info.
4995 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4996 EmitFunctionDecl(CalleeGlobalDecl, CalleeDecl->getLocation(), CalleeType,
4997 Func);
4998 }
4999
5000 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
5001 const auto *FD = cast<FunctionDecl>(GD.getDecl());
5002 // If there is a subprogram for this function available then use it.
5003 auto FI = SPCache.find(FD->getCanonicalDecl());
5004 llvm::DISubprogram *SP = nullptr;
5005 if (FI != SPCache.end())
5006 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
5007 if (!SP || !SP->isDefinition())
5008 SP = getFunctionStub(GD);
5009 FnBeginRegionCount.push_back(LexicalBlockStack.size());
5010 LexicalBlockStack.emplace_back(SP);
5011 setInlinedAt(Builder.getCurrentDebugLocation());
5012 EmitLocation(Builder, FD->getLocation());
5013 }
5014
5015 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
5016 assert(CurInlinedAt && "unbalanced inline scope stack");
5017 EmitFunctionEnd(Builder, nullptr);
5018 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
5019 }
5020
5021 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
5022 // Update our current location
5023 setLocation(Loc);
5024
5025 if (CurLoc.isInvalid() ||
5026 (CGM.getCodeGenOpts().DebugInfoMacroExpansionLoc && CurLoc.isMacroID()) ||
5027 LexicalBlockStack.empty())
5028 return;
5029
5030 llvm::MDNode *Scope = LexicalBlockStack.back();
5031 Builder.SetCurrentDebugLocation(
5032 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
5033 getColumnNumber(CurLoc), Scope, CurInlinedAt));
5034 }
5035
5036 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
5037 llvm::MDNode *Back = nullptr;
5038 if (!LexicalBlockStack.empty())
5039 Back = LexicalBlockStack.back().get();
5040 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
5041 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
5042 getColumnNumber(CurLoc)));
5043 }
5044
5045 void CGDebugInfo::AppendAddressSpaceXDeref(
5046 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
5047 std::optional<unsigned> DWARFAddressSpace =
5048 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
5049 if (!DWARFAddressSpace)
5050 return;
5051
5052 Expr.push_back(llvm::dwarf::DW_OP_constu);
5053 Expr.push_back(*DWARFAddressSpace);
5054 Expr.push_back(llvm::dwarf::DW_OP_swap);
5055 Expr.push_back(llvm::dwarf::DW_OP_xderef);
5056 }
5057
5058 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
5059 SourceLocation Loc) {
5060 // Set our current location.
5061 setLocation(Loc);
5062
5063 // Emit a line table change for the current location inside the new scope.
5064 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
5065 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
5066 LexicalBlockStack.back(), CurInlinedAt));
5067
5068 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5069 return;
5070
5071 // Create a new lexical block and push it on the stack.
5072 CreateLexicalBlock(Loc);
5073 }
5074
5075 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
5076 SourceLocation Loc) {
5077 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5078
5079 // Provide an entry in the line table for the end of the block.
5080 EmitLocation(Builder, Loc);
5081
5082 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5083 return;
5084
5085 LexicalBlockStack.pop_back();
5086 }
5087
5088 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
5089 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5090 unsigned RCount = FnBeginRegionCount.back();
5091 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
5092
5093 // Pop all regions for this function.
5094 while (LexicalBlockStack.size() != RCount) {
5095 // Provide an entry in the line table for the end of the block.
5096 EmitLocation(Builder, CurLoc);
5097 LexicalBlockStack.pop_back();
5098 }
5099 FnBeginRegionCount.pop_back();
5100
5101 if (Fn && Fn->getSubprogram())
5102 DBuilder.finalizeSubprogram(Fn->getSubprogram());
5103 }
5104
5105 CGDebugInfo::BlockByRefType
5106 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
5107 uint64_t *XOffset) {
5108 SmallVector<llvm::Metadata *, 5> EltTys;
5109 QualType FType;
5110 uint64_t FieldSize, FieldOffset;
5111 uint32_t FieldAlign;
5112
5113 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5114 QualType Type = VD->getType();
5115
5116 FieldOffset = 0;
5117 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5118 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
5119 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
5120 FType = CGM.getContext().IntTy;
5121 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
5122 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
5123
5124 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
5125 if (HasCopyAndDispose) {
5126 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5127 EltTys.push_back(
5128 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
5129 EltTys.push_back(
5130 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
5131 }
5132 bool HasByrefExtendedLayout;
5133 Qualifiers::ObjCLifetime Lifetime;
5134 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
5135 HasByrefExtendedLayout) &&
5136 HasByrefExtendedLayout) {
5137 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5138 EltTys.push_back(
5139 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
5140 }
5141
5142 CharUnits Align = CGM.getContext().getDeclAlign(VD);
5143 if (Align > CGM.getContext().toCharUnitsFromBits(
5144 CGM.getTarget().getPointerAlign(LangAS::Default))) {
5145 CharUnits FieldOffsetInBytes =
5146 CGM.getContext().toCharUnitsFromBits(FieldOffset);
5147 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
5148 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
5149
5150 if (NumPaddingBytes.isPositive()) {
5151 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
5152 FType = CGM.getContext().getConstantArrayType(
5153 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
5154 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
5155 }
5156 }
5157
5158 FType = Type;
5159 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
5160 FieldSize = CGM.getContext().getTypeSize(FType);
5161 FieldAlign = CGM.getContext().toBits(Align);
5162
5163 *XOffset = FieldOffset;
5164 llvm::DIType *FieldTy = DBuilder.createMemberType(
5165 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
5166 llvm::DINode::FlagZero, WrappedTy);
5167 EltTys.push_back(FieldTy);
5168 FieldOffset += FieldSize;
5169
5170 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5171 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
5172 llvm::DINode::FlagZero, nullptr, Elements),
5173 WrappedTy};
5174 }
5175
5176 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
5177 llvm::Value *Storage,
5178 std::optional<unsigned> ArgNo,
5179 CGBuilderTy &Builder,
5180 const bool UsePointerValue) {
5181 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5182 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5183 if (VD->hasAttr<NoDebugAttr>())
5184 return nullptr;
5185
5186 const bool VarIsArtificial = IsArtificial(VD);
5187
5188 llvm::DIFile *Unit = nullptr;
5189 if (!VarIsArtificial)
5190 Unit = getOrCreateFile(VD->getLocation());
5191 llvm::DIType *Ty;
5192 uint64_t XOffset = 0;
5193 if (VD->hasAttr<BlocksAttr>())
5194 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5195 else
5196 Ty = getOrCreateType(VD->getType(), Unit);
5197
5198 // If there is no debug info for this type then do not emit debug info
5199 // for this variable.
5200 if (!Ty)
5201 return nullptr;
5202
5203 // Get location information.
5204 unsigned Line = 0;
5205 unsigned Column = 0;
5206 if (!VarIsArtificial) {
5207 Line = getLineNumber(VD->getLocation());
5208 Column = getColumnNumber(VD->getLocation());
5209 }
5210 SmallVector<uint64_t, 13> Expr;
5211 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5212
5213 // While synthesized Objective-C property setters are "artificial" (i.e., they
5214 // are not spelled out in source), we want to pretend they are just like a
5215 // regular non-compiler generated method. Hence, don't mark explicitly passed
5216 // parameters of such methods as artificial.
5217 if (VarIsArtificial && !IsObjCSynthesizedPropertyExplicitParameter(VD))
5218 Flags |= llvm::DINode::FlagArtificial;
5219
5220 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5221
5222 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
5223 AppendAddressSpaceXDeref(AddressSpace, Expr);
5224
5225 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
5226 // object pointer flag.
5227 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
5228 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
5229 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5230 Flags |= llvm::DINode::FlagObjectPointer;
5231 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5232 if (PVD->isExplicitObjectParameter())
5233 Flags |= llvm::DINode::FlagObjectPointer;
5234 }
5235
5236 // Note: Older versions of clang used to emit byval references with an extra
5237 // DW_OP_deref, because they referenced the IR arg directly instead of
5238 // referencing an alloca. Newer versions of LLVM don't treat allocas
5239 // differently from other function arguments when used in a dbg.declare.
5240 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5241 StringRef Name = VD->getName();
5242 if (!Name.empty()) {
5243 // __block vars are stored on the heap if they are captured by a block that
5244 // can escape the local scope.
5245 if (VD->isEscapingByref()) {
5246 // Here, we need an offset *into* the alloca.
5247 CharUnits offset = CharUnits::fromQuantity(32);
5248 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5249 // offset of __forwarding field
5250 offset = CGM.getContext().toCharUnitsFromBits(
5251 CGM.getTarget().getPointerWidth(LangAS::Default));
5252 Expr.push_back(offset.getQuantity());
5253 Expr.push_back(llvm::dwarf::DW_OP_deref);
5254 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5255 // offset of x field
5256 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5257 Expr.push_back(offset.getQuantity());
5258 }
5259 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
5260 // If VD is an anonymous union then Storage represents value for
5261 // all union fields.
5262 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
5263 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
5264 // GDB has trouble finding local variables in anonymous unions, so we emit
5265 // artificial local variables for each of the members.
5266 //
5267 // FIXME: Remove this code as soon as GDB supports this.
5268 // The debug info verifier in LLVM operates based on the assumption that a
5269 // variable has the same size as its storage and we had to disable the
5270 // check for artificial variables.
5271 for (const auto *Field : RD->fields()) {
5272 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5273 StringRef FieldName = Field->getName();
5274
5275 // Ignore unnamed fields. Do not ignore unnamed records.
5276 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
5277 continue;
5278
5279 // Use VarDecl's Tag, Scope and Line number.
5280 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
5281 auto *D = DBuilder.createAutoVariable(
5282 Scope, FieldName, Unit, Line, FieldTy,
5283 CGM.getCodeGenOpts().OptimizationLevel != 0,
5284 Flags | llvm::DINode::FlagArtificial, FieldAlign);
5285
5286 // Insert an llvm.dbg.declare into the current block.
5287 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5288 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5289 Column, Scope,
5290 CurInlinedAt),
5291 Builder.GetInsertBlock());
5292 }
5293 }
5294 }
5295
5296 // Clang stores the sret pointer provided by the caller in a static alloca.
5297 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5298 // the address of the variable.
5299 if (UsePointerValue) {
5300 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5301 "Debug info already contains DW_OP_deref.");
5302 Expr.push_back(llvm::dwarf::DW_OP_deref);
5303 }
5304
5305 // Create the descriptor for the variable.
5306 llvm::DILocalVariable *D = nullptr;
5307 if (ArgNo) {
5308 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
5309 D = DBuilder.createParameterVariable(
5310 Scope, Name, *ArgNo, Unit, Line, Ty,
5311 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Annotations);
5312 } else {
5313 // For normal local variable, we will try to find out whether 'VD' is the
5314 // copy parameter of coroutine.
5315 // If yes, we are going to use DIVariable of the origin parameter instead
5316 // of creating the new one.
5317 // If no, it might be a normal alloc, we just create a new one for it.
5318
5319 // Check whether the VD is move parameters.
5320 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
5321 // The scope of parameter and move-parameter should be distinct
5322 // DISubprogram.
5323 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
5324 return nullptr;
5325
5326 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
5327 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
5328 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
5329 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
5330 Decl *Decl = DeclGroup.getSingleDecl();
5331 if (VD == dyn_cast_or_null<VarDecl>(Decl))
5332 return true;
5333 }
5334 return false;
5335 });
5336
5337 if (Iter != CoroutineParameterMappings.end()) {
5338 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
5339 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
5340 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
5341 });
5342 if (Iter2 != ParamDbgMappings.end())
5343 return const_cast<llvm::DILocalVariable *>(Iter2->second);
5344 }
5345 return nullptr;
5346 };
5347
5348 // If we couldn't find a move param DIVariable, create a new one.
5349 D = RemapCoroArgToLocalVar();
5350 // Or we will create a new DIVariable for this Decl if D dose not exists.
5351 if (!D)
5352 D = DBuilder.createAutoVariable(
5353 Scope, Name, Unit, Line, Ty,
5354 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Align);
5355 }
5356 // Insert an llvm.dbg.declare into the current block.
5357 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5358 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5359 Column, Scope, CurInlinedAt),
5360 Builder.GetInsertBlock());
5361
5362 return D;
5363 }
5364
5365 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
5366 llvm::Value *Storage,
5367 std::optional<unsigned> ArgNo,
5368 CGBuilderTy &Builder,
5369 const bool UsePointerValue) {
5370 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5371 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5372 if (BD->hasAttr<NoDebugAttr>())
5373 return nullptr;
5374
5375 // Skip the tuple like case, we don't handle that here
5376 if (isa<DeclRefExpr>(BD->getBinding()))
5377 return nullptr;
5378
5379 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
5380 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
5381
5382 // If there is no debug info for this type then do not emit debug info
5383 // for this variable.
5384 if (!Ty)
5385 return nullptr;
5386
5387 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
5388 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
5389
5390 SmallVector<uint64_t, 3> Expr;
5391 AppendAddressSpaceXDeref(AddressSpace, Expr);
5392
5393 // Clang stores the sret pointer provided by the caller in a static alloca.
5394 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5395 // the address of the variable.
5396 if (UsePointerValue) {
5397 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5398 "Debug info already contains DW_OP_deref.");
5399 Expr.push_back(llvm::dwarf::DW_OP_deref);
5400 }
5401
5402 unsigned Line = getLineNumber(BD->getLocation());
5403 unsigned Column = getColumnNumber(BD->getLocation());
5404 StringRef Name = BD->getName();
5405 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5406 // Create the descriptor for the variable.
5407 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5408 Scope, Name, Unit, Line, Ty, CGM.getCodeGenOpts().OptimizationLevel != 0,
5409 llvm::DINode::FlagZero, Align);
5410
5411 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5412 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5413 const unsigned fieldIndex = FD->getFieldIndex();
5414 const clang::CXXRecordDecl *parent =
5415 (const CXXRecordDecl *)FD->getParent();
5416 const ASTRecordLayout &layout =
5417 CGM.getContext().getASTRecordLayout(parent);
5418 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5419 if (FD->isBitField()) {
5420 const CGRecordLayout &RL =
5421 CGM.getTypes().getCGRecordLayout(FD->getParent());
5422 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5423 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5424 // storage.
5425 if (!Info.StorageOffset.isZero()) {
5426 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5427 Expr.push_back(Info.StorageOffset.getQuantity());
5428 }
5429 // Use LLVM_extract_bits to extract the appropriate bits from this
5430 // bitfield.
5431 Expr.push_back(Info.IsSigned
5432 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5433 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5434 Expr.push_back(Info.Offset);
5435 // If we have an oversized bitfield then the value won't be more than
5436 // the size of the type.
5437 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5438 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5439 } else if (fieldOffset != 0) {
5440 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5441 "Unexpected non-bitfield with non-byte-aligned offset");
5442 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5443 Expr.push_back(
5444 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5445 }
5446 }
5447 } else if (const ArraySubscriptExpr *ASE =
5448 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5449 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5450 const uint64_t value = IL->getValue().getZExtValue();
5451 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5452
5453 if (value != 0) {
5454 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5455 Expr.push_back(CGM.getContext()
5456 .toCharUnitsFromBits(value * typeSize)
5457 .getQuantity());
5458 }
5459 }
5460 }
5461
5462 // Insert an llvm.dbg.declare into the current block.
5463 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5464 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5465 Column, Scope, CurInlinedAt),
5466 Builder.GetInsertBlock());
5467
5468 return D;
5469 }
5470
5471 llvm::DILocalVariable *
5472 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5473 CGBuilderTy &Builder,
5474 const bool UsePointerValue) {
5475 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5476
5477 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5478 for (BindingDecl *B : DD->flat_bindings())
5479 EmitDeclare(B, Storage, std::nullopt, Builder,
5480 VD->getType()->isReferenceType());
5481 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5482 // correspond to a user variable.
5483 return nullptr;
5484 }
5485
5486 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5487 }
5488
5489 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
5490 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5491 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5492
5493 if (D->hasAttr<NoDebugAttr>())
5494 return;
5495
5496 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5497 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5498
5499 // Get location information.
5500 unsigned Line = getLineNumber(D->getLocation());
5501 unsigned Column = getColumnNumber(D->getLocation());
5502
5503 StringRef Name = D->getName();
5504
5505 // Create the descriptor for the label.
5506 auto *L = DBuilder.createLabel(Scope, Name, Unit, Line, Column,
5507 /*IsArtificial=*/false,
5508 /*CoroSuspendIdx=*/std::nullopt,
5509 CGM.getCodeGenOpts().OptimizationLevel != 0);
5510
5511 // Insert an llvm.dbg.label into the current block.
5512 DBuilder.insertLabel(L,
5513 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5514 Scope, CurInlinedAt),
5515 Builder.GetInsertBlock()->end());
5516 }
5517
5518 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5519 llvm::DIType *Ty) {
5520 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5521 if (CachedTy)
5522 Ty = CachedTy;
5523 return DBuilder.createObjectPointerType(Ty, /*Implicit=*/true);
5524 }
5525
5526 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
5527 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5528 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5529 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5530 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5531
5532 if (Builder.GetInsertBlock() == nullptr)
5533 return;
5534 if (VD->hasAttr<NoDebugAttr>())
5535 return;
5536
5537 bool isByRef = VD->hasAttr<BlocksAttr>();
5538
5539 uint64_t XOffset = 0;
5540 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5541 llvm::DIType *Ty;
5542 if (isByRef)
5543 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5544 else
5545 Ty = getOrCreateType(VD->getType(), Unit);
5546
5547 // Self is passed along as an implicit non-arg variable in a
5548 // block. Mark it as the object pointer.
5549 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5550 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5551 Ty = CreateSelfType(VD->getType(), Ty);
5552
5553 // Get location information.
5554 const unsigned Line =
5555 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5556 unsigned Column = getColumnNumber(VD->getLocation());
5557
5558 const llvm::DataLayout &target = CGM.getDataLayout();
5559
5560 CharUnits offset = CharUnits::fromQuantity(
5561 target.getStructLayout(blockInfo.StructureType)
5562 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5563
5564 SmallVector<uint64_t, 9> addr;
5565 addr.push_back(llvm::dwarf::DW_OP_deref);
5566 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5567 addr.push_back(offset.getQuantity());
5568 if (isByRef) {
5569 addr.push_back(llvm::dwarf::DW_OP_deref);
5570 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5571 // offset of __forwarding field
5572 offset =
5573 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5574 addr.push_back(offset.getQuantity());
5575 addr.push_back(llvm::dwarf::DW_OP_deref);
5576 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5577 // offset of x field
5578 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5579 addr.push_back(offset.getQuantity());
5580 }
5581
5582 // Create the descriptor for the variable.
5583 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5584 auto *D = DBuilder.createAutoVariable(
5585 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5586 Line, Ty, false, llvm::DINode::FlagZero, Align);
5587
5588 // Insert an llvm.dbg.declare into the current block.
5589 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5590 LexicalBlockStack.back(), CurInlinedAt);
5591 auto *Expr = DBuilder.createExpression(addr);
5592 if (InsertPoint)
5593 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint->getIterator());
5594 else
5595 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5596 }
5597
5598 llvm::DILocalVariable *
5599 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
5600 unsigned ArgNo, CGBuilderTy &Builder,
5601 bool UsePointerValue) {
5602 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5603 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5604 }
5605
5606 namespace {
5607 struct BlockLayoutChunk {
5608 uint64_t OffsetInBits;
5609 const BlockDecl::Capture *Capture;
5610 };
5611 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5612 return l.OffsetInBits < r.OffsetInBits;
5613 }
5614 } // namespace
5615
5616 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5617 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5618 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5619 SmallVectorImpl<llvm::Metadata *> &Fields) {
5620 // Blocks in OpenCL have unique constraints which make the standard fields
5621 // redundant while requiring size and align fields for enqueue_kernel. See
5622 // initializeForBlockHeader in CGBlocks.cpp
5623 if (CGM.getLangOpts().OpenCL) {
5624 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5625 BlockLayout.getElementOffsetInBits(0),
5626 Unit, Unit));
5627 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5628 BlockLayout.getElementOffsetInBits(1),
5629 Unit, Unit));
5630 } else {
5631 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5632 BlockLayout.getElementOffsetInBits(0),
5633 Unit, Unit));
5634 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5635 BlockLayout.getElementOffsetInBits(1),
5636 Unit, Unit));
5637 Fields.push_back(
5638 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5639 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5640 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5641 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5642 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5643 BlockLayout.getElementOffsetInBits(3),
5644 Unit, Unit));
5645 Fields.push_back(createFieldType(
5646 "__descriptor",
5647 Context.getPointerType(Block.NeedsCopyDispose
5648 ? Context.getBlockDescriptorExtendedType()
5649 : Context.getBlockDescriptorType()),
5650 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5651 }
5652 }
5653
5654 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
5655 StringRef Name,
5656 unsigned ArgNo,
5657 llvm::AllocaInst *Alloca,
5658 CGBuilderTy &Builder) {
5659 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5660 ASTContext &C = CGM.getContext();
5661 const BlockDecl *blockDecl = block.getBlockDecl();
5662
5663 // Collect some general information about the block's location.
5664 SourceLocation loc = blockDecl->getCaretLocation();
5665 llvm::DIFile *tunit = getOrCreateFile(loc);
5666 unsigned line = getLineNumber(loc);
5667 unsigned column = getColumnNumber(loc);
5668
5669 // Build the debug-info type for the block literal.
5670 getDeclContextDescriptor(blockDecl);
5671
5672 const llvm::StructLayout *blockLayout =
5673 CGM.getDataLayout().getStructLayout(block.StructureType);
5674
5675 SmallVector<llvm::Metadata *, 16> fields;
5676 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5677 fields);
5678
5679 // We want to sort the captures by offset, not because DWARF
5680 // requires this, but because we're paranoid about debuggers.
5681 SmallVector<BlockLayoutChunk, 8> chunks;
5682
5683 // 'this' capture.
5684 if (blockDecl->capturesCXXThis()) {
5685 BlockLayoutChunk chunk;
5686 chunk.OffsetInBits =
5687 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5688 chunk.Capture = nullptr;
5689 chunks.push_back(chunk);
5690 }
5691
5692 // Variable captures.
5693 for (const auto &capture : blockDecl->captures()) {
5694 const VarDecl *variable = capture.getVariable();
5695 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5696
5697 // Ignore constant captures.
5698 if (captureInfo.isConstant())
5699 continue;
5700
5701 BlockLayoutChunk chunk;
5702 chunk.OffsetInBits =
5703 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5704 chunk.Capture = &capture;
5705 chunks.push_back(chunk);
5706 }
5707
5708 // Sort by offset.
5709 llvm::array_pod_sort(chunks.begin(), chunks.end());
5710
5711 for (const BlockLayoutChunk &Chunk : chunks) {
5712 uint64_t offsetInBits = Chunk.OffsetInBits;
5713 const BlockDecl::Capture *capture = Chunk.Capture;
5714
5715 // If we have a null capture, this must be the C++ 'this' capture.
5716 if (!capture) {
5717 QualType type;
5718 if (auto *Method =
5719 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5720 type = Method->getThisType();
5721 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5722 type = CGM.getContext().getCanonicalTagType(RDecl);
5723 else
5724 llvm_unreachable("unexpected block declcontext");
5725
5726 fields.push_back(createFieldType("this", type, loc, AS_public,
5727 offsetInBits, tunit, tunit));
5728 continue;
5729 }
5730
5731 const VarDecl *variable = capture->getVariable();
5732 StringRef name = variable->getName();
5733
5734 llvm::DIType *fieldType;
5735 if (capture->isByRef()) {
5736 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5737 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5738 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5739 uint64_t xoffset;
5740 fieldType =
5741 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5742 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5743 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5744 PtrInfo.Width, Align, offsetInBits,
5745 llvm::DINode::FlagZero, fieldType);
5746 } else {
5747 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5748 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5749 offsetInBits, Align, tunit, tunit);
5750 }
5751 fields.push_back(fieldType);
5752 }
5753
5754 SmallString<36> typeName;
5755 llvm::raw_svector_ostream(typeName)
5756 << "__block_literal_" << CGM.getUniqueBlockCount();
5757
5758 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5759
5760 llvm::DIType *type =
5761 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5762 CGM.getContext().toBits(block.BlockSize), 0,
5763 llvm::DINode::FlagZero, nullptr, fieldsArray);
5764 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5765
5766 // Get overall information about the block.
5767 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5768 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5769
5770 // Create the descriptor for the parameter.
5771 auto *debugVar = DBuilder.createParameterVariable(
5772 scope, Name, ArgNo, tunit, line, type,
5773 CGM.getCodeGenOpts().OptimizationLevel != 0, flags);
5774
5775 // Insert an llvm.dbg.declare into the current block.
5776 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5777 llvm::DILocation::get(CGM.getLLVMContext(), line,
5778 column, scope, CurInlinedAt),
5779 Builder.GetInsertBlock());
5780 }
5781
5782 llvm::DIDerivedType *
5783 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5784 if (!D || !D->isStaticDataMember())
5785 return nullptr;
5786
5787 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5788 if (MI != StaticDataMemberCache.end()) {
5789 assert(MI->second && "Static data member declaration should still exist");
5790 return MI->second;
5791 }
5792
5793 // If the member wasn't found in the cache, lazily construct and add it to the
5794 // type (used when a limited form of the type is emitted).
5795 auto DC = D->getDeclContext();
5796 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5797 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5798 }
5799
5800 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5801 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5802 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5803 llvm::DIGlobalVariableExpression *GVE = nullptr;
5804
5805 for (const auto *Field : RD->fields()) {
5806 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5807 StringRef FieldName = Field->getName();
5808
5809 // Ignore unnamed fields, but recurse into anonymous records.
5810 if (FieldName.empty()) {
5811 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5812 GVE = CollectAnonRecordDecls(RT->getDecl()->getDefinitionOrSelf(), Unit,
5813 LineNo, LinkageName, Var, DContext);
5814 continue;
5815 }
5816 // Use VarDecl's Tag, Scope and Line number.
5817 GVE = DBuilder.createGlobalVariableExpression(
5818 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5819 Var->hasLocalLinkage());
5820 Var->addDebugInfo(GVE);
5821 }
5822 return GVE;
5823 }
5824
5825 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);
5826 static bool ReferencesAnonymousEntity(RecordType *RT) {
5827 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5828 // info we produce in the DWARF, so we can't get Clang's full name back.
5829 // But so long as it's not one of those, it doesn't matter if some sub-type
5830 // of the record (a template parameter) can't be reconstituted - because the
5831 // un-reconstitutable type itself will carry its own name.
5832 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5833 if (!RD)
5834 return false;
5835 if (!RD->getIdentifier())
5836 return true;
5837 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5838 if (!TSpecial)
5839 return false;
5840 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5841 }
5842 static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args) {
5843 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5844 switch (TA.getKind()) {
5845 case TemplateArgument::Pack:
5846 return ReferencesAnonymousEntity(TA.getPackAsArray());
5847 case TemplateArgument::Type: {
5848 struct ReferencesAnonymous
5849 : public RecursiveASTVisitor<ReferencesAnonymous> {
5850 bool RefAnon = false;
5851 bool VisitRecordType(RecordType *RT) {
5852 if (ReferencesAnonymousEntity(RT)) {
5853 RefAnon = true;
5854 return false;
5855 }
5856 return true;
5857 }
5858 };
5859 ReferencesAnonymous RT;
5860 RT.TraverseType(TA.getAsType());
5861 if (RT.RefAnon)
5862 return true;
5863 break;
5864 }
5865 default:
5866 break;
5867 }
5868 return false;
5869 });
5870 }
5871 namespace {
5872 struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5873 bool Reconstitutable = true;
5874 bool VisitVectorType(VectorType *FT) {
5875 Reconstitutable = false;
5876 return false;
5877 }
5878 bool VisitAtomicType(AtomicType *FT) {
5879 Reconstitutable = false;
5880 return false;
5881 }
5882 bool TraverseEnumType(EnumType *ET, bool = false) {
5883 // Unnamed enums can't be reconstituted due to a lack of column info we
5884 // produce in the DWARF, so we can't get Clang's full name back.
5885 if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5886 if (!ED->getIdentifier()) {
5887 Reconstitutable = false;
5888 return false;
5889 }
5890 if (!ED->getDefinitionOrSelf()->isExternallyVisible()) {
5891 Reconstitutable = false;
5892 return false;
5893 }
5894 }
5895 return true;
5896 }
5897 bool VisitFunctionProtoType(FunctionProtoType *FT) {
5898 // noexcept is not encoded in DWARF, so the reversi
5899 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5900 Reconstitutable &= !FT->getNoReturnAttr();
5901 return Reconstitutable;
5902 }
5903 bool VisitRecordType(RecordType *RT, bool = false) {
5904 if (ReferencesAnonymousEntity(RT)) {
5905 Reconstitutable = false;
5906 return false;
5907 }
5908 return true;
5909 }
5910 };
5911 } // anonymous namespace
5912
5913 // Test whether a type name could be rebuilt from emitted debug info.
5914 static bool IsReconstitutableType(QualType QT) {
5915 ReconstitutableType T;
5916 T.TraverseType(QT);
5917 return T.Reconstitutable;
5918 }
5919
5920 bool CGDebugInfo::HasReconstitutableArgs(
5921 ArrayRef<TemplateArgument> Args) const {
5922 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5923 switch (TA.getKind()) {
5924 case TemplateArgument::Template:
5925 // Easy to reconstitute - the value of the parameter in the debug
5926 // info is the string name of the template. The template name
5927 // itself won't benefit from any name rebuilding, but that's a
5928 // representational limitation - maybe DWARF could be
5929 // changed/improved to use some more structural representation.
5930 return true;
5931 case TemplateArgument::Declaration:
5932 // Reference and pointer non-type template parameters point to
5933 // variables, functions, etc and their value is, at best (for
5934 // variables) represented as an address - not a reference to the
5935 // DWARF describing the variable/function/etc. This makes it hard,
5936 // possibly impossible to rebuild the original name - looking up
5937 // the address in the executable file's symbol table would be
5938 // needed.
5939 return false;
5940 case TemplateArgument::NullPtr:
5941 // These could be rebuilt, but figured they're close enough to the
5942 // declaration case, and not worth rebuilding.
5943 return false;
5944 case TemplateArgument::Pack:
5945 // A pack is invalid if any of the elements of the pack are
5946 // invalid.
5947 return HasReconstitutableArgs(TA.getPackAsArray());
5948 case TemplateArgument::Integral:
5949 // Larger integers get encoded as DWARF blocks which are a bit
5950 // harder to parse back into a large integer, etc - so punting on
5951 // this for now. Re-parsing the integers back into APInt is
5952 // probably feasible some day.
5953 return TA.getAsIntegral().getBitWidth() <= 64 &&
5954 IsReconstitutableType(TA.getIntegralType());
5955 case TemplateArgument::StructuralValue:
5956 return false;
5957 case TemplateArgument::Type:
5958 return IsReconstitutableType(TA.getAsType());
5959 case TemplateArgument::Expression:
5960 return IsReconstitutableType(TA.getAsExpr()->getType());
5961 default:
5962 llvm_unreachable("Other, unresolved, template arguments should "
5963 "not be seen here");
5964 }
5965 });
5966 }
5967
5968 std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5969 std::string Name;
5970 llvm::raw_string_ostream OS(Name);
5971 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5972 if (!ND)
5973 return Name;
5974 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5975 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5976
5977 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
5978 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
5979
5980 std::optional<TemplateArgs> Args;
5981
5982 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5983 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5984 Args = GetTemplateArgs(RD);
5985 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5986 Args = GetTemplateArgs(FD);
5987 auto NameKind = ND->getDeclName().getNameKind();
5988 IsOperatorOverload |=
5989 NameKind == DeclarationName::CXXOperatorName ||
5990 NameKind == DeclarationName::CXXConversionFunctionName;
5991 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5992 Args = GetTemplateArgs(VD);
5993 }
5994
5995 // A conversion operator presents complications/ambiguity if there's a
5996 // conversion to class template that is itself a template, eg:
5997 // template<typename T>
5998 // operator ns::t1<T, int>();
5999 // This should be named, eg: "operator ns::t1<float, int><float>"
6000 // (ignoring clang bug that means this is currently "operator t1<float>")
6001 // but if the arguments were stripped, the consumer couldn't differentiate
6002 // whether the template argument list for the conversion type was the
6003 // function's argument list (& no reconstitution was needed) or not.
6004 // This could be handled if reconstitutable names had a separate attribute
6005 // annotating them as such - this would remove the ambiguity.
6006 //
6007 // Alternatively the template argument list could be parsed enough to check
6008 // whether there's one list or two, then compare that with the DWARF
6009 // description of the return type and the template argument lists to determine
6010 // how many lists there should be and if one is missing it could be assumed(?)
6011 // to be the function's template argument list & then be rebuilt.
6012 //
6013 // Other operator overloads that aren't conversion operators could be
6014 // reconstituted but would require a bit more nuance about detecting the
6015 // difference between these different operators during that rebuilding.
6016 bool Reconstitutable =
6017 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
6018
6019 PrintingPolicy PP = getPrintingPolicy();
6020
6021 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
6022 !Reconstitutable) {
6023 ND->getNameForDiagnostic(OS, PP, Qualified);
6024 } else {
6025 bool Mangled = TemplateNamesKind ==
6026 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
6027 // check if it's a template
6028 if (Mangled)
6029 OS << "_STN|";
6030
6031 OS << ND->getDeclName();
6032 std::string EncodedOriginalName;
6033 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
6034 EncodedOriginalNameOS << ND->getDeclName();
6035
6036 if (Mangled) {
6037 OS << "|";
6038 printTemplateArgumentList(OS, Args->Args, PP);
6039 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
6040 #ifndef NDEBUG
6041 std::string CanonicalOriginalName;
6042 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
6043 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
6044 assert(EncodedOriginalName == CanonicalOriginalName);
6045 #endif
6046 }
6047 }
6048 return Name;
6049 }
6050
6051 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
6052 const VarDecl *D) {
6053 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6054 if (D->hasAttr<NoDebugAttr>())
6055 return;
6056
6057 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
6058 return GetName(D, true);
6059 });
6060
6061 // If we already created a DIGlobalVariable for this declaration, just attach
6062 // it to the llvm::GlobalVariable.
6063 auto Cached = DeclCache.find(D->getCanonicalDecl());
6064 if (Cached != DeclCache.end())
6065 return Var->addDebugInfo(
6066 cast<llvm::DIGlobalVariableExpression>(Cached->second));
6067
6068 // Create global variable debug descriptor.
6069 llvm::DIFile *Unit = nullptr;
6070 llvm::DIScope *DContext = nullptr;
6071 unsigned LineNo;
6072 StringRef DeclName, LinkageName;
6073 QualType T;
6074 llvm::MDTuple *TemplateParameters = nullptr;
6075 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
6076 TemplateParameters, DContext);
6077
6078 // Attempt to store one global variable for the declaration - even if we
6079 // emit a lot of fields.
6080 llvm::DIGlobalVariableExpression *GVE = nullptr;
6081
6082 // If this is an anonymous union then we'll want to emit a global
6083 // variable for each member of the anonymous union so that it's possible
6084 // to find the name of any field in the union.
6085 if (T->isUnionType() && DeclName.empty()) {
6086 const auto *RD = T->castAsRecordDecl();
6087 assert(RD->isAnonymousStructOrUnion() &&
6088 "unnamed non-anonymous struct or union?");
6089 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
6090 } else {
6091 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6092
6093 SmallVector<uint64_t, 4> Expr;
6094 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
6095 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
6096 if (D->hasAttr<CUDASharedAttr>())
6097 AddressSpace =
6098 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
6099 else if (D->hasAttr<CUDAConstantAttr>())
6100 AddressSpace =
6101 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
6102 }
6103 AppendAddressSpaceXDeref(AddressSpace, Expr);
6104
6105 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
6106 GVE = DBuilder.createGlobalVariableExpression(
6107 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
6108 Var->hasLocalLinkage(), true,
6109 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
6110 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
6111 Align, Annotations);
6112 Var->addDebugInfo(GVE);
6113 }
6114 DeclCache[D->getCanonicalDecl()].reset(GVE);
6115 }
6116
6117 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
6118 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6119 if (VD->hasAttr<NoDebugAttr>())
6120 return;
6121 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
6122 return GetName(VD, true);
6123 });
6124
6125 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
6126 // Create the descriptor for the variable.
6127 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
6128 StringRef Name = VD->getName();
6129 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
6130
6131 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
6132 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
6133 if (CGM.getCodeGenOpts().EmitCodeView) {
6134 // If CodeView, emit enums as global variables, unless they are defined
6135 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
6136 // enums in classes, and because it is difficult to attach this scope
6137 // information to the global variable.
6138 if (isa<RecordDecl>(ED->getDeclContext()))
6139 return;
6140 } else {
6141 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
6142 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
6143 // first time `ZERO` is referenced in a function.
6144 CanQualType T = CGM.getContext().getCanonicalTagType(ED);
6145 [[maybe_unused]] llvm::DIType *EDTy = getOrCreateType(T, Unit);
6146 assert(EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
6147 return;
6148 }
6149 }
6150
6151 // Do not emit separate definitions for function local consts.
6152 if (isa<FunctionDecl>(VD->getDeclContext()))
6153 return;
6154
6155 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6156 auto *VarD = dyn_cast<VarDecl>(VD);
6157 if (VarD && VarD->isStaticDataMember()) {
6158 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
6159 getDeclContextDescriptor(VarD);
6160 // Ensure that the type is retained even though it's otherwise unreferenced.
6161 //
6162 // FIXME: This is probably unnecessary, since Ty should reference RD
6163 // through its scope.
6164 RetainedTypes.push_back(
6165 CGM.getContext().getCanonicalTagType(RD).getAsOpaquePtr());
6166
6167 return;
6168 }
6169 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
6170
6171 auto &GV = DeclCache[VD];
6172 if (GV)
6173 return;
6174
6175 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
6176 llvm::MDTuple *TemplateParameters = nullptr;
6177
6178 if (isa<VarTemplateSpecializationDecl>(VD))
6179 if (VarD) {
6180 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
6181 TemplateParameters = parameterNodes.get();
6182 }
6183
6184 GV.reset(DBuilder.createGlobalVariableExpression(
6185 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
6186 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
6187 TemplateParameters, Align));
6188 }
6189
6190 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
6191 const VarDecl *D) {
6192 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6193 if (D->hasAttr<NoDebugAttr>())
6194 return;
6195
6196 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6197 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
6198 StringRef Name = D->getName();
6199 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
6200
6201 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6202 llvm::DIGlobalVariableExpression *GVE =
6203 DBuilder.createGlobalVariableExpression(
6204 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
6205 Ty, false, false, nullptr, nullptr, nullptr, Align);
6206 Var->addDebugInfo(GVE);
6207 }
6208
6209 void CGDebugInfo::EmitPseudoVariable(CGBuilderTy &Builder,
6210 llvm::Instruction *Value, QualType Ty) {
6211 // Only when -g2 or above is specified, debug info for variables will be
6212 // generated.
6213 if (CGM.getCodeGenOpts().getDebugInfo() <=
6214 llvm::codegenoptions::DebugLineTablesOnly)
6215 return;
6216
6217 llvm::DILocation *DIL = Value->getDebugLoc().get();
6218 if (!DIL)
6219 return;
6220
6221 llvm::DIFile *Unit = DIL->getFile();
6222 llvm::DIType *Type = getOrCreateType(Ty, Unit);
6223
6224 // Check if Value is already a declared variable and has debug info, in this
6225 // case we have nothing to do. Clang emits a declared variable as alloca, and
6226 // it is loaded upon use, so we identify such pattern here.
6227 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
6228 llvm::Value *Var = Load->getPointerOperand();
6229 // There can be implicit type cast applied on a variable if it is an opaque
6230 // ptr, in this case its debug info may not match the actual type of object
6231 // being used as in the next instruction, so we will need to emit a pseudo
6232 // variable for type-casted value.
6233 auto DeclareTypeMatches = [&](llvm::DbgVariableRecord *DbgDeclare) {
6234 return DbgDeclare->getVariable()->getType() == Type;
6235 };
6236 if (any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
6237 return;
6238 }
6239
6240 llvm::DILocalVariable *D =
6241 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
6242 Type, false, llvm::DINode::FlagArtificial);
6243
6244 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
6245 DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,
6246 *InsertPoint);
6247 }
6248 }
6249
6250 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
6251 const GlobalDecl GD) {
6252
6253 assert(GV);
6254
6255 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6256 return;
6257
6258 const auto *D = cast<ValueDecl>(GD.getDecl());
6259 if (D->hasAttr<NoDebugAttr>())
6260 return;
6261
6262 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
6263 llvm::DINode *DI;
6264
6265 if (!AliaseeDecl)
6266 // FIXME: Aliasee not declared yet - possibly declared later
6267 // For example,
6268 //
6269 // 1 extern int newname __attribute__((alias("oldname")));
6270 // 2 int oldname = 1;
6271 //
6272 // No debug info would be generated for 'newname' in this case.
6273 //
6274 // Fix compiler to generate "newname" as imported_declaration
6275 // pointing to the DIE of "oldname".
6276 return;
6277 if (!(DI = getDeclarationOrDefinition(
6278 AliaseeDecl.getCanonicalDecl().getDecl())))
6279 return;
6280
6281 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6282 auto Loc = D->getLocation();
6283
6284 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
6285 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
6286
6287 // Record this DIE in the cache for nested declaration reference.
6288 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
6289 }
6290
6291 void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
6292 const StringLiteral *S) {
6293 SourceLocation Loc = S->getStrTokenLoc(0);
6294 SourceManager &SM = CGM.getContext().getSourceManager();
6295 PresumedLoc PLoc = SM.getPresumedLoc(getMacroDebugLoc(CGM, Loc));
6296 if (!PLoc.isValid())
6297 return;
6298
6299 llvm::DIFile *File = getOrCreateFile(Loc);
6300 llvm::DIGlobalVariableExpression *Debug =
6301 DBuilder.createGlobalVariableExpression(
6302 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
6303 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
6304 GV->addDebugInfo(Debug);
6305 }
6306
6307 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
6308 if (!LexicalBlockStack.empty())
6309 return LexicalBlockStack.back();
6310 llvm::DIScope *Mod = getParentModuleOrNull(D);
6311 return getContextDescriptor(D, Mod ? Mod : TheCU);
6312 }
6313
6314 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
6315 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6316 return;
6317 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
6318 if (!NSDecl->isAnonymousNamespace() ||
6319 CGM.getCodeGenOpts().DebugExplicitImport) {
6320 auto Loc = UD.getLocation();
6321 if (!Loc.isValid())
6322 Loc = CurLoc;
6323 DBuilder.createImportedModule(
6324 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
6325 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
6326 }
6327 }
6328
6329 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl &USD) {
6330 if (llvm::DINode *Target =
6331 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
6332 auto Loc = USD.getLocation();
6333 DBuilder.createImportedDeclaration(
6334 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
6335 getOrCreateFile(Loc), getLineNumber(Loc));
6336 }
6337 }
6338
6339 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
6340 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6341 return;
6342 assert(UD.shadow_size() &&
6343 "We shouldn't be codegening an invalid UsingDecl containing no decls");
6344
6345 for (const auto *USD : UD.shadows()) {
6346 // FIXME: Skip functions with undeduced auto return type for now since we
6347 // don't currently have the plumbing for separate declarations & definitions
6348 // of free functions and mismatched types (auto in the declaration, concrete
6349 // return type in the definition)
6350 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
6351 if (const auto *AT = FD->getType()
6352 ->castAs<FunctionProtoType>()
6353 ->getContainedAutoType())
6354 if (AT->getDeducedType().isNull())
6355 continue;
6356
6357 EmitUsingShadowDecl(*USD);
6358 // Emitting one decl is sufficient - debuggers can detect that this is an
6359 // overloaded name & provide lookup for all the overloads.
6360 break;
6361 }
6362 }
6363
6364 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl &UD) {
6365 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6366 return;
6367 assert(UD.shadow_size() &&
6368 "We shouldn't be codegening an invalid UsingEnumDecl"
6369 " containing no decls");
6370
6371 for (const auto *USD : UD.shadows())
6372 EmitUsingShadowDecl(*USD);
6373 }
6374
6375 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
6376 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
6377 return;
6378 if (Module *M = ID.getImportedModule()) {
6379 auto Info = ASTSourceDescriptor(*M);
6380 auto Loc = ID.getLocation();
6381 DBuilder.createImportedDeclaration(
6382 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
6383 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
6384 getLineNumber(Loc));
6385 }
6386 }
6387
6388 llvm::DIImportedEntity *
6389 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
6390 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6391 return nullptr;
6392 auto &VH = NamespaceAliasCache[&NA];
6393 if (VH)
6394 return cast<llvm::DIImportedEntity>(VH);
6395 llvm::DIImportedEntity *R;
6396 auto Loc = NA.getLocation();
6397 if (const auto *Underlying =
6398 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6399 // This could cache & dedup here rather than relying on metadata deduping.
6400 R = DBuilder.createImportedDeclaration(
6401 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6402 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6403 getLineNumber(Loc), NA.getName());
6404 else
6405 R = DBuilder.createImportedDeclaration(
6406 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6407 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6408 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6409 VH.reset(R);
6410 return R;
6411 }
6412
6413 llvm::DINamespace *
6414 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6415 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6416 // if necessary, and this way multiple declarations of the same namespace in
6417 // different parent modules stay distinct.
6418 auto I = NamespaceCache.find(NSDecl);
6419 if (I != NamespaceCache.end())
6420 return cast<llvm::DINamespace>(I->second);
6421
6422 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6423 // Don't trust the context if it is a DIModule (see comment above).
6424 llvm::DINamespace *NS =
6425 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6426 NamespaceCache[NSDecl].reset(NS);
6427 return NS;
6428 }
6429
6430 void CGDebugInfo::setDwoId(uint64_t Signature) {
6431 assert(TheCU && "no main compile unit");
6432 TheCU->setDWOId(Signature);
6433 }
6434
6435 void CGDebugInfo::finalize() {
6436 // Creating types might create further types - invalidating the current
6437 // element and the size(), so don't cache/reference them.
6438 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6439 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6440 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6441 ? CreateTypeDefinition(E.Type, E.Unit)
6442 : E.Decl;
6443 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6444 }
6445
6446 // Add methods to interface.
6447 for (const auto &P : ObjCMethodCache) {
6448 if (P.second.empty())
6449 continue;
6450
6451 QualType QTy(P.first->getTypeForDecl(), 0);
6452 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6453 assert(It != TypeCache.end());
6454
6455 llvm::DICompositeType *InterfaceDecl =
6456 cast<llvm::DICompositeType>(It->second);
6457
6458 auto CurElts = InterfaceDecl->getElements();
6459 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6460
6461 // For DWARF v4 or earlier, only add objc_direct methods.
6462 for (auto &SubprogramDirect : P.second)
6463 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6464 EltTys.push_back(SubprogramDirect.getPointer());
6465
6466 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6467 DBuilder.replaceArrays(InterfaceDecl, Elements);
6468 }
6469
6470 for (const auto &P : ReplaceMap) {
6471 assert(P.second);
6472 auto *Ty = cast<llvm::DIType>(P.second);
6473 assert(Ty->isForwardDecl());
6474
6475 auto It = TypeCache.find(P.first);
6476 assert(It != TypeCache.end());
6477 assert(It->second);
6478
6479 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6480 cast<llvm::DIType>(It->second));
6481 }
6482
6483 for (const auto &P : FwdDeclReplaceMap) {
6484 assert(P.second);
6485 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6486 llvm::Metadata *Repl;
6487
6488 auto It = DeclCache.find(P.first);
6489 // If there has been no definition for the declaration, call RAUW
6490 // with ourselves, that will destroy the temporary MDNode and
6491 // replace it with a standard one, avoiding leaking memory.
6492 if (It == DeclCache.end())
6493 Repl = P.second;
6494 else
6495 Repl = It->second;
6496
6497 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6498 Repl = GVE->getVariable();
6499 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6500 }
6501
6502 // We keep our own list of retained types, because we need to look
6503 // up the final type in the type cache.
6504 for (auto &RT : RetainedTypes)
6505 if (auto MD = TypeCache[RT])
6506 DBuilder.retainType(cast<llvm::DIType>(MD));
6507
6508 DBuilder.finalize();
6509 }
6510
6511 // Don't ignore in case of explicit cast where it is referenced indirectly.
6512 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
6513 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
6514 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6515 DBuilder.retainType(DieTy);
6516 }
6517
6518 void CGDebugInfo::EmitAndRetainType(QualType Ty) {
6519 if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
6520 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6521 DBuilder.retainType(DieTy);
6522 }
6523
6524 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
6525 if (LexicalBlockStack.empty())
6526 return llvm::DebugLoc();
6527
6528 llvm::MDNode *Scope = LexicalBlockStack.back();
6529 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6530 getColumnNumber(Loc), Scope);
6531 }
6532
6533 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6534 // Call site-related attributes are only useful in optimized programs, and
6535 // when there's a possibility of debugging backtraces.
6536 if (CGM.getCodeGenOpts().OptimizationLevel == 0 ||
6537 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6538 DebugKind == llvm::codegenoptions::LocTrackingOnly ||
6539 !CGM.getCodeGenOpts().DebugCallSiteInfo)
6540 return llvm::DINode::FlagZero;
6541
6542 // Call site-related attributes are available in DWARF v5. Some debuggers,
6543 // while not fully DWARF v5-compliant, may accept these attributes as if they
6544 // were part of DWARF v4.
6545 bool SupportsDWARFv4Ext =
6546 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6547 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6548 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6549
6550 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6551 return llvm::DINode::FlagZero;
6552
6553 return llvm::DINode::FlagAllCallsDescribed;
6554 }
6555
6556 llvm::DIExpression *
6557 CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6558 const APValue &Val) {
6559 // FIXME: Add a representation for integer constants wider than 64 bits.
6560 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6561 return nullptr;
6562
6563 if (Val.isFloat())
6564 return DBuilder.createConstantValueExpression(
6565 Val.getFloat().bitcastToAPInt().getZExtValue());
6566
6567 if (!Val.isInt())
6568 return nullptr;
6569
6570 llvm::APSInt const &ValInt = Val.getInt();
6571 std::optional<uint64_t> ValIntOpt;
6572 if (ValInt.isUnsigned())
6573 ValIntOpt = ValInt.tryZExtValue();
6574 else if (auto tmp = ValInt.trySExtValue())
6575 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6576 // use std::optional::transform
6577 ValIntOpt = static_cast<uint64_t>(*tmp);
6578
6579 if (ValIntOpt)
6580 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6581
6582 return nullptr;
6583 }
6584
6585 CodeGenFunction::LexicalScope::LexicalScope(CodeGenFunction &CGF,
6586 SourceRange Range)
6587 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
6588 CGF.CurLexicalScope = this;
6589 if (CGDebugInfo *DI = CGF.getDebugInfo())
6590 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
6591 }
6592
6593 CodeGenFunction::LexicalScope::~LexicalScope() {
6594 if (CGDebugInfo *DI = CGF.getDebugInfo())
6595 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
6596
6597 // If we should perform a cleanup, force them now. Note that
6598 // this ends the cleanup scope before rescoping any labels.
6599 if (PerformCleanup) {
6600 ApplyDebugLocation DL(CGF, Range.getEnd());
6601 ForceCleanup();
6602 }
6603 }
6604
6605 static std::string SanitizerHandlerToCheckLabel(SanitizerHandler Handler) {
6606 std::string Label;
6607 switch (Handler) {
6608 #define SANITIZER_CHECK(Enum, Name, Version, Msg) \
6609 case Enum: \
6610 Label = "__ubsan_check_" #Name; \
6611 break;
6612
6613 LIST_SANITIZER_CHECKS
6614 #undef SANITIZER_CHECK
6615 };
6616
6617 // Label doesn't require sanitization
6618 return Label;
6619 }
6620
6621 static std::string
6622 SanitizerOrdinalToCheckLabel(SanitizerKind::SanitizerOrdinal Ordinal) {
6623 std::string Label;
6624 switch (Ordinal) {
6625 #define SANITIZER(NAME, ID) \
6626 case SanitizerKind::SO_##ID: \
6627 Label = "__ubsan_check_" NAME; \
6628 break;
6629 #include "clang/Basic/Sanitizers.def"
6630 default:
6631 llvm_unreachable("unexpected sanitizer kind");
6632 }
6633
6634 // Sanitize label (convert hyphens to underscores; also futureproof against
6635 // non-alpha)
6636 for (unsigned int i = 0; i < Label.length(); i++)
6637 if (!std::isalpha(Label[i]))
6638 Label[i] = '_';
6639
6640 return Label;
6641 }
6642
6643 llvm::DILocation *CodeGenFunction::SanitizerAnnotateDebugInfo(
6644 ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals,
6645 SanitizerHandler Handler) {
6646 llvm::DILocation *CheckDebugLoc = Builder.getCurrentDebugLocation();
6647 auto *DI = getDebugInfo();
6648 if (!DI || !CheckDebugLoc)
6649 return CheckDebugLoc;
6650 const auto &AnnotateDebugInfo =
6651 CGM.getCodeGenOpts().SanitizeAnnotateDebugInfo;
6652 if (AnnotateDebugInfo.empty())
6653 return CheckDebugLoc;
6654
6655 std::string Label;
6656 if (Ordinals.size() == 1)
6657 Label = SanitizerOrdinalToCheckLabel(Ordinals[0]);
6658 else
6659 Label = SanitizerHandlerToCheckLabel(Handler);
6660
6661 if (any_of(Ordinals, [&](auto Ord) { return AnnotateDebugInfo.has(Ord); }))
6662 return DI->CreateSyntheticInlineAt(CheckDebugLoc, Label);
6663
6664 return CheckDebugLoc;
6665 }
6666
6667 SanitizerDebugLocation::SanitizerDebugLocation(
6668 CodeGenFunction *CGF, ArrayRef<SanitizerKind::SanitizerOrdinal> Ordinals,
6669 SanitizerHandler Handler)
6670 : CGF(CGF),
6671 Apply(*CGF, CGF->SanitizerAnnotateDebugInfo(Ordinals, Handler)) {
6672 assert(!CGF->IsSanitizerScope);
6673 CGF->IsSanitizerScope = true;
6674 }
6675
6676 SanitizerDebugLocation::~SanitizerDebugLocation() {
6677 assert(CGF->IsSanitizerScope);
6678 CGF->IsSanitizerScope = false;
6679 }