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