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