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