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