1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This coordinates the debug information generation while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CGDebugInfo.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/DeclFriend.h"
25 #include "clang/AST/DeclObjC.h"
26 #include "clang/AST/DeclTemplate.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/RecordLayout.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/VTableBuilder.h"
31 #include "clang/Basic/CodeGenOptions.h"
32 #include "clang/Basic/FileManager.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/Version.h"
35 #include "clang/Frontend/FrontendOptions.h"
36 #include "clang/Lex/HeaderSearchOptions.h"
37 #include "clang/Lex/ModuleMap.h"
38 #include "clang/Lex/PreprocessorOptions.h"
39 #include "llvm/ADT/DenseSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/IR/Constants.h"
43 #include "llvm/IR/DataLayout.h"
44 #include "llvm/IR/DerivedTypes.h"
45 #include "llvm/IR/Instructions.h"
46 #include "llvm/IR/Intrinsics.h"
47 #include "llvm/IR/Metadata.h"
48 #include "llvm/IR/Module.h"
49 #include "llvm/Support/FileSystem.h"
50 #include "llvm/Support/MD5.h"
51 #include "llvm/Support/Path.h"
52 #include "llvm/Support/SHA1.h"
53 #include "llvm/Support/SHA256.h"
54 #include "llvm/Support/TimeProfiler.h"
56 using namespace clang
;
57 using namespace clang::CodeGen
;
59 static uint32_t getTypeAlignIfRequired(const Type
*Ty
, const ASTContext
&Ctx
) {
60 auto TI
= Ctx
.getTypeInfo(Ty
);
61 return TI
.isAlignRequired() ? TI
.Align
: 0;
64 static uint32_t getTypeAlignIfRequired(QualType Ty
, const ASTContext
&Ctx
) {
65 return getTypeAlignIfRequired(Ty
.getTypePtr(), Ctx
);
68 static uint32_t getDeclAlignIfRequired(const Decl
*D
, const ASTContext
&Ctx
) {
69 return D
->hasAttr
<AlignedAttr
>() ? D
->getMaxAlignment() : 0;
72 CGDebugInfo::CGDebugInfo(CodeGenModule
&CGM
)
73 : CGM(CGM
), DebugKind(CGM
.getCodeGenOpts().getDebugInfo()),
74 DebugTypeExtRefs(CGM
.getCodeGenOpts().DebugTypeExtRefs
),
75 DBuilder(CGM
.getModule()) {
79 CGDebugInfo::~CGDebugInfo() {
80 assert(LexicalBlockStack
.empty() &&
81 "Region stack mismatch, stack not empty!");
84 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
,
85 SourceLocation TemporaryLocation
)
87 init(TemporaryLocation
);
90 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
,
92 SourceLocation TemporaryLocation
)
94 init(TemporaryLocation
, DefaultToEmpty
);
97 void ApplyDebugLocation::init(SourceLocation TemporaryLocation
,
98 bool DefaultToEmpty
) {
99 auto *DI
= CGF
->getDebugInfo();
105 OriginalLocation
= CGF
->Builder
.getCurrentDebugLocation();
107 if (OriginalLocation
&& !DI
->CGM
.getExpressionLocationsEnabled())
110 if (TemporaryLocation
.isValid()) {
111 DI
->EmitLocation(CGF
->Builder
, TemporaryLocation
);
115 if (DefaultToEmpty
) {
116 CGF
->Builder
.SetCurrentDebugLocation(llvm::DebugLoc());
120 // Construct a location that has a valid scope, but no line info.
121 assert(!DI
->LexicalBlockStack
.empty());
122 CGF
->Builder
.SetCurrentDebugLocation(
123 llvm::DILocation::get(DI
->LexicalBlockStack
.back()->getContext(), 0, 0,
124 DI
->LexicalBlockStack
.back(), DI
->getInlinedAt()));
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
, const Expr
*E
)
129 init(E
->getExprLoc());
132 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction
&CGF
, llvm::DebugLoc Loc
)
134 if (!CGF
.getDebugInfo()) {
138 OriginalLocation
= CGF
.Builder
.getCurrentDebugLocation();
140 CGF
.Builder
.SetCurrentDebugLocation(std::move(Loc
));
143 ApplyDebugLocation::~ApplyDebugLocation() {
144 // Query CGF so the location isn't overwritten when location updates are
145 // temporarily disabled (for C++ default function arguments)
147 CGF
->Builder
.SetCurrentDebugLocation(std::move(OriginalLocation
));
150 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction
&CGF
,
151 GlobalDecl InlinedFn
)
153 if (!CGF
.getDebugInfo()) {
157 auto &DI
= *CGF
.getDebugInfo();
158 SavedLocation
= DI
.getLocation();
159 assert((DI
.getInlinedAt() ==
160 CGF
.Builder
.getCurrentDebugLocation()->getInlinedAt()) &&
161 "CGDebugInfo and IRBuilder are out of sync");
163 DI
.EmitInlineFunctionStart(CGF
.Builder
, InlinedFn
);
166 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
169 auto &DI
= *CGF
->getDebugInfo();
170 DI
.EmitInlineFunctionEnd(CGF
->Builder
);
171 DI
.EmitLocation(CGF
->Builder
, SavedLocation
);
174 void CGDebugInfo::setLocation(SourceLocation Loc
) {
175 // If the new location isn't valid return.
179 CurLoc
= CGM
.getContext().getSourceManager().getExpansionLoc(Loc
);
181 // If we've changed files in the middle of a lexical scope go ahead
182 // and create a new lexical scope with file node if it's different
183 // from the one in the scope.
184 if (LexicalBlockStack
.empty())
187 SourceManager
&SM
= CGM
.getContext().getSourceManager();
188 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
189 PresumedLoc PCLoc
= SM
.getPresumedLoc(CurLoc
);
190 if (PCLoc
.isInvalid() || Scope
->getFile() == getOrCreateFile(CurLoc
))
193 if (auto *LBF
= dyn_cast
<llvm::DILexicalBlockFile
>(Scope
)) {
194 LexicalBlockStack
.pop_back();
195 LexicalBlockStack
.emplace_back(DBuilder
.createLexicalBlockFile(
196 LBF
->getScope(), getOrCreateFile(CurLoc
)));
197 } else if (isa
<llvm::DILexicalBlock
>(Scope
) ||
198 isa
<llvm::DISubprogram
>(Scope
)) {
199 LexicalBlockStack
.pop_back();
200 LexicalBlockStack
.emplace_back(
201 DBuilder
.createLexicalBlockFile(Scope
, getOrCreateFile(CurLoc
)));
205 llvm::DIScope
*CGDebugInfo::getDeclContextDescriptor(const Decl
*D
) {
206 llvm::DIScope
*Mod
= getParentModuleOrNull(D
);
207 return getContextDescriptor(cast
<Decl
>(D
->getDeclContext()),
211 llvm::DIScope
*CGDebugInfo::getContextDescriptor(const Decl
*Context
,
212 llvm::DIScope
*Default
) {
216 auto I
= RegionMap
.find(Context
);
217 if (I
!= RegionMap
.end()) {
218 llvm::Metadata
*V
= I
->second
;
219 return dyn_cast_or_null
<llvm::DIScope
>(V
);
223 if (const auto *NSDecl
= dyn_cast
<NamespaceDecl
>(Context
))
224 return getOrCreateNamespace(NSDecl
);
226 if (const auto *RDecl
= dyn_cast
<RecordDecl
>(Context
))
227 if (!RDecl
->isDependentType())
228 return getOrCreateType(CGM
.getContext().getTypeDeclType(RDecl
),
233 PrintingPolicy
CGDebugInfo::getPrintingPolicy() const {
234 PrintingPolicy PP
= CGM
.getContext().getPrintingPolicy();
236 // If we're emitting codeview, it's important to try to match MSVC's naming so
237 // that visualizers written for MSVC will trigger for our class names. In
238 // particular, we can't have spaces between arguments of standard templates
239 // like basic_string and vector, but we must have spaces between consecutive
240 // angle brackets that close nested template argument lists.
241 if (CGM
.getCodeGenOpts().EmitCodeView
) {
242 PP
.MSVCFormatting
= true;
243 PP
.SplitTemplateClosers
= true;
245 // For DWARF, printing rules are underspecified.
246 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
247 PP
.SplitTemplateClosers
= true;
250 PP
.SuppressInlineNamespace
= false;
251 PP
.PrintCanonicalTypes
= true;
252 PP
.UsePreferredNames
= false;
253 PP
.AlwaysIncludeTypeForTemplateArgument
= true;
254 PP
.UseEnumerators
= false;
256 // Apply -fdebug-prefix-map.
257 PP
.Callbacks
= &PrintCB
;
261 StringRef
CGDebugInfo::getFunctionName(const FunctionDecl
*FD
) {
262 return internString(GetName(FD
));
265 StringRef
CGDebugInfo::getObjCMethodName(const ObjCMethodDecl
*OMD
) {
266 SmallString
<256> MethodName
;
267 llvm::raw_svector_ostream
OS(MethodName
);
268 OS
<< (OMD
->isInstanceMethod() ? '-' : '+') << '[';
269 const DeclContext
*DC
= OMD
->getDeclContext();
270 if (const auto *OID
= dyn_cast
<ObjCImplementationDecl
>(DC
)) {
271 OS
<< OID
->getName();
272 } else if (const auto *OID
= dyn_cast
<ObjCInterfaceDecl
>(DC
)) {
273 OS
<< OID
->getName();
274 } else if (const auto *OC
= dyn_cast
<ObjCCategoryDecl
>(DC
)) {
275 if (OC
->IsClassExtension()) {
276 OS
<< OC
->getClassInterface()->getName();
278 OS
<< OC
->getIdentifier()->getNameStart() << '('
279 << OC
->getIdentifier()->getNameStart() << ')';
281 } else if (const auto *OCD
= dyn_cast
<ObjCCategoryImplDecl
>(DC
)) {
282 OS
<< OCD
->getClassInterface()->getName() << '(' << OCD
->getName() << ')';
284 OS
<< ' ' << OMD
->getSelector().getAsString() << ']';
286 return internString(OS
.str());
289 StringRef
CGDebugInfo::getSelectorName(Selector S
) {
290 return internString(S
.getAsString());
293 StringRef
CGDebugInfo::getClassName(const RecordDecl
*RD
) {
294 if (isa
<ClassTemplateSpecializationDecl
>(RD
)) {
295 // Copy this name on the side and use its reference.
296 return internString(GetName(RD
));
299 // quick optimization to avoid having to intern strings that are already
300 // stored reliably elsewhere
301 if (const IdentifierInfo
*II
= RD
->getIdentifier())
302 return II
->getName();
304 // The CodeView printer in LLVM wants to see the names of unnamed types
305 // because they need to have a unique identifier.
306 // These names are used to reconstruct the fully qualified type names.
307 if (CGM
.getCodeGenOpts().EmitCodeView
) {
308 if (const TypedefNameDecl
*D
= RD
->getTypedefNameForAnonDecl()) {
309 assert(RD
->getDeclContext() == D
->getDeclContext() &&
310 "Typedef should not be in another decl context!");
311 assert(D
->getDeclName().getAsIdentifierInfo() &&
312 "Typedef was not named!");
313 return D
->getDeclName().getAsIdentifierInfo()->getName();
316 if (CGM
.getLangOpts().CPlusPlus
) {
319 ASTContext
&Context
= CGM
.getContext();
320 if (const DeclaratorDecl
*DD
= Context
.getDeclaratorForUnnamedTagDecl(RD
))
321 // Anonymous types without a name for linkage purposes have their
322 // declarator mangled in if they have one.
323 Name
= DD
->getName();
324 else if (const TypedefNameDecl
*TND
=
325 Context
.getTypedefNameForUnnamedTagDecl(RD
))
326 // Anonymous types without a name for linkage purposes have their
327 // associate typedef mangled in if they have one.
328 Name
= TND
->getName();
330 // Give lambdas a display name based on their name mangling.
331 if (const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
332 if (CXXRD
->isLambda())
334 CGM
.getCXXABI().getMangleContext().getLambdaString(CXXRD
));
337 SmallString
<256> UnnamedType("<unnamed-type-");
340 return internString(UnnamedType
);
348 std::optional
<llvm::DIFile::ChecksumKind
>
349 CGDebugInfo::computeChecksum(FileID FID
, SmallString
<64> &Checksum
) const {
352 if (!CGM
.getCodeGenOpts().EmitCodeView
&&
353 CGM
.getCodeGenOpts().DwarfVersion
< 5)
356 SourceManager
&SM
= CGM
.getContext().getSourceManager();
357 std::optional
<llvm::MemoryBufferRef
> MemBuffer
= SM
.getBufferOrNone(FID
);
361 auto Data
= llvm::arrayRefFromStringRef(MemBuffer
->getBuffer());
362 switch (CGM
.getCodeGenOpts().getDebugSrcHash()) {
363 case clang::CodeGenOptions::DSH_MD5
:
364 llvm::toHex(llvm::MD5::hash(Data
), /*LowerCase=*/true, Checksum
);
365 return llvm::DIFile::CSK_MD5
;
366 case clang::CodeGenOptions::DSH_SHA1
:
367 llvm::toHex(llvm::SHA1::hash(Data
), /*LowerCase=*/true, Checksum
);
368 return llvm::DIFile::CSK_SHA1
;
369 case clang::CodeGenOptions::DSH_SHA256
:
370 llvm::toHex(llvm::SHA256::hash(Data
), /*LowerCase=*/true, Checksum
);
371 return llvm::DIFile::CSK_SHA256
;
373 llvm_unreachable("Unhandled DebugSrcHashKind enum");
376 std::optional
<StringRef
> CGDebugInfo::getSource(const SourceManager
&SM
,
378 if (!CGM
.getCodeGenOpts().EmbedSource
)
381 bool SourceInvalid
= false;
382 StringRef Source
= SM
.getBufferData(FID
, &SourceInvalid
);
390 llvm::DIFile
*CGDebugInfo::getOrCreateFile(SourceLocation Loc
) {
391 SourceManager
&SM
= CGM
.getContext().getSourceManager();
394 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
;
396 if (Loc
.isInvalid()) {
397 // The DIFile used by the CU is distinct from the main source file. Call
398 // createFile() below for canonicalization if the source file was specified
399 // with an absolute path.
400 FileName
= TheCU
->getFile()->getFilename();
401 CSInfo
= TheCU
->getFile()->getChecksum();
403 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
);
404 FileName
= PLoc
.getFilename();
406 if (FileName
.empty()) {
407 FileName
= TheCU
->getFile()->getFilename();
409 FileName
= PLoc
.getFilename();
411 FID
= PLoc
.getFileID();
414 // Cache the results.
415 auto It
= DIFileCache
.find(FileName
.data());
416 if (It
!= DIFileCache
.end()) {
417 // Verify that the information still exists.
418 if (llvm::Metadata
*V
= It
->second
)
419 return cast
<llvm::DIFile
>(V
);
422 // Put Checksum at a scope where it will persist past the createFile call.
423 SmallString
<64> Checksum
;
425 std::optional
<llvm::DIFile::ChecksumKind
> CSKind
=
426 computeChecksum(FID
, Checksum
);
428 CSInfo
.emplace(*CSKind
, Checksum
);
430 return createFile(FileName
, CSInfo
, getSource(SM
, SM
.getFileID(Loc
)));
433 llvm::DIFile
*CGDebugInfo::createFile(
435 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
,
436 std::optional
<StringRef
> Source
) {
439 std::string RemappedFile
= remapDIPath(FileName
);
440 std::string CurDir
= remapDIPath(getCurrentDirname());
441 SmallString
<128> DirBuf
;
442 SmallString
<128> FileBuf
;
443 if (llvm::sys::path::is_absolute(RemappedFile
)) {
444 // Strip the common prefix (if it is more than just "/" or "C:\") from
445 // current directory and FileName for a more space-efficient encoding.
446 auto FileIt
= llvm::sys::path::begin(RemappedFile
);
447 auto FileE
= llvm::sys::path::end(RemappedFile
);
448 auto CurDirIt
= llvm::sys::path::begin(CurDir
);
449 auto CurDirE
= llvm::sys::path::end(CurDir
);
450 for (; CurDirIt
!= CurDirE
&& *CurDirIt
== *FileIt
; ++CurDirIt
, ++FileIt
)
451 llvm::sys::path::append(DirBuf
, *CurDirIt
);
452 if (llvm::sys::path::root_path(DirBuf
) == DirBuf
) {
453 // Don't strip the common prefix if it is only the root ("/" or "C:\")
454 // since that would make LLVM diagnostic locations confusing.
458 for (; FileIt
!= FileE
; ++FileIt
)
459 llvm::sys::path::append(FileBuf
, *FileIt
);
464 if (!llvm::sys::path::is_absolute(FileName
))
468 llvm::DIFile
*F
= DBuilder
.createFile(File
, Dir
, CSInfo
, Source
);
469 DIFileCache
[FileName
.data()].reset(F
);
473 std::string
CGDebugInfo::remapDIPath(StringRef Path
) const {
474 SmallString
<256> P
= Path
;
475 for (auto &[From
, To
] : llvm::reverse(CGM
.getCodeGenOpts().DebugPrefixMap
))
476 if (llvm::sys::path::replace_path_prefix(P
, From
, To
))
478 return P
.str().str();
481 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc
) {
484 SourceManager
&SM
= CGM
.getContext().getSourceManager();
485 return SM
.getPresumedLoc(Loc
).getLine();
488 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc
, bool Force
) {
489 // We may not want column information at all.
490 if (!Force
&& !CGM
.getCodeGenOpts().DebugColumnInfo
)
493 // If the location is invalid then use the current column.
494 if (Loc
.isInvalid() && CurLoc
.isInvalid())
496 SourceManager
&SM
= CGM
.getContext().getSourceManager();
497 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
.isValid() ? Loc
: CurLoc
);
498 return PLoc
.isValid() ? PLoc
.getColumn() : 0;
501 StringRef
CGDebugInfo::getCurrentDirname() {
502 if (!CGM
.getCodeGenOpts().DebugCompilationDir
.empty())
503 return CGM
.getCodeGenOpts().DebugCompilationDir
;
505 if (!CWDName
.empty())
507 llvm::ErrorOr
<std::string
> CWD
=
508 CGM
.getFileSystem()->getCurrentWorkingDirectory();
511 return CWDName
= internString(*CWD
);
514 void CGDebugInfo::CreateCompileUnit() {
515 SmallString
<64> Checksum
;
516 std::optional
<llvm::DIFile::ChecksumKind
> CSKind
;
517 std::optional
<llvm::DIFile::ChecksumInfo
<StringRef
>> CSInfo
;
519 // Should we be asking the SourceManager for the main file name, instead of
520 // accepting it as an argument? This just causes the main file name to
521 // mismatch with source locations and create extra lexical scopes or
522 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
523 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
524 // because that's what the SourceManager says)
526 // Get absolute path name.
527 SourceManager
&SM
= CGM
.getContext().getSourceManager();
528 auto &CGO
= CGM
.getCodeGenOpts();
529 const LangOptions
&LO
= CGM
.getLangOpts();
530 std::string MainFileName
= CGO
.MainFileName
;
531 if (MainFileName
.empty())
532 MainFileName
= "<stdin>";
534 // The main file name provided via the "-main-file-name" option contains just
535 // the file name itself with no path information. This file name may have had
536 // a relative path, so we look into the actual file entry for the main
537 // file to determine the real absolute path for the file.
538 std::string MainFileDir
;
539 if (OptionalFileEntryRef MainFile
=
540 SM
.getFileEntryRefForID(SM
.getMainFileID())) {
541 MainFileDir
= std::string(MainFile
->getDir().getName());
542 if (!llvm::sys::path::is_absolute(MainFileName
)) {
543 llvm::SmallString
<1024> MainFileDirSS(MainFileDir
);
544 llvm::sys::path::Style Style
=
545 LO
.UseTargetPathSeparator
546 ? (CGM
.getTarget().getTriple().isOSWindows()
547 ? llvm::sys::path::Style::windows_backslash
548 : llvm::sys::path::Style::posix
)
549 : llvm::sys::path::Style::native
;
550 llvm::sys::path::append(MainFileDirSS
, Style
, MainFileName
);
551 MainFileName
= std::string(
552 llvm::sys::path::remove_leading_dotslash(MainFileDirSS
, Style
));
554 // If the main file name provided is identical to the input file name, and
555 // if the input file is a preprocessed source, use the module name for
556 // debug info. The module name comes from the name specified in the first
557 // linemarker if the input is a preprocessed source. In this case we don't
558 // know the content to compute a checksum.
559 if (MainFile
->getName() == MainFileName
&&
560 FrontendOptions::getInputKindForExtension(
561 MainFile
->getName().rsplit('.').second
)
563 MainFileName
= CGM
.getModule().getName().str();
565 CSKind
= computeChecksum(SM
.getMainFileID(), Checksum
);
569 llvm::dwarf::SourceLanguage LangTag
;
572 LangTag
= llvm::dwarf::DW_LANG_ObjC_plus_plus
;
573 else if (CGO
.DebugStrictDwarf
&& CGO
.DwarfVersion
< 5)
574 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus
;
575 else if (LO
.CPlusPlus14
)
576 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus_14
;
577 else if (LO
.CPlusPlus11
)
578 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus_11
;
580 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus
;
581 } else if (LO
.ObjC
) {
582 LangTag
= llvm::dwarf::DW_LANG_ObjC
;
583 } else if (LO
.OpenCL
&& (!CGM
.getCodeGenOpts().DebugStrictDwarf
||
584 CGM
.getCodeGenOpts().DwarfVersion
>= 5)) {
585 LangTag
= llvm::dwarf::DW_LANG_OpenCL
;
586 } else if (LO
.RenderScript
) {
587 LangTag
= llvm::dwarf::DW_LANG_GOOGLE_RenderScript
;
588 } else if (LO
.C11
&& !(CGO
.DebugStrictDwarf
&& CGO
.DwarfVersion
< 5)) {
589 LangTag
= llvm::dwarf::DW_LANG_C11
;
591 LangTag
= llvm::dwarf::DW_LANG_C99
;
593 LangTag
= llvm::dwarf::DW_LANG_C89
;
596 std::string Producer
= getClangFullVersion();
598 // Figure out which version of the ObjC runtime we have.
599 unsigned RuntimeVers
= 0;
601 RuntimeVers
= LO
.ObjCRuntime
.isNonFragile() ? 2 : 1;
603 llvm::DICompileUnit::DebugEmissionKind EmissionKind
;
605 case llvm::codegenoptions::NoDebugInfo
:
606 case llvm::codegenoptions::LocTrackingOnly
:
607 EmissionKind
= llvm::DICompileUnit::NoDebug
;
609 case llvm::codegenoptions::DebugLineTablesOnly
:
610 EmissionKind
= llvm::DICompileUnit::LineTablesOnly
;
612 case llvm::codegenoptions::DebugDirectivesOnly
:
613 EmissionKind
= llvm::DICompileUnit::DebugDirectivesOnly
;
615 case llvm::codegenoptions::DebugInfoConstructor
:
616 case llvm::codegenoptions::LimitedDebugInfo
:
617 case llvm::codegenoptions::FullDebugInfo
:
618 case llvm::codegenoptions::UnusedTypeInfo
:
619 EmissionKind
= llvm::DICompileUnit::FullDebug
;
624 auto &CGOpts
= CGM
.getCodeGenOpts();
625 // The DIFile used by the CU is distinct from the main source
626 // file. Its directory part specifies what becomes the
627 // DW_AT_comp_dir (the compilation directory), even if the source
628 // file was specified with an absolute path.
630 CSInfo
.emplace(*CSKind
, Checksum
);
631 llvm::DIFile
*CUFile
= DBuilder
.createFile(
632 remapDIPath(MainFileName
), remapDIPath(getCurrentDirname()), CSInfo
,
633 getSource(SM
, SM
.getMainFileID()));
635 StringRef Sysroot
, SDK
;
636 if (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
) {
637 Sysroot
= CGM
.getHeaderSearchOpts().Sysroot
;
638 auto B
= llvm::sys::path::rbegin(Sysroot
);
639 auto E
= llvm::sys::path::rend(Sysroot
);
641 std::find_if(B
, E
, [](auto SDK
) { return SDK
.ends_with(".sdk"); });
646 llvm::DICompileUnit::DebugNameTableKind NameTableKind
=
647 static_cast<llvm::DICompileUnit::DebugNameTableKind
>(
648 CGOpts
.DebugNameTable
);
649 if (CGM
.getTarget().getTriple().isNVPTX())
650 NameTableKind
= llvm::DICompileUnit::DebugNameTableKind::None
;
651 else if (CGM
.getTarget().getTriple().getVendor() == llvm::Triple::Apple
)
652 NameTableKind
= llvm::DICompileUnit::DebugNameTableKind::Apple
;
654 // Create new compile unit.
655 TheCU
= DBuilder
.createCompileUnit(
656 LangTag
, CUFile
, CGOpts
.EmitVersionIdentMetadata
? Producer
: "",
657 LO
.Optimize
|| CGOpts
.PrepareForLTO
|| CGOpts
.PrepareForThinLTO
,
658 CGOpts
.DwarfDebugFlags
, RuntimeVers
, CGOpts
.SplitDwarfFile
, EmissionKind
,
659 DwoId
, CGOpts
.SplitDwarfInlining
, CGOpts
.DebugInfoForProfiling
,
660 NameTableKind
, CGOpts
.DebugRangesBaseAddress
, remapDIPath(Sysroot
), SDK
);
663 llvm::DIType
*CGDebugInfo::CreateType(const BuiltinType
*BT
) {
664 llvm::dwarf::TypeKind Encoding
;
666 switch (BT
->getKind()) {
667 #define BUILTIN_TYPE(Id, SingletonId)
668 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
669 #include "clang/AST/BuiltinTypes.def"
670 case BuiltinType::Dependent
:
671 llvm_unreachable("Unexpected builtin type");
672 case BuiltinType::NullPtr
:
673 return DBuilder
.createNullPtrType();
674 case BuiltinType::Void
:
676 case BuiltinType::ObjCClass
:
679 DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
680 "objc_class", TheCU
, TheCU
->getFile(), 0);
682 case BuiltinType::ObjCId
: {
683 // typedef struct objc_class *Class;
684 // typedef struct objc_object {
693 DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
694 "objc_class", TheCU
, TheCU
->getFile(), 0);
696 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
698 auto *ISATy
= DBuilder
.createPointerType(ClassTy
, Size
);
700 ObjTy
= DBuilder
.createStructType(TheCU
, "objc_object", TheCU
->getFile(), 0,
701 0, 0, llvm::DINode::FlagZero
, nullptr,
702 llvm::DINodeArray());
704 DBuilder
.replaceArrays(
705 ObjTy
, DBuilder
.getOrCreateArray(&*DBuilder
.createMemberType(
706 ObjTy
, "isa", TheCU
->getFile(), 0, Size
, 0, 0,
707 llvm::DINode::FlagZero
, ISATy
)));
710 case BuiltinType::ObjCSel
: {
712 SelTy
= DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
713 "objc_selector", TheCU
,
714 TheCU
->getFile(), 0);
718 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
719 case BuiltinType::Id: \
720 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
722 #include "clang/Basic/OpenCLImageTypes.def"
723 case BuiltinType::OCLSampler
:
724 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy
);
725 case BuiltinType::OCLEvent
:
726 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy
);
727 case BuiltinType::OCLClkEvent
:
728 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy
);
729 case BuiltinType::OCLQueue
:
730 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy
);
731 case BuiltinType::OCLReserveID
:
732 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy
);
733 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
734 case BuiltinType::Id: \
735 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
736 #include "clang/Basic/OpenCLExtensionTypes.def"
738 #define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
739 #include "clang/Basic/AArch64SVEACLETypes.def"
741 ASTContext::BuiltinVectorTypeInfo Info
=
742 // For svcount_t, only the lower 2 bytes are relevant.
743 BT
->getKind() == BuiltinType::SveCount
744 ? ASTContext::BuiltinVectorTypeInfo(
745 CGM
.getContext().BoolTy
, llvm::ElementCount::getFixed(16),
747 : CGM
.getContext().getBuiltinVectorTypeInfo(BT
);
749 // A single vector of bytes may not suffice as the representation of
750 // svcount_t tuples because of the gap between the active 16bits of
751 // successive tuple members. Currently no such tuples are defined for
752 // svcount_t, so assert that NumVectors is 1.
753 assert((BT
->getKind() != BuiltinType::SveCount
|| Info
.NumVectors
== 1) &&
754 "Unsupported number of vectors for svcount_t");
756 // Debuggers can't extract 1bit from a vector, so will display a
757 // bitpattern for predicates instead.
758 unsigned NumElems
= Info
.EC
.getKnownMinValue() * Info
.NumVectors
;
759 if (Info
.ElementType
== CGM
.getContext().BoolTy
) {
761 Info
.ElementType
= CGM
.getContext().UnsignedCharTy
;
764 llvm::Metadata
*LowerBound
, *UpperBound
;
765 LowerBound
= llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
766 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), 0));
767 if (Info
.EC
.isScalable()) {
768 unsigned NumElemsPerVG
= NumElems
/ 2;
769 SmallVector
<uint64_t, 9> Expr(
770 {llvm::dwarf::DW_OP_constu
, NumElemsPerVG
, llvm::dwarf::DW_OP_bregx
,
771 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul
,
772 llvm::dwarf::DW_OP_constu
, 1, llvm::dwarf::DW_OP_minus
});
773 UpperBound
= DBuilder
.createExpression(Expr
);
775 UpperBound
= llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
776 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), NumElems
- 1));
778 llvm::Metadata
*Subscript
= DBuilder
.getOrCreateSubrange(
779 /*count*/ nullptr, LowerBound
, UpperBound
, /*stride*/ nullptr);
780 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
781 llvm::DIType
*ElemTy
=
782 getOrCreateType(Info
.ElementType
, TheCU
->getFile());
783 auto Align
= getTypeAlignIfRequired(BT
, CGM
.getContext());
784 return DBuilder
.createVectorType(/*Size*/ 0, Align
, ElemTy
,
787 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
788 // So we return a safe type here to avoid generating an error.
789 #define PPC_VECTOR_TYPE(Name, Id, size) \
790 case BuiltinType::Id:
791 #include "clang/Basic/PPCTypes.def"
792 return CreateType(cast
<const BuiltinType
>(CGM
.getContext().IntTy
));
794 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
795 #include "clang/Basic/RISCVVTypes.def"
797 ASTContext::BuiltinVectorTypeInfo Info
=
798 CGM
.getContext().getBuiltinVectorTypeInfo(BT
);
800 unsigned ElementCount
= Info
.EC
.getKnownMinValue();
801 unsigned SEW
= CGM
.getContext().getTypeSize(Info
.ElementType
);
803 bool Fractional
= false;
805 unsigned FixedSize
= ElementCount
* SEW
;
806 if (Info
.ElementType
== CGM
.getContext().BoolTy
) {
807 // Mask type only occupies one vector register.
809 } else if (FixedSize
< 64) {
810 // In RVV scalable vector types, we encode 64 bits in the fixed part.
812 LMUL
= 64 / FixedSize
;
814 LMUL
= FixedSize
/ 64;
817 // Element count = (VLENB / SEW) x LMUL
818 SmallVector
<uint64_t, 12> Expr(
819 // The DW_OP_bregx operation has two operands: a register which is
820 // specified by an unsigned LEB128 number, followed by a signed LEB128
822 {llvm::dwarf::DW_OP_bregx
, // Read the contents of a register.
823 4096 + 0xC22, // RISC-V VLENB CSR register.
824 0, // Offset for DW_OP_bregx. It is dummy here.
825 llvm::dwarf::DW_OP_constu
,
826 SEW
/ 8, // SEW is in bits.
827 llvm::dwarf::DW_OP_div
, llvm::dwarf::DW_OP_constu
, LMUL
});
829 Expr
.push_back(llvm::dwarf::DW_OP_div
);
831 Expr
.push_back(llvm::dwarf::DW_OP_mul
);
832 // Element max index = count - 1
833 Expr
.append({llvm::dwarf::DW_OP_constu
, 1, llvm::dwarf::DW_OP_minus
});
836 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
837 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), 0));
838 auto *UpperBound
= DBuilder
.createExpression(Expr
);
839 llvm::Metadata
*Subscript
= DBuilder
.getOrCreateSubrange(
840 /*count*/ nullptr, LowerBound
, UpperBound
, /*stride*/ nullptr);
841 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
842 llvm::DIType
*ElemTy
=
843 getOrCreateType(Info
.ElementType
, TheCU
->getFile());
845 auto Align
= getTypeAlignIfRequired(BT
, CGM
.getContext());
846 return DBuilder
.createVectorType(/*Size=*/0, Align
, ElemTy
,
850 #define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
851 case BuiltinType::Id: { \
854 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
855 MangledName, TheCU, TheCU->getFile(), 0); \
856 return SingletonId; \
858 #include "clang/Basic/WebAssemblyReferenceTypes.def"
860 case BuiltinType::UChar
:
861 case BuiltinType::Char_U
:
862 Encoding
= llvm::dwarf::DW_ATE_unsigned_char
;
864 case BuiltinType::Char_S
:
865 case BuiltinType::SChar
:
866 Encoding
= llvm::dwarf::DW_ATE_signed_char
;
868 case BuiltinType::Char8
:
869 case BuiltinType::Char16
:
870 case BuiltinType::Char32
:
871 Encoding
= llvm::dwarf::DW_ATE_UTF
;
873 case BuiltinType::UShort
:
874 case BuiltinType::UInt
:
875 case BuiltinType::UInt128
:
876 case BuiltinType::ULong
:
877 case BuiltinType::WChar_U
:
878 case BuiltinType::ULongLong
:
879 Encoding
= llvm::dwarf::DW_ATE_unsigned
;
881 case BuiltinType::Short
:
882 case BuiltinType::Int
:
883 case BuiltinType::Int128
:
884 case BuiltinType::Long
:
885 case BuiltinType::WChar_S
:
886 case BuiltinType::LongLong
:
887 Encoding
= llvm::dwarf::DW_ATE_signed
;
889 case BuiltinType::Bool
:
890 Encoding
= llvm::dwarf::DW_ATE_boolean
;
892 case BuiltinType::Half
:
893 case BuiltinType::Float
:
894 case BuiltinType::LongDouble
:
895 case BuiltinType::Float16
:
896 case BuiltinType::BFloat16
:
897 case BuiltinType::Float128
:
898 case BuiltinType::Double
:
899 case BuiltinType::Ibm128
:
900 // FIXME: For targets where long double, __ibm128 and __float128 have the
901 // same size, they are currently indistinguishable in the debugger without
902 // some special treatment. However, there is currently no consensus on
903 // encoding and this should be updated once a DWARF encoding exists for
904 // distinct floating point types of the same size.
905 Encoding
= llvm::dwarf::DW_ATE_float
;
907 case BuiltinType::ShortAccum
:
908 case BuiltinType::Accum
:
909 case BuiltinType::LongAccum
:
910 case BuiltinType::ShortFract
:
911 case BuiltinType::Fract
:
912 case BuiltinType::LongFract
:
913 case BuiltinType::SatShortFract
:
914 case BuiltinType::SatFract
:
915 case BuiltinType::SatLongFract
:
916 case BuiltinType::SatShortAccum
:
917 case BuiltinType::SatAccum
:
918 case BuiltinType::SatLongAccum
:
919 Encoding
= llvm::dwarf::DW_ATE_signed_fixed
;
921 case BuiltinType::UShortAccum
:
922 case BuiltinType::UAccum
:
923 case BuiltinType::ULongAccum
:
924 case BuiltinType::UShortFract
:
925 case BuiltinType::UFract
:
926 case BuiltinType::ULongFract
:
927 case BuiltinType::SatUShortAccum
:
928 case BuiltinType::SatUAccum
:
929 case BuiltinType::SatULongAccum
:
930 case BuiltinType::SatUShortFract
:
931 case BuiltinType::SatUFract
:
932 case BuiltinType::SatULongFract
:
933 Encoding
= llvm::dwarf::DW_ATE_unsigned_fixed
;
937 BTName
= BT
->getName(CGM
.getLangOpts());
938 // Bit size and offset of the type.
939 uint64_t Size
= CGM
.getContext().getTypeSize(BT
);
940 return DBuilder
.createBasicType(BTName
, Size
, Encoding
);
943 llvm::DIType
*CGDebugInfo::CreateType(const BitIntType
*Ty
) {
945 StringRef Name
= Ty
->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
946 llvm::dwarf::TypeKind Encoding
= Ty
->isUnsigned()
947 ? llvm::dwarf::DW_ATE_unsigned
948 : llvm::dwarf::DW_ATE_signed
;
950 return DBuilder
.createBasicType(Name
, CGM
.getContext().getTypeSize(Ty
),
954 llvm::DIType
*CGDebugInfo::CreateType(const ComplexType
*Ty
) {
955 // Bit size and offset of the type.
956 llvm::dwarf::TypeKind Encoding
= llvm::dwarf::DW_ATE_complex_float
;
957 if (Ty
->isComplexIntegerType())
958 Encoding
= llvm::dwarf::DW_ATE_lo_user
;
960 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
961 return DBuilder
.createBasicType("complex", Size
, Encoding
);
964 static void stripUnusedQualifiers(Qualifiers
&Q
) {
965 // Ignore these qualifiers for now.
966 Q
.removeObjCGCAttr();
967 Q
.removeAddressSpace();
968 Q
.removeObjCLifetime();
972 static llvm::dwarf::Tag
getNextQualifier(Qualifiers
&Q
) {
975 return llvm::dwarf::DW_TAG_const_type
;
977 if (Q
.hasVolatile()) {
979 return llvm::dwarf::DW_TAG_volatile_type
;
981 if (Q
.hasRestrict()) {
983 return llvm::dwarf::DW_TAG_restrict_type
;
985 return (llvm::dwarf::Tag
)0;
988 llvm::DIType
*CGDebugInfo::CreateQualifiedType(QualType Ty
,
989 llvm::DIFile
*Unit
) {
990 QualifierCollector Qc
;
991 const Type
*T
= Qc
.strip(Ty
);
993 stripUnusedQualifiers(Qc
);
995 // We will create one Derived type for one qualifier and recurse to handle any
997 llvm::dwarf::Tag Tag
= getNextQualifier(Qc
);
999 assert(Qc
.empty() && "Unknown type qualifier for debug info");
1000 return getOrCreateType(QualType(T
, 0), Unit
);
1003 auto *FromTy
= getOrCreateType(Qc
.apply(CGM
.getContext(), T
), Unit
);
1005 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1006 // CVR derived types.
1007 return DBuilder
.createQualifiedType(Tag
, FromTy
);
1010 llvm::DIType
*CGDebugInfo::CreateQualifiedType(const FunctionProtoType
*F
,
1011 llvm::DIFile
*Unit
) {
1012 FunctionProtoType::ExtProtoInfo EPI
= F
->getExtProtoInfo();
1013 Qualifiers
&Q
= EPI
.TypeQuals
;
1014 stripUnusedQualifiers(Q
);
1016 // We will create one Derived type for one qualifier and recurse to handle any
1018 llvm::dwarf::Tag Tag
= getNextQualifier(Q
);
1020 assert(Q
.empty() && "Unknown type qualifier for debug info");
1025 getOrCreateType(CGM
.getContext().getFunctionType(F
->getReturnType(),
1026 F
->getParamTypes(), EPI
),
1029 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1030 // CVR derived types.
1031 return DBuilder
.createQualifiedType(Tag
, FromTy
);
1034 llvm::DIType
*CGDebugInfo::CreateType(const ObjCObjectPointerType
*Ty
,
1035 llvm::DIFile
*Unit
) {
1037 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1038 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1039 // debug info, we want to emit 'id' in both cases.
1040 if (Ty
->isObjCQualifiedIdType())
1041 return getOrCreateType(CGM
.getContext().getObjCIdType(), Unit
);
1043 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
1044 Ty
->getPointeeType(), Unit
);
1047 llvm::DIType
*CGDebugInfo::CreateType(const PointerType
*Ty
,
1048 llvm::DIFile
*Unit
) {
1049 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
1050 Ty
->getPointeeType(), Unit
);
1053 /// \return whether a C++ mangling exists for the type defined by TD.
1054 static bool hasCXXMangling(const TagDecl
*TD
, llvm::DICompileUnit
*TheCU
) {
1055 switch (TheCU
->getSourceLanguage()) {
1056 case llvm::dwarf::DW_LANG_C_plus_plus
:
1057 case llvm::dwarf::DW_LANG_C_plus_plus_11
:
1058 case llvm::dwarf::DW_LANG_C_plus_plus_14
:
1060 case llvm::dwarf::DW_LANG_ObjC_plus_plus
:
1061 return isa
<CXXRecordDecl
>(TD
) || isa
<EnumDecl
>(TD
);
1067 // Determines if the debug info for this tag declaration needs a type
1068 // identifier. The purpose of the unique identifier is to deduplicate type
1069 // information for identical types across TUs. Because of the C++ one definition
1070 // rule (ODR), it is valid to assume that the type is defined the same way in
1071 // every TU and its debug info is equivalent.
1073 // C does not have the ODR, and it is common for codebases to contain multiple
1074 // different definitions of a struct with the same name in different TUs.
1075 // Therefore, if the type doesn't have a C++ mangling, don't give it an
1076 // identifer. Type information in C is smaller and simpler than C++ type
1077 // information, so the increase in debug info size is negligible.
1079 // If the type is not externally visible, it should be unique to the current TU,
1080 // and should not need an identifier to participate in type deduplication.
1081 // However, when emitting CodeView, the format internally uses these
1082 // unique type name identifers for references between debug info. For example,
1083 // the method of a class in an anonymous namespace uses the identifer to refer
1084 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
1085 // for such types, so when emitting CodeView, always use identifiers for C++
1086 // types. This may create problems when attempting to emit CodeView when the MS
1087 // C++ ABI is not in use.
1088 static bool needsTypeIdentifier(const TagDecl
*TD
, CodeGenModule
&CGM
,
1089 llvm::DICompileUnit
*TheCU
) {
1090 // We only add a type identifier for types with C++ name mangling.
1091 if (!hasCXXMangling(TD
, TheCU
))
1094 // Externally visible types with C++ mangling need a type identifier.
1095 if (TD
->isExternallyVisible())
1098 // CodeView types with C++ mangling need a type identifier.
1099 if (CGM
.getCodeGenOpts().EmitCodeView
)
1105 // Returns a unique type identifier string if one exists, or an empty string.
1106 static SmallString
<256> getTypeIdentifier(const TagType
*Ty
, CodeGenModule
&CGM
,
1107 llvm::DICompileUnit
*TheCU
) {
1108 SmallString
<256> Identifier
;
1109 const TagDecl
*TD
= Ty
->getDecl();
1111 if (!needsTypeIdentifier(TD
, CGM
, TheCU
))
1113 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(TD
))
1114 if (RD
->getDefinition())
1115 if (RD
->isDynamicClass() &&
1116 CGM
.getVTableLinkage(RD
) == llvm::GlobalValue::ExternalLinkage
)
1119 // TODO: This is using the RTTI name. Is there a better way to get
1120 // a unique string for a type?
1121 llvm::raw_svector_ostream
Out(Identifier
);
1122 CGM
.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty
, 0), Out
);
1126 /// \return the appropriate DWARF tag for a composite type.
1127 static llvm::dwarf::Tag
getTagForRecord(const RecordDecl
*RD
) {
1128 llvm::dwarf::Tag Tag
;
1129 if (RD
->isStruct() || RD
->isInterface())
1130 Tag
= llvm::dwarf::DW_TAG_structure_type
;
1131 else if (RD
->isUnion())
1132 Tag
= llvm::dwarf::DW_TAG_union_type
;
1134 // FIXME: This could be a struct type giving a default visibility different
1135 // than C++ class type, but needs llvm metadata changes first.
1136 assert(RD
->isClass());
1137 Tag
= llvm::dwarf::DW_TAG_class_type
;
1142 llvm::DICompositeType
*
1143 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType
*Ty
,
1144 llvm::DIScope
*Ctx
) {
1145 const RecordDecl
*RD
= Ty
->getDecl();
1146 if (llvm::DIType
*T
= getTypeOrNull(CGM
.getContext().getRecordType(RD
)))
1147 return cast
<llvm::DICompositeType
>(T
);
1148 llvm::DIFile
*DefUnit
= getOrCreateFile(RD
->getLocation());
1149 const unsigned Line
=
1150 getLineNumber(RD
->getLocation().isValid() ? RD
->getLocation() : CurLoc
);
1151 StringRef RDName
= getClassName(RD
);
1156 const RecordDecl
*D
= RD
->getDefinition();
1157 if (D
&& D
->isCompleteDefinition())
1158 Size
= CGM
.getContext().getTypeSize(Ty
);
1160 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagFwdDecl
;
1162 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1163 // add the flag if a record has no definition because we don't know whether
1164 // it will be trivial or not.
1165 if (const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
1166 if (!CXXRD
->hasDefinition() ||
1167 (CXXRD
->hasDefinition() && !CXXRD
->isTrivial()))
1168 Flags
|= llvm::DINode::FlagNonTrivial
;
1171 SmallString
<256> Identifier
;
1172 // Don't include a linkage name in line tables only.
1173 if (CGM
.getCodeGenOpts().hasReducedDebugInfo())
1174 Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
1175 llvm::DICompositeType
*RetTy
= DBuilder
.createReplaceableCompositeType(
1176 getTagForRecord(RD
), RDName
, Ctx
, DefUnit
, Line
, 0, Size
, Align
, Flags
,
1178 if (CGM
.getCodeGenOpts().DebugFwdTemplateParams
)
1179 if (auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
1180 DBuilder
.replaceArrays(RetTy
, llvm::DINodeArray(),
1181 CollectCXXTemplateParams(TSpecial
, DefUnit
));
1182 ReplaceMap
.emplace_back(
1183 std::piecewise_construct
, std::make_tuple(Ty
),
1184 std::make_tuple(static_cast<llvm::Metadata
*>(RetTy
)));
1188 llvm::DIType
*CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag
,
1191 llvm::DIFile
*Unit
) {
1192 // Bit size, align and offset of the type.
1193 // Size is always the size of a pointer.
1194 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1195 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
1196 std::optional
<unsigned> DWARFAddressSpace
=
1197 CGM
.getTarget().getDWARFAddressSpace(
1198 CGM
.getTypes().getTargetAddressSpace(PointeeTy
));
1200 SmallVector
<llvm::Metadata
*, 4> Annots
;
1201 auto *BTFAttrTy
= dyn_cast
<BTFTagAttributedType
>(PointeeTy
);
1203 StringRef Tag
= BTFAttrTy
->getAttr()->getBTFTypeTag();
1205 llvm::Metadata
*Ops
[2] = {
1206 llvm::MDString::get(CGM
.getLLVMContext(), StringRef("btf_type_tag")),
1207 llvm::MDString::get(CGM
.getLLVMContext(), Tag
)};
1208 Annots
.insert(Annots
.begin(),
1209 llvm::MDNode::get(CGM
.getLLVMContext(), Ops
));
1211 BTFAttrTy
= dyn_cast
<BTFTagAttributedType
>(BTFAttrTy
->getWrappedType());
1214 llvm::DINodeArray Annotations
= nullptr;
1215 if (Annots
.size() > 0)
1216 Annotations
= DBuilder
.getOrCreateArray(Annots
);
1218 if (Tag
== llvm::dwarf::DW_TAG_reference_type
||
1219 Tag
== llvm::dwarf::DW_TAG_rvalue_reference_type
)
1220 return DBuilder
.createReferenceType(Tag
, getOrCreateType(PointeeTy
, Unit
),
1221 Size
, Align
, DWARFAddressSpace
);
1223 return DBuilder
.createPointerType(getOrCreateType(PointeeTy
, Unit
), Size
,
1224 Align
, DWARFAddressSpace
, StringRef(),
1228 llvm::DIType
*CGDebugInfo::getOrCreateStructPtrType(StringRef Name
,
1229 llvm::DIType
*&Cache
) {
1232 Cache
= DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
, Name
,
1233 TheCU
, TheCU
->getFile(), 0);
1234 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
1235 Cache
= DBuilder
.createPointerType(Cache
, Size
);
1239 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1240 const BlockPointerType
*Ty
, llvm::DIFile
*Unit
, llvm::DIDerivedType
*DescTy
,
1241 unsigned LineNo
, SmallVectorImpl
<llvm::Metadata
*> &EltTys
) {
1244 // Advanced by calls to CreateMemberType in increments of FType, then
1245 // returned as the overall size of the default elements.
1246 uint64_t FieldOffset
= 0;
1248 // Blocks in OpenCL have unique constraints which make the standard fields
1249 // redundant while requiring size and align fields for enqueue_kernel. See
1250 // initializeForBlockHeader in CGBlocks.cpp
1251 if (CGM
.getLangOpts().OpenCL
) {
1252 FType
= CGM
.getContext().IntTy
;
1253 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__size", &FieldOffset
));
1254 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__align", &FieldOffset
));
1256 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1257 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
1258 FType
= CGM
.getContext().IntTy
;
1259 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
1260 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__reserved", &FieldOffset
));
1261 FType
= CGM
.getContext().getPointerType(Ty
->getPointeeType());
1262 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__FuncPtr", &FieldOffset
));
1263 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1264 uint64_t FieldSize
= CGM
.getContext().getTypeSize(Ty
);
1265 uint32_t FieldAlign
= CGM
.getContext().getTypeAlign(Ty
);
1266 EltTys
.push_back(DBuilder
.createMemberType(
1267 Unit
, "__descriptor", nullptr, LineNo
, FieldSize
, FieldAlign
,
1268 FieldOffset
, llvm::DINode::FlagZero
, DescTy
));
1269 FieldOffset
+= FieldSize
;
1275 llvm::DIType
*CGDebugInfo::CreateType(const BlockPointerType
*Ty
,
1276 llvm::DIFile
*Unit
) {
1277 SmallVector
<llvm::Metadata
*, 8> EltTys
;
1279 uint64_t FieldOffset
;
1280 llvm::DINodeArray Elements
;
1283 FType
= CGM
.getContext().UnsignedLongTy
;
1284 EltTys
.push_back(CreateMemberType(Unit
, FType
, "reserved", &FieldOffset
));
1285 EltTys
.push_back(CreateMemberType(Unit
, FType
, "Size", &FieldOffset
));
1287 Elements
= DBuilder
.getOrCreateArray(EltTys
);
1290 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagAppleBlock
;
1293 DBuilder
.createStructType(Unit
, "__block_descriptor", nullptr, 0,
1294 FieldOffset
, 0, Flags
, nullptr, Elements
);
1296 // Bit size, align and offset of the type.
1297 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1299 auto *DescTy
= DBuilder
.createPointerType(EltTy
, Size
);
1301 FieldOffset
= collectDefaultElementTypesForBlockPointer(Ty
, Unit
, DescTy
,
1304 Elements
= DBuilder
.getOrCreateArray(EltTys
);
1306 // The __block_literal_generic structs are marked with a special
1307 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1308 // the debugger needs to know about. To allow type uniquing, emit
1309 // them without a name or a location.
1310 EltTy
= DBuilder
.createStructType(Unit
, "", nullptr, 0, FieldOffset
, 0,
1311 Flags
, nullptr, Elements
);
1313 return DBuilder
.createPointerType(EltTy
, Size
);
1316 llvm::DIType
*CGDebugInfo::CreateType(const TemplateSpecializationType
*Ty
,
1317 llvm::DIFile
*Unit
) {
1318 assert(Ty
->isTypeAlias());
1319 llvm::DIType
*Src
= getOrCreateType(Ty
->getAliasedType(), Unit
);
1321 const TemplateDecl
*TD
= Ty
->getTemplateName().getAsTemplateDecl();
1322 if (isa
<BuiltinTemplateDecl
>(TD
))
1325 const auto *AliasDecl
= cast
<TypeAliasTemplateDecl
>(TD
)->getTemplatedDecl();
1326 if (AliasDecl
->hasAttr
<NoDebugAttr
>())
1329 SmallString
<128> NS
;
1330 llvm::raw_svector_ostream
OS(NS
);
1332 auto PP
= getPrintingPolicy();
1333 Ty
->getTemplateName().print(OS
, PP
, TemplateName::Qualified::None
);
1335 // Disable PrintCanonicalTypes here because we want
1336 // the DW_AT_name to benefit from the TypePrinter's ability
1337 // to skip defaulted template arguments.
1339 // FIXME: Once -gsimple-template-names is enabled by default
1340 // and we attach template parameters to alias template DIEs
1341 // we don't need to worry about customizing the PrintingPolicy
1343 PP
.PrintCanonicalTypes
= false;
1344 printTemplateArgumentList(OS
, Ty
->template_arguments(), PP
,
1345 TD
->getTemplateParameters());
1347 SourceLocation Loc
= AliasDecl
->getLocation();
1348 return DBuilder
.createTypedef(Src
, OS
.str(), getOrCreateFile(Loc
),
1350 getDeclContextDescriptor(AliasDecl
));
1353 /// Convert an AccessSpecifier into the corresponding DINode flag.
1354 /// As an optimization, return 0 if the access specifier equals the
1355 /// default for the containing type.
1356 static llvm::DINode::DIFlags
getAccessFlag(AccessSpecifier Access
,
1357 const RecordDecl
*RD
) {
1358 AccessSpecifier Default
= clang::AS_none
;
1359 if (RD
&& RD
->isClass())
1360 Default
= clang::AS_private
;
1361 else if (RD
&& (RD
->isStruct() || RD
->isUnion()))
1362 Default
= clang::AS_public
;
1364 if (Access
== Default
)
1365 return llvm::DINode::FlagZero
;
1368 case clang::AS_private
:
1369 return llvm::DINode::FlagPrivate
;
1370 case clang::AS_protected
:
1371 return llvm::DINode::FlagProtected
;
1372 case clang::AS_public
:
1373 return llvm::DINode::FlagPublic
;
1374 case clang::AS_none
:
1375 return llvm::DINode::FlagZero
;
1377 llvm_unreachable("unexpected access enumerator");
1380 llvm::DIType
*CGDebugInfo::CreateType(const TypedefType
*Ty
,
1381 llvm::DIFile
*Unit
) {
1382 llvm::DIType
*Underlying
=
1383 getOrCreateType(Ty
->getDecl()->getUnderlyingType(), Unit
);
1385 if (Ty
->getDecl()->hasAttr
<NoDebugAttr
>())
1388 // We don't set size information, but do specify where the typedef was
1390 SourceLocation Loc
= Ty
->getDecl()->getLocation();
1392 uint32_t Align
= getDeclAlignIfRequired(Ty
->getDecl(), CGM
.getContext());
1393 // Typedefs are derived from some other type.
1394 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(Ty
->getDecl());
1396 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1397 const DeclContext
*DC
= Ty
->getDecl()->getDeclContext();
1398 if (isa
<RecordDecl
>(DC
))
1399 Flags
= getAccessFlag(Ty
->getDecl()->getAccess(), cast
<RecordDecl
>(DC
));
1401 return DBuilder
.createTypedef(Underlying
, Ty
->getDecl()->getName(),
1402 getOrCreateFile(Loc
), getLineNumber(Loc
),
1403 getDeclContextDescriptor(Ty
->getDecl()), Align
,
1404 Flags
, Annotations
);
1407 static unsigned getDwarfCC(CallingConv CC
) {
1410 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1414 return llvm::dwarf::DW_CC_BORLAND_stdcall
;
1415 case CC_X86FastCall
:
1416 return llvm::dwarf::DW_CC_BORLAND_msfastcall
;
1417 case CC_X86ThisCall
:
1418 return llvm::dwarf::DW_CC_BORLAND_thiscall
;
1419 case CC_X86VectorCall
:
1420 return llvm::dwarf::DW_CC_LLVM_vectorcall
;
1422 return llvm::dwarf::DW_CC_BORLAND_pascal
;
1424 return llvm::dwarf::DW_CC_LLVM_Win64
;
1426 return llvm::dwarf::DW_CC_LLVM_X86_64SysV
;
1428 case CC_AArch64VectorCall
:
1429 case CC_AArch64SVEPCS
:
1430 return llvm::dwarf::DW_CC_LLVM_AAPCS
;
1432 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP
;
1433 case CC_IntelOclBicc
:
1434 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc
;
1435 case CC_SpirFunction
:
1436 return llvm::dwarf::DW_CC_LLVM_SpirFunction
;
1437 case CC_OpenCLKernel
:
1438 case CC_AMDGPUKernelCall
:
1439 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel
;
1441 return llvm::dwarf::DW_CC_LLVM_Swift
;
1443 return llvm::dwarf::DW_CC_LLVM_SwiftTail
;
1444 case CC_PreserveMost
:
1445 return llvm::dwarf::DW_CC_LLVM_PreserveMost
;
1446 case CC_PreserveAll
:
1447 return llvm::dwarf::DW_CC_LLVM_PreserveAll
;
1449 return llvm::dwarf::DW_CC_LLVM_X86RegCall
;
1451 return llvm::dwarf::DW_CC_LLVM_M68kRTD
;
1452 case CC_PreserveNone
:
1453 return llvm::dwarf::DW_CC_LLVM_PreserveNone
;
1454 case CC_RISCVVectorCall
:
1455 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall
;
1460 static llvm::DINode::DIFlags
getRefFlags(const FunctionProtoType
*Func
) {
1461 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1462 if (Func
->getExtProtoInfo().RefQualifier
== RQ_LValue
)
1463 Flags
|= llvm::DINode::FlagLValueReference
;
1464 if (Func
->getExtProtoInfo().RefQualifier
== RQ_RValue
)
1465 Flags
|= llvm::DINode::FlagRValueReference
;
1469 llvm::DIType
*CGDebugInfo::CreateType(const FunctionType
*Ty
,
1470 llvm::DIFile
*Unit
) {
1471 const auto *FPT
= dyn_cast
<FunctionProtoType
>(Ty
);
1473 if (llvm::DIType
*QTy
= CreateQualifiedType(FPT
, Unit
))
1477 // Create the type without any qualifiers
1479 SmallVector
<llvm::Metadata
*, 16> EltTys
;
1481 // Add the result type at least.
1482 EltTys
.push_back(getOrCreateType(Ty
->getReturnType(), Unit
));
1484 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1485 // Set up remainder of arguments if there is a prototype.
1486 // otherwise emit it as a variadic function.
1488 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
1490 Flags
= getRefFlags(FPT
);
1491 for (const QualType
&ParamType
: FPT
->param_types())
1492 EltTys
.push_back(getOrCreateType(ParamType
, Unit
));
1493 if (FPT
->isVariadic())
1494 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
1497 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(EltTys
);
1498 llvm::DIType
*F
= DBuilder
.createSubroutineType(
1499 EltTypeArray
, Flags
, getDwarfCC(Ty
->getCallConv()));
1503 llvm::DIDerivedType
*
1504 CGDebugInfo::createBitFieldType(const FieldDecl
*BitFieldDecl
,
1505 llvm::DIScope
*RecordTy
, const RecordDecl
*RD
) {
1506 StringRef Name
= BitFieldDecl
->getName();
1507 QualType Ty
= BitFieldDecl
->getType();
1508 if (BitFieldDecl
->hasAttr
<PreferredTypeAttr
>())
1509 Ty
= BitFieldDecl
->getAttr
<PreferredTypeAttr
>()->getType();
1510 SourceLocation Loc
= BitFieldDecl
->getLocation();
1511 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1512 llvm::DIType
*DebugType
= getOrCreateType(Ty
, VUnit
);
1514 // Get the location for the field.
1515 llvm::DIFile
*File
= getOrCreateFile(Loc
);
1516 unsigned Line
= getLineNumber(Loc
);
1518 const CGBitFieldInfo
&BitFieldInfo
=
1519 CGM
.getTypes().getCGRecordLayout(RD
).getBitFieldInfo(BitFieldDecl
);
1520 uint64_t SizeInBits
= BitFieldInfo
.Size
;
1521 assert(SizeInBits
> 0 && "found named 0-width bitfield");
1522 uint64_t StorageOffsetInBits
=
1523 CGM
.getContext().toBits(BitFieldInfo
.StorageOffset
);
1524 uint64_t Offset
= BitFieldInfo
.Offset
;
1525 // The bit offsets for big endian machines are reversed for big
1526 // endian target, compensate for that as the DIDerivedType requires
1527 // un-reversed offsets.
1528 if (CGM
.getDataLayout().isBigEndian())
1529 Offset
= BitFieldInfo
.StorageSize
- BitFieldInfo
.Size
- Offset
;
1530 uint64_t OffsetInBits
= StorageOffsetInBits
+ Offset
;
1531 llvm::DINode::DIFlags Flags
= getAccessFlag(BitFieldDecl
->getAccess(), RD
);
1532 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(BitFieldDecl
);
1533 return DBuilder
.createBitFieldMemberType(
1534 RecordTy
, Name
, File
, Line
, SizeInBits
, OffsetInBits
, StorageOffsetInBits
,
1535 Flags
, DebugType
, Annotations
);
1538 llvm::DIDerivedType
*CGDebugInfo::createBitFieldSeparatorIfNeeded(
1539 const FieldDecl
*BitFieldDecl
, const llvm::DIDerivedType
*BitFieldDI
,
1540 llvm::ArrayRef
<llvm::Metadata
*> PreviousFieldsDI
, const RecordDecl
*RD
) {
1542 if (!CGM
.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())
1546 Add a *single* zero-bitfield separator between two non-zero bitfields
1547 separated by one or more zero-bitfields. This is used to distinguish between
1548 structures such the ones below, where the memory layout is the same, but how
1549 the ABI assigns fields to registers differs.
1553 char a : 8; // on amdgpu, passed on v4
1560 char a : 8; // on amdgpu, passed on v4
1563 char x : 8; // passed on v5
1567 if (PreviousFieldsDI
.empty())
1570 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1571 auto *PreviousMDEntry
=
1572 PreviousFieldsDI
.empty() ? nullptr : PreviousFieldsDI
.back();
1573 auto *PreviousMDField
=
1574 dyn_cast_or_null
<llvm::DIDerivedType
>(PreviousMDEntry
);
1575 if (!PreviousMDField
|| !PreviousMDField
->isBitField() ||
1576 PreviousMDField
->getSizeInBits() == 0)
1579 auto PreviousBitfield
= RD
->field_begin();
1580 std::advance(PreviousBitfield
, BitFieldDecl
->getFieldIndex() - 1);
1582 assert(PreviousBitfield
->isBitField());
1584 ASTContext
&Context
= CGM
.getContext();
1585 if (!PreviousBitfield
->isZeroLengthBitField(Context
))
1588 QualType Ty
= PreviousBitfield
->getType();
1589 SourceLocation Loc
= PreviousBitfield
->getLocation();
1590 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1591 llvm::DIType
*DebugType
= getOrCreateType(Ty
, VUnit
);
1592 llvm::DIScope
*RecordTy
= BitFieldDI
->getScope();
1594 llvm::DIFile
*File
= getOrCreateFile(Loc
);
1595 unsigned Line
= getLineNumber(Loc
);
1597 uint64_t StorageOffsetInBits
=
1598 cast
<llvm::ConstantInt
>(BitFieldDI
->getStorageOffsetInBits())
1601 llvm::DINode::DIFlags Flags
=
1602 getAccessFlag(PreviousBitfield
->getAccess(), RD
);
1603 llvm::DINodeArray Annotations
=
1604 CollectBTFDeclTagAnnotations(*PreviousBitfield
);
1605 return DBuilder
.createBitFieldMemberType(
1606 RecordTy
, "", File
, Line
, 0, StorageOffsetInBits
, StorageOffsetInBits
,
1607 Flags
, DebugType
, Annotations
);
1610 llvm::DIType
*CGDebugInfo::createFieldType(
1611 StringRef name
, QualType type
, SourceLocation loc
, AccessSpecifier AS
,
1612 uint64_t offsetInBits
, uint32_t AlignInBits
, llvm::DIFile
*tunit
,
1613 llvm::DIScope
*scope
, const RecordDecl
*RD
, llvm::DINodeArray Annotations
) {
1614 llvm::DIType
*debugType
= getOrCreateType(type
, tunit
);
1616 // Get the location for the field.
1617 llvm::DIFile
*file
= getOrCreateFile(loc
);
1618 const unsigned line
= getLineNumber(loc
.isValid() ? loc
: CurLoc
);
1620 uint64_t SizeInBits
= 0;
1621 auto Align
= AlignInBits
;
1622 if (!type
->isIncompleteArrayType()) {
1623 TypeInfo TI
= CGM
.getContext().getTypeInfo(type
);
1624 SizeInBits
= TI
.Width
;
1626 Align
= getTypeAlignIfRequired(type
, CGM
.getContext());
1629 llvm::DINode::DIFlags flags
= getAccessFlag(AS
, RD
);
1630 return DBuilder
.createMemberType(scope
, name
, file
, line
, SizeInBits
, Align
,
1631 offsetInBits
, flags
, debugType
, Annotations
);
1634 void CGDebugInfo::CollectRecordLambdaFields(
1635 const CXXRecordDecl
*CXXDecl
, SmallVectorImpl
<llvm::Metadata
*> &elements
,
1636 llvm::DIType
*RecordTy
) {
1637 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1638 // has the name and the location of the variable so we should iterate over
1639 // both concurrently.
1640 const ASTRecordLayout
&layout
= CGM
.getContext().getASTRecordLayout(CXXDecl
);
1641 RecordDecl::field_iterator Field
= CXXDecl
->field_begin();
1642 unsigned fieldno
= 0;
1643 for (CXXRecordDecl::capture_const_iterator I
= CXXDecl
->captures_begin(),
1644 E
= CXXDecl
->captures_end();
1645 I
!= E
; ++I
, ++Field
, ++fieldno
) {
1646 const LambdaCapture
&C
= *I
;
1647 if (C
.capturesVariable()) {
1648 SourceLocation Loc
= C
.getLocation();
1649 assert(!Field
->isBitField() && "lambdas don't have bitfield members!");
1650 ValueDecl
*V
= C
.getCapturedVar();
1651 StringRef VName
= V
->getName();
1652 llvm::DIFile
*VUnit
= getOrCreateFile(Loc
);
1653 auto Align
= getDeclAlignIfRequired(V
, CGM
.getContext());
1654 llvm::DIType
*FieldType
= createFieldType(
1655 VName
, Field
->getType(), Loc
, Field
->getAccess(),
1656 layout
.getFieldOffset(fieldno
), Align
, VUnit
, RecordTy
, CXXDecl
);
1657 elements
.push_back(FieldType
);
1658 } else if (C
.capturesThis()) {
1659 // TODO: Need to handle 'this' in some way by probably renaming the
1660 // this of the lambda class and having a field member of 'this' or
1661 // by using AT_object_pointer for the function and having that be
1662 // used as 'this' for semantic references.
1663 FieldDecl
*f
= *Field
;
1664 llvm::DIFile
*VUnit
= getOrCreateFile(f
->getLocation());
1665 QualType type
= f
->getType();
1666 StringRef ThisName
=
1667 CGM
.getCodeGenOpts().EmitCodeView
? "__this" : "this";
1668 llvm::DIType
*fieldType
= createFieldType(
1669 ThisName
, type
, f
->getLocation(), f
->getAccess(),
1670 layout
.getFieldOffset(fieldno
), VUnit
, RecordTy
, CXXDecl
);
1672 elements
.push_back(fieldType
);
1677 llvm::DIDerivedType
*
1678 CGDebugInfo::CreateRecordStaticField(const VarDecl
*Var
, llvm::DIType
*RecordTy
,
1679 const RecordDecl
*RD
) {
1680 // Create the descriptor for the static variable, with or without
1681 // constant initializers.
1682 Var
= Var
->getCanonicalDecl();
1683 llvm::DIFile
*VUnit
= getOrCreateFile(Var
->getLocation());
1684 llvm::DIType
*VTy
= getOrCreateType(Var
->getType(), VUnit
);
1686 unsigned LineNumber
= getLineNumber(Var
->getLocation());
1687 StringRef VName
= Var
->getName();
1689 // FIXME: to avoid complications with type merging we should
1690 // emit the constant on the definition instead of the declaration.
1691 llvm::Constant
*C
= nullptr;
1692 if (Var
->getInit()) {
1693 const APValue
*Value
= Var
->evaluateValue();
1696 C
= llvm::ConstantInt::get(CGM
.getLLVMContext(), Value
->getInt());
1697 if (Value
->isFloat())
1698 C
= llvm::ConstantFP::get(CGM
.getLLVMContext(), Value
->getFloat());
1702 llvm::DINode::DIFlags Flags
= getAccessFlag(Var
->getAccess(), RD
);
1703 auto Tag
= CGM
.getCodeGenOpts().DwarfVersion
>= 5
1704 ? llvm::dwarf::DW_TAG_variable
1705 : llvm::dwarf::DW_TAG_member
;
1706 auto Align
= getDeclAlignIfRequired(Var
, CGM
.getContext());
1707 llvm::DIDerivedType
*GV
= DBuilder
.createStaticMemberType(
1708 RecordTy
, VName
, VUnit
, LineNumber
, VTy
, Flags
, C
, Tag
, Align
);
1709 StaticDataMemberCache
[Var
->getCanonicalDecl()].reset(GV
);
1713 void CGDebugInfo::CollectRecordNormalField(
1714 const FieldDecl
*field
, uint64_t OffsetInBits
, llvm::DIFile
*tunit
,
1715 SmallVectorImpl
<llvm::Metadata
*> &elements
, llvm::DIType
*RecordTy
,
1716 const RecordDecl
*RD
) {
1717 StringRef name
= field
->getName();
1718 QualType type
= field
->getType();
1720 // Ignore unnamed fields unless they're anonymous structs/unions.
1721 if (name
.empty() && !type
->isRecordType())
1724 llvm::DIType
*FieldType
;
1725 if (field
->isBitField()) {
1726 llvm::DIDerivedType
*BitFieldType
;
1727 FieldType
= BitFieldType
= createBitFieldType(field
, RecordTy
, RD
);
1728 if (llvm::DIType
*Separator
=
1729 createBitFieldSeparatorIfNeeded(field
, BitFieldType
, elements
, RD
))
1730 elements
.push_back(Separator
);
1732 auto Align
= getDeclAlignIfRequired(field
, CGM
.getContext());
1733 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(field
);
1735 createFieldType(name
, type
, field
->getLocation(), field
->getAccess(),
1736 OffsetInBits
, Align
, tunit
, RecordTy
, RD
, Annotations
);
1739 elements
.push_back(FieldType
);
1742 void CGDebugInfo::CollectRecordNestedType(
1743 const TypeDecl
*TD
, SmallVectorImpl
<llvm::Metadata
*> &elements
) {
1744 QualType Ty
= CGM
.getContext().getTypeDeclType(TD
);
1745 // Injected class names are not considered nested records.
1746 if (isa
<InjectedClassNameType
>(Ty
))
1748 SourceLocation Loc
= TD
->getLocation();
1749 llvm::DIType
*nestedType
= getOrCreateType(Ty
, getOrCreateFile(Loc
));
1750 elements
.push_back(nestedType
);
1753 void CGDebugInfo::CollectRecordFields(
1754 const RecordDecl
*record
, llvm::DIFile
*tunit
,
1755 SmallVectorImpl
<llvm::Metadata
*> &elements
,
1756 llvm::DICompositeType
*RecordTy
) {
1757 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(record
);
1759 if (CXXDecl
&& CXXDecl
->isLambda())
1760 CollectRecordLambdaFields(CXXDecl
, elements
, RecordTy
);
1762 const ASTRecordLayout
&layout
= CGM
.getContext().getASTRecordLayout(record
);
1764 // Field number for non-static fields.
1765 unsigned fieldNo
= 0;
1767 // Static and non-static members should appear in the same order as
1768 // the corresponding declarations in the source program.
1769 for (const auto *I
: record
->decls())
1770 if (const auto *V
= dyn_cast
<VarDecl
>(I
)) {
1771 if (V
->hasAttr
<NoDebugAttr
>())
1774 // Skip variable template specializations when emitting CodeView. MSVC
1775 // doesn't emit them.
1776 if (CGM
.getCodeGenOpts().EmitCodeView
&&
1777 isa
<VarTemplateSpecializationDecl
>(V
))
1780 if (isa
<VarTemplatePartialSpecializationDecl
>(V
))
1783 // Reuse the existing static member declaration if one exists
1784 auto MI
= StaticDataMemberCache
.find(V
->getCanonicalDecl());
1785 if (MI
!= StaticDataMemberCache
.end()) {
1786 assert(MI
->second
&&
1787 "Static data member declaration should still exist");
1788 elements
.push_back(MI
->second
);
1790 auto Field
= CreateRecordStaticField(V
, RecordTy
, record
);
1791 elements
.push_back(Field
);
1793 } else if (const auto *field
= dyn_cast
<FieldDecl
>(I
)) {
1794 CollectRecordNormalField(field
, layout
.getFieldOffset(fieldNo
), tunit
,
1795 elements
, RecordTy
, record
);
1797 // Bump field number for next field.
1799 } else if (CGM
.getCodeGenOpts().EmitCodeView
) {
1800 // Debug info for nested types is included in the member list only for
1802 if (const auto *nestedType
= dyn_cast
<TypeDecl
>(I
)) {
1803 // MSVC doesn't generate nested type for anonymous struct/union.
1804 if (isa
<RecordDecl
>(I
) &&
1805 cast
<RecordDecl
>(I
)->isAnonymousStructOrUnion())
1807 if (!nestedType
->isImplicit() &&
1808 nestedType
->getDeclContext() == record
)
1809 CollectRecordNestedType(nestedType
, elements
);
1815 llvm::DISubroutineType
*
1816 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl
*Method
,
1817 llvm::DIFile
*Unit
) {
1818 const FunctionProtoType
*Func
= Method
->getType()->getAs
<FunctionProtoType
>();
1819 if (Method
->isStatic())
1820 return cast_or_null
<llvm::DISubroutineType
>(
1821 getOrCreateType(QualType(Func
, 0), Unit
));
1822 return getOrCreateInstanceMethodType(Method
->getThisType(), Func
, Unit
);
1825 llvm::DISubroutineType
*CGDebugInfo::getOrCreateInstanceMethodType(
1826 QualType ThisPtr
, const FunctionProtoType
*Func
, llvm::DIFile
*Unit
) {
1827 FunctionProtoType::ExtProtoInfo EPI
= Func
->getExtProtoInfo();
1828 Qualifiers
&Qc
= EPI
.TypeQuals
;
1830 Qc
.removeVolatile();
1831 Qc
.removeRestrict();
1832 Qc
.removeUnaligned();
1833 // Keep the removed qualifiers in sync with
1834 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
1835 // On a 'real' member function type, these qualifiers are carried on the type
1836 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
1837 // tags around them. (But, in the raw function types with qualifiers, they have
1838 // to use wrapper types.)
1840 // Add "this" pointer.
1841 const auto *OriginalFunc
= cast
<llvm::DISubroutineType
>(
1842 getOrCreateType(CGM
.getContext().getFunctionType(
1843 Func
->getReturnType(), Func
->getParamTypes(), EPI
),
1845 llvm::DITypeRefArray Args
= OriginalFunc
->getTypeArray();
1846 assert(Args
.size() && "Invalid number of arguments!");
1848 SmallVector
<llvm::Metadata
*, 16> Elts
;
1850 // First element is always return type. For 'void' functions it is NULL.
1851 Elts
.push_back(Args
[0]);
1853 // "this" pointer is always first argument.
1854 const CXXRecordDecl
*RD
= ThisPtr
->getPointeeCXXRecordDecl();
1855 if (isa
<ClassTemplateSpecializationDecl
>(RD
)) {
1856 // Create pointer type directly in this case.
1857 const PointerType
*ThisPtrTy
= cast
<PointerType
>(ThisPtr
);
1858 uint64_t Size
= CGM
.getContext().getTypeSize(ThisPtrTy
);
1859 auto Align
= getTypeAlignIfRequired(ThisPtrTy
, CGM
.getContext());
1860 llvm::DIType
*PointeeType
=
1861 getOrCreateType(ThisPtrTy
->getPointeeType(), Unit
);
1862 llvm::DIType
*ThisPtrType
=
1863 DBuilder
.createPointerType(PointeeType
, Size
, Align
);
1864 TypeCache
[ThisPtr
.getAsOpaquePtr()].reset(ThisPtrType
);
1865 // TODO: This and the artificial type below are misleading, the
1866 // types aren't artificial the argument is, but the current
1867 // metadata doesn't represent that.
1868 ThisPtrType
= DBuilder
.createObjectPointerType(ThisPtrType
);
1869 Elts
.push_back(ThisPtrType
);
1871 llvm::DIType
*ThisPtrType
= getOrCreateType(ThisPtr
, Unit
);
1872 TypeCache
[ThisPtr
.getAsOpaquePtr()].reset(ThisPtrType
);
1873 ThisPtrType
= DBuilder
.createObjectPointerType(ThisPtrType
);
1874 Elts
.push_back(ThisPtrType
);
1877 // Copy rest of the arguments.
1878 for (unsigned i
= 1, e
= Args
.size(); i
!= e
; ++i
)
1879 Elts
.push_back(Args
[i
]);
1881 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(Elts
);
1883 return DBuilder
.createSubroutineType(EltTypeArray
, OriginalFunc
->getFlags(),
1884 getDwarfCC(Func
->getCallConv()));
1887 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1888 /// inside a function.
1889 static bool isFunctionLocalClass(const CXXRecordDecl
*RD
) {
1890 if (const auto *NRD
= dyn_cast
<CXXRecordDecl
>(RD
->getDeclContext()))
1891 return isFunctionLocalClass(NRD
);
1892 if (isa
<FunctionDecl
>(RD
->getDeclContext()))
1897 llvm::DISubprogram
*CGDebugInfo::CreateCXXMemberFunction(
1898 const CXXMethodDecl
*Method
, llvm::DIFile
*Unit
, llvm::DIType
*RecordTy
) {
1900 isa
<CXXConstructorDecl
>(Method
) || isa
<CXXDestructorDecl
>(Method
);
1902 StringRef MethodName
= getFunctionName(Method
);
1903 llvm::DISubroutineType
*MethodTy
= getOrCreateMethodType(Method
, Unit
);
1905 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1906 // make sense to give a single ctor/dtor a linkage name.
1907 StringRef MethodLinkageName
;
1908 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1909 // property to use here. It may've been intended to model "is non-external
1910 // type" but misses cases of non-function-local but non-external classes such
1911 // as those in anonymous namespaces as well as the reverse - external types
1912 // that are function local, such as those in (non-local) inline functions.
1913 if (!IsCtorOrDtor
&& !isFunctionLocalClass(Method
->getParent()))
1914 MethodLinkageName
= CGM
.getMangledName(Method
);
1916 // Get the location for the method.
1917 llvm::DIFile
*MethodDefUnit
= nullptr;
1918 unsigned MethodLine
= 0;
1919 if (!Method
->isImplicit()) {
1920 MethodDefUnit
= getOrCreateFile(Method
->getLocation());
1921 MethodLine
= getLineNumber(Method
->getLocation());
1924 // Collect virtual method info.
1925 llvm::DIType
*ContainingType
= nullptr;
1926 unsigned VIndex
= 0;
1927 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
1928 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
1929 int ThisAdjustment
= 0;
1931 if (VTableContextBase::hasVtableSlot(Method
)) {
1932 if (Method
->isPureVirtual())
1933 SPFlags
|= llvm::DISubprogram::SPFlagPureVirtual
;
1935 SPFlags
|= llvm::DISubprogram::SPFlagVirtual
;
1937 if (CGM
.getTarget().getCXXABI().isItaniumFamily()) {
1938 // It doesn't make sense to give a virtual destructor a vtable index,
1939 // since a single destructor has two entries in the vtable.
1940 if (!isa
<CXXDestructorDecl
>(Method
))
1941 VIndex
= CGM
.getItaniumVTableContext().getMethodVTableIndex(Method
);
1943 // Emit MS ABI vftable information. There is only one entry for the
1945 const auto *DD
= dyn_cast
<CXXDestructorDecl
>(Method
);
1946 GlobalDecl GD
= DD
? GlobalDecl(DD
, Dtor_Deleting
) : GlobalDecl(Method
);
1947 MethodVFTableLocation ML
=
1948 CGM
.getMicrosoftVTableContext().getMethodVFTableLocation(GD
);
1951 // CodeView only records the vftable offset in the class that introduces
1952 // the virtual method. This is possible because, unlike Itanium, the MS
1953 // C++ ABI does not include all virtual methods from non-primary bases in
1954 // the vtable for the most derived class. For example, if C inherits from
1955 // A and B, C's primary vftable will not include B's virtual methods.
1956 if (Method
->size_overridden_methods() == 0)
1957 Flags
|= llvm::DINode::FlagIntroducedVirtual
;
1959 // The 'this' adjustment accounts for both the virtual and non-virtual
1960 // portions of the adjustment. Presumably the debugger only uses it when
1961 // it knows the dynamic type of an object.
1962 ThisAdjustment
= CGM
.getCXXABI()
1963 .getVirtualFunctionPrologueThisAdjustment(GD
)
1966 ContainingType
= RecordTy
;
1969 if (Method
->getCanonicalDecl()->isDeleted())
1970 SPFlags
|= llvm::DISubprogram::SPFlagDeleted
;
1972 if (Method
->isNoReturn())
1973 Flags
|= llvm::DINode::FlagNoReturn
;
1975 if (Method
->isStatic())
1976 Flags
|= llvm::DINode::FlagStaticMember
;
1977 if (Method
->isImplicit())
1978 Flags
|= llvm::DINode::FlagArtificial
;
1979 Flags
|= getAccessFlag(Method
->getAccess(), Method
->getParent());
1980 if (const auto *CXXC
= dyn_cast
<CXXConstructorDecl
>(Method
)) {
1981 if (CXXC
->isExplicit())
1982 Flags
|= llvm::DINode::FlagExplicit
;
1983 } else if (const auto *CXXC
= dyn_cast
<CXXConversionDecl
>(Method
)) {
1984 if (CXXC
->isExplicit())
1985 Flags
|= llvm::DINode::FlagExplicit
;
1987 if (Method
->hasPrototype())
1988 Flags
|= llvm::DINode::FlagPrototyped
;
1989 if (Method
->getRefQualifier() == RQ_LValue
)
1990 Flags
|= llvm::DINode::FlagLValueReference
;
1991 if (Method
->getRefQualifier() == RQ_RValue
)
1992 Flags
|= llvm::DINode::FlagRValueReference
;
1993 if (!Method
->isExternallyVisible())
1994 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
1995 if (CGM
.getLangOpts().Optimize
)
1996 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
1998 // In this debug mode, emit type info for a class when its constructor type
2000 if (DebugKind
== llvm::codegenoptions::DebugInfoConstructor
)
2001 if (const CXXConstructorDecl
*CD
= dyn_cast
<CXXConstructorDecl
>(Method
))
2002 completeUnusedClass(*CD
->getParent());
2004 llvm::DINodeArray TParamsArray
= CollectFunctionTemplateParams(Method
, Unit
);
2005 llvm::DISubprogram
*SP
= DBuilder
.createMethod(
2006 RecordTy
, MethodName
, MethodLinkageName
, MethodDefUnit
, MethodLine
,
2007 MethodTy
, VIndex
, ThisAdjustment
, ContainingType
, Flags
, SPFlags
,
2008 TParamsArray
.get());
2010 SPCache
[Method
->getCanonicalDecl()].reset(SP
);
2015 void CGDebugInfo::CollectCXXMemberFunctions(
2016 const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2017 SmallVectorImpl
<llvm::Metadata
*> &EltTys
, llvm::DIType
*RecordTy
) {
2019 // Since we want more than just the individual member decls if we
2020 // have templated functions iterate over every declaration to gather
2022 for (const auto *I
: RD
->decls()) {
2023 const auto *Method
= dyn_cast
<CXXMethodDecl
>(I
);
2024 // If the member is implicit, don't add it to the member list. This avoids
2025 // the member being added to type units by LLVM, while still allowing it
2026 // to be emitted into the type declaration/reference inside the compile
2028 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2029 // FIXME: Handle Using(Shadow?)Decls here to create
2030 // DW_TAG_imported_declarations inside the class for base decls brought into
2031 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2032 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2034 if (!Method
|| Method
->isImplicit() || Method
->hasAttr
<NoDebugAttr
>())
2037 if (Method
->getType()->castAs
<FunctionProtoType
>()->getContainedAutoType())
2040 // Reuse the existing member function declaration if it exists.
2041 // It may be associated with the declaration of the type & should be
2042 // reused as we're building the definition.
2044 // This situation can arise in the vtable-based debug info reduction where
2045 // implicit members are emitted in a non-vtable TU.
2046 auto MI
= SPCache
.find(Method
->getCanonicalDecl());
2047 EltTys
.push_back(MI
== SPCache
.end()
2048 ? CreateCXXMemberFunction(Method
, Unit
, RecordTy
)
2049 : static_cast<llvm::Metadata
*>(MI
->second
));
2053 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2054 SmallVectorImpl
<llvm::Metadata
*> &EltTys
,
2055 llvm::DIType
*RecordTy
) {
2056 llvm::DenseSet
<CanonicalDeclPtr
<const CXXRecordDecl
>> SeenTypes
;
2057 CollectCXXBasesAux(RD
, Unit
, EltTys
, RecordTy
, RD
->bases(), SeenTypes
,
2058 llvm::DINode::FlagZero
);
2060 // If we are generating CodeView debug info, we also need to emit records for
2061 // indirect virtual base classes.
2062 if (CGM
.getCodeGenOpts().EmitCodeView
) {
2063 CollectCXXBasesAux(RD
, Unit
, EltTys
, RecordTy
, RD
->vbases(), SeenTypes
,
2064 llvm::DINode::FlagIndirectVirtualBase
);
2068 void CGDebugInfo::CollectCXXBasesAux(
2069 const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2070 SmallVectorImpl
<llvm::Metadata
*> &EltTys
, llvm::DIType
*RecordTy
,
2071 const CXXRecordDecl::base_class_const_range
&Bases
,
2072 llvm::DenseSet
<CanonicalDeclPtr
<const CXXRecordDecl
>> &SeenTypes
,
2073 llvm::DINode::DIFlags StartingFlags
) {
2074 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
2075 for (const auto &BI
: Bases
) {
2077 cast
<CXXRecordDecl
>(BI
.getType()->castAs
<RecordType
>()->getDecl());
2078 if (!SeenTypes
.insert(Base
).second
)
2080 auto *BaseTy
= getOrCreateType(BI
.getType(), Unit
);
2081 llvm::DINode::DIFlags BFlags
= StartingFlags
;
2082 uint64_t BaseOffset
;
2083 uint32_t VBPtrOffset
= 0;
2085 if (BI
.isVirtual()) {
2086 if (CGM
.getTarget().getCXXABI().isItaniumFamily()) {
2087 // virtual base offset offset is -ve. The code generator emits dwarf
2088 // expression where it expects +ve number.
2089 BaseOffset
= 0 - CGM
.getItaniumVTableContext()
2090 .getVirtualBaseOffsetOffset(RD
, Base
)
2093 // In the MS ABI, store the vbtable offset, which is analogous to the
2094 // vbase offset offset in Itanium.
2096 4 * CGM
.getMicrosoftVTableContext().getVBTableIndex(RD
, Base
);
2097 VBPtrOffset
= CGM
.getContext()
2098 .getASTRecordLayout(RD
)
2102 BFlags
|= llvm::DINode::FlagVirtual
;
2104 BaseOffset
= CGM
.getContext().toBits(RL
.getBaseClassOffset(Base
));
2105 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2106 // BI->isVirtual() and bits when not.
2108 BFlags
|= getAccessFlag(BI
.getAccessSpecifier(), RD
);
2109 llvm::DIType
*DTy
= DBuilder
.createInheritance(RecordTy
, BaseTy
, BaseOffset
,
2110 VBPtrOffset
, BFlags
);
2111 EltTys
.push_back(DTy
);
2116 CGDebugInfo::CollectTemplateParams(std::optional
<TemplateArgs
> OArgs
,
2117 llvm::DIFile
*Unit
) {
2119 return llvm::DINodeArray();
2120 TemplateArgs
&Args
= *OArgs
;
2121 SmallVector
<llvm::Metadata
*, 16> TemplateParams
;
2122 for (unsigned i
= 0, e
= Args
.Args
.size(); i
!= e
; ++i
) {
2123 const TemplateArgument
&TA
= Args
.Args
[i
];
2125 const bool defaultParameter
= TA
.getIsDefaulted();
2127 Name
= Args
.TList
->getParam(i
)->getName();
2129 switch (TA
.getKind()) {
2130 case TemplateArgument::Type
: {
2131 llvm::DIType
*TTy
= getOrCreateType(TA
.getAsType(), Unit
);
2132 TemplateParams
.push_back(DBuilder
.createTemplateTypeParameter(
2133 TheCU
, Name
, TTy
, defaultParameter
));
2136 case TemplateArgument::Integral
: {
2137 llvm::DIType
*TTy
= getOrCreateType(TA
.getIntegralType(), Unit
);
2138 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2139 TheCU
, Name
, TTy
, defaultParameter
,
2140 llvm::ConstantInt::get(CGM
.getLLVMContext(), TA
.getAsIntegral())));
2142 case TemplateArgument::Declaration
: {
2143 const ValueDecl
*D
= TA
.getAsDecl();
2144 QualType T
= TA
.getParamTypeForDecl().getDesugaredType(CGM
.getContext());
2145 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2146 llvm::Constant
*V
= nullptr;
2147 // Skip retrieve the value if that template parameter has cuda device
2148 // attribute, i.e. that value is not available at the host side.
2149 if (!CGM
.getLangOpts().CUDA
|| CGM
.getLangOpts().CUDAIsDevice
||
2150 !D
->hasAttr
<CUDADeviceAttr
>()) {
2151 // Variable pointer template parameters have a value that is the address
2153 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
2154 V
= CGM
.GetAddrOfGlobalVar(VD
);
2155 // Member function pointers have special support for building them,
2156 // though this is currently unsupported in LLVM CodeGen.
2157 else if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(D
);
2158 MD
&& MD
->isImplicitObjectMemberFunction())
2159 V
= CGM
.getCXXABI().EmitMemberFunctionPointer(MD
);
2160 else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
2161 V
= CGM
.GetAddrOfFunction(FD
);
2162 // Member data pointers have special handling too to compute the fixed
2163 // offset within the object.
2164 else if (const auto *MPT
=
2165 dyn_cast
<MemberPointerType
>(T
.getTypePtr())) {
2166 // These five lines (& possibly the above member function pointer
2167 // handling) might be able to be refactored to use similar code in
2168 // CodeGenModule::getMemberPointerConstant
2169 uint64_t fieldOffset
= CGM
.getContext().getFieldOffset(D
);
2171 CGM
.getContext().toCharUnitsFromBits((int64_t)fieldOffset
);
2172 V
= CGM
.getCXXABI().EmitMemberDataPointer(MPT
, chars
);
2173 } else if (const auto *GD
= dyn_cast
<MSGuidDecl
>(D
)) {
2174 V
= CGM
.GetAddrOfMSGuidDecl(GD
).getPointer();
2175 } else if (const auto *TPO
= dyn_cast
<TemplateParamObjectDecl
>(D
)) {
2176 if (T
->isRecordType())
2177 V
= ConstantEmitter(CGM
).emitAbstract(
2178 SourceLocation(), TPO
->getValue(), TPO
->getType());
2180 V
= CGM
.GetAddrOfTemplateParamObject(TPO
).getPointer();
2182 assert(V
&& "Failed to find template parameter pointer");
2183 V
= V
->stripPointerCasts();
2185 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2186 TheCU
, Name
, TTy
, defaultParameter
, cast_or_null
<llvm::Constant
>(V
)));
2188 case TemplateArgument::NullPtr
: {
2189 QualType T
= TA
.getNullPtrType();
2190 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2191 llvm::Constant
*V
= nullptr;
2192 // Special case member data pointer null values since they're actually -1
2194 if (const auto *MPT
= dyn_cast
<MemberPointerType
>(T
.getTypePtr()))
2195 // But treat member function pointers as simple zero integers because
2196 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2197 // CodeGen grows handling for values of non-null member function
2198 // pointers then perhaps we could remove this special case and rely on
2199 // EmitNullMemberPointer for member function pointers.
2200 if (MPT
->isMemberDataPointer())
2201 V
= CGM
.getCXXABI().EmitNullMemberPointer(MPT
);
2203 V
= llvm::ConstantInt::get(CGM
.Int8Ty
, 0);
2204 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2205 TheCU
, Name
, TTy
, defaultParameter
, V
));
2207 case TemplateArgument::StructuralValue
: {
2208 QualType T
= TA
.getStructuralValueType();
2209 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2210 llvm::Constant
*V
= ConstantEmitter(CGM
).emitAbstract(
2211 SourceLocation(), TA
.getAsStructuralValue(), T
);
2212 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2213 TheCU
, Name
, TTy
, defaultParameter
, V
));
2215 case TemplateArgument::Template
: {
2216 std::string QualName
;
2217 llvm::raw_string_ostream
OS(QualName
);
2218 TA
.getAsTemplate().getAsTemplateDecl()->printQualifiedName(
2219 OS
, getPrintingPolicy());
2220 TemplateParams
.push_back(DBuilder
.createTemplateTemplateParameter(
2221 TheCU
, Name
, nullptr, OS
.str(), defaultParameter
));
2224 case TemplateArgument::Pack
:
2225 TemplateParams
.push_back(DBuilder
.createTemplateParameterPack(
2226 TheCU
, Name
, nullptr,
2227 CollectTemplateParams({{nullptr, TA
.getPackAsArray()}}, Unit
)));
2229 case TemplateArgument::Expression
: {
2230 const Expr
*E
= TA
.getAsExpr();
2231 QualType T
= E
->getType();
2233 T
= CGM
.getContext().getLValueReferenceType(T
);
2234 llvm::Constant
*V
= ConstantEmitter(CGM
).emitAbstract(E
, T
);
2235 assert(V
&& "Expression in template argument isn't constant");
2236 llvm::DIType
*TTy
= getOrCreateType(T
, Unit
);
2237 TemplateParams
.push_back(DBuilder
.createTemplateValueParameter(
2238 TheCU
, Name
, TTy
, defaultParameter
, V
->stripPointerCasts()));
2240 // And the following should never occur:
2241 case TemplateArgument::TemplateExpansion
:
2242 case TemplateArgument::Null
:
2244 "These argument types shouldn't exist in concrete types");
2247 return DBuilder
.getOrCreateArray(TemplateParams
);
2250 std::optional
<CGDebugInfo::TemplateArgs
>
2251 CGDebugInfo::GetTemplateArgs(const FunctionDecl
*FD
) const {
2252 if (FD
->getTemplatedKind() ==
2253 FunctionDecl::TK_FunctionTemplateSpecialization
) {
2254 const TemplateParameterList
*TList
= FD
->getTemplateSpecializationInfo()
2256 ->getTemplateParameters();
2257 return {{TList
, FD
->getTemplateSpecializationArgs()->asArray()}};
2259 return std::nullopt
;
2261 std::optional
<CGDebugInfo::TemplateArgs
>
2262 CGDebugInfo::GetTemplateArgs(const VarDecl
*VD
) const {
2263 // Always get the full list of parameters, not just the ones from the
2264 // specialization. A partial specialization may have fewer parameters than
2265 // there are arguments.
2266 auto *TS
= dyn_cast
<VarTemplateSpecializationDecl
>(VD
);
2268 return std::nullopt
;
2269 VarTemplateDecl
*T
= TS
->getSpecializedTemplate();
2270 const TemplateParameterList
*TList
= T
->getTemplateParameters();
2271 auto TA
= TS
->getTemplateArgs().asArray();
2272 return {{TList
, TA
}};
2274 std::optional
<CGDebugInfo::TemplateArgs
>
2275 CGDebugInfo::GetTemplateArgs(const RecordDecl
*RD
) const {
2276 if (auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
2277 // Always get the full list of parameters, not just the ones from the
2278 // specialization. A partial specialization may have fewer parameters than
2279 // there are arguments.
2280 TemplateParameterList
*TPList
=
2281 TSpecial
->getSpecializedTemplate()->getTemplateParameters();
2282 const TemplateArgumentList
&TAList
= TSpecial
->getTemplateArgs();
2283 return {{TPList
, TAList
.asArray()}};
2285 return std::nullopt
;
2289 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl
*FD
,
2290 llvm::DIFile
*Unit
) {
2291 return CollectTemplateParams(GetTemplateArgs(FD
), Unit
);
2294 llvm::DINodeArray
CGDebugInfo::CollectVarTemplateParams(const VarDecl
*VL
,
2295 llvm::DIFile
*Unit
) {
2296 return CollectTemplateParams(GetTemplateArgs(VL
), Unit
);
2299 llvm::DINodeArray
CGDebugInfo::CollectCXXTemplateParams(const RecordDecl
*RD
,
2300 llvm::DIFile
*Unit
) {
2301 return CollectTemplateParams(GetTemplateArgs(RD
), Unit
);
2304 llvm::DINodeArray
CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl
*D
) {
2305 if (!D
->hasAttr
<BTFDeclTagAttr
>())
2308 SmallVector
<llvm::Metadata
*, 4> Annotations
;
2309 for (const auto *I
: D
->specific_attrs
<BTFDeclTagAttr
>()) {
2310 llvm::Metadata
*Ops
[2] = {
2311 llvm::MDString::get(CGM
.getLLVMContext(), StringRef("btf_decl_tag")),
2312 llvm::MDString::get(CGM
.getLLVMContext(), I
->getBTFDeclTag())};
2313 Annotations
.push_back(llvm::MDNode::get(CGM
.getLLVMContext(), Ops
));
2315 return DBuilder
.getOrCreateArray(Annotations
);
2318 llvm::DIType
*CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile
*Unit
) {
2320 return VTablePtrType
;
2322 ASTContext
&Context
= CGM
.getContext();
2325 llvm::Metadata
*STy
= getOrCreateType(Context
.IntTy
, Unit
);
2326 llvm::DITypeRefArray SElements
= DBuilder
.getOrCreateTypeArray(STy
);
2327 llvm::DIType
*SubTy
= DBuilder
.createSubroutineType(SElements
);
2328 unsigned Size
= Context
.getTypeSize(Context
.VoidPtrTy
);
2329 unsigned VtblPtrAddressSpace
= CGM
.getTarget().getVtblPtrAddressSpace();
2330 std::optional
<unsigned> DWARFAddressSpace
=
2331 CGM
.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace
);
2333 llvm::DIType
*vtbl_ptr_type
= DBuilder
.createPointerType(
2334 SubTy
, Size
, 0, DWARFAddressSpace
, "__vtbl_ptr_type");
2335 VTablePtrType
= DBuilder
.createPointerType(vtbl_ptr_type
, Size
);
2336 return VTablePtrType
;
2339 StringRef
CGDebugInfo::getVTableName(const CXXRecordDecl
*RD
) {
2340 // Copy the gdb compatible name on the side and use its reference.
2341 return internString("_vptr$", RD
->getNameAsString());
2344 StringRef
CGDebugInfo::getDynamicInitializerName(const VarDecl
*VD
,
2345 DynamicInitKind StubKind
,
2346 llvm::Function
*InitFn
) {
2347 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2349 if (!CGM
.getCodeGenOpts().EmitCodeView
||
2350 StubKind
== DynamicInitKind::GlobalArrayDestructor
)
2351 return InitFn
->getName();
2353 // Print the normal qualified name for the variable, then break off the last
2354 // NNS, and add the appropriate other text. Clang always prints the global
2355 // variable name without template arguments, so we can use rsplit("::") and
2356 // then recombine the pieces.
2357 SmallString
<128> QualifiedGV
;
2361 llvm::raw_svector_ostream
OS(QualifiedGV
);
2362 VD
->printQualifiedName(OS
, getPrintingPolicy());
2363 std::tie(Quals
, GVName
) = OS
.str().rsplit("::");
2365 std::swap(Quals
, GVName
);
2368 SmallString
<128> InitName
;
2369 llvm::raw_svector_ostream
OS(InitName
);
2371 OS
<< Quals
<< "::";
2374 case DynamicInitKind::NoStub
:
2375 case DynamicInitKind::GlobalArrayDestructor
:
2376 llvm_unreachable("not an initializer");
2377 case DynamicInitKind::Initializer
:
2378 OS
<< "`dynamic initializer for '";
2380 case DynamicInitKind::AtExit
:
2381 OS
<< "`dynamic atexit destructor for '";
2387 // Add any template specialization args.
2388 if (const auto *VTpl
= dyn_cast
<VarTemplateSpecializationDecl
>(VD
)) {
2389 printTemplateArgumentList(OS
, VTpl
->getTemplateArgs().asArray(),
2390 getPrintingPolicy());
2395 return internString(OS
.str());
2398 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl
*RD
, llvm::DIFile
*Unit
,
2399 SmallVectorImpl
<llvm::Metadata
*> &EltTys
) {
2400 // If this class is not dynamic then there is not any vtable info to collect.
2401 if (!RD
->isDynamicClass())
2404 // Don't emit any vtable shape or vptr info if this class doesn't have an
2405 // extendable vfptr. This can happen if the class doesn't have virtual
2406 // methods, or in the MS ABI if those virtual methods only come from virtually
2408 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
2409 if (!RL
.hasExtendableVFPtr())
2412 // CodeView needs to know how large the vtable of every dynamic class is, so
2413 // emit a special named pointer type into the element list. The vptr type
2414 // points to this type as well.
2415 llvm::DIType
*VPtrTy
= nullptr;
2416 bool NeedVTableShape
= CGM
.getCodeGenOpts().EmitCodeView
&&
2417 CGM
.getTarget().getCXXABI().isMicrosoft();
2418 if (NeedVTableShape
) {
2420 CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
2421 const VTableLayout
&VFTLayout
=
2422 CGM
.getMicrosoftVTableContext().getVFTableLayout(RD
, CharUnits::Zero());
2423 unsigned VSlotCount
=
2424 VFTLayout
.vtable_components().size() - CGM
.getLangOpts().RTTIData
;
2425 unsigned VTableWidth
= PtrWidth
* VSlotCount
;
2426 unsigned VtblPtrAddressSpace
= CGM
.getTarget().getVtblPtrAddressSpace();
2427 std::optional
<unsigned> DWARFAddressSpace
=
2428 CGM
.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace
);
2430 // Create a very wide void* type and insert it directly in the element list.
2431 llvm::DIType
*VTableType
= DBuilder
.createPointerType(
2432 nullptr, VTableWidth
, 0, DWARFAddressSpace
, "__vtbl_ptr_type");
2433 EltTys
.push_back(VTableType
);
2435 // The vptr is a pointer to this special vtable type.
2436 VPtrTy
= DBuilder
.createPointerType(VTableType
, PtrWidth
);
2439 // If there is a primary base then the artificial vptr member lives there.
2440 if (RL
.getPrimaryBase())
2444 VPtrTy
= getOrCreateVTablePtrType(Unit
);
2446 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
2447 llvm::DIType
*VPtrMember
=
2448 DBuilder
.createMemberType(Unit
, getVTableName(RD
), Unit
, 0, Size
, 0, 0,
2449 llvm::DINode::FlagArtificial
, VPtrTy
);
2450 EltTys
.push_back(VPtrMember
);
2453 llvm::DIType
*CGDebugInfo::getOrCreateRecordType(QualType RTy
,
2454 SourceLocation Loc
) {
2455 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
2456 llvm::DIType
*T
= getOrCreateType(RTy
, getOrCreateFile(Loc
));
2460 llvm::DIType
*CGDebugInfo::getOrCreateInterfaceType(QualType D
,
2461 SourceLocation Loc
) {
2462 return getOrCreateStandaloneType(D
, Loc
);
2465 llvm::DIType
*CGDebugInfo::getOrCreateStandaloneType(QualType D
,
2466 SourceLocation Loc
) {
2467 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
2468 assert(!D
.isNull() && "null type");
2469 llvm::DIType
*T
= getOrCreateType(D
, getOrCreateFile(Loc
));
2470 assert(T
&& "could not create debug info for type");
2472 RetainedTypes
.push_back(D
.getAsOpaquePtr());
2476 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::CallBase
*CI
,
2477 QualType AllocatedTy
,
2478 SourceLocation Loc
) {
2479 if (CGM
.getCodeGenOpts().getDebugInfo() <=
2480 llvm::codegenoptions::DebugLineTablesOnly
)
2483 if (AllocatedTy
->isVoidType())
2484 node
= llvm::MDNode::get(CGM
.getLLVMContext(), std::nullopt
);
2486 node
= getOrCreateType(AllocatedTy
, getOrCreateFile(Loc
));
2488 CI
->setMetadata("heapallocsite", node
);
2491 void CGDebugInfo::completeType(const EnumDecl
*ED
) {
2492 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
2494 QualType Ty
= CGM
.getContext().getEnumType(ED
);
2495 void *TyPtr
= Ty
.getAsOpaquePtr();
2496 auto I
= TypeCache
.find(TyPtr
);
2497 if (I
== TypeCache
.end() || !cast
<llvm::DIType
>(I
->second
)->isForwardDecl())
2499 llvm::DIType
*Res
= CreateTypeDefinition(Ty
->castAs
<EnumType
>());
2500 assert(!Res
->isForwardDecl());
2501 TypeCache
[TyPtr
].reset(Res
);
2504 void CGDebugInfo::completeType(const RecordDecl
*RD
) {
2505 if (DebugKind
> llvm::codegenoptions::LimitedDebugInfo
||
2506 !CGM
.getLangOpts().CPlusPlus
)
2507 completeRequiredType(RD
);
2510 /// Return true if the class or any of its methods are marked dllimport.
2511 static bool isClassOrMethodDLLImport(const CXXRecordDecl
*RD
) {
2512 if (RD
->hasAttr
<DLLImportAttr
>())
2514 for (const CXXMethodDecl
*MD
: RD
->methods())
2515 if (MD
->hasAttr
<DLLImportAttr
>())
2520 /// Does a type definition exist in an imported clang module?
2521 static bool isDefinedInClangModule(const RecordDecl
*RD
) {
2522 // Only definitions that where imported from an AST file come from a module.
2523 if (!RD
|| !RD
->isFromASTFile())
2525 // Anonymous entities cannot be addressed. Treat them as not from module.
2526 if (!RD
->isExternallyVisible() && RD
->getName().empty())
2528 if (auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
)) {
2529 if (!CXXDecl
->isCompleteDefinition())
2531 // Check wether RD is a template.
2532 auto TemplateKind
= CXXDecl
->getTemplateSpecializationKind();
2533 if (TemplateKind
!= TSK_Undeclared
) {
2534 // Unfortunately getOwningModule() isn't accurate enough to find the
2535 // owning module of a ClassTemplateSpecializationDecl that is inside a
2536 // namespace spanning multiple modules.
2537 bool Explicit
= false;
2538 if (auto *TD
= dyn_cast
<ClassTemplateSpecializationDecl
>(CXXDecl
))
2539 Explicit
= TD
->isExplicitInstantiationOrSpecialization();
2540 if (!Explicit
&& CXXDecl
->getEnclosingNamespaceContext())
2542 // This is a template, check the origin of the first member.
2543 if (CXXDecl
->field_begin() == CXXDecl
->field_end())
2544 return TemplateKind
== TSK_ExplicitInstantiationDeclaration
;
2545 if (!CXXDecl
->field_begin()->isFromASTFile())
2552 void CGDebugInfo::completeClassData(const RecordDecl
*RD
) {
2553 if (auto *CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
2554 if (CXXRD
->isDynamicClass() &&
2555 CGM
.getVTableLinkage(CXXRD
) ==
2556 llvm::GlobalValue::AvailableExternallyLinkage
&&
2557 !isClassOrMethodDLLImport(CXXRD
))
2560 if (DebugTypeExtRefs
&& isDefinedInClangModule(RD
->getDefinition()))
2566 void CGDebugInfo::completeClass(const RecordDecl
*RD
) {
2567 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
2569 QualType Ty
= CGM
.getContext().getRecordType(RD
);
2570 void *TyPtr
= Ty
.getAsOpaquePtr();
2571 auto I
= TypeCache
.find(TyPtr
);
2572 if (I
!= TypeCache
.end() && !cast
<llvm::DIType
>(I
->second
)->isForwardDecl())
2575 // We want the canonical definition of the structure to not
2576 // be the typedef. Since that would lead to circular typedef
2578 auto [Res
, PrefRes
] = CreateTypeDefinition(Ty
->castAs
<RecordType
>());
2579 assert(!Res
->isForwardDecl());
2580 TypeCache
[TyPtr
].reset(Res
);
2583 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I
,
2584 CXXRecordDecl::method_iterator End
) {
2585 for (CXXMethodDecl
*MD
: llvm::make_range(I
, End
))
2586 if (FunctionDecl
*Tmpl
= MD
->getInstantiatedFromMemberFunction())
2587 if (!Tmpl
->isImplicit() && Tmpl
->isThisDeclarationADefinition() &&
2588 !MD
->getMemberSpecializationInfo()->isExplicitSpecialization())
2593 static bool canUseCtorHoming(const CXXRecordDecl
*RD
) {
2594 // Constructor homing can be used for classes that cannnot be constructed
2595 // without emitting code for one of their constructors. This is classes that
2596 // don't have trivial or constexpr constructors, or can be created from
2597 // aggregate initialization. Also skip lambda objects because they don't call
2600 // Skip this optimization if the class or any of its methods are marked
2602 if (isClassOrMethodDLLImport(RD
))
2605 if (RD
->isLambda() || RD
->isAggregate() ||
2606 RD
->hasTrivialDefaultConstructor() ||
2607 RD
->hasConstexprNonCopyMoveConstructor())
2610 for (const CXXConstructorDecl
*Ctor
: RD
->ctors()) {
2611 if (Ctor
->isCopyOrMoveConstructor())
2613 if (!Ctor
->isDeleted())
2619 static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind
,
2620 bool DebugTypeExtRefs
, const RecordDecl
*RD
,
2621 const LangOptions
&LangOpts
) {
2622 if (DebugTypeExtRefs
&& isDefinedInClangModule(RD
->getDefinition()))
2625 if (auto *ES
= RD
->getASTContext().getExternalSource())
2626 if (ES
->hasExternalDefinitions(RD
) == ExternalASTSource::EK_Always
)
2629 // Only emit forward declarations in line tables only to keep debug info size
2630 // small. This only applies to CodeView, since we don't emit types in DWARF
2631 // line tables only.
2632 if (DebugKind
== llvm::codegenoptions::DebugLineTablesOnly
)
2635 if (DebugKind
> llvm::codegenoptions::LimitedDebugInfo
||
2636 RD
->hasAttr
<StandaloneDebugAttr
>())
2639 if (!LangOpts
.CPlusPlus
)
2642 if (!RD
->isCompleteDefinitionRequired())
2645 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
);
2650 // Only emit complete debug info for a dynamic class when its vtable is
2651 // emitted. However, Microsoft debuggers don't resolve type information
2652 // across DLL boundaries, so skip this optimization if the class or any of its
2653 // methods are marked dllimport. This isn't a complete solution, since objects
2654 // without any dllimport methods can be used in one DLL and constructed in
2655 // another, but it is the current behavior of LimitedDebugInfo.
2656 if (CXXDecl
->hasDefinition() && CXXDecl
->isDynamicClass() &&
2657 !isClassOrMethodDLLImport(CXXDecl
))
2660 TemplateSpecializationKind Spec
= TSK_Undeclared
;
2661 if (const auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
2662 Spec
= SD
->getSpecializationKind();
2664 if (Spec
== TSK_ExplicitInstantiationDeclaration
&&
2665 hasExplicitMemberDefinition(CXXDecl
->method_begin(),
2666 CXXDecl
->method_end()))
2669 // In constructor homing mode, only emit complete debug info for a class
2670 // when its constructor is emitted.
2671 if ((DebugKind
== llvm::codegenoptions::DebugInfoConstructor
) &&
2672 canUseCtorHoming(CXXDecl
))
2678 void CGDebugInfo::completeRequiredType(const RecordDecl
*RD
) {
2679 if (shouldOmitDefinition(DebugKind
, DebugTypeExtRefs
, RD
, CGM
.getLangOpts()))
2682 QualType Ty
= CGM
.getContext().getRecordType(RD
);
2683 llvm::DIType
*T
= getTypeOrNull(Ty
);
2684 if (T
&& T
->isForwardDecl())
2685 completeClassData(RD
);
2688 llvm::DIType
*CGDebugInfo::CreateType(const RecordType
*Ty
) {
2689 RecordDecl
*RD
= Ty
->getDecl();
2690 llvm::DIType
*T
= cast_or_null
<llvm::DIType
>(getTypeOrNull(QualType(Ty
, 0)));
2691 if (T
|| shouldOmitDefinition(DebugKind
, DebugTypeExtRefs
, RD
,
2692 CGM
.getLangOpts())) {
2694 T
= getOrCreateRecordFwdDecl(Ty
, getDeclContextDescriptor(RD
));
2698 auto [Def
, Pref
] = CreateTypeDefinition(Ty
);
2700 return Pref
? Pref
: Def
;
2703 llvm::DIType
*CGDebugInfo::GetPreferredNameType(const CXXRecordDecl
*RD
,
2704 llvm::DIFile
*Unit
) {
2708 auto const *PNA
= RD
->getAttr
<PreferredNameAttr
>();
2712 return getOrCreateType(PNA
->getTypedefType(), Unit
);
2715 std::pair
<llvm::DIType
*, llvm::DIType
*>
2716 CGDebugInfo::CreateTypeDefinition(const RecordType
*Ty
) {
2717 RecordDecl
*RD
= Ty
->getDecl();
2719 // Get overall information about the record type for the debug info.
2720 llvm::DIFile
*DefUnit
= getOrCreateFile(RD
->getLocation());
2722 // Records and classes and unions can all be recursive. To handle them, we
2723 // first generate a debug descriptor for the struct as a forward declaration.
2724 // Then (if it is a definition) we go through and get debug info for all of
2725 // its members. Finally, we create a descriptor for the complete type (which
2726 // may refer to the forward decl if the struct is recursive) and replace all
2727 // uses of the forward declaration with the final definition.
2728 llvm::DICompositeType
*FwdDecl
= getOrCreateLimitedType(Ty
);
2730 const RecordDecl
*D
= RD
->getDefinition();
2731 if (!D
|| !D
->isCompleteDefinition())
2732 return {FwdDecl
, nullptr};
2734 if (const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
))
2735 CollectContainingType(CXXDecl
, FwdDecl
);
2737 // Push the struct on region stack.
2738 LexicalBlockStack
.emplace_back(&*FwdDecl
);
2739 RegionMap
[Ty
->getDecl()].reset(FwdDecl
);
2741 // Convert all the elements.
2742 SmallVector
<llvm::Metadata
*, 16> EltTys
;
2743 // what about nested types?
2745 // Note: The split of CXXDecl information here is intentional, the
2746 // gdb tests will depend on a certain ordering at printout. The debug
2747 // information offsets are still correct if we merge them all together
2749 const auto *CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
);
2751 CollectCXXBases(CXXDecl
, DefUnit
, EltTys
, FwdDecl
);
2752 CollectVTableInfo(CXXDecl
, DefUnit
, EltTys
);
2755 // Collect data fields (including static variables and any initializers).
2756 CollectRecordFields(RD
, DefUnit
, EltTys
, FwdDecl
);
2758 CollectCXXMemberFunctions(CXXDecl
, DefUnit
, EltTys
, FwdDecl
);
2760 LexicalBlockStack
.pop_back();
2761 RegionMap
.erase(Ty
->getDecl());
2763 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
2764 DBuilder
.replaceArrays(FwdDecl
, Elements
);
2766 if (FwdDecl
->isTemporary())
2768 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl
));
2770 RegionMap
[Ty
->getDecl()].reset(FwdDecl
);
2772 if (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
)
2773 if (auto *PrefDI
= GetPreferredNameType(CXXDecl
, DefUnit
))
2774 return {FwdDecl
, PrefDI
};
2776 return {FwdDecl
, nullptr};
2779 llvm::DIType
*CGDebugInfo::CreateType(const ObjCObjectType
*Ty
,
2780 llvm::DIFile
*Unit
) {
2781 // Ignore protocols.
2782 return getOrCreateType(Ty
->getBaseType(), Unit
);
2785 llvm::DIType
*CGDebugInfo::CreateType(const ObjCTypeParamType
*Ty
,
2786 llvm::DIFile
*Unit
) {
2787 // Ignore protocols.
2788 SourceLocation Loc
= Ty
->getDecl()->getLocation();
2790 // Use Typedefs to represent ObjCTypeParamType.
2791 return DBuilder
.createTypedef(
2792 getOrCreateType(Ty
->getDecl()->getUnderlyingType(), Unit
),
2793 Ty
->getDecl()->getName(), getOrCreateFile(Loc
), getLineNumber(Loc
),
2794 getDeclContextDescriptor(Ty
->getDecl()));
2797 /// \return true if Getter has the default name for the property PD.
2798 static bool hasDefaultGetterName(const ObjCPropertyDecl
*PD
,
2799 const ObjCMethodDecl
*Getter
) {
2804 assert(Getter
->getDeclName().isObjCZeroArgSelector());
2805 return PD
->getName() ==
2806 Getter
->getDeclName().getObjCSelector().getNameForSlot(0);
2809 /// \return true if Setter has the default name for the property PD.
2810 static bool hasDefaultSetterName(const ObjCPropertyDecl
*PD
,
2811 const ObjCMethodDecl
*Setter
) {
2816 assert(Setter
->getDeclName().isObjCOneArgSelector());
2817 return SelectorTable::constructSetterName(PD
->getName()) ==
2818 Setter
->getDeclName().getObjCSelector().getNameForSlot(0);
2821 llvm::DIType
*CGDebugInfo::CreateType(const ObjCInterfaceType
*Ty
,
2822 llvm::DIFile
*Unit
) {
2823 ObjCInterfaceDecl
*ID
= Ty
->getDecl();
2827 // Return a forward declaration if this type was imported from a clang module,
2828 // and this is not the compile unit with the implementation of the type (which
2829 // may contain hidden ivars).
2830 if (DebugTypeExtRefs
&& ID
->isFromASTFile() && ID
->getDefinition() &&
2831 !ID
->getImplementation())
2832 return DBuilder
.createForwardDecl(llvm::dwarf::DW_TAG_structure_type
,
2834 getDeclContextDescriptor(ID
), Unit
, 0);
2836 // Get overall information about the record type for the debug info.
2837 llvm::DIFile
*DefUnit
= getOrCreateFile(ID
->getLocation());
2838 unsigned Line
= getLineNumber(ID
->getLocation());
2840 static_cast<llvm::dwarf::SourceLanguage
>(TheCU
->getSourceLanguage());
2842 // If this is just a forward declaration return a special forward-declaration
2843 // debug type since we won't be able to lay out the entire type.
2844 ObjCInterfaceDecl
*Def
= ID
->getDefinition();
2845 if (!Def
|| !Def
->getImplementation()) {
2846 llvm::DIScope
*Mod
= getParentModuleOrNull(ID
);
2847 llvm::DIType
*FwdDecl
= DBuilder
.createReplaceableCompositeType(
2848 llvm::dwarf::DW_TAG_structure_type
, ID
->getName(), Mod
? Mod
: TheCU
,
2849 DefUnit
, Line
, RuntimeLang
);
2850 ObjCInterfaceCache
.push_back(ObjCInterfaceCacheEntry(Ty
, FwdDecl
, Unit
));
2854 return CreateTypeDefinition(Ty
, Unit
);
2857 llvm::DIModule
*CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod
,
2858 bool CreateSkeletonCU
) {
2859 // Use the Module pointer as the key into the cache. This is a
2860 // nullptr if the "Module" is a PCH, which is safe because we don't
2861 // support chained PCH debug info, so there can only be a single PCH.
2862 const Module
*M
= Mod
.getModuleOrNull();
2863 auto ModRef
= ModuleCache
.find(M
);
2864 if (ModRef
!= ModuleCache
.end())
2865 return cast
<llvm::DIModule
>(ModRef
->second
);
2867 // Macro definitions that were defined with "-D" on the command line.
2868 SmallString
<128> ConfigMacros
;
2870 llvm::raw_svector_ostream
OS(ConfigMacros
);
2871 const auto &PPOpts
= CGM
.getPreprocessorOpts();
2873 // Translate the macro definitions back into a command line.
2874 for (auto &M
: PPOpts
.Macros
) {
2877 const std::string
&Macro
= M
.first
;
2878 bool Undef
= M
.second
;
2879 OS
<< "\"-" << (Undef
? 'U' : 'D');
2880 for (char c
: Macro
)
2895 bool IsRootModule
= M
? !M
->Parent
: true;
2896 // When a module name is specified as -fmodule-name, that module gets a
2897 // clang::Module object, but it won't actually be built or imported; it will
2899 if (CreateSkeletonCU
&& IsRootModule
&& Mod
.getASTFile().empty() && M
)
2900 assert(StringRef(M
->Name
).starts_with(CGM
.getLangOpts().ModuleName
) &&
2901 "clang module without ASTFile must be specified by -fmodule-name");
2903 // Return a StringRef to the remapped Path.
2904 auto RemapPath
= [this](StringRef Path
) -> std::string
{
2905 std::string Remapped
= remapDIPath(Path
);
2906 StringRef
Relative(Remapped
);
2907 StringRef CompDir
= TheCU
->getDirectory();
2908 if (Relative
.consume_front(CompDir
))
2909 Relative
.consume_front(llvm::sys::path::get_separator());
2911 return Relative
.str();
2914 if (CreateSkeletonCU
&& IsRootModule
&& !Mod
.getASTFile().empty()) {
2915 // PCH files don't have a signature field in the control block,
2916 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2917 // We use the lower 64 bits for debug info.
2919 uint64_t Signature
= 0;
2920 if (const auto &ModSig
= Mod
.getSignature())
2921 Signature
= ModSig
.truncatedValue();
2925 llvm::DIBuilder
DIB(CGM
.getModule());
2927 if (!llvm::sys::path::is_absolute(Mod
.getASTFile())) {
2928 if (CGM
.getHeaderSearchOpts().ModuleFileHomeIsCwd
)
2929 PCM
= getCurrentDirname();
2931 PCM
= Mod
.getPath();
2933 llvm::sys::path::append(PCM
, Mod
.getASTFile());
2934 DIB
.createCompileUnit(
2935 TheCU
->getSourceLanguage(),
2936 // TODO: Support "Source" from external AST providers?
2937 DIB
.createFile(Mod
.getModuleName(), TheCU
->getDirectory()),
2938 TheCU
->getProducer(), false, StringRef(), 0, RemapPath(PCM
),
2939 llvm::DICompileUnit::FullDebug
, Signature
);
2943 llvm::DIModule
*Parent
=
2944 IsRootModule
? nullptr
2945 : getOrCreateModuleRef(ASTSourceDescriptor(*M
->Parent
),
2947 std::string IncludePath
= Mod
.getPath().str();
2948 llvm::DIModule
*DIMod
=
2949 DBuilder
.createModule(Parent
, Mod
.getModuleName(), ConfigMacros
,
2950 RemapPath(IncludePath
));
2951 ModuleCache
[M
].reset(DIMod
);
2955 llvm::DIType
*CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType
*Ty
,
2956 llvm::DIFile
*Unit
) {
2957 ObjCInterfaceDecl
*ID
= Ty
->getDecl();
2958 llvm::DIFile
*DefUnit
= getOrCreateFile(ID
->getLocation());
2959 unsigned Line
= getLineNumber(ID
->getLocation());
2960 unsigned RuntimeLang
= TheCU
->getSourceLanguage();
2962 // Bit size, align and offset of the type.
2963 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
2964 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
2966 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
2967 if (ID
->getImplementation())
2968 Flags
|= llvm::DINode::FlagObjcClassComplete
;
2970 llvm::DIScope
*Mod
= getParentModuleOrNull(ID
);
2971 llvm::DICompositeType
*RealDecl
= DBuilder
.createStructType(
2972 Mod
? Mod
: Unit
, ID
->getName(), DefUnit
, Line
, Size
, Align
, Flags
,
2973 nullptr, llvm::DINodeArray(), RuntimeLang
);
2975 QualType
QTy(Ty
, 0);
2976 TypeCache
[QTy
.getAsOpaquePtr()].reset(RealDecl
);
2978 // Push the struct on region stack.
2979 LexicalBlockStack
.emplace_back(RealDecl
);
2980 RegionMap
[Ty
->getDecl()].reset(RealDecl
);
2982 // Convert all the elements.
2983 SmallVector
<llvm::Metadata
*, 16> EltTys
;
2985 ObjCInterfaceDecl
*SClass
= ID
->getSuperClass();
2987 llvm::DIType
*SClassTy
=
2988 getOrCreateType(CGM
.getContext().getObjCInterfaceType(SClass
), Unit
);
2992 llvm::DIType
*InhTag
= DBuilder
.createInheritance(RealDecl
, SClassTy
, 0, 0,
2993 llvm::DINode::FlagZero
);
2994 EltTys
.push_back(InhTag
);
2997 // Create entries for all of the properties.
2998 auto AddProperty
= [&](const ObjCPropertyDecl
*PD
) {
2999 SourceLocation Loc
= PD
->getLocation();
3000 llvm::DIFile
*PUnit
= getOrCreateFile(Loc
);
3001 unsigned PLine
= getLineNumber(Loc
);
3002 ObjCMethodDecl
*Getter
= PD
->getGetterMethodDecl();
3003 ObjCMethodDecl
*Setter
= PD
->getSetterMethodDecl();
3004 llvm::MDNode
*PropertyNode
= DBuilder
.createObjCProperty(
3005 PD
->getName(), PUnit
, PLine
,
3006 hasDefaultGetterName(PD
, Getter
) ? ""
3007 : getSelectorName(PD
->getGetterName()),
3008 hasDefaultSetterName(PD
, Setter
) ? ""
3009 : getSelectorName(PD
->getSetterName()),
3010 PD
->getPropertyAttributes(), getOrCreateType(PD
->getType(), PUnit
));
3011 EltTys
.push_back(PropertyNode
);
3014 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3015 // empty/tombstone keys in the data type (and bool is too small for that).
3016 typedef std::pair
<char, const IdentifierInfo
*> IsClassAndIdent
;
3017 /// List of already emitted properties. Two distinct class and instance
3018 /// properties can share the same identifier (but not two instance
3019 /// properties or two class properties).
3020 llvm::DenseSet
<IsClassAndIdent
> PropertySet
;
3021 /// Returns the IsClassAndIdent key for the given property.
3022 auto GetIsClassAndIdent
= [](const ObjCPropertyDecl
*PD
) {
3023 return std::make_pair(PD
->isClassProperty(), PD
->getIdentifier());
3025 for (const ObjCCategoryDecl
*ClassExt
: ID
->known_extensions())
3026 for (auto *PD
: ClassExt
->properties()) {
3027 PropertySet
.insert(GetIsClassAndIdent(PD
));
3030 for (const auto *PD
: ID
->properties()) {
3031 // Don't emit duplicate metadata for properties that were already in a
3033 if (!PropertySet
.insert(GetIsClassAndIdent(PD
)).second
)
3039 const ASTRecordLayout
&RL
= CGM
.getContext().getASTObjCInterfaceLayout(ID
);
3040 unsigned FieldNo
= 0;
3041 for (ObjCIvarDecl
*Field
= ID
->all_declared_ivar_begin(); Field
;
3042 Field
= Field
->getNextIvar(), ++FieldNo
) {
3043 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
3047 StringRef FieldName
= Field
->getName();
3049 // Ignore unnamed fields.
3050 if (FieldName
.empty())
3053 // Get the location for the field.
3054 llvm::DIFile
*FieldDefUnit
= getOrCreateFile(Field
->getLocation());
3055 unsigned FieldLine
= getLineNumber(Field
->getLocation());
3056 QualType FType
= Field
->getType();
3057 uint64_t FieldSize
= 0;
3058 uint32_t FieldAlign
= 0;
3060 if (!FType
->isIncompleteArrayType()) {
3062 // Bit size, align and offset of the type.
3063 FieldSize
= Field
->isBitField()
3064 ? Field
->getBitWidthValue(CGM
.getContext())
3065 : CGM
.getContext().getTypeSize(FType
);
3066 FieldAlign
= getTypeAlignIfRequired(FType
, CGM
.getContext());
3069 uint64_t FieldOffset
;
3070 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
3071 // We don't know the runtime offset of an ivar if we're using the
3072 // non-fragile ABI. For bitfields, use the bit offset into the first
3073 // byte of storage of the bitfield. For other fields, use zero.
3074 if (Field
->isBitField()) {
3076 CGM
.getObjCRuntime().ComputeBitfieldBitOffset(CGM
, ID
, Field
);
3077 FieldOffset
%= CGM
.getContext().getCharWidth();
3082 FieldOffset
= RL
.getFieldOffset(FieldNo
);
3085 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3086 if (Field
->getAccessControl() == ObjCIvarDecl::Protected
)
3087 Flags
= llvm::DINode::FlagProtected
;
3088 else if (Field
->getAccessControl() == ObjCIvarDecl::Private
)
3089 Flags
= llvm::DINode::FlagPrivate
;
3090 else if (Field
->getAccessControl() == ObjCIvarDecl::Public
)
3091 Flags
= llvm::DINode::FlagPublic
;
3093 if (Field
->isBitField())
3094 Flags
|= llvm::DINode::FlagBitField
;
3096 llvm::MDNode
*PropertyNode
= nullptr;
3097 if (ObjCImplementationDecl
*ImpD
= ID
->getImplementation()) {
3098 if (ObjCPropertyImplDecl
*PImpD
=
3099 ImpD
->FindPropertyImplIvarDecl(Field
->getIdentifier())) {
3100 if (ObjCPropertyDecl
*PD
= PImpD
->getPropertyDecl()) {
3101 SourceLocation Loc
= PD
->getLocation();
3102 llvm::DIFile
*PUnit
= getOrCreateFile(Loc
);
3103 unsigned PLine
= getLineNumber(Loc
);
3104 ObjCMethodDecl
*Getter
= PImpD
->getGetterMethodDecl();
3105 ObjCMethodDecl
*Setter
= PImpD
->getSetterMethodDecl();
3106 PropertyNode
= DBuilder
.createObjCProperty(
3107 PD
->getName(), PUnit
, PLine
,
3108 hasDefaultGetterName(PD
, Getter
)
3110 : getSelectorName(PD
->getGetterName()),
3111 hasDefaultSetterName(PD
, Setter
)
3113 : getSelectorName(PD
->getSetterName()),
3114 PD
->getPropertyAttributes(),
3115 getOrCreateType(PD
->getType(), PUnit
));
3119 FieldTy
= DBuilder
.createObjCIVar(FieldName
, FieldDefUnit
, FieldLine
,
3120 FieldSize
, FieldAlign
, FieldOffset
, Flags
,
3121 FieldTy
, PropertyNode
);
3122 EltTys
.push_back(FieldTy
);
3125 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
3126 DBuilder
.replaceArrays(RealDecl
, Elements
);
3128 LexicalBlockStack
.pop_back();
3132 llvm::DIType
*CGDebugInfo::CreateType(const VectorType
*Ty
,
3133 llvm::DIFile
*Unit
) {
3134 if (Ty
->isExtVectorBoolType()) {
3135 // Boolean ext_vector_type(N) are special because their real element type
3136 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3137 // For now, we pretend the boolean vector were actually a vector of bytes
3138 // (where each byte represents 8 bits of the actual vector).
3139 // FIXME Debug info should actually represent this proper as a vector mask
3141 auto &Ctx
= CGM
.getContext();
3142 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3143 uint64_t NumVectorBytes
= Size
/ Ctx
.getCharWidth();
3145 // Construct the vector of 'char' type.
3146 QualType CharVecTy
=
3147 Ctx
.getVectorType(Ctx
.CharTy
, NumVectorBytes
, VectorKind::Generic
);
3148 return CreateType(CharVecTy
->getAs
<VectorType
>(), Unit
);
3151 llvm::DIType
*ElementTy
= getOrCreateType(Ty
->getElementType(), Unit
);
3152 int64_t Count
= Ty
->getNumElements();
3154 llvm::Metadata
*Subscript
;
3155 QualType
QTy(Ty
, 0);
3156 auto SizeExpr
= SizeExprCache
.find(QTy
);
3157 if (SizeExpr
!= SizeExprCache
.end())
3158 Subscript
= DBuilder
.getOrCreateSubrange(
3159 SizeExpr
->getSecond() /*count*/, nullptr /*lowerBound*/,
3160 nullptr /*upperBound*/, nullptr /*stride*/);
3163 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3164 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Count
? Count
: -1));
3165 Subscript
= DBuilder
.getOrCreateSubrange(
3166 CountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3167 nullptr /*stride*/);
3169 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscript
);
3171 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3172 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3174 return DBuilder
.createVectorType(Size
, Align
, ElementTy
, SubscriptArray
);
3177 llvm::DIType
*CGDebugInfo::CreateType(const ConstantMatrixType
*Ty
,
3178 llvm::DIFile
*Unit
) {
3179 // FIXME: Create another debug type for matrices
3180 // For the time being, it treats it like a nested ArrayType.
3182 llvm::DIType
*ElementTy
= getOrCreateType(Ty
->getElementType(), Unit
);
3183 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3184 uint32_t Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3186 // Create ranges for both dimensions.
3187 llvm::SmallVector
<llvm::Metadata
*, 2> Subscripts
;
3188 auto *ColumnCountNode
=
3189 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3190 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Ty
->getNumColumns()));
3191 auto *RowCountNode
=
3192 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3193 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Ty
->getNumRows()));
3194 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3195 ColumnCountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3196 nullptr /*stride*/));
3197 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3198 RowCountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3199 nullptr /*stride*/));
3200 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscripts
);
3201 return DBuilder
.createArrayType(Size
, Align
, ElementTy
, SubscriptArray
);
3204 llvm::DIType
*CGDebugInfo::CreateType(const ArrayType
*Ty
, llvm::DIFile
*Unit
) {
3208 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3209 if (const auto *VAT
= dyn_cast
<VariableArrayType
>(Ty
)) {
3211 Align
= getTypeAlignIfRequired(CGM
.getContext().getBaseElementType(VAT
),
3213 } else if (Ty
->isIncompleteArrayType()) {
3215 if (Ty
->getElementType()->isIncompleteType())
3218 Align
= getTypeAlignIfRequired(Ty
->getElementType(), CGM
.getContext());
3219 } else if (Ty
->isIncompleteType()) {
3223 // Size and align of the whole array, not the element type.
3224 Size
= CGM
.getContext().getTypeSize(Ty
);
3225 Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3228 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3229 // interior arrays, do we care? Why aren't nested arrays represented the
3230 // obvious/recursive way?
3231 SmallVector
<llvm::Metadata
*, 8> Subscripts
;
3232 QualType
EltTy(Ty
, 0);
3233 while ((Ty
= dyn_cast
<ArrayType
>(EltTy
))) {
3234 // If the number of elements is known, then count is that number. Otherwise,
3235 // it's -1. This allows us to represent a subrange with an array of 0
3236 // elements, like this:
3241 int64_t Count
= -1; // Count == -1 is an unbounded array.
3242 if (const auto *CAT
= dyn_cast
<ConstantArrayType
>(Ty
))
3243 Count
= CAT
->getZExtSize();
3244 else if (const auto *VAT
= dyn_cast
<VariableArrayType
>(Ty
)) {
3245 if (Expr
*Size
= VAT
->getSizeExpr()) {
3246 Expr::EvalResult Result
;
3247 if (Size
->EvaluateAsInt(Result
, CGM
.getContext()))
3248 Count
= Result
.Val
.getInt().getExtValue();
3252 auto SizeNode
= SizeExprCache
.find(EltTy
);
3253 if (SizeNode
!= SizeExprCache
.end())
3254 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3255 SizeNode
->getSecond() /*count*/, nullptr /*lowerBound*/,
3256 nullptr /*upperBound*/, nullptr /*stride*/));
3259 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3260 llvm::Type::getInt64Ty(CGM
.getLLVMContext()), Count
));
3261 Subscripts
.push_back(DBuilder
.getOrCreateSubrange(
3262 CountNode
/*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3263 nullptr /*stride*/));
3265 EltTy
= Ty
->getElementType();
3268 llvm::DINodeArray SubscriptArray
= DBuilder
.getOrCreateArray(Subscripts
);
3270 return DBuilder
.createArrayType(Size
, Align
, getOrCreateType(EltTy
, Unit
),
3274 llvm::DIType
*CGDebugInfo::CreateType(const LValueReferenceType
*Ty
,
3275 llvm::DIFile
*Unit
) {
3276 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type
, Ty
,
3277 Ty
->getPointeeType(), Unit
);
3280 llvm::DIType
*CGDebugInfo::CreateType(const RValueReferenceType
*Ty
,
3281 llvm::DIFile
*Unit
) {
3282 llvm::dwarf::Tag Tag
= llvm::dwarf::DW_TAG_rvalue_reference_type
;
3283 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3284 if (CGM
.getCodeGenOpts().DebugStrictDwarf
&&
3285 CGM
.getCodeGenOpts().DwarfVersion
< 4)
3286 Tag
= llvm::dwarf::DW_TAG_reference_type
;
3288 return CreatePointerLikeType(Tag
, Ty
, Ty
->getPointeeType(), Unit
);
3291 llvm::DIType
*CGDebugInfo::CreateType(const MemberPointerType
*Ty
,
3293 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3296 if (!Ty
->isIncompleteType()) {
3297 Size
= CGM
.getContext().getTypeSize(Ty
);
3299 // Set the MS inheritance model. There is no flag for the unspecified model.
3300 if (CGM
.getTarget().getCXXABI().isMicrosoft()) {
3301 switch (Ty
->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
3302 case MSInheritanceModel::Single
:
3303 Flags
|= llvm::DINode::FlagSingleInheritance
;
3305 case MSInheritanceModel::Multiple
:
3306 Flags
|= llvm::DINode::FlagMultipleInheritance
;
3308 case MSInheritanceModel::Virtual
:
3309 Flags
|= llvm::DINode::FlagVirtualInheritance
;
3311 case MSInheritanceModel::Unspecified
:
3317 llvm::DIType
*ClassType
= getOrCreateType(QualType(Ty
->getClass(), 0), U
);
3318 if (Ty
->isMemberDataPointerType())
3319 return DBuilder
.createMemberPointerType(
3320 getOrCreateType(Ty
->getPointeeType(), U
), ClassType
, Size
, /*Align=*/0,
3323 const FunctionProtoType
*FPT
=
3324 Ty
->getPointeeType()->castAs
<FunctionProtoType
>();
3325 return DBuilder
.createMemberPointerType(
3326 getOrCreateInstanceMethodType(
3327 CXXMethodDecl::getThisType(FPT
, Ty
->getMostRecentCXXRecordDecl()),
3329 ClassType
, Size
, /*Align=*/0, Flags
);
3332 llvm::DIType
*CGDebugInfo::CreateType(const AtomicType
*Ty
, llvm::DIFile
*U
) {
3333 auto *FromTy
= getOrCreateType(Ty
->getValueType(), U
);
3334 return DBuilder
.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type
, FromTy
);
3337 llvm::DIType
*CGDebugInfo::CreateType(const PipeType
*Ty
, llvm::DIFile
*U
) {
3338 return getOrCreateType(Ty
->getElementType(), U
);
3341 llvm::DIType
*CGDebugInfo::CreateEnumType(const EnumType
*Ty
) {
3342 const EnumDecl
*ED
= Ty
->getDecl();
3346 if (!ED
->getTypeForDecl()->isIncompleteType()) {
3347 Size
= CGM
.getContext().getTypeSize(ED
->getTypeForDecl());
3348 Align
= getDeclAlignIfRequired(ED
, CGM
.getContext());
3351 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3353 bool isImportedFromModule
=
3354 DebugTypeExtRefs
&& ED
->isFromASTFile() && ED
->getDefinition();
3356 // If this is just a forward declaration, construct an appropriately
3357 // marked node and just return it.
3358 if (isImportedFromModule
|| !ED
->getDefinition()) {
3359 // Note that it is possible for enums to be created as part of
3360 // their own declcontext. In this case a FwdDecl will be created
3361 // twice. This doesn't cause a problem because both FwdDecls are
3362 // entered into the ReplaceMap: finalize() will replace the first
3363 // FwdDecl with the second and then replace the second with
3365 llvm::DIScope
*EDContext
= getDeclContextDescriptor(ED
);
3366 llvm::DIFile
*DefUnit
= getOrCreateFile(ED
->getLocation());
3367 llvm::TempDIScope
TmpContext(DBuilder
.createReplaceableCompositeType(
3368 llvm::dwarf::DW_TAG_enumeration_type
, "", TheCU
, DefUnit
, 0));
3370 unsigned Line
= getLineNumber(ED
->getLocation());
3371 StringRef EDName
= ED
->getName();
3372 llvm::DIType
*RetTy
= DBuilder
.createReplaceableCompositeType(
3373 llvm::dwarf::DW_TAG_enumeration_type
, EDName
, EDContext
, DefUnit
, Line
,
3374 0, Size
, Align
, llvm::DINode::FlagFwdDecl
, Identifier
);
3376 ReplaceMap
.emplace_back(
3377 std::piecewise_construct
, std::make_tuple(Ty
),
3378 std::make_tuple(static_cast<llvm::Metadata
*>(RetTy
)));
3382 return CreateTypeDefinition(Ty
);
3385 llvm::DIType
*CGDebugInfo::CreateTypeDefinition(const EnumType
*Ty
) {
3386 const EnumDecl
*ED
= Ty
->getDecl();
3389 if (!ED
->getTypeForDecl()->isIncompleteType()) {
3390 Size
= CGM
.getContext().getTypeSize(ED
->getTypeForDecl());
3391 Align
= getDeclAlignIfRequired(ED
, CGM
.getContext());
3394 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3396 SmallVector
<llvm::Metadata
*, 16> Enumerators
;
3397 ED
= ED
->getDefinition();
3398 for (const auto *Enum
: ED
->enumerators()) {
3399 Enumerators
.push_back(
3400 DBuilder
.createEnumerator(Enum
->getName(), Enum
->getInitVal()));
3403 // Return a CompositeType for the enum itself.
3404 llvm::DINodeArray EltArray
= DBuilder
.getOrCreateArray(Enumerators
);
3406 llvm::DIFile
*DefUnit
= getOrCreateFile(ED
->getLocation());
3407 unsigned Line
= getLineNumber(ED
->getLocation());
3408 llvm::DIScope
*EnumContext
= getDeclContextDescriptor(ED
);
3409 llvm::DIType
*ClassTy
= getOrCreateType(ED
->getIntegerType(), DefUnit
);
3410 return DBuilder
.createEnumerationType(
3411 EnumContext
, ED
->getName(), DefUnit
, Line
, Size
, Align
, EltArray
, ClassTy
,
3412 /*RunTimeLang=*/0, Identifier
, ED
->isScoped());
3415 llvm::DIMacro
*CGDebugInfo::CreateMacro(llvm::DIMacroFile
*Parent
,
3416 unsigned MType
, SourceLocation LineLoc
,
3417 StringRef Name
, StringRef Value
) {
3418 unsigned Line
= LineLoc
.isInvalid() ? 0 : getLineNumber(LineLoc
);
3419 return DBuilder
.createMacro(Parent
, Line
, MType
, Name
, Value
);
3422 llvm::DIMacroFile
*CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile
*Parent
,
3423 SourceLocation LineLoc
,
3424 SourceLocation FileLoc
) {
3425 llvm::DIFile
*FName
= getOrCreateFile(FileLoc
);
3426 unsigned Line
= LineLoc
.isInvalid() ? 0 : getLineNumber(LineLoc
);
3427 return DBuilder
.createTempMacroFile(Parent
, Line
, FName
);
3430 static QualType
UnwrapTypeForDebugInfo(QualType T
, const ASTContext
&C
) {
3433 Qualifiers InnerQuals
= T
.getLocalQualifiers();
3434 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3435 // that is already there.
3436 Quals
+= Qualifiers::removeCommonQualifiers(Quals
, InnerQuals
);
3437 Quals
+= InnerQuals
;
3439 switch (T
->getTypeClass()) {
3441 return C
.getQualifiedType(T
.getTypePtr(), Quals
);
3442 case Type::TemplateSpecialization
: {
3443 const auto *Spec
= cast
<TemplateSpecializationType
>(T
);
3444 if (Spec
->isTypeAlias())
3445 return C
.getQualifiedType(T
.getTypePtr(), Quals
);
3446 T
= Spec
->desugar();
3449 case Type::TypeOfExpr
:
3450 T
= cast
<TypeOfExprType
>(T
)->getUnderlyingExpr()->getType();
3453 T
= cast
<TypeOfType
>(T
)->getUnmodifiedType();
3455 case Type::Decltype
:
3456 T
= cast
<DecltypeType
>(T
)->getUnderlyingType();
3458 case Type::UnaryTransform
:
3459 T
= cast
<UnaryTransformType
>(T
)->getUnderlyingType();
3461 case Type::Attributed
:
3462 T
= cast
<AttributedType
>(T
)->getEquivalentType();
3464 case Type::BTFTagAttributed
:
3465 T
= cast
<BTFTagAttributedType
>(T
)->getWrappedType();
3467 case Type::CountAttributed
:
3468 T
= cast
<CountAttributedType
>(T
)->desugar();
3470 case Type::Elaborated
:
3471 T
= cast
<ElaboratedType
>(T
)->getNamedType();
3474 T
= cast
<UsingType
>(T
)->getUnderlyingType();
3477 T
= cast
<ParenType
>(T
)->getInnerType();
3479 case Type::MacroQualified
:
3480 T
= cast
<MacroQualifiedType
>(T
)->getUnderlyingType();
3482 case Type::SubstTemplateTypeParm
:
3483 T
= cast
<SubstTemplateTypeParmType
>(T
)->getReplacementType();
3486 case Type::DeducedTemplateSpecialization
: {
3487 QualType DT
= cast
<DeducedType
>(T
)->getDeducedType();
3488 assert(!DT
.isNull() && "Undeduced types shouldn't reach here.");
3492 case Type::PackIndexing
: {
3493 T
= cast
<PackIndexingType
>(T
)->getSelectedType();
3496 case Type::Adjusted
:
3498 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3499 T
= cast
<AdjustedType
>(T
)->getAdjustedType();
3503 assert(T
!= LastT
&& "Type unwrapping failed to unwrap!");
3508 llvm::DIType
*CGDebugInfo::getTypeOrNull(QualType Ty
) {
3509 assert(Ty
== UnwrapTypeForDebugInfo(Ty
, CGM
.getContext()));
3510 auto It
= TypeCache
.find(Ty
.getAsOpaquePtr());
3511 if (It
!= TypeCache
.end()) {
3512 // Verify that the debug info still exists.
3513 if (llvm::Metadata
*V
= It
->second
)
3514 return cast
<llvm::DIType
>(V
);
3520 void CGDebugInfo::completeTemplateDefinition(
3521 const ClassTemplateSpecializationDecl
&SD
) {
3522 completeUnusedClass(SD
);
3525 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl
&D
) {
3526 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
||
3530 completeClassData(&D
);
3531 // In case this type has no member function definitions being emitted, ensure
3533 RetainedTypes
.push_back(CGM
.getContext().getRecordType(&D
).getAsOpaquePtr());
3536 llvm::DIType
*CGDebugInfo::getOrCreateType(QualType Ty
, llvm::DIFile
*Unit
) {
3540 llvm::TimeTraceScope
TimeScope("DebugType", [&]() {
3542 llvm::raw_string_ostream
OS(Name
);
3543 Ty
.print(OS
, getPrintingPolicy());
3547 // Unwrap the type as needed for debug information.
3548 Ty
= UnwrapTypeForDebugInfo(Ty
, CGM
.getContext());
3550 if (auto *T
= getTypeOrNull(Ty
))
3553 llvm::DIType
*Res
= CreateTypeNode(Ty
, Unit
);
3554 void *TyPtr
= Ty
.getAsOpaquePtr();
3556 // And update the type cache.
3557 TypeCache
[TyPtr
].reset(Res
);
3562 llvm::DIModule
*CGDebugInfo::getParentModuleOrNull(const Decl
*D
) {
3563 // A forward declaration inside a module header does not belong to the module.
3564 if (isa
<RecordDecl
>(D
) && !cast
<RecordDecl
>(D
)->getDefinition())
3566 if (DebugTypeExtRefs
&& D
->isFromASTFile()) {
3567 // Record a reference to an imported clang module or precompiled header.
3568 auto *Reader
= CGM
.getContext().getExternalSource();
3569 auto Idx
= D
->getOwningModuleID();
3570 auto Info
= Reader
->getSourceDescriptor(Idx
);
3572 return getOrCreateModuleRef(*Info
, /*SkeletonCU=*/true);
3573 } else if (ClangModuleMap
) {
3574 // We are building a clang module or a precompiled header.
3576 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3577 // and it wouldn't be necessary to specify the parent scope
3578 // because the type is already unique by definition (it would look
3579 // like the output of -fno-standalone-debug). On the other hand,
3580 // the parent scope helps a consumer to quickly locate the object
3581 // file where the type's definition is located, so it might be
3582 // best to make this behavior a command line or debugger tuning
3584 if (Module
*M
= D
->getOwningModule()) {
3585 // This is a (sub-)module.
3586 auto Info
= ASTSourceDescriptor(*M
);
3587 return getOrCreateModuleRef(Info
, /*SkeletonCU=*/false);
3589 // This the precompiled header being built.
3590 return getOrCreateModuleRef(PCHDescriptor
, /*SkeletonCU=*/false);
3597 llvm::DIType
*CGDebugInfo::CreateTypeNode(QualType Ty
, llvm::DIFile
*Unit
) {
3598 // Handle qualifiers, which recursively handles what they refer to.
3599 if (Ty
.hasLocalQualifiers())
3600 return CreateQualifiedType(Ty
, Unit
);
3602 // Work out details of type.
3603 switch (Ty
->getTypeClass()) {
3604 #define TYPE(Class, Base)
3605 #define ABSTRACT_TYPE(Class, Base)
3606 #define NON_CANONICAL_TYPE(Class, Base)
3607 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3608 #include "clang/AST/TypeNodes.inc"
3609 llvm_unreachable("Dependent types cannot show up in debug information");
3611 case Type::ExtVector
:
3613 return CreateType(cast
<VectorType
>(Ty
), Unit
);
3614 case Type::ConstantMatrix
:
3615 return CreateType(cast
<ConstantMatrixType
>(Ty
), Unit
);
3616 case Type::ObjCObjectPointer
:
3617 return CreateType(cast
<ObjCObjectPointerType
>(Ty
), Unit
);
3618 case Type::ObjCObject
:
3619 return CreateType(cast
<ObjCObjectType
>(Ty
), Unit
);
3620 case Type::ObjCTypeParam
:
3621 return CreateType(cast
<ObjCTypeParamType
>(Ty
), Unit
);
3622 case Type::ObjCInterface
:
3623 return CreateType(cast
<ObjCInterfaceType
>(Ty
), Unit
);
3625 return CreateType(cast
<BuiltinType
>(Ty
));
3627 return CreateType(cast
<ComplexType
>(Ty
));
3629 return CreateType(cast
<PointerType
>(Ty
), Unit
);
3630 case Type::BlockPointer
:
3631 return CreateType(cast
<BlockPointerType
>(Ty
), Unit
);
3633 return CreateType(cast
<TypedefType
>(Ty
), Unit
);
3635 return CreateType(cast
<RecordType
>(Ty
));
3637 return CreateEnumType(cast
<EnumType
>(Ty
));
3638 case Type::FunctionProto
:
3639 case Type::FunctionNoProto
:
3640 return CreateType(cast
<FunctionType
>(Ty
), Unit
);
3641 case Type::ConstantArray
:
3642 case Type::VariableArray
:
3643 case Type::IncompleteArray
:
3644 case Type::ArrayParameter
:
3645 return CreateType(cast
<ArrayType
>(Ty
), Unit
);
3647 case Type::LValueReference
:
3648 return CreateType(cast
<LValueReferenceType
>(Ty
), Unit
);
3649 case Type::RValueReference
:
3650 return CreateType(cast
<RValueReferenceType
>(Ty
), Unit
);
3652 case Type::MemberPointer
:
3653 return CreateType(cast
<MemberPointerType
>(Ty
), Unit
);
3656 return CreateType(cast
<AtomicType
>(Ty
), Unit
);
3659 return CreateType(cast
<BitIntType
>(Ty
));
3661 return CreateType(cast
<PipeType
>(Ty
), Unit
);
3663 case Type::TemplateSpecialization
:
3664 return CreateType(cast
<TemplateSpecializationType
>(Ty
), Unit
);
3666 case Type::CountAttributed
:
3668 case Type::Attributed
:
3669 case Type::BTFTagAttributed
:
3670 case Type::Adjusted
:
3672 case Type::DeducedTemplateSpecialization
:
3673 case Type::Elaborated
:
3676 case Type::MacroQualified
:
3677 case Type::SubstTemplateTypeParm
:
3678 case Type::TypeOfExpr
:
3680 case Type::Decltype
:
3681 case Type::PackIndexing
:
3682 case Type::UnaryTransform
:
3686 llvm_unreachable("type should have been unwrapped!");
3689 llvm::DICompositeType
*
3690 CGDebugInfo::getOrCreateLimitedType(const RecordType
*Ty
) {
3691 QualType
QTy(Ty
, 0);
3693 auto *T
= cast_or_null
<llvm::DICompositeType
>(getTypeOrNull(QTy
));
3695 // We may have cached a forward decl when we could have created
3696 // a non-forward decl. Go ahead and create a non-forward decl
3698 if (T
&& !T
->isForwardDecl())
3701 // Otherwise create the type.
3702 llvm::DICompositeType
*Res
= CreateLimitedType(Ty
);
3704 // Propagate members from the declaration to the definition
3705 // CreateType(const RecordType*) will overwrite this with the members in the
3706 // correct order if the full type is needed.
3707 DBuilder
.replaceArrays(Res
, T
? T
->getElements() : llvm::DINodeArray());
3709 // And update the type cache.
3710 TypeCache
[QTy
.getAsOpaquePtr()].reset(Res
);
3714 // TODO: Currently used for context chains when limiting debug info.
3715 llvm::DICompositeType
*CGDebugInfo::CreateLimitedType(const RecordType
*Ty
) {
3716 RecordDecl
*RD
= Ty
->getDecl();
3718 // Get overall information about the record type for the debug info.
3719 StringRef RDName
= getClassName(RD
);
3720 const SourceLocation Loc
= RD
->getLocation();
3721 llvm::DIFile
*DefUnit
= nullptr;
3723 if (Loc
.isValid()) {
3724 DefUnit
= getOrCreateFile(Loc
);
3725 Line
= getLineNumber(Loc
);
3728 llvm::DIScope
*RDContext
= getDeclContextDescriptor(RD
);
3730 // If we ended up creating the type during the context chain construction,
3731 // just return that.
3732 auto *T
= cast_or_null
<llvm::DICompositeType
>(
3733 getTypeOrNull(CGM
.getContext().getRecordType(RD
)));
3734 if (T
&& (!T
->isForwardDecl() || !RD
->getDefinition()))
3737 // If this is just a forward or incomplete declaration, construct an
3738 // appropriately marked node and just return it.
3739 const RecordDecl
*D
= RD
->getDefinition();
3740 if (!D
|| !D
->isCompleteDefinition())
3741 return getOrCreateRecordFwdDecl(Ty
, RDContext
);
3743 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
3744 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3745 // struct or struct member, where it only increases alignment unless 'packed'
3746 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3748 auto Align
= getTypeAlignIfRequired(Ty
, CGM
.getContext());
3750 SmallString
<256> Identifier
= getTypeIdentifier(Ty
, CGM
, TheCU
);
3752 // Explicitly record the calling convention and export symbols for C++
3754 auto Flags
= llvm::DINode::FlagZero
;
3755 if (auto CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
3756 if (CGM
.getCXXABI().getRecordArgABI(CXXRD
) == CGCXXABI::RAA_Indirect
)
3757 Flags
|= llvm::DINode::FlagTypePassByReference
;
3759 Flags
|= llvm::DINode::FlagTypePassByValue
;
3761 // Record if a C++ record is non-trivial type.
3762 if (!CXXRD
->isTrivial())
3763 Flags
|= llvm::DINode::FlagNonTrivial
;
3765 // Record exports it symbols to the containing structure.
3766 if (CXXRD
->isAnonymousStructOrUnion())
3767 Flags
|= llvm::DINode::FlagExportSymbols
;
3769 Flags
|= getAccessFlag(CXXRD
->getAccess(),
3770 dyn_cast
<CXXRecordDecl
>(CXXRD
->getDeclContext()));
3773 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
3774 llvm::DICompositeType
*RealDecl
= DBuilder
.createReplaceableCompositeType(
3775 getTagForRecord(RD
), RDName
, RDContext
, DefUnit
, Line
, 0, Size
, Align
,
3776 Flags
, Identifier
, Annotations
);
3778 // Elements of composite types usually have back to the type, creating
3779 // uniquing cycles. Distinct nodes are more efficient.
3780 switch (RealDecl
->getTag()) {
3782 llvm_unreachable("invalid composite type tag");
3784 case llvm::dwarf::DW_TAG_array_type
:
3785 case llvm::dwarf::DW_TAG_enumeration_type
:
3786 // Array elements and most enumeration elements don't have back references,
3787 // so they don't tend to be involved in uniquing cycles and there is some
3788 // chance of merging them when linking together two modules. Only make
3789 // them distinct if they are ODR-uniqued.
3790 if (Identifier
.empty())
3794 case llvm::dwarf::DW_TAG_structure_type
:
3795 case llvm::dwarf::DW_TAG_union_type
:
3796 case llvm::dwarf::DW_TAG_class_type
:
3797 // Immediately resolve to a distinct node.
3799 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl
));
3803 RegionMap
[Ty
->getDecl()].reset(RealDecl
);
3804 TypeCache
[QualType(Ty
, 0).getAsOpaquePtr()].reset(RealDecl
);
3806 if (const auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
))
3807 DBuilder
.replaceArrays(RealDecl
, llvm::DINodeArray(),
3808 CollectCXXTemplateParams(TSpecial
, DefUnit
));
3812 void CGDebugInfo::CollectContainingType(const CXXRecordDecl
*RD
,
3813 llvm::DICompositeType
*RealDecl
) {
3814 // A class's primary base or the class itself contains the vtable.
3815 llvm::DIType
*ContainingType
= nullptr;
3816 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
3817 if (const CXXRecordDecl
*PBase
= RL
.getPrimaryBase()) {
3818 // Seek non-virtual primary base root.
3820 const ASTRecordLayout
&BRL
= CGM
.getContext().getASTRecordLayout(PBase
);
3821 const CXXRecordDecl
*PBT
= BRL
.getPrimaryBase();
3822 if (PBT
&& !BRL
.isPrimaryBaseVirtual())
3827 ContainingType
= getOrCreateType(QualType(PBase
->getTypeForDecl(), 0),
3828 getOrCreateFile(RD
->getLocation()));
3829 } else if (RD
->isDynamicClass())
3830 ContainingType
= RealDecl
;
3832 DBuilder
.replaceVTableHolder(RealDecl
, ContainingType
);
3835 llvm::DIType
*CGDebugInfo::CreateMemberType(llvm::DIFile
*Unit
, QualType FType
,
3836 StringRef Name
, uint64_t *Offset
) {
3837 llvm::DIType
*FieldTy
= CGDebugInfo::getOrCreateType(FType
, Unit
);
3838 uint64_t FieldSize
= CGM
.getContext().getTypeSize(FType
);
3839 auto FieldAlign
= getTypeAlignIfRequired(FType
, CGM
.getContext());
3841 DBuilder
.createMemberType(Unit
, Name
, Unit
, 0, FieldSize
, FieldAlign
,
3842 *Offset
, llvm::DINode::FlagZero
, FieldTy
);
3843 *Offset
+= FieldSize
;
3847 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD
, llvm::DIFile
*Unit
,
3849 StringRef
&LinkageName
,
3850 llvm::DIScope
*&FDContext
,
3851 llvm::DINodeArray
&TParamsArray
,
3852 llvm::DINode::DIFlags
&Flags
) {
3853 const auto *FD
= cast
<FunctionDecl
>(GD
.getCanonicalDecl().getDecl());
3854 Name
= getFunctionName(FD
);
3855 // Use mangled name as linkage name for C/C++ functions.
3856 if (FD
->getType()->getAs
<FunctionProtoType
>())
3857 LinkageName
= CGM
.getMangledName(GD
);
3858 if (FD
->hasPrototype())
3859 Flags
|= llvm::DINode::FlagPrototyped
;
3860 // No need to replicate the linkage name if it isn't different from the
3861 // subprogram name, no need to have it at all unless coverage is enabled or
3862 // debug is set to more than just line tables or extra debug info is needed.
3863 if (LinkageName
== Name
||
3864 (CGM
.getCodeGenOpts().CoverageNotesFile
.empty() &&
3865 CGM
.getCodeGenOpts().CoverageDataFile
.empty() &&
3866 !CGM
.getCodeGenOpts().DebugInfoForProfiling
&&
3867 !CGM
.getCodeGenOpts().PseudoProbeForProfiling
&&
3868 DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
))
3869 LinkageName
= StringRef();
3871 // Emit the function scope in line tables only mode (if CodeView) to
3872 // differentiate between function names.
3873 if (CGM
.getCodeGenOpts().hasReducedDebugInfo() ||
3874 (DebugKind
== llvm::codegenoptions::DebugLineTablesOnly
&&
3875 CGM
.getCodeGenOpts().EmitCodeView
)) {
3876 if (const NamespaceDecl
*NSDecl
=
3877 dyn_cast_or_null
<NamespaceDecl
>(FD
->getDeclContext()))
3878 FDContext
= getOrCreateNamespace(NSDecl
);
3879 else if (const RecordDecl
*RDecl
=
3880 dyn_cast_or_null
<RecordDecl
>(FD
->getDeclContext())) {
3881 llvm::DIScope
*Mod
= getParentModuleOrNull(RDecl
);
3882 FDContext
= getContextDescriptor(RDecl
, Mod
? Mod
: TheCU
);
3885 if (CGM
.getCodeGenOpts().hasReducedDebugInfo()) {
3886 // Check if it is a noreturn-marked function
3887 if (FD
->isNoReturn())
3888 Flags
|= llvm::DINode::FlagNoReturn
;
3889 // Collect template parameters.
3890 TParamsArray
= CollectFunctionTemplateParams(FD
, Unit
);
3894 void CGDebugInfo::collectVarDeclProps(const VarDecl
*VD
, llvm::DIFile
*&Unit
,
3895 unsigned &LineNo
, QualType
&T
,
3896 StringRef
&Name
, StringRef
&LinkageName
,
3897 llvm::MDTuple
*&TemplateParameters
,
3898 llvm::DIScope
*&VDContext
) {
3899 Unit
= getOrCreateFile(VD
->getLocation());
3900 LineNo
= getLineNumber(VD
->getLocation());
3902 setLocation(VD
->getLocation());
3905 if (T
->isIncompleteArrayType()) {
3906 // CodeGen turns int[] into int[1] so we'll do the same here.
3907 llvm::APInt
ConstVal(32, 1);
3908 QualType ET
= CGM
.getContext().getAsArrayType(T
)->getElementType();
3910 T
= CGM
.getContext().getConstantArrayType(ET
, ConstVal
, nullptr,
3911 ArraySizeModifier::Normal
, 0);
3914 Name
= VD
->getName();
3915 if (VD
->getDeclContext() && !isa
<FunctionDecl
>(VD
->getDeclContext()) &&
3916 !isa
<ObjCMethodDecl
>(VD
->getDeclContext()))
3917 LinkageName
= CGM
.getMangledName(VD
);
3918 if (LinkageName
== Name
)
3919 LinkageName
= StringRef();
3921 if (isa
<VarTemplateSpecializationDecl
>(VD
)) {
3922 llvm::DINodeArray parameterNodes
= CollectVarTemplateParams(VD
, &*Unit
);
3923 TemplateParameters
= parameterNodes
.get();
3925 TemplateParameters
= nullptr;
3928 // Since we emit declarations (DW_AT_members) for static members, place the
3929 // definition of those static members in the namespace they were declared in
3930 // in the source code (the lexical decl context).
3931 // FIXME: Generalize this for even non-member global variables where the
3932 // declaration and definition may have different lexical decl contexts, once
3933 // we have support for emitting declarations of (non-member) global variables.
3934 const DeclContext
*DC
= VD
->isStaticDataMember() ? VD
->getLexicalDeclContext()
3935 : VD
->getDeclContext();
3936 // When a record type contains an in-line initialization of a static data
3937 // member, and the record type is marked as __declspec(dllexport), an implicit
3938 // definition of the member will be created in the record context. DWARF
3939 // doesn't seem to have a nice way to describe this in a form that consumers
3940 // are likely to understand, so fake the "normal" situation of a definition
3941 // outside the class by putting it in the global scope.
3943 DC
= CGM
.getContext().getTranslationUnitDecl();
3945 llvm::DIScope
*Mod
= getParentModuleOrNull(VD
);
3946 VDContext
= getContextDescriptor(cast
<Decl
>(DC
), Mod
? Mod
: TheCU
);
3949 llvm::DISubprogram
*CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD
,
3951 llvm::DINodeArray TParamsArray
;
3952 StringRef Name
, LinkageName
;
3953 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
3954 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
3955 SourceLocation Loc
= GD
.getDecl()->getLocation();
3956 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
3957 llvm::DIScope
*DContext
= Unit
;
3958 unsigned Line
= getLineNumber(Loc
);
3959 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, DContext
, TParamsArray
,
3961 auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
3963 // Build function type.
3964 SmallVector
<QualType
, 16> ArgTypes
;
3965 for (const ParmVarDecl
*Parm
: FD
->parameters())
3966 ArgTypes
.push_back(Parm
->getType());
3968 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
3969 QualType FnType
= CGM
.getContext().getFunctionType(
3970 FD
->getReturnType(), ArgTypes
, FunctionProtoType::ExtProtoInfo(CC
));
3971 if (!FD
->isExternallyVisible())
3972 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
3973 if (CGM
.getLangOpts().Optimize
)
3974 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
3977 Flags
|= getCallSiteRelatedAttrs();
3978 SPFlags
|= llvm::DISubprogram::SPFlagDefinition
;
3979 return DBuilder
.createFunction(
3980 DContext
, Name
, LinkageName
, Unit
, Line
,
3981 getOrCreateFunctionType(GD
.getDecl(), FnType
, Unit
), 0, Flags
, SPFlags
,
3982 TParamsArray
.get(), getFunctionDeclaration(FD
));
3985 llvm::DISubprogram
*SP
= DBuilder
.createTempFunctionFwdDecl(
3986 DContext
, Name
, LinkageName
, Unit
, Line
,
3987 getOrCreateFunctionType(GD
.getDecl(), FnType
, Unit
), 0, Flags
, SPFlags
,
3988 TParamsArray
.get(), getFunctionDeclaration(FD
));
3989 const FunctionDecl
*CanonDecl
= FD
->getCanonicalDecl();
3990 FwdDeclReplaceMap
.emplace_back(std::piecewise_construct
,
3991 std::make_tuple(CanonDecl
),
3992 std::make_tuple(SP
));
3996 llvm::DISubprogram
*CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD
) {
3997 return getFunctionFwdDeclOrStub(GD
, /* Stub = */ false);
4000 llvm::DISubprogram
*CGDebugInfo::getFunctionStub(GlobalDecl GD
) {
4001 return getFunctionFwdDeclOrStub(GD
, /* Stub = */ true);
4004 llvm::DIGlobalVariable
*
4005 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl
*VD
) {
4007 StringRef Name
, LinkageName
;
4008 SourceLocation Loc
= VD
->getLocation();
4009 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
4010 llvm::DIScope
*DContext
= Unit
;
4011 unsigned Line
= getLineNumber(Loc
);
4012 llvm::MDTuple
*TemplateParameters
= nullptr;
4014 collectVarDeclProps(VD
, Unit
, Line
, T
, Name
, LinkageName
, TemplateParameters
,
4016 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
4017 auto *GV
= DBuilder
.createTempGlobalVariableFwdDecl(
4018 DContext
, Name
, LinkageName
, Unit
, Line
, getOrCreateType(T
, Unit
),
4019 !VD
->isExternallyVisible(), nullptr, TemplateParameters
, Align
);
4020 FwdDeclReplaceMap
.emplace_back(
4021 std::piecewise_construct
,
4022 std::make_tuple(cast
<VarDecl
>(VD
->getCanonicalDecl())),
4023 std::make_tuple(static_cast<llvm::Metadata
*>(GV
)));
4027 llvm::DINode
*CGDebugInfo::getDeclarationOrDefinition(const Decl
*D
) {
4028 // We only need a declaration (not a definition) of the type - so use whatever
4029 // we would otherwise do to get a type for a pointee. (forward declarations in
4030 // limited debug info, full definitions (if the type definition is available)
4031 // in unlimited debug info)
4032 if (const auto *TD
= dyn_cast
<TypeDecl
>(D
))
4033 return getOrCreateType(CGM
.getContext().getTypeDeclType(TD
),
4034 getOrCreateFile(TD
->getLocation()));
4035 auto I
= DeclCache
.find(D
->getCanonicalDecl());
4037 if (I
!= DeclCache
.end()) {
4039 if (auto *GVE
= dyn_cast_or_null
<llvm::DIGlobalVariableExpression
>(N
))
4040 return GVE
->getVariable();
4041 return cast
<llvm::DINode
>(N
);
4044 // Search imported declaration cache if it is already defined
4045 // as imported declaration.
4046 auto IE
= ImportedDeclCache
.find(D
->getCanonicalDecl());
4048 if (IE
!= ImportedDeclCache
.end()) {
4049 auto N
= IE
->second
;
4050 if (auto *GVE
= dyn_cast_or_null
<llvm::DIImportedEntity
>(N
))
4051 return cast
<llvm::DINode
>(GVE
);
4052 return dyn_cast_or_null
<llvm::DINode
>(N
);
4055 // No definition for now. Emit a forward definition that might be
4056 // merged with a potential upcoming definition.
4057 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
4058 return getFunctionForwardDeclaration(FD
);
4059 else if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
4060 return getGlobalVariableForwardDeclaration(VD
);
4065 llvm::DISubprogram
*CGDebugInfo::getFunctionDeclaration(const Decl
*D
) {
4066 if (!D
|| DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4069 const auto *FD
= dyn_cast
<FunctionDecl
>(D
);
4074 auto *S
= getDeclContextDescriptor(D
);
4076 auto MI
= SPCache
.find(FD
->getCanonicalDecl());
4077 if (MI
== SPCache
.end()) {
4078 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FD
->getCanonicalDecl())) {
4079 return CreateCXXMemberFunction(MD
, getOrCreateFile(MD
->getLocation()),
4080 cast
<llvm::DICompositeType
>(S
));
4083 if (MI
!= SPCache
.end()) {
4084 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(MI
->second
);
4085 if (SP
&& !SP
->isDefinition())
4089 for (auto *NextFD
: FD
->redecls()) {
4090 auto MI
= SPCache
.find(NextFD
->getCanonicalDecl());
4091 if (MI
!= SPCache
.end()) {
4092 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(MI
->second
);
4093 if (SP
&& !SP
->isDefinition())
4100 llvm::DISubprogram
*CGDebugInfo::getObjCMethodDeclaration(
4101 const Decl
*D
, llvm::DISubroutineType
*FnType
, unsigned LineNo
,
4102 llvm::DINode::DIFlags Flags
, llvm::DISubprogram::DISPFlags SPFlags
) {
4103 if (!D
|| DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4106 const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
);
4110 if (CGM
.getCodeGenOpts().DwarfVersion
< 5 && !OMD
->isDirectMethod())
4113 if (OMD
->isDirectMethod())
4114 SPFlags
|= llvm::DISubprogram::SPFlagObjCDirect
;
4116 // Starting with DWARF V5 method declarations are emitted as children of
4117 // the interface type.
4118 auto *ID
= dyn_cast_or_null
<ObjCInterfaceDecl
>(D
->getDeclContext());
4120 ID
= OMD
->getClassInterface();
4123 QualType
QTy(ID
->getTypeForDecl(), 0);
4124 auto It
= TypeCache
.find(QTy
.getAsOpaquePtr());
4125 if (It
== TypeCache
.end())
4127 auto *InterfaceType
= cast
<llvm::DICompositeType
>(It
->second
);
4128 llvm::DISubprogram
*FD
= DBuilder
.createFunction(
4129 InterfaceType
, getObjCMethodName(OMD
), StringRef(),
4130 InterfaceType
->getFile(), LineNo
, FnType
, LineNo
, Flags
, SPFlags
);
4131 DBuilder
.finalizeSubprogram(FD
);
4132 ObjCMethodCache
[ID
].push_back({FD
, OMD
->isDirectMethod()});
4136 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
4137 // implicit parameter "this".
4138 llvm::DISubroutineType
*CGDebugInfo::getOrCreateFunctionType(const Decl
*D
,
4141 // In CodeView, we emit the function types in line tables only because the
4142 // only way to distinguish between functions is by display name and type.
4143 if (!D
|| (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
&&
4144 !CGM
.getCodeGenOpts().EmitCodeView
))
4145 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4146 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4147 return DBuilder
.createSubroutineType(
4148 DBuilder
.getOrCreateTypeArray(std::nullopt
));
4150 if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(D
))
4151 return getOrCreateMethodType(Method
, F
);
4153 const auto *FTy
= FnType
->getAs
<FunctionType
>();
4154 CallingConv CC
= FTy
? FTy
->getCallConv() : CallingConv::CC_C
;
4156 if (const auto *OMethod
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4157 // Add "self" and "_cmd"
4158 SmallVector
<llvm::Metadata
*, 16> Elts
;
4160 // First element is always return type. For 'void' functions it is NULL.
4161 QualType ResultTy
= OMethod
->getReturnType();
4163 // Replace the instancetype keyword with the actual type.
4164 if (ResultTy
== CGM
.getContext().getObjCInstanceType())
4165 ResultTy
= CGM
.getContext().getPointerType(
4166 QualType(OMethod
->getClassInterface()->getTypeForDecl(), 0));
4168 Elts
.push_back(getOrCreateType(ResultTy
, F
));
4169 // "self" pointer is always first argument.
4170 QualType SelfDeclTy
;
4171 if (auto *SelfDecl
= OMethod
->getSelfDecl())
4172 SelfDeclTy
= SelfDecl
->getType();
4173 else if (auto *FPT
= dyn_cast
<FunctionProtoType
>(FnType
))
4174 if (FPT
->getNumParams() > 1)
4175 SelfDeclTy
= FPT
->getParamType(0);
4176 if (!SelfDeclTy
.isNull())
4178 CreateSelfType(SelfDeclTy
, getOrCreateType(SelfDeclTy
, F
)));
4179 // "_cmd" pointer is always second argument.
4180 Elts
.push_back(DBuilder
.createArtificialType(
4181 getOrCreateType(CGM
.getContext().getObjCSelType(), F
)));
4182 // Get rest of the arguments.
4183 for (const auto *PI
: OMethod
->parameters())
4184 Elts
.push_back(getOrCreateType(PI
->getType(), F
));
4185 // Variadic methods need a special marker at the end of the type list.
4186 if (OMethod
->isVariadic())
4187 Elts
.push_back(DBuilder
.createUnspecifiedParameter());
4189 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(Elts
);
4190 return DBuilder
.createSubroutineType(EltTypeArray
, llvm::DINode::FlagZero
,
4194 // Handle variadic function types; they need an additional
4195 // unspecified parameter.
4196 if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
))
4197 if (FD
->isVariadic()) {
4198 SmallVector
<llvm::Metadata
*, 16> EltTys
;
4199 EltTys
.push_back(getOrCreateType(FD
->getReturnType(), F
));
4200 if (const auto *FPT
= dyn_cast
<FunctionProtoType
>(FnType
))
4201 for (QualType ParamType
: FPT
->param_types())
4202 EltTys
.push_back(getOrCreateType(ParamType
, F
));
4203 EltTys
.push_back(DBuilder
.createUnspecifiedParameter());
4204 llvm::DITypeRefArray EltTypeArray
= DBuilder
.getOrCreateTypeArray(EltTys
);
4205 return DBuilder
.createSubroutineType(EltTypeArray
, llvm::DINode::FlagZero
,
4209 return cast
<llvm::DISubroutineType
>(getOrCreateType(FnType
, F
));
4213 CGDebugInfo::getFunctionType(const FunctionDecl
*FD
, QualType RetTy
,
4214 const SmallVectorImpl
<const VarDecl
*> &Args
) {
4215 CallingConv CC
= CallingConv::CC_C
;
4217 if (const auto *SrcFnTy
= FD
->getType()->getAs
<FunctionType
>())
4218 CC
= SrcFnTy
->getCallConv();
4219 SmallVector
<QualType
, 16> ArgTypes
;
4220 for (const VarDecl
*VD
: Args
)
4221 ArgTypes
.push_back(VD
->getType());
4222 return CGM
.getContext().getFunctionType(RetTy
, ArgTypes
,
4223 FunctionProtoType::ExtProtoInfo(CC
));
4226 void CGDebugInfo::emitFunctionStart(GlobalDecl GD
, SourceLocation Loc
,
4227 SourceLocation ScopeLoc
, QualType FnType
,
4228 llvm::Function
*Fn
, bool CurFuncIsThunk
) {
4230 StringRef LinkageName
;
4232 FnBeginRegionCount
.push_back(LexicalBlockStack
.size());
4234 const Decl
*D
= GD
.getDecl();
4235 bool HasDecl
= (D
!= nullptr);
4237 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4238 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
4239 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
4240 llvm::DIScope
*FDContext
= Unit
;
4241 llvm::DINodeArray TParamsArray
;
4243 // Use llvm function name.
4244 LinkageName
= Fn
->getName();
4245 } else if (const auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
4246 // If there is a subprogram for this function available then use it.
4247 auto FI
= SPCache
.find(FD
->getCanonicalDecl());
4248 if (FI
!= SPCache
.end()) {
4249 auto *SP
= dyn_cast_or_null
<llvm::DISubprogram
>(FI
->second
);
4250 if (SP
&& SP
->isDefinition()) {
4251 LexicalBlockStack
.emplace_back(SP
);
4252 RegionMap
[D
].reset(SP
);
4256 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, FDContext
,
4257 TParamsArray
, Flags
);
4258 } else if (const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4259 Name
= getObjCMethodName(OMD
);
4260 Flags
|= llvm::DINode::FlagPrototyped
;
4261 } else if (isa
<VarDecl
>(D
) &&
4262 GD
.getDynamicInitKind() != DynamicInitKind::NoStub
) {
4263 // This is a global initializer or atexit destructor for a global variable.
4264 Name
= getDynamicInitializerName(cast
<VarDecl
>(D
), GD
.getDynamicInitKind(),
4267 Name
= Fn
->getName();
4269 if (isa
<BlockDecl
>(D
))
4272 Flags
|= llvm::DINode::FlagPrototyped
;
4274 if (Name
.starts_with("\01"))
4275 Name
= Name
.substr(1);
4277 assert((!D
|| !isa
<VarDecl
>(D
) ||
4278 GD
.getDynamicInitKind() != DynamicInitKind::NoStub
) &&
4279 "Unexpected DynamicInitKind !");
4281 if (!HasDecl
|| D
->isImplicit() || D
->hasAttr
<ArtificialAttr
>() ||
4282 isa
<VarDecl
>(D
) || isa
<CapturedDecl
>(D
)) {
4283 Flags
|= llvm::DINode::FlagArtificial
;
4284 // Artificial functions should not silently reuse CurLoc.
4285 CurLoc
= SourceLocation();
4289 Flags
|= llvm::DINode::FlagThunk
;
4291 if (Fn
->hasLocalLinkage())
4292 SPFlags
|= llvm::DISubprogram::SPFlagLocalToUnit
;
4293 if (CGM
.getLangOpts().Optimize
)
4294 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
4296 llvm::DINode::DIFlags FlagsForDef
= Flags
| getCallSiteRelatedAttrs();
4297 llvm::DISubprogram::DISPFlags SPFlagsForDef
=
4298 SPFlags
| llvm::DISubprogram::SPFlagDefinition
;
4300 const unsigned LineNo
= getLineNumber(Loc
.isValid() ? Loc
: CurLoc
);
4301 unsigned ScopeLine
= getLineNumber(ScopeLoc
);
4302 llvm::DISubroutineType
*DIFnType
= getOrCreateFunctionType(D
, FnType
, Unit
);
4303 llvm::DISubprogram
*Decl
= nullptr;
4304 llvm::DINodeArray Annotations
= nullptr;
4306 Decl
= isa
<ObjCMethodDecl
>(D
)
4307 ? getObjCMethodDeclaration(D
, DIFnType
, LineNo
, Flags
, SPFlags
)
4308 : getFunctionDeclaration(D
);
4309 Annotations
= CollectBTFDeclTagAnnotations(D
);
4312 // FIXME: The function declaration we're constructing here is mostly reusing
4313 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4314 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4315 // all subprograms instead of the actual context since subprogram definitions
4316 // are emitted as CU level entities by the backend.
4317 llvm::DISubprogram
*SP
= DBuilder
.createFunction(
4318 FDContext
, Name
, LinkageName
, Unit
, LineNo
, DIFnType
, ScopeLine
,
4319 FlagsForDef
, SPFlagsForDef
, TParamsArray
.get(), Decl
, nullptr,
4321 Fn
->setSubprogram(SP
);
4322 // We might get here with a VarDecl in the case we're generating
4323 // code for the initialization of globals. Do not record these decls
4324 // as they will overwrite the actual VarDecl Decl in the cache.
4325 if (HasDecl
&& isa
<FunctionDecl
>(D
))
4326 DeclCache
[D
->getCanonicalDecl()].reset(SP
);
4328 // Push the function onto the lexical block stack.
4329 LexicalBlockStack
.emplace_back(SP
);
4332 RegionMap
[D
].reset(SP
);
4335 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD
, SourceLocation Loc
,
4336 QualType FnType
, llvm::Function
*Fn
) {
4338 StringRef LinkageName
;
4340 const Decl
*D
= GD
.getDecl();
4344 llvm::TimeTraceScope
TimeScope("DebugFunction", [&]() {
4345 return GetName(D
, true);
4348 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4349 llvm::DIFile
*Unit
= getOrCreateFile(Loc
);
4350 bool IsDeclForCallSite
= Fn
? true : false;
4351 llvm::DIScope
*FDContext
=
4352 IsDeclForCallSite
? Unit
: getDeclContextDescriptor(D
);
4353 llvm::DINodeArray TParamsArray
;
4354 if (isa
<FunctionDecl
>(D
)) {
4355 // If there is a DISubprogram for this function available then use it.
4356 collectFunctionDeclProps(GD
, Unit
, Name
, LinkageName
, FDContext
,
4357 TParamsArray
, Flags
);
4358 } else if (const auto *OMD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
4359 Name
= getObjCMethodName(OMD
);
4360 Flags
|= llvm::DINode::FlagPrototyped
;
4362 llvm_unreachable("not a function or ObjC method");
4364 if (!Name
.empty() && Name
[0] == '\01')
4365 Name
= Name
.substr(1);
4367 if (D
->isImplicit()) {
4368 Flags
|= llvm::DINode::FlagArtificial
;
4369 // Artificial functions without a location should not silently reuse CurLoc.
4370 if (Loc
.isInvalid())
4371 CurLoc
= SourceLocation();
4373 unsigned LineNo
= getLineNumber(Loc
);
4374 unsigned ScopeLine
= 0;
4375 llvm::DISubprogram::DISPFlags SPFlags
= llvm::DISubprogram::SPFlagZero
;
4376 if (CGM
.getLangOpts().Optimize
)
4377 SPFlags
|= llvm::DISubprogram::SPFlagOptimized
;
4379 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
4380 llvm::DISubroutineType
*STy
= getOrCreateFunctionType(D
, FnType
, Unit
);
4381 llvm::DISubprogram
*SP
= DBuilder
.createFunction(
4382 FDContext
, Name
, LinkageName
, Unit
, LineNo
, STy
, ScopeLine
, Flags
,
4383 SPFlags
, TParamsArray
.get(), nullptr, nullptr, Annotations
);
4385 // Preserve btf_decl_tag attributes for parameters of extern functions
4386 // for BPF target. The parameters created in this loop are attached as
4387 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4388 if (IsDeclForCallSite
&& CGM
.getTarget().getTriple().isBPF()) {
4389 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
4390 llvm::DITypeRefArray ParamTypes
= STy
->getTypeArray();
4392 for (ParmVarDecl
*PD
: FD
->parameters()) {
4393 llvm::DINodeArray ParamAnnotations
= CollectBTFDeclTagAnnotations(PD
);
4394 DBuilder
.createParameterVariable(
4395 SP
, PD
->getName(), ArgNo
, Unit
, LineNo
, ParamTypes
[ArgNo
], true,
4396 llvm::DINode::FlagZero
, ParamAnnotations
);
4402 if (IsDeclForCallSite
)
4403 Fn
->setSubprogram(SP
);
4405 DBuilder
.finalizeSubprogram(SP
);
4408 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase
*CallOrInvoke
,
4409 QualType CalleeType
,
4410 const FunctionDecl
*CalleeDecl
) {
4413 auto *Func
= CallOrInvoke
->getCalledFunction();
4416 if (Func
->getSubprogram())
4419 // Do not emit a declaration subprogram for a function with nodebug
4420 // attribute, or if call site info isn't required.
4421 if (CalleeDecl
->hasAttr
<NoDebugAttr
>() ||
4422 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero
)
4425 // If there is no DISubprogram attached to the function being called,
4426 // create the one describing the function in order to have complete
4427 // call site debug info.
4428 if (!CalleeDecl
->isStatic() && !CalleeDecl
->isInlined())
4429 EmitFunctionDecl(CalleeDecl
, CalleeDecl
->getLocation(), CalleeType
, Func
);
4432 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy
&Builder
, GlobalDecl GD
) {
4433 const auto *FD
= cast
<FunctionDecl
>(GD
.getDecl());
4434 // If there is a subprogram for this function available then use it.
4435 auto FI
= SPCache
.find(FD
->getCanonicalDecl());
4436 llvm::DISubprogram
*SP
= nullptr;
4437 if (FI
!= SPCache
.end())
4438 SP
= dyn_cast_or_null
<llvm::DISubprogram
>(FI
->second
);
4439 if (!SP
|| !SP
->isDefinition())
4440 SP
= getFunctionStub(GD
);
4441 FnBeginRegionCount
.push_back(LexicalBlockStack
.size());
4442 LexicalBlockStack
.emplace_back(SP
);
4443 setInlinedAt(Builder
.getCurrentDebugLocation());
4444 EmitLocation(Builder
, FD
->getLocation());
4447 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy
&Builder
) {
4448 assert(CurInlinedAt
&& "unbalanced inline scope stack");
4449 EmitFunctionEnd(Builder
, nullptr);
4450 setInlinedAt(llvm::DebugLoc(CurInlinedAt
).getInlinedAt());
4453 void CGDebugInfo::EmitLocation(CGBuilderTy
&Builder
, SourceLocation Loc
) {
4454 // Update our current location
4457 if (CurLoc
.isInvalid() || CurLoc
.isMacroID() || LexicalBlockStack
.empty())
4460 llvm::MDNode
*Scope
= LexicalBlockStack
.back();
4461 Builder
.SetCurrentDebugLocation(
4462 llvm::DILocation::get(CGM
.getLLVMContext(), getLineNumber(CurLoc
),
4463 getColumnNumber(CurLoc
), Scope
, CurInlinedAt
));
4466 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc
) {
4467 llvm::MDNode
*Back
= nullptr;
4468 if (!LexicalBlockStack
.empty())
4469 Back
= LexicalBlockStack
.back().get();
4470 LexicalBlockStack
.emplace_back(DBuilder
.createLexicalBlock(
4471 cast
<llvm::DIScope
>(Back
), getOrCreateFile(CurLoc
), getLineNumber(CurLoc
),
4472 getColumnNumber(CurLoc
)));
4475 void CGDebugInfo::AppendAddressSpaceXDeref(
4476 unsigned AddressSpace
, SmallVectorImpl
<uint64_t> &Expr
) const {
4477 std::optional
<unsigned> DWARFAddressSpace
=
4478 CGM
.getTarget().getDWARFAddressSpace(AddressSpace
);
4479 if (!DWARFAddressSpace
)
4482 Expr
.push_back(llvm::dwarf::DW_OP_constu
);
4483 Expr
.push_back(*DWARFAddressSpace
);
4484 Expr
.push_back(llvm::dwarf::DW_OP_swap
);
4485 Expr
.push_back(llvm::dwarf::DW_OP_xderef
);
4488 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy
&Builder
,
4489 SourceLocation Loc
) {
4490 // Set our current location.
4493 // Emit a line table change for the current location inside the new scope.
4494 Builder
.SetCurrentDebugLocation(llvm::DILocation::get(
4495 CGM
.getLLVMContext(), getLineNumber(Loc
), getColumnNumber(Loc
),
4496 LexicalBlockStack
.back(), CurInlinedAt
));
4498 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4501 // Create a new lexical block and push it on the stack.
4502 CreateLexicalBlock(Loc
);
4505 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy
&Builder
,
4506 SourceLocation Loc
) {
4507 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4509 // Provide an entry in the line table for the end of the block.
4510 EmitLocation(Builder
, Loc
);
4512 if (DebugKind
<= llvm::codegenoptions::DebugLineTablesOnly
)
4515 LexicalBlockStack
.pop_back();
4518 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy
&Builder
, llvm::Function
*Fn
) {
4519 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4520 unsigned RCount
= FnBeginRegionCount
.back();
4521 assert(RCount
<= LexicalBlockStack
.size() && "Region stack mismatch");
4523 // Pop all regions for this function.
4524 while (LexicalBlockStack
.size() != RCount
) {
4525 // Provide an entry in the line table for the end of the block.
4526 EmitLocation(Builder
, CurLoc
);
4527 LexicalBlockStack
.pop_back();
4529 FnBeginRegionCount
.pop_back();
4531 if (Fn
&& Fn
->getSubprogram())
4532 DBuilder
.finalizeSubprogram(Fn
->getSubprogram());
4535 CGDebugInfo::BlockByRefType
4536 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl
*VD
,
4537 uint64_t *XOffset
) {
4538 SmallVector
<llvm::Metadata
*, 5> EltTys
;
4540 uint64_t FieldSize
, FieldOffset
;
4541 uint32_t FieldAlign
;
4543 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
4544 QualType Type
= VD
->getType();
4547 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4548 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
4549 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__forwarding", &FieldOffset
));
4550 FType
= CGM
.getContext().IntTy
;
4551 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
4552 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__size", &FieldOffset
));
4554 bool HasCopyAndDispose
= CGM
.getContext().BlockRequiresCopying(Type
, VD
);
4555 if (HasCopyAndDispose
) {
4556 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4558 CreateMemberType(Unit
, FType
, "__copy_helper", &FieldOffset
));
4560 CreateMemberType(Unit
, FType
, "__destroy_helper", &FieldOffset
));
4562 bool HasByrefExtendedLayout
;
4563 Qualifiers::ObjCLifetime Lifetime
;
4564 if (CGM
.getContext().getByrefLifetime(Type
, Lifetime
,
4565 HasByrefExtendedLayout
) &&
4566 HasByrefExtendedLayout
) {
4567 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
4569 CreateMemberType(Unit
, FType
, "__byref_variable_layout", &FieldOffset
));
4572 CharUnits Align
= CGM
.getContext().getDeclAlign(VD
);
4573 if (Align
> CGM
.getContext().toCharUnitsFromBits(
4574 CGM
.getTarget().getPointerAlign(LangAS::Default
))) {
4575 CharUnits FieldOffsetInBytes
=
4576 CGM
.getContext().toCharUnitsFromBits(FieldOffset
);
4577 CharUnits AlignedOffsetInBytes
= FieldOffsetInBytes
.alignTo(Align
);
4578 CharUnits NumPaddingBytes
= AlignedOffsetInBytes
- FieldOffsetInBytes
;
4580 if (NumPaddingBytes
.isPositive()) {
4581 llvm::APInt
pad(32, NumPaddingBytes
.getQuantity());
4582 FType
= CGM
.getContext().getConstantArrayType(
4583 CGM
.getContext().CharTy
, pad
, nullptr, ArraySizeModifier::Normal
, 0);
4584 EltTys
.push_back(CreateMemberType(Unit
, FType
, "", &FieldOffset
));
4589 llvm::DIType
*WrappedTy
= getOrCreateType(FType
, Unit
);
4590 FieldSize
= CGM
.getContext().getTypeSize(FType
);
4591 FieldAlign
= CGM
.getContext().toBits(Align
);
4593 *XOffset
= FieldOffset
;
4594 llvm::DIType
*FieldTy
= DBuilder
.createMemberType(
4595 Unit
, VD
->getName(), Unit
, 0, FieldSize
, FieldAlign
, FieldOffset
,
4596 llvm::DINode::FlagZero
, WrappedTy
);
4597 EltTys
.push_back(FieldTy
);
4598 FieldOffset
+= FieldSize
;
4600 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
4601 return {DBuilder
.createStructType(Unit
, "", Unit
, 0, FieldOffset
, 0,
4602 llvm::DINode::FlagZero
, nullptr, Elements
),
4606 llvm::DILocalVariable
*CGDebugInfo::EmitDeclare(const VarDecl
*VD
,
4607 llvm::Value
*Storage
,
4608 std::optional
<unsigned> ArgNo
,
4609 CGBuilderTy
&Builder
,
4610 const bool UsePointerValue
) {
4611 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4612 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4613 if (VD
->hasAttr
<NoDebugAttr
>())
4617 VD
->isImplicit() || (isa
<Decl
>(VD
->getDeclContext()) &&
4618 cast
<Decl
>(VD
->getDeclContext())->isImplicit());
4619 llvm::DIFile
*Unit
= nullptr;
4621 Unit
= getOrCreateFile(VD
->getLocation());
4623 uint64_t XOffset
= 0;
4624 if (VD
->hasAttr
<BlocksAttr
>())
4625 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
).WrappedType
;
4627 Ty
= getOrCreateType(VD
->getType(), Unit
);
4629 // If there is no debug info for this type then do not emit debug info
4630 // for this variable.
4634 // Get location information.
4636 unsigned Column
= 0;
4638 Line
= getLineNumber(VD
->getLocation());
4639 Column
= getColumnNumber(VD
->getLocation());
4641 SmallVector
<uint64_t, 13> Expr
;
4642 llvm::DINode::DIFlags Flags
= llvm::DINode::FlagZero
;
4643 if (VD
->isImplicit())
4644 Flags
|= llvm::DINode::FlagArtificial
;
4646 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
4648 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(VD
->getType());
4649 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
4651 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4652 // object pointer flag.
4653 if (const auto *IPD
= dyn_cast
<ImplicitParamDecl
>(VD
)) {
4654 if (IPD
->getParameterKind() == ImplicitParamKind::CXXThis
||
4655 IPD
->getParameterKind() == ImplicitParamKind::ObjCSelf
)
4656 Flags
|= llvm::DINode::FlagObjectPointer
;
4659 // Note: Older versions of clang used to emit byval references with an extra
4660 // DW_OP_deref, because they referenced the IR arg directly instead of
4661 // referencing an alloca. Newer versions of LLVM don't treat allocas
4662 // differently from other function arguments when used in a dbg.declare.
4663 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4664 StringRef Name
= VD
->getName();
4665 if (!Name
.empty()) {
4666 // __block vars are stored on the heap if they are captured by a block that
4667 // can escape the local scope.
4668 if (VD
->isEscapingByref()) {
4669 // Here, we need an offset *into* the alloca.
4670 CharUnits offset
= CharUnits::fromQuantity(32);
4671 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4672 // offset of __forwarding field
4673 offset
= CGM
.getContext().toCharUnitsFromBits(
4674 CGM
.getTarget().getPointerWidth(LangAS::Default
));
4675 Expr
.push_back(offset
.getQuantity());
4676 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4677 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4678 // offset of x field
4679 offset
= CGM
.getContext().toCharUnitsFromBits(XOffset
);
4680 Expr
.push_back(offset
.getQuantity());
4682 } else if (const auto *RT
= dyn_cast
<RecordType
>(VD
->getType())) {
4683 // If VD is an anonymous union then Storage represents value for
4684 // all union fields.
4685 const RecordDecl
*RD
= RT
->getDecl();
4686 if (RD
->isUnion() && RD
->isAnonymousStructOrUnion()) {
4687 // GDB has trouble finding local variables in anonymous unions, so we emit
4688 // artificial local variables for each of the members.
4690 // FIXME: Remove this code as soon as GDB supports this.
4691 // The debug info verifier in LLVM operates based on the assumption that a
4692 // variable has the same size as its storage and we had to disable the
4693 // check for artificial variables.
4694 for (const auto *Field
: RD
->fields()) {
4695 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
4696 StringRef FieldName
= Field
->getName();
4698 // Ignore unnamed fields. Do not ignore unnamed records.
4699 if (FieldName
.empty() && !isa
<RecordType
>(Field
->getType()))
4702 // Use VarDecl's Tag, Scope and Line number.
4703 auto FieldAlign
= getDeclAlignIfRequired(Field
, CGM
.getContext());
4704 auto *D
= DBuilder
.createAutoVariable(
4705 Scope
, FieldName
, Unit
, Line
, FieldTy
, CGM
.getLangOpts().Optimize
,
4706 Flags
| llvm::DINode::FlagArtificial
, FieldAlign
);
4708 // Insert an llvm.dbg.declare into the current block.
4709 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4710 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4713 Builder
.GetInsertBlock());
4718 // Clang stores the sret pointer provided by the caller in a static alloca.
4719 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4720 // the address of the variable.
4721 if (UsePointerValue
) {
4722 assert(!llvm::is_contained(Expr
, llvm::dwarf::DW_OP_deref
) &&
4723 "Debug info already contains DW_OP_deref.");
4724 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4727 // Create the descriptor for the variable.
4728 llvm::DILocalVariable
*D
= nullptr;
4730 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(VD
);
4731 D
= DBuilder
.createParameterVariable(Scope
, Name
, *ArgNo
, Unit
, Line
, Ty
,
4732 CGM
.getLangOpts().Optimize
, Flags
,
4735 // For normal local variable, we will try to find out whether 'VD' is the
4736 // copy parameter of coroutine.
4737 // If yes, we are going to use DIVariable of the origin parameter instead
4738 // of creating the new one.
4739 // If no, it might be a normal alloc, we just create a new one for it.
4741 // Check whether the VD is move parameters.
4742 auto RemapCoroArgToLocalVar
= [&]() -> llvm::DILocalVariable
* {
4743 // The scope of parameter and move-parameter should be distinct
4745 if (!isa
<llvm::DISubprogram
>(Scope
) || !Scope
->isDistinct())
4748 auto Iter
= llvm::find_if(CoroutineParameterMappings
, [&](auto &Pair
) {
4749 Stmt
*StmtPtr
= const_cast<Stmt
*>(Pair
.second
);
4750 if (DeclStmt
*DeclStmtPtr
= dyn_cast
<DeclStmt
>(StmtPtr
)) {
4751 DeclGroupRef DeclGroup
= DeclStmtPtr
->getDeclGroup();
4752 Decl
*Decl
= DeclGroup
.getSingleDecl();
4753 if (VD
== dyn_cast_or_null
<VarDecl
>(Decl
))
4759 if (Iter
!= CoroutineParameterMappings
.end()) {
4760 ParmVarDecl
*PD
= const_cast<ParmVarDecl
*>(Iter
->first
);
4761 auto Iter2
= llvm::find_if(ParamDbgMappings
, [&](auto &DbgPair
) {
4762 return DbgPair
.first
== PD
&& DbgPair
.second
->getScope() == Scope
;
4764 if (Iter2
!= ParamDbgMappings
.end())
4765 return const_cast<llvm::DILocalVariable
*>(Iter2
->second
);
4770 // If we couldn't find a move param DIVariable, create a new one.
4771 D
= RemapCoroArgToLocalVar();
4772 // Or we will create a new DIVariable for this Decl if D dose not exists.
4774 D
= DBuilder
.createAutoVariable(Scope
, Name
, Unit
, Line
, Ty
,
4775 CGM
.getLangOpts().Optimize
, Flags
, Align
);
4777 // Insert an llvm.dbg.declare into the current block.
4778 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4779 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4780 Column
, Scope
, CurInlinedAt
),
4781 Builder
.GetInsertBlock());
4786 llvm::DIType
*CGDebugInfo::CreateBindingDeclType(const BindingDecl
*BD
) {
4787 llvm::DIFile
*Unit
= getOrCreateFile(BD
->getLocation());
4789 // If the declaration is bound to a bitfield struct field, its type may have a
4790 // size that is different from its deduced declaration type's.
4791 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BD
->getBinding())) {
4792 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl())) {
4793 if (FD
->isBitField()) {
4794 ASTContext
&Context
= CGM
.getContext();
4795 const CGRecordLayout
&RL
=
4796 CGM
.getTypes().getCGRecordLayout(FD
->getParent());
4797 const CGBitFieldInfo
&Info
= RL
.getBitFieldInfo(FD
);
4799 // Find an integer type with the same bitwidth as the bitfield size. If
4800 // no suitable type is present in the target, give up on producing debug
4801 // information as it would be wrong. It is certainly possible to produce
4802 // correct debug info, but the logic isn't currently implemented.
4803 uint64_t BitfieldSizeInBits
= Info
.Size
;
4805 Context
.getIntTypeForBitwidth(BitfieldSizeInBits
, Info
.IsSigned
);
4808 Qualifiers Quals
= BD
->getType().getQualifiers();
4809 QualType FinalTy
= Context
.getQualifiedType(IntTy
, Quals
);
4810 llvm::DIType
*Ty
= getOrCreateType(FinalTy
, Unit
);
4817 return getOrCreateType(BD
->getType(), Unit
);
4820 llvm::DILocalVariable
*CGDebugInfo::EmitDeclare(const BindingDecl
*BD
,
4821 llvm::Value
*Storage
,
4822 std::optional
<unsigned> ArgNo
,
4823 CGBuilderTy
&Builder
,
4824 const bool UsePointerValue
) {
4825 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4826 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4827 if (BD
->hasAttr
<NoDebugAttr
>())
4830 // Skip the tuple like case, we don't handle that here
4831 if (isa
<DeclRefExpr
>(BD
->getBinding()))
4834 llvm::DIType
*Ty
= CreateBindingDeclType(BD
);
4836 // If there is no debug info for this type then do not emit debug info
4837 // for this variable.
4841 auto Align
= getDeclAlignIfRequired(BD
, CGM
.getContext());
4842 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(BD
->getType());
4844 SmallVector
<uint64_t, 3> Expr
;
4845 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
4847 // Clang stores the sret pointer provided by the caller in a static alloca.
4848 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4849 // the address of the variable.
4850 if (UsePointerValue
) {
4851 assert(!llvm::is_contained(Expr
, llvm::dwarf::DW_OP_deref
) &&
4852 "Debug info already contains DW_OP_deref.");
4853 Expr
.push_back(llvm::dwarf::DW_OP_deref
);
4856 unsigned Line
= getLineNumber(BD
->getLocation());
4857 unsigned Column
= getColumnNumber(BD
->getLocation());
4858 StringRef Name
= BD
->getName();
4859 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4860 llvm::DIFile
*Unit
= getOrCreateFile(BD
->getLocation());
4861 // Create the descriptor for the variable.
4862 llvm::DILocalVariable
*D
= DBuilder
.createAutoVariable(
4863 Scope
, Name
, Unit
, Line
, Ty
, CGM
.getLangOpts().Optimize
,
4864 llvm::DINode::FlagZero
, Align
);
4866 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(BD
->getBinding())) {
4867 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(ME
->getMemberDecl())) {
4868 const unsigned fieldIndex
= FD
->getFieldIndex();
4869 const clang::CXXRecordDecl
*parent
=
4870 (const CXXRecordDecl
*)FD
->getParent();
4871 const ASTRecordLayout
&layout
=
4872 CGM
.getContext().getASTRecordLayout(parent
);
4873 const uint64_t fieldOffset
= layout
.getFieldOffset(fieldIndex
);
4875 if (fieldOffset
!= 0) {
4876 // Currently if the field offset is not a multiple of byte, the produced
4877 // location would not be accurate. Therefore give up.
4878 if (fieldOffset
% CGM
.getContext().getCharWidth() != 0)
4881 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4883 CGM
.getContext().toCharUnitsFromBits(fieldOffset
).getQuantity());
4886 } else if (const ArraySubscriptExpr
*ASE
=
4887 dyn_cast
<ArraySubscriptExpr
>(BD
->getBinding())) {
4888 if (const IntegerLiteral
*IL
= dyn_cast
<IntegerLiteral
>(ASE
->getIdx())) {
4889 const uint64_t value
= IL
->getValue().getZExtValue();
4890 const uint64_t typeSize
= CGM
.getContext().getTypeSize(BD
->getType());
4893 Expr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
4894 Expr
.push_back(CGM
.getContext()
4895 .toCharUnitsFromBits(value
* typeSize
)
4901 // Insert an llvm.dbg.declare into the current block.
4902 DBuilder
.insertDeclare(Storage
, D
, DBuilder
.createExpression(Expr
),
4903 llvm::DILocation::get(CGM
.getLLVMContext(), Line
,
4904 Column
, Scope
, CurInlinedAt
),
4905 Builder
.GetInsertBlock());
4910 llvm::DILocalVariable
*
4911 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl
*VD
, llvm::Value
*Storage
,
4912 CGBuilderTy
&Builder
,
4913 const bool UsePointerValue
) {
4914 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4916 if (auto *DD
= dyn_cast
<DecompositionDecl
>(VD
)) {
4917 for (auto *B
: DD
->bindings()) {
4918 EmitDeclare(B
, Storage
, std::nullopt
, Builder
,
4919 VD
->getType()->isReferenceType());
4921 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
4922 // correspond to a user variable.
4926 return EmitDeclare(VD
, Storage
, std::nullopt
, Builder
, UsePointerValue
);
4929 void CGDebugInfo::EmitLabel(const LabelDecl
*D
, CGBuilderTy
&Builder
) {
4930 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4931 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4933 if (D
->hasAttr
<NoDebugAttr
>())
4936 auto *Scope
= cast
<llvm::DIScope
>(LexicalBlockStack
.back());
4937 llvm::DIFile
*Unit
= getOrCreateFile(D
->getLocation());
4939 // Get location information.
4940 unsigned Line
= getLineNumber(D
->getLocation());
4941 unsigned Column
= getColumnNumber(D
->getLocation());
4943 StringRef Name
= D
->getName();
4945 // Create the descriptor for the label.
4947 DBuilder
.createLabel(Scope
, Name
, Unit
, Line
, CGM
.getLangOpts().Optimize
);
4949 // Insert an llvm.dbg.label into the current block.
4950 DBuilder
.insertLabel(L
,
4951 llvm::DILocation::get(CGM
.getLLVMContext(), Line
, Column
,
4952 Scope
, CurInlinedAt
),
4953 Builder
.GetInsertBlock());
4956 llvm::DIType
*CGDebugInfo::CreateSelfType(const QualType
&QualTy
,
4958 llvm::DIType
*CachedTy
= getTypeOrNull(QualTy
);
4961 return DBuilder
.createObjectPointerType(Ty
);
4964 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4965 const VarDecl
*VD
, llvm::Value
*Storage
, CGBuilderTy
&Builder
,
4966 const CGBlockInfo
&blockInfo
, llvm::Instruction
*InsertPoint
) {
4967 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
4968 assert(!LexicalBlockStack
.empty() && "Region stack mismatch, stack empty!");
4970 if (Builder
.GetInsertBlock() == nullptr)
4972 if (VD
->hasAttr
<NoDebugAttr
>())
4975 bool isByRef
= VD
->hasAttr
<BlocksAttr
>();
4977 uint64_t XOffset
= 0;
4978 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
4981 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
).WrappedType
;
4983 Ty
= getOrCreateType(VD
->getType(), Unit
);
4985 // Self is passed along as an implicit non-arg variable in a
4986 // block. Mark it as the object pointer.
4987 if (const auto *IPD
= dyn_cast
<ImplicitParamDecl
>(VD
))
4988 if (IPD
->getParameterKind() == ImplicitParamKind::ObjCSelf
)
4989 Ty
= CreateSelfType(VD
->getType(), Ty
);
4991 // Get location information.
4992 const unsigned Line
=
4993 getLineNumber(VD
->getLocation().isValid() ? VD
->getLocation() : CurLoc
);
4994 unsigned Column
= getColumnNumber(VD
->getLocation());
4996 const llvm::DataLayout
&target
= CGM
.getDataLayout();
4998 CharUnits offset
= CharUnits::fromQuantity(
4999 target
.getStructLayout(blockInfo
.StructureType
)
5000 ->getElementOffset(blockInfo
.getCapture(VD
).getIndex()));
5002 SmallVector
<uint64_t, 9> addr
;
5003 addr
.push_back(llvm::dwarf::DW_OP_deref
);
5004 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
5005 addr
.push_back(offset
.getQuantity());
5007 addr
.push_back(llvm::dwarf::DW_OP_deref
);
5008 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
5009 // offset of __forwarding field
5011 CGM
.getContext().toCharUnitsFromBits(target
.getPointerSizeInBits(0));
5012 addr
.push_back(offset
.getQuantity());
5013 addr
.push_back(llvm::dwarf::DW_OP_deref
);
5014 addr
.push_back(llvm::dwarf::DW_OP_plus_uconst
);
5015 // offset of x field
5016 offset
= CGM
.getContext().toCharUnitsFromBits(XOffset
);
5017 addr
.push_back(offset
.getQuantity());
5020 // Create the descriptor for the variable.
5021 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
5022 auto *D
= DBuilder
.createAutoVariable(
5023 cast
<llvm::DILocalScope
>(LexicalBlockStack
.back()), VD
->getName(), Unit
,
5024 Line
, Ty
, false, llvm::DINode::FlagZero
, Align
);
5026 // Insert an llvm.dbg.declare into the current block.
5027 auto DL
= llvm::DILocation::get(CGM
.getLLVMContext(), Line
, Column
,
5028 LexicalBlockStack
.back(), CurInlinedAt
);
5029 auto *Expr
= DBuilder
.createExpression(addr
);
5031 DBuilder
.insertDeclare(Storage
, D
, Expr
, DL
, InsertPoint
);
5033 DBuilder
.insertDeclare(Storage
, D
, Expr
, DL
, Builder
.GetInsertBlock());
5036 llvm::DILocalVariable
*
5037 CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl
*VD
, llvm::Value
*AI
,
5038 unsigned ArgNo
, CGBuilderTy
&Builder
,
5039 bool UsePointerValue
) {
5040 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5041 return EmitDeclare(VD
, AI
, ArgNo
, Builder
, UsePointerValue
);
5045 struct BlockLayoutChunk
{
5046 uint64_t OffsetInBits
;
5047 const BlockDecl::Capture
*Capture
;
5049 bool operator<(const BlockLayoutChunk
&l
, const BlockLayoutChunk
&r
) {
5050 return l
.OffsetInBits
< r
.OffsetInBits
;
5054 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5055 const CGBlockInfo
&Block
, const ASTContext
&Context
, SourceLocation Loc
,
5056 const llvm::StructLayout
&BlockLayout
, llvm::DIFile
*Unit
,
5057 SmallVectorImpl
<llvm::Metadata
*> &Fields
) {
5058 // Blocks in OpenCL have unique constraints which make the standard fields
5059 // redundant while requiring size and align fields for enqueue_kernel. See
5060 // initializeForBlockHeader in CGBlocks.cpp
5061 if (CGM
.getLangOpts().OpenCL
) {
5062 Fields
.push_back(createFieldType("__size", Context
.IntTy
, Loc
, AS_public
,
5063 BlockLayout
.getElementOffsetInBits(0),
5065 Fields
.push_back(createFieldType("__align", Context
.IntTy
, Loc
, AS_public
,
5066 BlockLayout
.getElementOffsetInBits(1),
5069 Fields
.push_back(createFieldType("__isa", Context
.VoidPtrTy
, Loc
, AS_public
,
5070 BlockLayout
.getElementOffsetInBits(0),
5072 Fields
.push_back(createFieldType("__flags", Context
.IntTy
, Loc
, AS_public
,
5073 BlockLayout
.getElementOffsetInBits(1),
5076 createFieldType("__reserved", Context
.IntTy
, Loc
, AS_public
,
5077 BlockLayout
.getElementOffsetInBits(2), Unit
, Unit
));
5078 auto *FnTy
= Block
.getBlockExpr()->getFunctionType();
5079 auto FnPtrType
= CGM
.getContext().getPointerType(FnTy
->desugar());
5080 Fields
.push_back(createFieldType("__FuncPtr", FnPtrType
, Loc
, AS_public
,
5081 BlockLayout
.getElementOffsetInBits(3),
5083 Fields
.push_back(createFieldType(
5085 Context
.getPointerType(Block
.NeedsCopyDispose
5086 ? Context
.getBlockDescriptorExtendedType()
5087 : Context
.getBlockDescriptorType()),
5088 Loc
, AS_public
, BlockLayout
.getElementOffsetInBits(4), Unit
, Unit
));
5092 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo
&block
,
5095 llvm::AllocaInst
*Alloca
,
5096 CGBuilderTy
&Builder
) {
5097 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5098 ASTContext
&C
= CGM
.getContext();
5099 const BlockDecl
*blockDecl
= block
.getBlockDecl();
5101 // Collect some general information about the block's location.
5102 SourceLocation loc
= blockDecl
->getCaretLocation();
5103 llvm::DIFile
*tunit
= getOrCreateFile(loc
);
5104 unsigned line
= getLineNumber(loc
);
5105 unsigned column
= getColumnNumber(loc
);
5107 // Build the debug-info type for the block literal.
5108 getDeclContextDescriptor(blockDecl
);
5110 const llvm::StructLayout
*blockLayout
=
5111 CGM
.getDataLayout().getStructLayout(block
.StructureType
);
5113 SmallVector
<llvm::Metadata
*, 16> fields
;
5114 collectDefaultFieldsForBlockLiteralDeclare(block
, C
, loc
, *blockLayout
, tunit
,
5117 // We want to sort the captures by offset, not because DWARF
5118 // requires this, but because we're paranoid about debuggers.
5119 SmallVector
<BlockLayoutChunk
, 8> chunks
;
5122 if (blockDecl
->capturesCXXThis()) {
5123 BlockLayoutChunk chunk
;
5124 chunk
.OffsetInBits
=
5125 blockLayout
->getElementOffsetInBits(block
.CXXThisIndex
);
5126 chunk
.Capture
= nullptr;
5127 chunks
.push_back(chunk
);
5130 // Variable captures.
5131 for (const auto &capture
: blockDecl
->captures()) {
5132 const VarDecl
*variable
= capture
.getVariable();
5133 const CGBlockInfo::Capture
&captureInfo
= block
.getCapture(variable
);
5135 // Ignore constant captures.
5136 if (captureInfo
.isConstant())
5139 BlockLayoutChunk chunk
;
5140 chunk
.OffsetInBits
=
5141 blockLayout
->getElementOffsetInBits(captureInfo
.getIndex());
5142 chunk
.Capture
= &capture
;
5143 chunks
.push_back(chunk
);
5147 llvm::array_pod_sort(chunks
.begin(), chunks
.end());
5149 for (const BlockLayoutChunk
&Chunk
: chunks
) {
5150 uint64_t offsetInBits
= Chunk
.OffsetInBits
;
5151 const BlockDecl::Capture
*capture
= Chunk
.Capture
;
5153 // If we have a null capture, this must be the C++ 'this' capture.
5157 cast_or_null
<CXXMethodDecl
>(blockDecl
->getNonClosureContext()))
5158 type
= Method
->getThisType();
5159 else if (auto *RDecl
= dyn_cast
<CXXRecordDecl
>(blockDecl
->getParent()))
5160 type
= QualType(RDecl
->getTypeForDecl(), 0);
5162 llvm_unreachable("unexpected block declcontext");
5164 fields
.push_back(createFieldType("this", type
, loc
, AS_public
,
5165 offsetInBits
, tunit
, tunit
));
5169 const VarDecl
*variable
= capture
->getVariable();
5170 StringRef name
= variable
->getName();
5172 llvm::DIType
*fieldType
;
5173 if (capture
->isByRef()) {
5174 TypeInfo PtrInfo
= C
.getTypeInfo(C
.VoidPtrTy
);
5175 auto Align
= PtrInfo
.isAlignRequired() ? PtrInfo
.Align
: 0;
5176 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5179 EmitTypeForVarWithBlocksAttr(variable
, &xoffset
).BlockByRefWrapper
;
5180 fieldType
= DBuilder
.createPointerType(fieldType
, PtrInfo
.Width
);
5181 fieldType
= DBuilder
.createMemberType(tunit
, name
, tunit
, line
,
5182 PtrInfo
.Width
, Align
, offsetInBits
,
5183 llvm::DINode::FlagZero
, fieldType
);
5185 auto Align
= getDeclAlignIfRequired(variable
, CGM
.getContext());
5186 fieldType
= createFieldType(name
, variable
->getType(), loc
, AS_public
,
5187 offsetInBits
, Align
, tunit
, tunit
);
5189 fields
.push_back(fieldType
);
5192 SmallString
<36> typeName
;
5193 llvm::raw_svector_ostream(typeName
)
5194 << "__block_literal_" << CGM
.getUniqueBlockCount();
5196 llvm::DINodeArray fieldsArray
= DBuilder
.getOrCreateArray(fields
);
5198 llvm::DIType
*type
=
5199 DBuilder
.createStructType(tunit
, typeName
.str(), tunit
, line
,
5200 CGM
.getContext().toBits(block
.BlockSize
), 0,
5201 llvm::DINode::FlagZero
, nullptr, fieldsArray
);
5202 type
= DBuilder
.createPointerType(type
, CGM
.PointerWidthInBits
);
5204 // Get overall information about the block.
5205 llvm::DINode::DIFlags flags
= llvm::DINode::FlagArtificial
;
5206 auto *scope
= cast
<llvm::DILocalScope
>(LexicalBlockStack
.back());
5208 // Create the descriptor for the parameter.
5209 auto *debugVar
= DBuilder
.createParameterVariable(
5210 scope
, Name
, ArgNo
, tunit
, line
, type
, CGM
.getLangOpts().Optimize
, flags
);
5212 // Insert an llvm.dbg.declare into the current block.
5213 DBuilder
.insertDeclare(Alloca
, debugVar
, DBuilder
.createExpression(),
5214 llvm::DILocation::get(CGM
.getLLVMContext(), line
,
5215 column
, scope
, CurInlinedAt
),
5216 Builder
.GetInsertBlock());
5219 llvm::DIDerivedType
*
5220 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl
*D
) {
5221 if (!D
|| !D
->isStaticDataMember())
5224 auto MI
= StaticDataMemberCache
.find(D
->getCanonicalDecl());
5225 if (MI
!= StaticDataMemberCache
.end()) {
5226 assert(MI
->second
&& "Static data member declaration should still exist");
5230 // If the member wasn't found in the cache, lazily construct and add it to the
5231 // type (used when a limited form of the type is emitted).
5232 auto DC
= D
->getDeclContext();
5233 auto *Ctxt
= cast
<llvm::DICompositeType
>(getDeclContextDescriptor(D
));
5234 return CreateRecordStaticField(D
, Ctxt
, cast
<RecordDecl
>(DC
));
5237 llvm::DIGlobalVariableExpression
*CGDebugInfo::CollectAnonRecordDecls(
5238 const RecordDecl
*RD
, llvm::DIFile
*Unit
, unsigned LineNo
,
5239 StringRef LinkageName
, llvm::GlobalVariable
*Var
, llvm::DIScope
*DContext
) {
5240 llvm::DIGlobalVariableExpression
*GVE
= nullptr;
5242 for (const auto *Field
: RD
->fields()) {
5243 llvm::DIType
*FieldTy
= getOrCreateType(Field
->getType(), Unit
);
5244 StringRef FieldName
= Field
->getName();
5246 // Ignore unnamed fields, but recurse into anonymous records.
5247 if (FieldName
.empty()) {
5248 if (const auto *RT
= dyn_cast
<RecordType
>(Field
->getType()))
5249 GVE
= CollectAnonRecordDecls(RT
->getDecl(), Unit
, LineNo
, LinkageName
,
5253 // Use VarDecl's Tag, Scope and Line number.
5254 GVE
= DBuilder
.createGlobalVariableExpression(
5255 DContext
, FieldName
, LinkageName
, Unit
, LineNo
, FieldTy
,
5256 Var
->hasLocalLinkage());
5257 Var
->addDebugInfo(GVE
);
5262 static bool ReferencesAnonymousEntity(ArrayRef
<TemplateArgument
> Args
);
5263 static bool ReferencesAnonymousEntity(RecordType
*RT
) {
5264 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5265 // info we produce in the DWARF, so we can't get Clang's full name back.
5266 // But so long as it's not one of those, it doesn't matter if some sub-type
5267 // of the record (a template parameter) can't be reconstituted - because the
5268 // un-reconstitutable type itself will carry its own name.
5269 const auto *RD
= dyn_cast
<CXXRecordDecl
>(RT
->getDecl());
5272 if (!RD
->getIdentifier())
5274 auto *TSpecial
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
);
5277 return ReferencesAnonymousEntity(TSpecial
->getTemplateArgs().asArray());
5279 static bool ReferencesAnonymousEntity(ArrayRef
<TemplateArgument
> Args
) {
5280 return llvm::any_of(Args
, [&](const TemplateArgument
&TA
) {
5281 switch (TA
.getKind()) {
5282 case TemplateArgument::Pack
:
5283 return ReferencesAnonymousEntity(TA
.getPackAsArray());
5284 case TemplateArgument::Type
: {
5285 struct ReferencesAnonymous
5286 : public RecursiveASTVisitor
<ReferencesAnonymous
> {
5287 bool RefAnon
= false;
5288 bool VisitRecordType(RecordType
*RT
) {
5289 if (ReferencesAnonymousEntity(RT
)) {
5296 ReferencesAnonymous RT
;
5297 RT
.TraverseType(TA
.getAsType());
5309 struct ReconstitutableType
: public RecursiveASTVisitor
<ReconstitutableType
> {
5310 bool Reconstitutable
= true;
5311 bool VisitVectorType(VectorType
*FT
) {
5312 Reconstitutable
= false;
5315 bool VisitAtomicType(AtomicType
*FT
) {
5316 Reconstitutable
= false;
5319 bool VisitType(Type
*T
) {
5320 // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5321 // the DWARF, only the byte width.
5322 if (T
->isBitIntType()) {
5323 Reconstitutable
= false;
5328 bool TraverseEnumType(EnumType
*ET
) {
5329 // Unnamed enums can't be reconstituted due to a lack of column info we
5330 // produce in the DWARF, so we can't get Clang's full name back.
5331 if (const auto *ED
= dyn_cast
<EnumDecl
>(ET
->getDecl())) {
5332 if (!ED
->getIdentifier()) {
5333 Reconstitutable
= false;
5336 if (!ED
->isExternallyVisible()) {
5337 Reconstitutable
= false;
5343 bool VisitFunctionProtoType(FunctionProtoType
*FT
) {
5344 // noexcept is not encoded in DWARF, so the reversi
5345 Reconstitutable
&= !isNoexceptExceptionSpec(FT
->getExceptionSpecType());
5346 Reconstitutable
&= !FT
->getNoReturnAttr();
5347 return Reconstitutable
;
5349 bool VisitRecordType(RecordType
*RT
) {
5350 if (ReferencesAnonymousEntity(RT
)) {
5351 Reconstitutable
= false;
5357 } // anonymous namespace
5359 // Test whether a type name could be rebuilt from emitted debug info.
5360 static bool IsReconstitutableType(QualType QT
) {
5361 ReconstitutableType T
;
5363 return T
.Reconstitutable
;
5366 std::string
CGDebugInfo::GetName(const Decl
*D
, bool Qualified
) const {
5368 llvm::raw_string_ostream
OS(Name
);
5369 const NamedDecl
*ND
= dyn_cast
<NamedDecl
>(D
);
5372 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind
=
5373 CGM
.getCodeGenOpts().getDebugSimpleTemplateNames();
5375 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5376 TemplateNamesKind
= llvm::codegenoptions::DebugTemplateNamesKind::Full
;
5378 std::optional
<TemplateArgs
> Args
;
5380 bool IsOperatorOverload
= false; // isa<CXXConversionDecl>(ND);
5381 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
)) {
5382 Args
= GetTemplateArgs(RD
);
5383 } else if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
)) {
5384 Args
= GetTemplateArgs(FD
);
5385 auto NameKind
= ND
->getDeclName().getNameKind();
5386 IsOperatorOverload
|=
5387 NameKind
== DeclarationName::CXXOperatorName
||
5388 NameKind
== DeclarationName::CXXConversionFunctionName
;
5389 } else if (auto *VD
= dyn_cast
<VarDecl
>(ND
)) {
5390 Args
= GetTemplateArgs(VD
);
5392 std::function
<bool(ArrayRef
<TemplateArgument
>)> HasReconstitutableArgs
=
5393 [&](ArrayRef
<TemplateArgument
> Args
) {
5394 return llvm::all_of(Args
, [&](const TemplateArgument
&TA
) {
5395 switch (TA
.getKind()) {
5396 case TemplateArgument::Template
:
5397 // Easy to reconstitute - the value of the parameter in the debug
5398 // info is the string name of the template. (so the template name
5399 // itself won't benefit from any name rebuilding, but that's a
5400 // representational limitation - maybe DWARF could be
5401 // changed/improved to use some more structural representation)
5403 case TemplateArgument::Declaration
:
5404 // Reference and pointer non-type template parameters point to
5405 // variables, functions, etc and their value is, at best (for
5406 // variables) represented as an address - not a reference to the
5407 // DWARF describing the variable/function/etc. This makes it hard,
5408 // possibly impossible to rebuild the original name - looking up the
5409 // address in the executable file's symbol table would be needed.
5411 case TemplateArgument::NullPtr
:
5412 // These could be rebuilt, but figured they're close enough to the
5413 // declaration case, and not worth rebuilding.
5415 case TemplateArgument::Pack
:
5416 // A pack is invalid if any of the elements of the pack are invalid.
5417 return HasReconstitutableArgs(TA
.getPackAsArray());
5418 case TemplateArgument::Integral
:
5419 // Larger integers get encoded as DWARF blocks which are a bit
5420 // harder to parse back into a large integer, etc - so punting on
5421 // this for now. Re-parsing the integers back into APInt is probably
5422 // feasible some day.
5423 return TA
.getAsIntegral().getBitWidth() <= 64 &&
5424 IsReconstitutableType(TA
.getIntegralType());
5425 case TemplateArgument::StructuralValue
:
5427 case TemplateArgument::Type
:
5428 return IsReconstitutableType(TA
.getAsType());
5430 llvm_unreachable("Other, unresolved, template arguments should "
5431 "not be seen here");
5435 // A conversion operator presents complications/ambiguity if there's a
5436 // conversion to class template that is itself a template, eg:
5437 // template<typename T>
5438 // operator ns::t1<T, int>();
5439 // This should be named, eg: "operator ns::t1<float, int><float>"
5440 // (ignoring clang bug that means this is currently "operator t1<float>")
5441 // but if the arguments were stripped, the consumer couldn't differentiate
5442 // whether the template argument list for the conversion type was the
5443 // function's argument list (& no reconstitution was needed) or not.
5444 // This could be handled if reconstitutable names had a separate attribute
5445 // annotating them as such - this would remove the ambiguity.
5447 // Alternatively the template argument list could be parsed enough to check
5448 // whether there's one list or two, then compare that with the DWARF
5449 // description of the return type and the template argument lists to determine
5450 // how many lists there should be and if one is missing it could be assumed(?)
5451 // to be the function's template argument list & then be rebuilt.
5453 // Other operator overloads that aren't conversion operators could be
5454 // reconstituted but would require a bit more nuance about detecting the
5455 // difference between these different operators during that rebuilding.
5456 bool Reconstitutable
=
5457 Args
&& HasReconstitutableArgs(Args
->Args
) && !IsOperatorOverload
;
5459 PrintingPolicy PP
= getPrintingPolicy();
5461 if (TemplateNamesKind
== llvm::codegenoptions::DebugTemplateNamesKind::Full
||
5463 ND
->getNameForDiagnostic(OS
, PP
, Qualified
);
5465 bool Mangled
= TemplateNamesKind
==
5466 llvm::codegenoptions::DebugTemplateNamesKind::Mangled
;
5467 // check if it's a template
5471 OS
<< ND
->getDeclName();
5472 std::string EncodedOriginalName
;
5473 llvm::raw_string_ostream
EncodedOriginalNameOS(EncodedOriginalName
);
5474 EncodedOriginalNameOS
<< ND
->getDeclName();
5478 printTemplateArgumentList(OS
, Args
->Args
, PP
);
5479 printTemplateArgumentList(EncodedOriginalNameOS
, Args
->Args
, PP
);
5481 std::string CanonicalOriginalName
;
5482 llvm::raw_string_ostream
OriginalOS(CanonicalOriginalName
);
5483 ND
->getNameForDiagnostic(OriginalOS
, PP
, Qualified
);
5484 assert(EncodedOriginalNameOS
.str() == OriginalOS
.str());
5491 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable
*Var
,
5493 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5494 if (D
->hasAttr
<NoDebugAttr
>())
5497 llvm::TimeTraceScope
TimeScope("DebugGlobalVariable", [&]() {
5498 return GetName(D
, true);
5501 // If we already created a DIGlobalVariable for this declaration, just attach
5502 // it to the llvm::GlobalVariable.
5503 auto Cached
= DeclCache
.find(D
->getCanonicalDecl());
5504 if (Cached
!= DeclCache
.end())
5505 return Var
->addDebugInfo(
5506 cast
<llvm::DIGlobalVariableExpression
>(Cached
->second
));
5508 // Create global variable debug descriptor.
5509 llvm::DIFile
*Unit
= nullptr;
5510 llvm::DIScope
*DContext
= nullptr;
5512 StringRef DeclName
, LinkageName
;
5514 llvm::MDTuple
*TemplateParameters
= nullptr;
5515 collectVarDeclProps(D
, Unit
, LineNo
, T
, DeclName
, LinkageName
,
5516 TemplateParameters
, DContext
);
5518 // Attempt to store one global variable for the declaration - even if we
5519 // emit a lot of fields.
5520 llvm::DIGlobalVariableExpression
*GVE
= nullptr;
5522 // If this is an anonymous union then we'll want to emit a global
5523 // variable for each member of the anonymous union so that it's possible
5524 // to find the name of any field in the union.
5525 if (T
->isUnionType() && DeclName
.empty()) {
5526 const RecordDecl
*RD
= T
->castAs
<RecordType
>()->getDecl();
5527 assert(RD
->isAnonymousStructOrUnion() &&
5528 "unnamed non-anonymous struct or union?");
5529 GVE
= CollectAnonRecordDecls(RD
, Unit
, LineNo
, LinkageName
, Var
, DContext
);
5531 auto Align
= getDeclAlignIfRequired(D
, CGM
.getContext());
5533 SmallVector
<uint64_t, 4> Expr
;
5534 unsigned AddressSpace
= CGM
.getTypes().getTargetAddressSpace(D
->getType());
5535 if (CGM
.getLangOpts().CUDA
&& CGM
.getLangOpts().CUDAIsDevice
) {
5536 if (D
->hasAttr
<CUDASharedAttr
>())
5538 CGM
.getContext().getTargetAddressSpace(LangAS::cuda_shared
);
5539 else if (D
->hasAttr
<CUDAConstantAttr
>())
5541 CGM
.getContext().getTargetAddressSpace(LangAS::cuda_constant
);
5543 AppendAddressSpaceXDeref(AddressSpace
, Expr
);
5545 llvm::DINodeArray Annotations
= CollectBTFDeclTagAnnotations(D
);
5546 GVE
= DBuilder
.createGlobalVariableExpression(
5547 DContext
, DeclName
, LinkageName
, Unit
, LineNo
, getOrCreateType(T
, Unit
),
5548 Var
->hasLocalLinkage(), true,
5549 Expr
.empty() ? nullptr : DBuilder
.createExpression(Expr
),
5550 getOrCreateStaticDataMemberDeclarationOrNull(D
), TemplateParameters
,
5551 Align
, Annotations
);
5552 Var
->addDebugInfo(GVE
);
5554 DeclCache
[D
->getCanonicalDecl()].reset(GVE
);
5557 void CGDebugInfo::EmitGlobalVariable(const ValueDecl
*VD
, const APValue
&Init
) {
5558 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5559 if (VD
->hasAttr
<NoDebugAttr
>())
5561 llvm::TimeTraceScope
TimeScope("DebugConstGlobalVariable", [&]() {
5562 return GetName(VD
, true);
5565 auto Align
= getDeclAlignIfRequired(VD
, CGM
.getContext());
5566 // Create the descriptor for the variable.
5567 llvm::DIFile
*Unit
= getOrCreateFile(VD
->getLocation());
5568 StringRef Name
= VD
->getName();
5569 llvm::DIType
*Ty
= getOrCreateType(VD
->getType(), Unit
);
5571 if (const auto *ECD
= dyn_cast
<EnumConstantDecl
>(VD
)) {
5572 const auto *ED
= cast
<EnumDecl
>(ECD
->getDeclContext());
5573 assert(isa
<EnumType
>(ED
->getTypeForDecl()) && "Enum without EnumType?");
5575 if (CGM
.getCodeGenOpts().EmitCodeView
) {
5576 // If CodeView, emit enums as global variables, unless they are defined
5577 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5578 // enums in classes, and because it is difficult to attach this scope
5579 // information to the global variable.
5580 if (isa
<RecordDecl
>(ED
->getDeclContext()))
5583 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5584 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5585 // first time `ZERO` is referenced in a function.
5586 llvm::DIType
*EDTy
=
5587 getOrCreateType(QualType(ED
->getTypeForDecl(), 0), Unit
);
5588 assert (EDTy
->getTag() == llvm::dwarf::DW_TAG_enumeration_type
);
5594 // Do not emit separate definitions for function local consts.
5595 if (isa
<FunctionDecl
>(VD
->getDeclContext()))
5598 VD
= cast
<ValueDecl
>(VD
->getCanonicalDecl());
5599 auto *VarD
= dyn_cast
<VarDecl
>(VD
);
5600 if (VarD
&& VarD
->isStaticDataMember()) {
5601 auto *RD
= cast
<RecordDecl
>(VarD
->getDeclContext());
5602 getDeclContextDescriptor(VarD
);
5603 // Ensure that the type is retained even though it's otherwise unreferenced.
5605 // FIXME: This is probably unnecessary, since Ty should reference RD
5606 // through its scope.
5607 RetainedTypes
.push_back(
5608 CGM
.getContext().getRecordType(RD
).getAsOpaquePtr());
5612 llvm::DIScope
*DContext
= getDeclContextDescriptor(VD
);
5614 auto &GV
= DeclCache
[VD
];
5618 llvm::DIExpression
*InitExpr
= createConstantValueExpression(VD
, Init
);
5619 llvm::MDTuple
*TemplateParameters
= nullptr;
5621 if (isa
<VarTemplateSpecializationDecl
>(VD
))
5623 llvm::DINodeArray parameterNodes
= CollectVarTemplateParams(VarD
, &*Unit
);
5624 TemplateParameters
= parameterNodes
.get();
5627 GV
.reset(DBuilder
.createGlobalVariableExpression(
5628 DContext
, Name
, StringRef(), Unit
, getLineNumber(VD
->getLocation()), Ty
,
5629 true, true, InitExpr
, getOrCreateStaticDataMemberDeclarationOrNull(VarD
),
5630 TemplateParameters
, Align
));
5633 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable
*Var
,
5635 assert(CGM
.getCodeGenOpts().hasReducedDebugInfo());
5636 if (D
->hasAttr
<NoDebugAttr
>())
5639 auto Align
= getDeclAlignIfRequired(D
, CGM
.getContext());
5640 llvm::DIFile
*Unit
= getOrCreateFile(D
->getLocation());
5641 StringRef Name
= D
->getName();
5642 llvm::DIType
*Ty
= getOrCreateType(D
->getType(), Unit
);
5644 llvm::DIScope
*DContext
= getDeclContextDescriptor(D
);
5645 llvm::DIGlobalVariableExpression
*GVE
=
5646 DBuilder
.createGlobalVariableExpression(
5647 DContext
, Name
, StringRef(), Unit
, getLineNumber(D
->getLocation()),
5648 Ty
, false, false, nullptr, nullptr, nullptr, Align
);
5649 Var
->addDebugInfo(GVE
);
5652 void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue
*GV
,
5653 const GlobalDecl GD
) {
5657 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5660 const auto *D
= cast
<ValueDecl
>(GD
.getDecl());
5661 if (D
->hasAttr
<NoDebugAttr
>())
5664 auto AliaseeDecl
= CGM
.getMangledNameDecl(GV
->getName());
5668 // FIXME: Aliasee not declared yet - possibly declared later
5671 // 1 extern int newname __attribute__((alias("oldname")));
5672 // 2 int oldname = 1;
5674 // No debug info would be generated for 'newname' in this case.
5676 // Fix compiler to generate "newname" as imported_declaration
5677 // pointing to the DIE of "oldname".
5679 if (!(DI
= getDeclarationOrDefinition(
5680 AliaseeDecl
.getCanonicalDecl().getDecl())))
5683 llvm::DIScope
*DContext
= getDeclContextDescriptor(D
);
5684 auto Loc
= D
->getLocation();
5686 llvm::DIImportedEntity
*ImportDI
= DBuilder
.createImportedDeclaration(
5687 DContext
, DI
, getOrCreateFile(Loc
), getLineNumber(Loc
), D
->getName());
5689 // Record this DIE in the cache for nested declaration reference.
5690 ImportedDeclCache
[GD
.getCanonicalDecl().getDecl()].reset(ImportDI
);
5693 void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable
*GV
,
5694 const StringLiteral
*S
) {
5695 SourceLocation Loc
= S
->getStrTokenLoc(0);
5696 PresumedLoc PLoc
= CGM
.getContext().getSourceManager().getPresumedLoc(Loc
);
5697 if (!PLoc
.isValid())
5700 llvm::DIFile
*File
= getOrCreateFile(Loc
);
5701 llvm::DIGlobalVariableExpression
*Debug
=
5702 DBuilder
.createGlobalVariableExpression(
5703 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc
),
5704 getLineNumber(Loc
), getOrCreateType(S
->getType(), File
), true);
5705 GV
->addDebugInfo(Debug
);
5708 llvm::DIScope
*CGDebugInfo::getCurrentContextDescriptor(const Decl
*D
) {
5709 if (!LexicalBlockStack
.empty())
5710 return LexicalBlockStack
.back();
5711 llvm::DIScope
*Mod
= getParentModuleOrNull(D
);
5712 return getContextDescriptor(D
, Mod
? Mod
: TheCU
);
5715 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl
&UD
) {
5716 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5718 const NamespaceDecl
*NSDecl
= UD
.getNominatedNamespace();
5719 if (!NSDecl
->isAnonymousNamespace() ||
5720 CGM
.getCodeGenOpts().DebugExplicitImport
) {
5721 auto Loc
= UD
.getLocation();
5724 DBuilder
.createImportedModule(
5725 getCurrentContextDescriptor(cast
<Decl
>(UD
.getDeclContext())),
5726 getOrCreateNamespace(NSDecl
), getOrCreateFile(Loc
), getLineNumber(Loc
));
5730 void CGDebugInfo::EmitUsingShadowDecl(const UsingShadowDecl
&USD
) {
5731 if (llvm::DINode
*Target
=
5732 getDeclarationOrDefinition(USD
.getUnderlyingDecl())) {
5733 auto Loc
= USD
.getLocation();
5734 DBuilder
.createImportedDeclaration(
5735 getCurrentContextDescriptor(cast
<Decl
>(USD
.getDeclContext())), Target
,
5736 getOrCreateFile(Loc
), getLineNumber(Loc
));
5740 void CGDebugInfo::EmitUsingDecl(const UsingDecl
&UD
) {
5741 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5743 assert(UD
.shadow_size() &&
5744 "We shouldn't be codegening an invalid UsingDecl containing no decls");
5746 for (const auto *USD
: UD
.shadows()) {
5747 // FIXME: Skip functions with undeduced auto return type for now since we
5748 // don't currently have the plumbing for separate declarations & definitions
5749 // of free functions and mismatched types (auto in the declaration, concrete
5750 // return type in the definition)
5751 if (const auto *FD
= dyn_cast
<FunctionDecl
>(USD
->getUnderlyingDecl()))
5752 if (const auto *AT
= FD
->getType()
5753 ->castAs
<FunctionProtoType
>()
5754 ->getContainedAutoType())
5755 if (AT
->getDeducedType().isNull())
5758 EmitUsingShadowDecl(*USD
);
5759 // Emitting one decl is sufficient - debuggers can detect that this is an
5760 // overloaded name & provide lookup for all the overloads.
5765 void CGDebugInfo::EmitUsingEnumDecl(const UsingEnumDecl
&UD
) {
5766 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5768 assert(UD
.shadow_size() &&
5769 "We shouldn't be codegening an invalid UsingEnumDecl"
5770 " containing no decls");
5772 for (const auto *USD
: UD
.shadows())
5773 EmitUsingShadowDecl(*USD
);
5776 void CGDebugInfo::EmitImportDecl(const ImportDecl
&ID
) {
5777 if (CGM
.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB
)
5779 if (Module
*M
= ID
.getImportedModule()) {
5780 auto Info
= ASTSourceDescriptor(*M
);
5781 auto Loc
= ID
.getLocation();
5782 DBuilder
.createImportedDeclaration(
5783 getCurrentContextDescriptor(cast
<Decl
>(ID
.getDeclContext())),
5784 getOrCreateModuleRef(Info
, DebugTypeExtRefs
), getOrCreateFile(Loc
),
5785 getLineNumber(Loc
));
5789 llvm::DIImportedEntity
*
5790 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl
&NA
) {
5791 if (!CGM
.getCodeGenOpts().hasReducedDebugInfo())
5793 auto &VH
= NamespaceAliasCache
[&NA
];
5795 return cast
<llvm::DIImportedEntity
>(VH
);
5796 llvm::DIImportedEntity
*R
;
5797 auto Loc
= NA
.getLocation();
5798 if (const auto *Underlying
=
5799 dyn_cast
<NamespaceAliasDecl
>(NA
.getAliasedNamespace()))
5800 // This could cache & dedup here rather than relying on metadata deduping.
5801 R
= DBuilder
.createImportedDeclaration(
5802 getCurrentContextDescriptor(cast
<Decl
>(NA
.getDeclContext())),
5803 EmitNamespaceAlias(*Underlying
), getOrCreateFile(Loc
),
5804 getLineNumber(Loc
), NA
.getName());
5806 R
= DBuilder
.createImportedDeclaration(
5807 getCurrentContextDescriptor(cast
<Decl
>(NA
.getDeclContext())),
5808 getOrCreateNamespace(cast
<NamespaceDecl
>(NA
.getAliasedNamespace())),
5809 getOrCreateFile(Loc
), getLineNumber(Loc
), NA
.getName());
5815 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl
*NSDecl
) {
5816 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
5817 // if necessary, and this way multiple declarations of the same namespace in
5818 // different parent modules stay distinct.
5819 auto I
= NamespaceCache
.find(NSDecl
);
5820 if (I
!= NamespaceCache
.end())
5821 return cast
<llvm::DINamespace
>(I
->second
);
5823 llvm::DIScope
*Context
= getDeclContextDescriptor(NSDecl
);
5824 // Don't trust the context if it is a DIModule (see comment above).
5825 llvm::DINamespace
*NS
=
5826 DBuilder
.createNameSpace(Context
, NSDecl
->getName(), NSDecl
->isInline());
5827 NamespaceCache
[NSDecl
].reset(NS
);
5831 void CGDebugInfo::setDwoId(uint64_t Signature
) {
5832 assert(TheCU
&& "no main compile unit");
5833 TheCU
->setDWOId(Signature
);
5836 void CGDebugInfo::finalize() {
5837 // Creating types might create further types - invalidating the current
5838 // element and the size(), so don't cache/reference them.
5839 for (size_t i
= 0; i
!= ObjCInterfaceCache
.size(); ++i
) {
5840 ObjCInterfaceCacheEntry E
= ObjCInterfaceCache
[i
];
5841 llvm::DIType
*Ty
= E
.Type
->getDecl()->getDefinition()
5842 ? CreateTypeDefinition(E
.Type
, E
.Unit
)
5844 DBuilder
.replaceTemporary(llvm::TempDIType(E
.Decl
), Ty
);
5847 // Add methods to interface.
5848 for (const auto &P
: ObjCMethodCache
) {
5849 if (P
.second
.empty())
5852 QualType
QTy(P
.first
->getTypeForDecl(), 0);
5853 auto It
= TypeCache
.find(QTy
.getAsOpaquePtr());
5854 assert(It
!= TypeCache
.end());
5856 llvm::DICompositeType
*InterfaceDecl
=
5857 cast
<llvm::DICompositeType
>(It
->second
);
5859 auto CurElts
= InterfaceDecl
->getElements();
5860 SmallVector
<llvm::Metadata
*, 16> EltTys(CurElts
.begin(), CurElts
.end());
5862 // For DWARF v4 or earlier, only add objc_direct methods.
5863 for (auto &SubprogramDirect
: P
.second
)
5864 if (CGM
.getCodeGenOpts().DwarfVersion
>= 5 || SubprogramDirect
.getInt())
5865 EltTys
.push_back(SubprogramDirect
.getPointer());
5867 llvm::DINodeArray Elements
= DBuilder
.getOrCreateArray(EltTys
);
5868 DBuilder
.replaceArrays(InterfaceDecl
, Elements
);
5871 for (const auto &P
: ReplaceMap
) {
5873 auto *Ty
= cast
<llvm::DIType
>(P
.second
);
5874 assert(Ty
->isForwardDecl());
5876 auto It
= TypeCache
.find(P
.first
);
5877 assert(It
!= TypeCache
.end());
5880 DBuilder
.replaceTemporary(llvm::TempDIType(Ty
),
5881 cast
<llvm::DIType
>(It
->second
));
5884 for (const auto &P
: FwdDeclReplaceMap
) {
5886 llvm::TempMDNode
FwdDecl(cast
<llvm::MDNode
>(P
.second
));
5887 llvm::Metadata
*Repl
;
5889 auto It
= DeclCache
.find(P
.first
);
5890 // If there has been no definition for the declaration, call RAUW
5891 // with ourselves, that will destroy the temporary MDNode and
5892 // replace it with a standard one, avoiding leaking memory.
5893 if (It
== DeclCache
.end())
5898 if (auto *GVE
= dyn_cast_or_null
<llvm::DIGlobalVariableExpression
>(Repl
))
5899 Repl
= GVE
->getVariable();
5900 DBuilder
.replaceTemporary(std::move(FwdDecl
), cast
<llvm::MDNode
>(Repl
));
5903 // We keep our own list of retained types, because we need to look
5904 // up the final type in the type cache.
5905 for (auto &RT
: RetainedTypes
)
5906 if (auto MD
= TypeCache
[RT
])
5907 DBuilder
.retainType(cast
<llvm::DIType
>(MD
));
5909 DBuilder
.finalize();
5912 // Don't ignore in case of explicit cast where it is referenced indirectly.
5913 void CGDebugInfo::EmitExplicitCastType(QualType Ty
) {
5914 if (CGM
.getCodeGenOpts().hasReducedDebugInfo())
5915 if (auto *DieTy
= getOrCreateType(Ty
, TheCU
->getFile()))
5916 DBuilder
.retainType(DieTy
);
5919 void CGDebugInfo::EmitAndRetainType(QualType Ty
) {
5920 if (CGM
.getCodeGenOpts().hasMaybeUnusedDebugInfo())
5921 if (auto *DieTy
= getOrCreateType(Ty
, TheCU
->getFile()))
5922 DBuilder
.retainType(DieTy
);
5925 llvm::DebugLoc
CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc
) {
5926 if (LexicalBlockStack
.empty())
5927 return llvm::DebugLoc();
5929 llvm::MDNode
*Scope
= LexicalBlockStack
.back();
5930 return llvm::DILocation::get(CGM
.getLLVMContext(), getLineNumber(Loc
),
5931 getColumnNumber(Loc
), Scope
);
5934 llvm::DINode::DIFlags
CGDebugInfo::getCallSiteRelatedAttrs() const {
5935 // Call site-related attributes are only useful in optimized programs, and
5936 // when there's a possibility of debugging backtraces.
5937 if (!CGM
.getLangOpts().Optimize
||
5938 DebugKind
== llvm::codegenoptions::NoDebugInfo
||
5939 DebugKind
== llvm::codegenoptions::LocTrackingOnly
)
5940 return llvm::DINode::FlagZero
;
5942 // Call site-related attributes are available in DWARF v5. Some debuggers,
5943 // while not fully DWARF v5-compliant, may accept these attributes as if they
5944 // were part of DWARF v4.
5945 bool SupportsDWARFv4Ext
=
5946 CGM
.getCodeGenOpts().DwarfVersion
== 4 &&
5947 (CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB
||
5948 CGM
.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB
);
5950 if (!SupportsDWARFv4Ext
&& CGM
.getCodeGenOpts().DwarfVersion
< 5)
5951 return llvm::DINode::FlagZero
;
5953 return llvm::DINode::FlagAllCallsDescribed
;
5956 llvm::DIExpression
*
5957 CGDebugInfo::createConstantValueExpression(const clang::ValueDecl
*VD
,
5958 const APValue
&Val
) {
5959 // FIXME: Add a representation for integer constants wider than 64 bits.
5960 if (CGM
.getContext().getTypeSize(VD
->getType()) > 64)
5964 return DBuilder
.createConstantValueExpression(
5965 Val
.getFloat().bitcastToAPInt().getZExtValue());
5970 llvm::APSInt
const &ValInt
= Val
.getInt();
5971 std::optional
<uint64_t> ValIntOpt
;
5972 if (ValInt
.isUnsigned())
5973 ValIntOpt
= ValInt
.tryZExtValue();
5974 else if (auto tmp
= ValInt
.trySExtValue())
5975 // Transform a signed optional to unsigned optional. When cpp 23 comes,
5976 // use std::optional::transform
5977 ValIntOpt
= static_cast<uint64_t>(*tmp
);
5980 return DBuilder
.createConstantValueExpression(ValIntOpt
.value());