clang 20.0.0git
CGDebugInfo.cpp
Go to the documentation of this file.
1//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This coordinates the debug information generation while generating code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGDebugInfo.h"
14#include "CGBlocks.h"
15#include "CGCXXABI.h"
16#include "CGObjCRuntime.h"
17#include "CGRecordLayout.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "ConstantEmitter.h"
21#include "TargetInfo.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/DeclCXX.h"
26#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
34#include "clang/Basic/Version.h"
38#include "clang/Lex/ModuleMap.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/SmallVector.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/IR/Constants.h"
44#include "llvm/IR/DataLayout.h"
45#include "llvm/IR/DerivedTypes.h"
46#include "llvm/IR/Instructions.h"
47#include "llvm/IR/Intrinsics.h"
48#include "llvm/IR/Metadata.h"
49#include "llvm/IR/Module.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"
55#include <optional>
56using namespace clang;
57using namespace clang::CodeGen;
58
59static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
60 auto TI = Ctx.getTypeInfo(Ty);
61 if (TI.isAlignRequired())
62 return TI.Align;
63
64 // MaxFieldAlignmentAttr is the attribute added to types
65 // declared after #pragma pack(n).
66 if (auto *Decl = Ty->getAsRecordDecl())
67 if (Decl->hasAttr<MaxFieldAlignmentAttr>())
68 return TI.Align;
69
70 return 0;
71}
72
73static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
74 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
75}
76
77static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
78 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
79}
80
81/// Returns true if \ref VD is a a holding variable (aka a
82/// VarDecl retrieved using \ref BindingDecl::getHoldingVar).
83static bool IsDecomposedVarDecl(VarDecl const *VD) {
84 auto const *Init = VD->getInit();
85 if (!Init)
86 return false;
87
88 auto const *RefExpr =
89 llvm::dyn_cast_or_null<DeclRefExpr>(Init->IgnoreUnlessSpelledInSource());
90 if (!RefExpr)
91 return false;
92
93 return llvm::dyn_cast_or_null<DecompositionDecl>(RefExpr->getDecl());
94}
95
96/// Returns true if \ref VD is a compiler-generated variable
97/// and should be treated as artificial for the purposes
98/// of debug-info generation.
99static bool IsArtificial(VarDecl const *VD) {
100 // Tuple-like bindings are marked as implicit despite
101 // being spelled out in source. Don't treat them as artificial
102 // variables.
103 if (IsDecomposedVarDecl(VD))
104 return false;
105
106 return VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
107 cast<Decl>(VD->getDeclContext())->isImplicit());
108}
109
111 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
112 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
113 DBuilder(CGM.getModule()) {
114 CreateCompileUnit();
115}
116
118 assert(LexicalBlockStack.empty() &&
119 "Region stack mismatch, stack not empty!");
120}
121
122ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
123 SourceLocation TemporaryLocation)
124 : CGF(&CGF) {
125 init(TemporaryLocation);
126}
127
128ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
129 bool DefaultToEmpty,
130 SourceLocation TemporaryLocation)
131 : CGF(&CGF) {
132 init(TemporaryLocation, DefaultToEmpty);
133}
134
135void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
136 bool DefaultToEmpty) {
137 auto *DI = CGF->getDebugInfo();
138 if (!DI) {
139 CGF = nullptr;
140 return;
141 }
142
143 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
144
145 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
146 return;
147
148 if (TemporaryLocation.isValid()) {
149 DI->EmitLocation(CGF->Builder, TemporaryLocation);
150 return;
151 }
152
153 if (DefaultToEmpty) {
154 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
155 return;
156 }
157
158 // Construct a location that has a valid scope, but no line info.
159 assert(!DI->LexicalBlockStack.empty());
160 CGF->Builder.SetCurrentDebugLocation(
161 llvm::DILocation::get(DI->LexicalBlockStack.back()->getContext(), 0, 0,
162 DI->LexicalBlockStack.back(), DI->getInlinedAt()));
163}
164
165ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
166 : CGF(&CGF) {
167 init(E->getExprLoc());
168}
169
170ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
171 : CGF(&CGF) {
172 if (!CGF.getDebugInfo()) {
173 this->CGF = nullptr;
174 return;
175 }
176 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
177 if (Loc)
178 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
179}
180
182 // Query CGF so the location isn't overwritten when location updates are
183 // temporarily disabled (for C++ default function arguments)
184 if (CGF)
185 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
186}
187
189 GlobalDecl InlinedFn)
190 : CGF(&CGF) {
191 if (!CGF.getDebugInfo()) {
192 this->CGF = nullptr;
193 return;
194 }
195 auto &DI = *CGF.getDebugInfo();
196 SavedLocation = DI.getLocation();
197 assert((DI.getInlinedAt() ==
198 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
199 "CGDebugInfo and IRBuilder are out of sync");
200
201 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
202}
203
205 if (!CGF)
206 return;
207 auto &DI = *CGF->getDebugInfo();
209 DI.EmitLocation(CGF->Builder, SavedLocation);
210}
211
213 // If the new location isn't valid return.
214 if (Loc.isInvalid())
215 return;
216
218
219 // If we've changed files in the middle of a lexical scope go ahead
220 // and create a new lexical scope with file node if it's different
221 // from the one in the scope.
222 if (LexicalBlockStack.empty())
223 return;
224
226 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
227 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
228 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
229 return;
230
231 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
232 LexicalBlockStack.pop_back();
233 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
234 LBF->getScope(), getOrCreateFile(CurLoc)));
235 } else if (isa<llvm::DILexicalBlock>(Scope) ||
236 isa<llvm::DISubprogram>(Scope)) {
237 LexicalBlockStack.pop_back();
238 LexicalBlockStack.emplace_back(
239 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
240 }
241}
242
243llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
244 llvm::DIScope *Mod = getParentModuleOrNull(D);
245 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
246 Mod ? Mod : TheCU);
247}
248
249llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
250 llvm::DIScope *Default) {
251 if (!Context)
252 return Default;
253
254 auto I = RegionMap.find(Context);
255 if (I != RegionMap.end()) {
256 llvm::Metadata *V = I->second;
257 return dyn_cast_or_null<llvm::DIScope>(V);
258 }
259
260 // Check namespace.
261 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
262 return getOrCreateNamespace(NSDecl);
263
264 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
265 if (!RDecl->isDependentType())
266 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
267 TheCU->getFile());
268 return Default;
269}
270
271PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
273
274 // If we're emitting codeview, it's important to try to match MSVC's naming so
275 // that visualizers written for MSVC will trigger for our class names. In
276 // particular, we can't have spaces between arguments of standard templates
277 // like basic_string and vector, but we must have spaces between consecutive
278 // angle brackets that close nested template argument lists.
279 if (CGM.getCodeGenOpts().EmitCodeView) {
280 PP.MSVCFormatting = true;
281 PP.SplitTemplateClosers = true;
282 } else {
283 // For DWARF, printing rules are underspecified.
284 // SplitTemplateClosers yields better interop with GCC and GDB (PR46052).
285 PP.SplitTemplateClosers = true;
286 }
287
290 PP.PrintCanonicalTypes = true;
291 PP.UsePreferredNames = false;
293 PP.UseEnumerators = false;
294
295 // Apply -fdebug-prefix-map.
296 PP.Callbacks = &PrintCB;
297 return PP;
298}
299
300StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
301 return internString(GetName(FD));
302}
303
304StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
305 SmallString<256> MethodName;
306 llvm::raw_svector_ostream OS(MethodName);
307 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
308 const DeclContext *DC = OMD->getDeclContext();
309 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
310 OS << OID->getName();
311 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
312 OS << OID->getName();
313 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
314 if (OC->IsClassExtension()) {
315 OS << OC->getClassInterface()->getName();
316 } else {
317 OS << OC->getIdentifier()->getNameStart() << '('
318 << OC->getIdentifier()->getNameStart() << ')';
319 }
320 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
321 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
322 }
323 OS << ' ' << OMD->getSelector().getAsString() << ']';
324
325 return internString(OS.str());
326}
327
328StringRef CGDebugInfo::getSelectorName(Selector S) {
329 return internString(S.getAsString());
330}
331
332StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
333 if (isa<ClassTemplateSpecializationDecl>(RD)) {
334 // Copy this name on the side and use its reference.
335 return internString(GetName(RD));
336 }
337
338 // quick optimization to avoid having to intern strings that are already
339 // stored reliably elsewhere
340 if (const IdentifierInfo *II = RD->getIdentifier())
341 return II->getName();
342
343 // The CodeView printer in LLVM wants to see the names of unnamed types
344 // because they need to have a unique identifier.
345 // These names are used to reconstruct the fully qualified type names.
346 if (CGM.getCodeGenOpts().EmitCodeView) {
347 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
348 assert(RD->getDeclContext() == D->getDeclContext() &&
349 "Typedef should not be in another decl context!");
350 assert(D->getDeclName().getAsIdentifierInfo() &&
351 "Typedef was not named!");
352 return D->getDeclName().getAsIdentifierInfo()->getName();
353 }
354
355 if (CGM.getLangOpts().CPlusPlus) {
356 StringRef Name;
357
358 ASTContext &Context = CGM.getContext();
359 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
360 // Anonymous types without a name for linkage purposes have their
361 // declarator mangled in if they have one.
362 Name = DD->getName();
363 else if (const TypedefNameDecl *TND =
365 // Anonymous types without a name for linkage purposes have their
366 // associate typedef mangled in if they have one.
367 Name = TND->getName();
368
369 // Give lambdas a display name based on their name mangling.
370 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
371 if (CXXRD->isLambda())
372 return internString(
374
375 if (!Name.empty()) {
376 SmallString<256> UnnamedType("<unnamed-type-");
377 UnnamedType += Name;
378 UnnamedType += '>';
379 return internString(UnnamedType);
380 }
381 }
382 }
383
384 return StringRef();
385}
386
387std::optional<llvm::DIFile::ChecksumKind>
388CGDebugInfo::computeChecksum(FileID FID, SmallString<64> &Checksum) const {
389 Checksum.clear();
390
391 if (!CGM.getCodeGenOpts().EmitCodeView &&
392 CGM.getCodeGenOpts().DwarfVersion < 5)
393 return std::nullopt;
394
396 std::optional<llvm::MemoryBufferRef> MemBuffer = SM.getBufferOrNone(FID);
397 if (!MemBuffer)
398 return std::nullopt;
399
400 auto Data = llvm::arrayRefFromStringRef(MemBuffer->getBuffer());
401 switch (CGM.getCodeGenOpts().getDebugSrcHash()) {
403 llvm::toHex(llvm::MD5::hash(Data), /*LowerCase=*/true, Checksum);
404 return llvm::DIFile::CSK_MD5;
406 llvm::toHex(llvm::SHA1::hash(Data), /*LowerCase=*/true, Checksum);
407 return llvm::DIFile::CSK_SHA1;
409 llvm::toHex(llvm::SHA256::hash(Data), /*LowerCase=*/true, Checksum);
410 return llvm::DIFile::CSK_SHA256;
411 }
412 llvm_unreachable("Unhandled DebugSrcHashKind enum");
413}
414
415std::optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
416 FileID FID) {
417 if (!CGM.getCodeGenOpts().EmbedSource)
418 return std::nullopt;
419
420 bool SourceInvalid = false;
421 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
422
423 if (SourceInvalid)
424 return std::nullopt;
425
426 return Source;
427}
428
429llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
431 StringRef FileName;
432 FileID FID;
433 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
434
435 if (Loc.isInvalid()) {
436 // The DIFile used by the CU is distinct from the main source file. Call
437 // createFile() below for canonicalization if the source file was specified
438 // with an absolute path.
439 FileName = TheCU->getFile()->getFilename();
440 CSInfo = TheCU->getFile()->getChecksum();
441 } else {
442 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
443 FileName = PLoc.getFilename();
444
445 if (FileName.empty()) {
446 FileName = TheCU->getFile()->getFilename();
447 } else {
448 FileName = PLoc.getFilename();
449 }
450 FID = PLoc.getFileID();
451 }
452
453 // Cache the results.
454 auto It = DIFileCache.find(FileName.data());
455 if (It != DIFileCache.end()) {
456 // Verify that the information still exists.
457 if (llvm::Metadata *V = It->second)
458 return cast<llvm::DIFile>(V);
459 }
460
461 // Put Checksum at a scope where it will persist past the createFile call.
462 SmallString<64> Checksum;
463 if (!CSInfo) {
464 std::optional<llvm::DIFile::ChecksumKind> CSKind =
465 computeChecksum(FID, Checksum);
466 if (CSKind)
467 CSInfo.emplace(*CSKind, Checksum);
468 }
469 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
470}
471
472llvm::DIFile *CGDebugInfo::createFile(
473 StringRef FileName,
474 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
475 std::optional<StringRef> Source) {
476 StringRef Dir;
477 StringRef File;
478 std::string RemappedFile = remapDIPath(FileName);
479 std::string CurDir = remapDIPath(getCurrentDirname());
480 SmallString<128> DirBuf;
481 SmallString<128> FileBuf;
482 if (llvm::sys::path::is_absolute(RemappedFile)) {
483 // Strip the common prefix (if it is more than just "/" or "C:\") from
484 // current directory and FileName for a more space-efficient encoding.
485 auto FileIt = llvm::sys::path::begin(RemappedFile);
486 auto FileE = llvm::sys::path::end(RemappedFile);
487 auto CurDirIt = llvm::sys::path::begin(CurDir);
488 auto CurDirE = llvm::sys::path::end(CurDir);
489 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
490 llvm::sys::path::append(DirBuf, *CurDirIt);
491 if (llvm::sys::path::root_path(DirBuf) == DirBuf) {
492 // Don't strip the common prefix if it is only the root ("/" or "C:\")
493 // since that would make LLVM diagnostic locations confusing.
494 Dir = {};
495 File = RemappedFile;
496 } else {
497 for (; FileIt != FileE; ++FileIt)
498 llvm::sys::path::append(FileBuf, *FileIt);
499 Dir = DirBuf;
500 File = FileBuf;
501 }
502 } else {
503 if (!llvm::sys::path::is_absolute(FileName))
504 Dir = CurDir;
505 File = RemappedFile;
506 }
507 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
508 DIFileCache[FileName.data()].reset(F);
509 return F;
510}
511
512std::string CGDebugInfo::remapDIPath(StringRef Path) const {
514 for (auto &[From, To] : llvm::reverse(CGM.getCodeGenOpts().DebugPrefixMap))
515 if (llvm::sys::path::replace_path_prefix(P, From, To))
516 break;
517 return P.str().str();
518}
519
520unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
521 if (Loc.isInvalid())
522 return 0;
524 return SM.getPresumedLoc(Loc).getLine();
525}
526
527unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
528 // We may not want column information at all.
529 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
530 return 0;
531
532 // If the location is invalid then use the current column.
533 if (Loc.isInvalid() && CurLoc.isInvalid())
534 return 0;
536 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
537 return PLoc.isValid() ? PLoc.getColumn() : 0;
538}
539
540StringRef CGDebugInfo::getCurrentDirname() {
541 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
543
544 if (!CWDName.empty())
545 return CWDName;
546 llvm::ErrorOr<std::string> CWD =
547 CGM.getFileSystem()->getCurrentWorkingDirectory();
548 if (!CWD)
549 return StringRef();
550 return CWDName = internString(*CWD);
551}
552
553void CGDebugInfo::CreateCompileUnit() {
554 SmallString<64> Checksum;
555 std::optional<llvm::DIFile::ChecksumKind> CSKind;
556 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
557
558 // Should we be asking the SourceManager for the main file name, instead of
559 // accepting it as an argument? This just causes the main file name to
560 // mismatch with source locations and create extra lexical scopes or
561 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
562 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
563 // because that's what the SourceManager says)
564
565 // Get absolute path name.
567 auto &CGO = CGM.getCodeGenOpts();
568 const LangOptions &LO = CGM.getLangOpts();
569 std::string MainFileName = CGO.MainFileName;
570 if (MainFileName.empty())
571 MainFileName = "<stdin>";
572
573 // The main file name provided via the "-main-file-name" option contains just
574 // the file name itself with no path information. This file name may have had
575 // a relative path, so we look into the actual file entry for the main
576 // file to determine the real absolute path for the file.
577 std::string MainFileDir;
578 if (OptionalFileEntryRef MainFile =
579 SM.getFileEntryRefForID(SM.getMainFileID())) {
580 MainFileDir = std::string(MainFile->getDir().getName());
581 if (!llvm::sys::path::is_absolute(MainFileName)) {
582 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
583 llvm::sys::path::Style Style =
585 ? (CGM.getTarget().getTriple().isOSWindows()
586 ? llvm::sys::path::Style::windows_backslash
587 : llvm::sys::path::Style::posix)
588 : llvm::sys::path::Style::native;
589 llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
590 MainFileName = std::string(
591 llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
592 }
593 // If the main file name provided is identical to the input file name, and
594 // if the input file is a preprocessed source, use the module name for
595 // debug info. The module name comes from the name specified in the first
596 // linemarker if the input is a preprocessed source. In this case we don't
597 // know the content to compute a checksum.
598 if (MainFile->getName() == MainFileName &&
600 MainFile->getName().rsplit('.').second)
601 .isPreprocessed()) {
602 MainFileName = CGM.getModule().getName().str();
603 } else {
604 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
605 }
606 }
607
608 llvm::dwarf::SourceLanguage LangTag;
609 if (LO.CPlusPlus) {
610 if (LO.ObjC)
611 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
612 else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
613 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
614 else if (LO.CPlusPlus14)
615 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
616 else if (LO.CPlusPlus11)
617 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
618 else
619 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
620 } else if (LO.ObjC) {
621 LangTag = llvm::dwarf::DW_LANG_ObjC;
622 } else if (LO.OpenCL && (!CGM.getCodeGenOpts().DebugStrictDwarf ||
623 CGM.getCodeGenOpts().DwarfVersion >= 5)) {
624 LangTag = llvm::dwarf::DW_LANG_OpenCL;
625 } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
626 LangTag = llvm::dwarf::DW_LANG_C11;
627 } else if (LO.C99) {
628 LangTag = llvm::dwarf::DW_LANG_C99;
629 } else {
630 LangTag = llvm::dwarf::DW_LANG_C89;
631 }
632
633 std::string Producer = getClangFullVersion();
634
635 // Figure out which version of the ObjC runtime we have.
636 unsigned RuntimeVers = 0;
637 if (LO.ObjC)
638 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
639
640 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
641 switch (DebugKind) {
642 case llvm::codegenoptions::NoDebugInfo:
643 case llvm::codegenoptions::LocTrackingOnly:
644 EmissionKind = llvm::DICompileUnit::NoDebug;
645 break;
646 case llvm::codegenoptions::DebugLineTablesOnly:
647 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
648 break;
649 case llvm::codegenoptions::DebugDirectivesOnly:
650 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
651 break;
652 case llvm::codegenoptions::DebugInfoConstructor:
653 case llvm::codegenoptions::LimitedDebugInfo:
654 case llvm::codegenoptions::FullDebugInfo:
655 case llvm::codegenoptions::UnusedTypeInfo:
656 EmissionKind = llvm::DICompileUnit::FullDebug;
657 break;
658 }
659
660 uint64_t DwoId = 0;
661 auto &CGOpts = CGM.getCodeGenOpts();
662 // The DIFile used by the CU is distinct from the main source
663 // file. Its directory part specifies what becomes the
664 // DW_AT_comp_dir (the compilation directory), even if the source
665 // file was specified with an absolute path.
666 if (CSKind)
667 CSInfo.emplace(*CSKind, Checksum);
668 llvm::DIFile *CUFile = DBuilder.createFile(
669 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
670 getSource(SM, SM.getMainFileID()));
671
672 StringRef Sysroot, SDK;
673 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
674 Sysroot = CGM.getHeaderSearchOpts().Sysroot;
675 auto B = llvm::sys::path::rbegin(Sysroot);
676 auto E = llvm::sys::path::rend(Sysroot);
677 auto It =
678 std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });
679 if (It != E)
680 SDK = *It;
681 }
682
683 llvm::DICompileUnit::DebugNameTableKind NameTableKind =
684 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
685 CGOpts.DebugNameTable);
686 if (CGM.getTarget().getTriple().isNVPTX())
687 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;
688 else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
689 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;
690
691 // Create new compile unit.
692 TheCU = DBuilder.createCompileUnit(
693 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
694 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
695 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
696 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
697 NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
698}
699
700llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
701 llvm::dwarf::TypeKind Encoding;
702 StringRef BTName;
703 switch (BT->getKind()) {
704#define BUILTIN_TYPE(Id, SingletonId)
705#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
706#include "clang/AST/BuiltinTypes.def"
707 case BuiltinType::Dependent:
708 llvm_unreachable("Unexpected builtin type");
709 case BuiltinType::NullPtr:
710 return DBuilder.createNullPtrType();
711 case BuiltinType::Void:
712 return nullptr;
713 case BuiltinType::ObjCClass:
714 if (!ClassTy)
715 ClassTy =
716 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
717 "objc_class", TheCU, TheCU->getFile(), 0);
718 return ClassTy;
719 case BuiltinType::ObjCId: {
720 // typedef struct objc_class *Class;
721 // typedef struct objc_object {
722 // Class isa;
723 // } *id;
724
725 if (ObjTy)
726 return ObjTy;
727
728 if (!ClassTy)
729 ClassTy =
730 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
731 "objc_class", TheCU, TheCU->getFile(), 0);
732
733 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
734
735 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
736
737 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
738 0, 0, llvm::DINode::FlagZero, nullptr,
739 llvm::DINodeArray());
740
741 DBuilder.replaceArrays(
742 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
743 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
744 llvm::DINode::FlagZero, ISATy)));
745 return ObjTy;
746 }
747 case BuiltinType::ObjCSel: {
748 if (!SelTy)
749 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
750 "objc_selector", TheCU,
751 TheCU->getFile(), 0);
752 return SelTy;
753 }
754
755#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
756 case BuiltinType::Id: \
757 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
758 SingletonId);
759#include "clang/Basic/OpenCLImageTypes.def"
760 case BuiltinType::OCLSampler:
761 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
762 case BuiltinType::OCLEvent:
763 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
764 case BuiltinType::OCLClkEvent:
765 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
766 case BuiltinType::OCLQueue:
767 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
768 case BuiltinType::OCLReserveID:
769 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
770#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
771 case BuiltinType::Id: \
772 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
773#include "clang/Basic/OpenCLExtensionTypes.def"
774#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
775 case BuiltinType::Id: \
776 return getOrCreateStructPtrType(#Name, SingletonId);
777#include "clang/Basic/HLSLIntangibleTypes.def"
778
779#define SVE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
780#include "clang/Basic/AArch64SVEACLETypes.def"
781 {
782 if (BT->getKind() == BuiltinType::MFloat8) {
783 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
784 BTName = BT->getName(CGM.getLangOpts());
785 // Bit size and offset of the type.
787 return DBuilder.createBasicType(BTName, Size, Encoding);
788 }
790 // For svcount_t, only the lower 2 bytes are relevant.
791 BT->getKind() == BuiltinType::SveCount
793 CGM.getContext().BoolTy, llvm::ElementCount::getFixed(16),
794 1)
795 : CGM.getContext().getBuiltinVectorTypeInfo(BT);
796
797 // A single vector of bytes may not suffice as the representation of
798 // svcount_t tuples because of the gap between the active 16bits of
799 // successive tuple members. Currently no such tuples are defined for
800 // svcount_t, so assert that NumVectors is 1.
801 assert((BT->getKind() != BuiltinType::SveCount || Info.NumVectors == 1) &&
802 "Unsupported number of vectors for svcount_t");
803
804 // Debuggers can't extract 1bit from a vector, so will display a
805 // bitpattern for predicates instead.
806 unsigned NumElems = Info.EC.getKnownMinValue() * Info.NumVectors;
807 if (Info.ElementType == CGM.getContext().BoolTy) {
808 NumElems /= 8;
810 }
811
812 llvm::Metadata *LowerBound, *UpperBound;
813 LowerBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
814 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
815 if (Info.EC.isScalable()) {
816 unsigned NumElemsPerVG = NumElems / 2;
818 {llvm::dwarf::DW_OP_constu, NumElemsPerVG, llvm::dwarf::DW_OP_bregx,
819 /* AArch64::VG */ 46, 0, llvm::dwarf::DW_OP_mul,
820 llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
821 UpperBound = DBuilder.createExpression(Expr);
822 } else
823 UpperBound = llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
824 llvm::Type::getInt64Ty(CGM.getLLVMContext()), NumElems - 1));
825
826 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
827 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
828 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
829 llvm::DIType *ElemTy =
830 getOrCreateType(Info.ElementType, TheCU->getFile());
831 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
832 return DBuilder.createVectorType(/*Size*/ 0, Align, ElemTy,
833 SubscriptArray);
834 }
835 // It doesn't make sense to generate debug info for PowerPC MMA vector types.
836 // So we return a safe type here to avoid generating an error.
837#define PPC_VECTOR_TYPE(Name, Id, size) \
838 case BuiltinType::Id:
839#include "clang/Basic/PPCTypes.def"
840 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
841
842#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
843#include "clang/Basic/RISCVVTypes.def"
844 {
847
848 unsigned ElementCount = Info.EC.getKnownMinValue();
849 unsigned SEW = CGM.getContext().getTypeSize(Info.ElementType);
850
851 bool Fractional = false;
852 unsigned LMUL;
853 unsigned FixedSize = ElementCount * SEW;
854 if (Info.ElementType == CGM.getContext().BoolTy) {
855 // Mask type only occupies one vector register.
856 LMUL = 1;
857 } else if (FixedSize < 64) {
858 // In RVV scalable vector types, we encode 64 bits in the fixed part.
859 Fractional = true;
860 LMUL = 64 / FixedSize;
861 } else {
862 LMUL = FixedSize / 64;
863 }
864
865 // Element count = (VLENB / SEW) x LMUL
867 // The DW_OP_bregx operation has two operands: a register which is
868 // specified by an unsigned LEB128 number, followed by a signed LEB128
869 // offset.
870 {llvm::dwarf::DW_OP_bregx, // Read the contents of a register.
871 4096 + 0xC22, // RISC-V VLENB CSR register.
872 0, // Offset for DW_OP_bregx. It is dummy here.
873 llvm::dwarf::DW_OP_constu,
874 SEW / 8, // SEW is in bits.
875 llvm::dwarf::DW_OP_div, llvm::dwarf::DW_OP_constu, LMUL});
876 if (Fractional)
877 Expr.push_back(llvm::dwarf::DW_OP_div);
878 else
879 Expr.push_back(llvm::dwarf::DW_OP_mul);
880 // Element max index = count - 1
881 Expr.append({llvm::dwarf::DW_OP_constu, 1, llvm::dwarf::DW_OP_minus});
882
883 auto *LowerBound =
884 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
885 llvm::Type::getInt64Ty(CGM.getLLVMContext()), 0));
886 auto *UpperBound = DBuilder.createExpression(Expr);
887 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(
888 /*count*/ nullptr, LowerBound, UpperBound, /*stride*/ nullptr);
889 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
890 llvm::DIType *ElemTy =
891 getOrCreateType(Info.ElementType, TheCU->getFile());
892
893 auto Align = getTypeAlignIfRequired(BT, CGM.getContext());
894 return DBuilder.createVectorType(/*Size=*/0, Align, ElemTy,
895 SubscriptArray);
896 }
897
898#define WASM_REF_TYPE(Name, MangledName, Id, SingletonId, AS) \
899 case BuiltinType::Id: { \
900 if (!SingletonId) \
901 SingletonId = \
902 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, \
903 MangledName, TheCU, TheCU->getFile(), 0); \
904 return SingletonId; \
905 }
906#include "clang/Basic/WebAssemblyReferenceTypes.def"
907#define AMDGPU_OPAQUE_PTR_TYPE(Name, Id, SingletonId, Width, Align, AS) \
908 case BuiltinType::Id: { \
909 if (!SingletonId) \
910 SingletonId = \
911 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name, \
912 TheCU, TheCU->getFile(), 0); \
913 return SingletonId; \
914 }
915#define AMDGPU_NAMED_BARRIER_TYPE(Name, Id, SingletonId, Width, Align, Scope) \
916 case BuiltinType::Id: { \
917 if (!SingletonId) \
918 SingletonId = \
919 DBuilder.createBasicType(Name, Width, llvm::dwarf::DW_ATE_unsigned); \
920 return SingletonId; \
921 }
922#include "clang/Basic/AMDGPUTypes.def"
923 case BuiltinType::UChar:
924 case BuiltinType::Char_U:
925 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
926 break;
927 case BuiltinType::Char_S:
928 case BuiltinType::SChar:
929 Encoding = llvm::dwarf::DW_ATE_signed_char;
930 break;
931 case BuiltinType::Char8:
932 case BuiltinType::Char16:
933 case BuiltinType::Char32:
934 Encoding = llvm::dwarf::DW_ATE_UTF;
935 break;
936 case BuiltinType::UShort:
937 case BuiltinType::UInt:
938 case BuiltinType::UInt128:
939 case BuiltinType::ULong:
940 case BuiltinType::WChar_U:
941 case BuiltinType::ULongLong:
942 Encoding = llvm::dwarf::DW_ATE_unsigned;
943 break;
944 case BuiltinType::Short:
945 case BuiltinType::Int:
946 case BuiltinType::Int128:
947 case BuiltinType::Long:
948 case BuiltinType::WChar_S:
949 case BuiltinType::LongLong:
950 Encoding = llvm::dwarf::DW_ATE_signed;
951 break;
952 case BuiltinType::Bool:
953 Encoding = llvm::dwarf::DW_ATE_boolean;
954 break;
955 case BuiltinType::Half:
956 case BuiltinType::Float:
957 case BuiltinType::LongDouble:
958 case BuiltinType::Float16:
959 case BuiltinType::BFloat16:
960 case BuiltinType::Float128:
961 case BuiltinType::Double:
962 case BuiltinType::Ibm128:
963 // FIXME: For targets where long double, __ibm128 and __float128 have the
964 // same size, they are currently indistinguishable in the debugger without
965 // some special treatment. However, there is currently no consensus on
966 // encoding and this should be updated once a DWARF encoding exists for
967 // distinct floating point types of the same size.
968 Encoding = llvm::dwarf::DW_ATE_float;
969 break;
970 case BuiltinType::ShortAccum:
971 case BuiltinType::Accum:
972 case BuiltinType::LongAccum:
973 case BuiltinType::ShortFract:
974 case BuiltinType::Fract:
975 case BuiltinType::LongFract:
976 case BuiltinType::SatShortFract:
977 case BuiltinType::SatFract:
978 case BuiltinType::SatLongFract:
979 case BuiltinType::SatShortAccum:
980 case BuiltinType::SatAccum:
981 case BuiltinType::SatLongAccum:
982 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
983 break;
984 case BuiltinType::UShortAccum:
985 case BuiltinType::UAccum:
986 case BuiltinType::ULongAccum:
987 case BuiltinType::UShortFract:
988 case BuiltinType::UFract:
989 case BuiltinType::ULongFract:
990 case BuiltinType::SatUShortAccum:
991 case BuiltinType::SatUAccum:
992 case BuiltinType::SatULongAccum:
993 case BuiltinType::SatUShortFract:
994 case BuiltinType::SatUFract:
995 case BuiltinType::SatULongFract:
996 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
997 break;
998 }
999
1000 BTName = BT->getName(CGM.getLangOpts());
1001 // Bit size and offset of the type.
1002 uint64_t Size = CGM.getContext().getTypeSize(BT);
1003 return DBuilder.createBasicType(BTName, Size, Encoding);
1004}
1005
1006llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
1007
1008 StringRef Name = Ty->isUnsigned() ? "unsigned _BitInt" : "_BitInt";
1009 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
1010 ? llvm::dwarf::DW_ATE_unsigned
1011 : llvm::dwarf::DW_ATE_signed;
1012
1013 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
1014 Encoding);
1015}
1016
1017llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
1018 // Bit size and offset of the type.
1019 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
1020 if (Ty->isComplexIntegerType())
1021 Encoding = llvm::dwarf::DW_ATE_lo_user;
1022
1023 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1024 return DBuilder.createBasicType("complex", Size, Encoding);
1025}
1026
1028 // Ignore these qualifiers for now.
1029 Q.removeObjCGCAttr();
1032 Q.removeUnaligned();
1033}
1034
1035static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
1036 if (Q.hasConst()) {
1037 Q.removeConst();
1038 return llvm::dwarf::DW_TAG_const_type;
1039 }
1040 if (Q.hasVolatile()) {
1041 Q.removeVolatile();
1042 return llvm::dwarf::DW_TAG_volatile_type;
1043 }
1044 if (Q.hasRestrict()) {
1045 Q.removeRestrict();
1046 return llvm::dwarf::DW_TAG_restrict_type;
1047 }
1048 return (llvm::dwarf::Tag)0;
1049}
1050
1051llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
1052 llvm::DIFile *Unit) {
1054 const Type *T = Qc.strip(Ty);
1055
1057
1058 // We will create one Derived type for one qualifier and recurse to handle any
1059 // additional ones.
1060 llvm::dwarf::Tag Tag = getNextQualifier(Qc);
1061 if (!Tag) {
1062 assert(Qc.empty() && "Unknown type qualifier for debug info");
1063 return getOrCreateType(QualType(T, 0), Unit);
1064 }
1065
1066 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
1067
1068 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1069 // CVR derived types.
1070 return DBuilder.createQualifiedType(Tag, FromTy);
1071}
1072
1073llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
1074 llvm::DIFile *Unit) {
1076 Qualifiers &Q = EPI.TypeQuals;
1078
1079 // We will create one Derived type for one qualifier and recurse to handle any
1080 // additional ones.
1081 llvm::dwarf::Tag Tag = getNextQualifier(Q);
1082 if (!Tag) {
1083 assert(Q.empty() && "Unknown type qualifier for debug info");
1084 return nullptr;
1085 }
1086
1087 auto *FromTy =
1088 getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
1089 F->getParamTypes(), EPI),
1090 Unit);
1091
1092 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1093 // CVR derived types.
1094 return DBuilder.createQualifiedType(Tag, FromTy);
1095}
1096
1097llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1098 llvm::DIFile *Unit) {
1099
1100 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1101 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1102 // debug info, we want to emit 'id' in both cases.
1103 if (Ty->isObjCQualifiedIdType())
1104 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1105
1106 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1107 Ty->getPointeeType(), Unit);
1108}
1109
1110llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
1111 llvm::DIFile *Unit) {
1112 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1113 Ty->getPointeeType(), Unit);
1114}
1115
1116/// \return whether a C++ mangling exists for the type defined by TD.
1117static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1118 switch (TheCU->getSourceLanguage()) {
1119 case llvm::dwarf::DW_LANG_C_plus_plus:
1120 case llvm::dwarf::DW_LANG_C_plus_plus_11:
1121 case llvm::dwarf::DW_LANG_C_plus_plus_14:
1122 return true;
1123 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1124 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1125 default:
1126 return false;
1127 }
1128}
1129
1130// Determines if the debug info for this tag declaration needs a type
1131// identifier. The purpose of the unique identifier is to deduplicate type
1132// information for identical types across TUs. Because of the C++ one definition
1133// rule (ODR), it is valid to assume that the type is defined the same way in
1134// every TU and its debug info is equivalent.
1135//
1136// C does not have the ODR, and it is common for codebases to contain multiple
1137// different definitions of a struct with the same name in different TUs.
1138// Therefore, if the type doesn't have a C++ mangling, don't give it an
1139// identifer. Type information in C is smaller and simpler than C++ type
1140// information, so the increase in debug info size is negligible.
1141//
1142// If the type is not externally visible, it should be unique to the current TU,
1143// and should not need an identifier to participate in type deduplication.
1144// However, when emitting CodeView, the format internally uses these
1145// unique type name identifers for references between debug info. For example,
1146// the method of a class in an anonymous namespace uses the identifer to refer
1147// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1148// for such types, so when emitting CodeView, always use identifiers for C++
1149// types. This may create problems when attempting to emit CodeView when the MS
1150// C++ ABI is not in use.
1151static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1152 llvm::DICompileUnit *TheCU) {
1153 // We only add a type identifier for types with C++ name mangling.
1154 if (!hasCXXMangling(TD, TheCU))
1155 return false;
1156
1157 // Externally visible types with C++ mangling need a type identifier.
1158 if (TD->isExternallyVisible())
1159 return true;
1160
1161 // CodeView types with C++ mangling need a type identifier.
1162 if (CGM.getCodeGenOpts().EmitCodeView)
1163 return true;
1164
1165 return false;
1166}
1167
1168// Returns a unique type identifier string if one exists, or an empty string.
1170 llvm::DICompileUnit *TheCU) {
1172 const TagDecl *TD = Ty->getDecl();
1173
1174 if (!needsTypeIdentifier(TD, CGM, TheCU))
1175 return Identifier;
1176 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1177 if (RD->getDefinition())
1178 if (RD->isDynamicClass() &&
1179 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1180 return Identifier;
1181
1182 // TODO: This is using the RTTI name. Is there a better way to get
1183 // a unique string for a type?
1184 llvm::raw_svector_ostream Out(Identifier);
1186 return Identifier;
1187}
1188
1189/// \return the appropriate DWARF tag for a composite type.
1190static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1191 llvm::dwarf::Tag Tag;
1192 if (RD->isStruct() || RD->isInterface())
1193 Tag = llvm::dwarf::DW_TAG_structure_type;
1194 else if (RD->isUnion())
1195 Tag = llvm::dwarf::DW_TAG_union_type;
1196 else {
1197 // FIXME: This could be a struct type giving a default visibility different
1198 // than C++ class type, but needs llvm metadata changes first.
1199 assert(RD->isClass());
1200 Tag = llvm::dwarf::DW_TAG_class_type;
1201 }
1202 return Tag;
1203}
1204
1205llvm::DICompositeType *
1206CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1207 llvm::DIScope *Ctx) {
1208 const RecordDecl *RD = Ty->getDecl();
1209 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
1210 return cast<llvm::DICompositeType>(T);
1211 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1212 const unsigned Line =
1213 getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1214 StringRef RDName = getClassName(RD);
1215
1216 uint64_t Size = 0;
1217 uint32_t Align = 0;
1218
1219 const RecordDecl *D = RD->getDefinition();
1220 if (D && D->isCompleteDefinition())
1221 Size = CGM.getContext().getTypeSize(Ty);
1222
1223 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1224
1225 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1226 // add the flag if a record has no definition because we don't know whether
1227 // it will be trivial or not.
1228 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1229 if (!CXXRD->hasDefinition() ||
1230 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1231 Flags |= llvm::DINode::FlagNonTrivial;
1232
1233 // Create the type.
1235 // Don't include a linkage name in line tables only.
1237 Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1238 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1239 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1240 Identifier);
1241 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1242 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1243 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1244 CollectCXXTemplateParams(TSpecial, DefUnit));
1245 ReplaceMap.emplace_back(
1246 std::piecewise_construct, std::make_tuple(Ty),
1247 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1248 return RetTy;
1249}
1250
1251llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1252 const Type *Ty,
1253 QualType PointeeTy,
1254 llvm::DIFile *Unit) {
1255 // Bit size, align and offset of the type.
1256 // Size is always the size of a pointer.
1257 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1258 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1259 std::optional<unsigned> DWARFAddressSpace =
1261 CGM.getTypes().getTargetAddressSpace(PointeeTy));
1262
1263 const BTFTagAttributedType *BTFAttrTy;
1264 if (auto *Atomic = PointeeTy->getAs<AtomicType>())
1265 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Atomic->getValueType());
1266 else
1267 BTFAttrTy = dyn_cast<BTFTagAttributedType>(PointeeTy);
1269 while (BTFAttrTy) {
1270 StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
1271 if (!Tag.empty()) {
1272 llvm::Metadata *Ops[2] = {
1273 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
1274 llvm::MDString::get(CGM.getLLVMContext(), Tag)};
1275 Annots.insert(Annots.begin(),
1276 llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1277 }
1278 BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
1279 }
1280
1281 llvm::DINodeArray Annotations = nullptr;
1282 if (Annots.size() > 0)
1283 Annotations = DBuilder.getOrCreateArray(Annots);
1284
1285 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1286 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1287 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1288 Size, Align, DWARFAddressSpace);
1289 else
1290 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1291 Align, DWARFAddressSpace, StringRef(),
1292 Annotations);
1293}
1294
1295llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1296 llvm::DIType *&Cache) {
1297 if (Cache)
1298 return Cache;
1299 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1300 TheCU, TheCU->getFile(), 0);
1301 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1302 Cache = DBuilder.createPointerType(Cache, Size);
1303 return Cache;
1304}
1305
1306uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1307 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1308 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1309 QualType FType;
1310
1311 // Advanced by calls to CreateMemberType in increments of FType, then
1312 // returned as the overall size of the default elements.
1313 uint64_t FieldOffset = 0;
1314
1315 // Blocks in OpenCL have unique constraints which make the standard fields
1316 // redundant while requiring size and align fields for enqueue_kernel. See
1317 // initializeForBlockHeader in CGBlocks.cpp
1318 if (CGM.getLangOpts().OpenCL) {
1319 FType = CGM.getContext().IntTy;
1320 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1321 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1322 } else {
1323 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1324 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1325 FType = CGM.getContext().IntTy;
1326 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1327 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1328 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1329 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1330 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1331 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1332 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1333 EltTys.push_back(DBuilder.createMemberType(
1334 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1335 FieldOffset, llvm::DINode::FlagZero, DescTy));
1336 FieldOffset += FieldSize;
1337 }
1338
1339 return FieldOffset;
1340}
1341
1342llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1343 llvm::DIFile *Unit) {
1345 QualType FType;
1346 uint64_t FieldOffset;
1347 llvm::DINodeArray Elements;
1348
1349 FieldOffset = 0;
1350 FType = CGM.getContext().UnsignedLongTy;
1351 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1352 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1353
1354 Elements = DBuilder.getOrCreateArray(EltTys);
1355 EltTys.clear();
1356
1357 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1358
1359 auto *EltTy =
1360 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1361 FieldOffset, 0, Flags, nullptr, Elements);
1362
1363 // Bit size, align and offset of the type.
1364 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1365
1366 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1367
1368 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1369 0, EltTys);
1370
1371 Elements = DBuilder.getOrCreateArray(EltTys);
1372
1373 // The __block_literal_generic structs are marked with a special
1374 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1375 // the debugger needs to know about. To allow type uniquing, emit
1376 // them without a name or a location.
1377 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1378 Flags, nullptr, Elements);
1379
1380 return DBuilder.createPointerType(EltTy, Size);
1381}
1382
1385 assert(Ty->isTypeAlias());
1386 // TemplateSpecializationType doesn't know if its template args are
1387 // being substituted into a parameter pack. We can find out if that's
1388 // the case now by inspecting the TypeAliasTemplateDecl template
1389 // parameters. Insert Ty's template args into SpecArgs, bundling args
1390 // passed to a parameter pack into a TemplateArgument::Pack. It also
1391 // doesn't know the value of any defaulted args, so collect those now
1392 // too.
1394 ArrayRef SubstArgs = Ty->template_arguments();
1395 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1396 // If Param is a parameter pack, pack the remaining arguments.
1397 if (Param->isParameterPack()) {
1398 SpecArgs.push_back(TemplateArgument(SubstArgs));
1399 break;
1400 }
1401
1402 // Skip defaulted args.
1403 // FIXME: Ideally, we wouldn't do this. We can read the default values
1404 // for each parameter. However, defaulted arguments which are dependent
1405 // values or dependent types can't (easily?) be resolved here.
1406 if (SubstArgs.empty()) {
1407 // If SubstArgs is now empty (we're taking from it each iteration) and
1408 // this template parameter isn't a pack, then that should mean we're
1409 // using default values for the remaining template parameters (after
1410 // which there may be an empty pack too which we will ignore).
1411 break;
1412 }
1413
1414 // Take the next argument.
1415 SpecArgs.push_back(SubstArgs.front());
1416 SubstArgs = SubstArgs.drop_front();
1417 }
1418 return SpecArgs;
1419}
1420
1421llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1422 llvm::DIFile *Unit) {
1423 assert(Ty->isTypeAlias());
1424 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1425
1427 if (isa<BuiltinTemplateDecl>(TD))
1428 return Src;
1429
1430 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1431 if (AliasDecl->hasAttr<NoDebugAttr>())
1432 return Src;
1433
1435 llvm::raw_svector_ostream OS(NS);
1436
1437 auto PP = getPrintingPolicy();
1439
1440 SourceLocation Loc = AliasDecl->getLocation();
1441
1442 if (CGM.getCodeGenOpts().DebugTemplateAlias &&
1443 // FIXME: This is a workaround for the issue
1444 // https://github.com/llvm/llvm-project/issues/89774
1445 // The TemplateSpecializationType doesn't contain any instantiation
1446 // information; dependent template arguments can't be resolved. For now,
1447 // fall back to DW_TAG_typedefs for template aliases that are
1448 // instantiation dependent, e.g.:
1449 // ```
1450 // template <int>
1451 // using A = int;
1452 //
1453 // template<int I>
1454 // struct S {
1455 // using AA = A<I>; // Instantiation dependent.
1456 // AA aa;
1457 // };
1458 //
1459 // S<0> s;
1460 // ```
1461 // S::AA's underlying type A<I> is dependent on I so will be emitted as a
1462 // DW_TAG_typedef.
1464 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1465 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1466
1467 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1468 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1469 // doesn't have instantiation information, so
1470 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1471 // template args.
1472 std::string Name;
1473 llvm::raw_string_ostream OS(Name);
1474 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1475 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1476 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1477 !HasReconstitutableArgs(Args.Args))
1478 printTemplateArgumentList(OS, Args.Args, PP);
1479
1480 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1481 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1482 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1483 return AliasTy;
1484 }
1485
1487 TD->getTemplateParameters());
1488 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1489 getLineNumber(Loc),
1490 getDeclContextDescriptor(AliasDecl));
1491}
1492
1493/// Convert an AccessSpecifier into the corresponding DINode flag.
1494/// As an optimization, return 0 if the access specifier equals the
1495/// default for the containing type.
1496static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1497 const RecordDecl *RD) {
1499 if (RD && RD->isClass())
1501 else if (RD && (RD->isStruct() || RD->isUnion()))
1503
1504 if (Access == Default)
1505 return llvm::DINode::FlagZero;
1506
1507 switch (Access) {
1508 case clang::AS_private:
1509 return llvm::DINode::FlagPrivate;
1511 return llvm::DINode::FlagProtected;
1512 case clang::AS_public:
1513 return llvm::DINode::FlagPublic;
1514 case clang::AS_none:
1515 return llvm::DINode::FlagZero;
1516 }
1517 llvm_unreachable("unexpected access enumerator");
1518}
1519
1520llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1521 llvm::DIFile *Unit) {
1522 llvm::DIType *Underlying =
1523 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1524
1525 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1526 return Underlying;
1527
1528 // We don't set size information, but do specify where the typedef was
1529 // declared.
1531
1532 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1533 // Typedefs are derived from some other type.
1534 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(Ty->getDecl());
1535
1536 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1537 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1538 if (isa<RecordDecl>(DC))
1539 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1540
1541 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1542 getOrCreateFile(Loc), getLineNumber(Loc),
1543 getDeclContextDescriptor(Ty->getDecl()), Align,
1544 Flags, Annotations);
1545}
1546
1547static unsigned getDwarfCC(CallingConv CC) {
1548 switch (CC) {
1549 case CC_C:
1550 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1551 return 0;
1552
1553 case CC_X86StdCall:
1554 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1555 case CC_X86FastCall:
1556 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1557 case CC_X86ThisCall:
1558 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1559 case CC_X86VectorCall:
1560 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1561 case CC_X86Pascal:
1562 return llvm::dwarf::DW_CC_BORLAND_pascal;
1563 case CC_Win64:
1564 return llvm::dwarf::DW_CC_LLVM_Win64;
1565 case CC_X86_64SysV:
1566 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1567 case CC_AAPCS:
1569 case CC_AArch64SVEPCS:
1570 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1571 case CC_AAPCS_VFP:
1572 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1573 case CC_IntelOclBicc:
1574 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1575 case CC_SpirFunction:
1576 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1577 case CC_OpenCLKernel:
1579 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1580 case CC_Swift:
1581 return llvm::dwarf::DW_CC_LLVM_Swift;
1582 case CC_SwiftAsync:
1583 return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1584 case CC_PreserveMost:
1585 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1586 case CC_PreserveAll:
1587 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1588 case CC_X86RegCall:
1589 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1590 case CC_M68kRTD:
1591 return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1592 case CC_PreserveNone:
1593 return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1594 case CC_RISCVVectorCall:
1595 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1596 }
1597 return 0;
1598}
1599
1600static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1601 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1602 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1603 Flags |= llvm::DINode::FlagLValueReference;
1604 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1605 Flags |= llvm::DINode::FlagRValueReference;
1606 return Flags;
1607}
1608
1609llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1610 llvm::DIFile *Unit) {
1611 const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1612 if (FPT) {
1613 if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1614 return QTy;
1615 }
1616
1617 // Create the type without any qualifiers
1618
1620
1621 // Add the result type at least.
1622 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1623
1624 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1625 // Set up remainder of arguments if there is a prototype.
1626 // otherwise emit it as a variadic function.
1627 if (!FPT) {
1628 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1629 } else {
1630 Flags = getRefFlags(FPT);
1631 for (const QualType &ParamType : FPT->param_types())
1632 EltTys.push_back(getOrCreateType(ParamType, Unit));
1633 if (FPT->isVariadic())
1634 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1635 }
1636
1637 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1638 llvm::DIType *F = DBuilder.createSubroutineType(
1639 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1640 return F;
1641}
1642
1643llvm::DIDerivedType *
1644CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1645 llvm::DIScope *RecordTy, const RecordDecl *RD) {
1646 StringRef Name = BitFieldDecl->getName();
1647 QualType Ty = BitFieldDecl->getType();
1648 if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1649 Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1650 SourceLocation Loc = BitFieldDecl->getLocation();
1651 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1652 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1653
1654 // Get the location for the field.
1655 llvm::DIFile *File = getOrCreateFile(Loc);
1656 unsigned Line = getLineNumber(Loc);
1657
1658 const CGBitFieldInfo &BitFieldInfo =
1659 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1660 uint64_t SizeInBits = BitFieldInfo.Size;
1661 assert(SizeInBits > 0 && "found named 0-width bitfield");
1662 uint64_t StorageOffsetInBits =
1663 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1664 uint64_t Offset = BitFieldInfo.Offset;
1665 // The bit offsets for big endian machines are reversed for big
1666 // endian target, compensate for that as the DIDerivedType requires
1667 // un-reversed offsets.
1668 if (CGM.getDataLayout().isBigEndian())
1669 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1670 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1671 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1672 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1673 return DBuilder.createBitFieldMemberType(
1674 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1675 Flags, DebugType, Annotations);
1676}
1677
1678llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1679 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1680 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1681
1683 return nullptr;
1684
1685 /*
1686 Add a *single* zero-bitfield separator between two non-zero bitfields
1687 separated by one or more zero-bitfields. This is used to distinguish between
1688 structures such the ones below, where the memory layout is the same, but how
1689 the ABI assigns fields to registers differs.
1690
1691 struct foo {
1692 int space[4];
1693 char a : 8; // on amdgpu, passed on v4
1694 char b : 8;
1695 char x : 8;
1696 char y : 8;
1697 };
1698 struct bar {
1699 int space[4];
1700 char a : 8; // on amdgpu, passed on v4
1701 char b : 8;
1702 char : 0;
1703 char x : 8; // passed on v5
1704 char y : 8;
1705 };
1706 */
1707 if (PreviousFieldsDI.empty())
1708 return nullptr;
1709
1710 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1711 auto *PreviousMDEntry =
1712 PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1713 auto *PreviousMDField =
1714 dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1715 if (!PreviousMDField || !PreviousMDField->isBitField() ||
1716 PreviousMDField->getSizeInBits() == 0)
1717 return nullptr;
1718
1719 auto PreviousBitfield = RD->field_begin();
1720 std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1721
1722 assert(PreviousBitfield->isBitField());
1723
1724 ASTContext &Context = CGM.getContext();
1725 if (!PreviousBitfield->isZeroLengthBitField(Context))
1726 return nullptr;
1727
1728 QualType Ty = PreviousBitfield->getType();
1729 SourceLocation Loc = PreviousBitfield->getLocation();
1730 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1731 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1732 llvm::DIScope *RecordTy = BitFieldDI->getScope();
1733
1734 llvm::DIFile *File = getOrCreateFile(Loc);
1735 unsigned Line = getLineNumber(Loc);
1736
1737 uint64_t StorageOffsetInBits =
1738 cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1739 ->getZExtValue();
1740
1741 llvm::DINode::DIFlags Flags =
1742 getAccessFlag(PreviousBitfield->getAccess(), RD);
1743 llvm::DINodeArray Annotations =
1744 CollectBTFDeclTagAnnotations(*PreviousBitfield);
1745 return DBuilder.createBitFieldMemberType(
1746 RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
1747 Flags, DebugType, Annotations);
1748}
1749
1750llvm::DIType *CGDebugInfo::createFieldType(
1751 StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
1752 uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
1753 llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
1754 llvm::DIType *debugType = getOrCreateType(type, tunit);
1755
1756 // Get the location for the field.
1757 llvm::DIFile *file = getOrCreateFile(loc);
1758 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
1759
1760 uint64_t SizeInBits = 0;
1761 auto Align = AlignInBits;
1762 if (!type->isIncompleteArrayType()) {
1763 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1764 SizeInBits = TI.Width;
1765 if (!Align)
1766 Align = getTypeAlignIfRequired(type, CGM.getContext());
1767 }
1768
1769 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1770 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1771 offsetInBits, flags, debugType, Annotations);
1772}
1773
1774llvm::DISubprogram *
1775CGDebugInfo::createInlinedTrapSubprogram(StringRef FuncName,
1776 llvm::DIFile *FileScope) {
1777 // We are caching the subprogram because we don't want to duplicate
1778 // subprograms with the same message. Note that `SPFlagDefinition` prevents
1779 // subprograms from being uniqued.
1780 llvm::DISubprogram *&SP = InlinedTrapFuncMap[FuncName];
1781
1782 if (!SP) {
1783 llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(nullptr);
1784 SP = DBuilder.createFunction(
1785 /*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(),
1786 /*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy,
1787 /*ScopeLine=*/0,
1788 /*Flags=*/llvm::DINode::FlagArtificial,
1789 /*SPFlags=*/llvm::DISubprogram::SPFlagDefinition,
1790 /*TParams=*/nullptr, /*ThrownTypes=*/nullptr, /*Annotations=*/nullptr);
1791 }
1792
1793 return SP;
1794}
1795
1796void CGDebugInfo::CollectRecordLambdaFields(
1797 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1798 llvm::DIType *RecordTy) {
1799 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1800 // has the name and the location of the variable so we should iterate over
1801 // both concurrently.
1802 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1804 unsigned fieldno = 0;
1806 E = CXXDecl->captures_end();
1807 I != E; ++I, ++Field, ++fieldno) {
1808 const LambdaCapture &C = *I;
1809 if (C.capturesVariable()) {
1810 SourceLocation Loc = C.getLocation();
1811 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1812 ValueDecl *V = C.getCapturedVar();
1813 StringRef VName = V->getName();
1814 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1815 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1816 llvm::DIType *FieldType = createFieldType(
1817 VName, Field->getType(), Loc, Field->getAccess(),
1818 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1819 elements.push_back(FieldType);
1820 } else if (C.capturesThis()) {
1821 // TODO: Need to handle 'this' in some way by probably renaming the
1822 // this of the lambda class and having a field member of 'this' or
1823 // by using AT_object_pointer for the function and having that be
1824 // used as 'this' for semantic references.
1825 FieldDecl *f = *Field;
1826 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1827 QualType type = f->getType();
1828 StringRef ThisName =
1829 CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
1830 llvm::DIType *fieldType = createFieldType(
1831 ThisName, type, f->getLocation(), f->getAccess(),
1832 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1833
1834 elements.push_back(fieldType);
1835 }
1836 }
1837}
1838
1839llvm::DIDerivedType *
1840CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1841 const RecordDecl *RD) {
1842 // Create the descriptor for the static variable, with or without
1843 // constant initializers.
1844 Var = Var->getCanonicalDecl();
1845 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1846 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1847
1848 unsigned LineNumber = getLineNumber(Var->getLocation());
1849 StringRef VName = Var->getName();
1850
1851 // FIXME: to avoid complications with type merging we should
1852 // emit the constant on the definition instead of the declaration.
1853 llvm::Constant *C = nullptr;
1854 if (Var->getInit()) {
1855 const APValue *Value = Var->evaluateValue();
1856 if (Value) {
1857 if (Value->isInt())
1858 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1859 if (Value->isFloat())
1860 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1861 }
1862 }
1863
1864 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1865 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
1866 ? llvm::dwarf::DW_TAG_variable
1867 : llvm::dwarf::DW_TAG_member;
1868 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1869 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1870 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
1871 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1872 return GV;
1873}
1874
1875void CGDebugInfo::CollectRecordNormalField(
1876 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1877 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1878 const RecordDecl *RD) {
1879 StringRef name = field->getName();
1880 QualType type = field->getType();
1881
1882 // Ignore unnamed fields unless they're anonymous structs/unions.
1883 if (name.empty() && !type->isRecordType())
1884 return;
1885
1886 llvm::DIType *FieldType;
1887 if (field->isBitField()) {
1888 llvm::DIDerivedType *BitFieldType;
1889 FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
1890 if (llvm::DIType *Separator =
1891 createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
1892 elements.push_back(Separator);
1893 } else {
1894 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1895 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
1896 FieldType =
1897 createFieldType(name, type, field->getLocation(), field->getAccess(),
1898 OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
1899 }
1900
1901 elements.push_back(FieldType);
1902}
1903
1904void CGDebugInfo::CollectRecordNestedType(
1905 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1906 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1907 // Injected class names are not considered nested records.
1908 if (isa<InjectedClassNameType>(Ty))
1909 return;
1911 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1912 elements.push_back(nestedType);
1913}
1914
1915void CGDebugInfo::CollectRecordFields(
1916 const RecordDecl *record, llvm::DIFile *tunit,
1918 llvm::DICompositeType *RecordTy) {
1919 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1920
1921 if (CXXDecl && CXXDecl->isLambda())
1922 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1923 else {
1924 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1925
1926 // Field number for non-static fields.
1927 unsigned fieldNo = 0;
1928
1929 // Static and non-static members should appear in the same order as
1930 // the corresponding declarations in the source program.
1931 for (const auto *I : record->decls())
1932 if (const auto *V = dyn_cast<VarDecl>(I)) {
1933 if (V->hasAttr<NoDebugAttr>())
1934 continue;
1935
1936 // Skip variable template specializations when emitting CodeView. MSVC
1937 // doesn't emit them.
1938 if (CGM.getCodeGenOpts().EmitCodeView &&
1939 isa<VarTemplateSpecializationDecl>(V))
1940 continue;
1941
1942 if (isa<VarTemplatePartialSpecializationDecl>(V))
1943 continue;
1944
1945 // Reuse the existing static member declaration if one exists
1946 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1947 if (MI != StaticDataMemberCache.end()) {
1948 assert(MI->second &&
1949 "Static data member declaration should still exist");
1950 elements.push_back(MI->second);
1951 } else {
1952 auto Field = CreateRecordStaticField(V, RecordTy, record);
1953 elements.push_back(Field);
1954 }
1955 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1956 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1957 elements, RecordTy, record);
1958
1959 // Bump field number for next field.
1960 ++fieldNo;
1961 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1962 // Debug info for nested types is included in the member list only for
1963 // CodeView.
1964 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
1965 // MSVC doesn't generate nested type for anonymous struct/union.
1966 if (isa<RecordDecl>(I) &&
1967 cast<RecordDecl>(I)->isAnonymousStructOrUnion())
1968 continue;
1969 if (!nestedType->isImplicit() &&
1970 nestedType->getDeclContext() == record)
1971 CollectRecordNestedType(nestedType, elements);
1972 }
1973 }
1974 }
1975}
1976
1977llvm::DISubroutineType *
1978CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1979 llvm::DIFile *Unit) {
1980 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1981 if (Method->isStatic())
1982 return cast_or_null<llvm::DISubroutineType>(
1983 getOrCreateType(QualType(Func, 0), Unit));
1984
1985 QualType ThisType;
1987 ThisType = Method->getThisType();
1988
1989 return getOrCreateInstanceMethodType(ThisType, Func, Unit);
1990}
1991
1992llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1993 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1994 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
1995 Qualifiers &Qc = EPI.TypeQuals;
1996 Qc.removeConst();
1997 Qc.removeVolatile();
1998 Qc.removeRestrict();
1999 Qc.removeUnaligned();
2000 // Keep the removed qualifiers in sync with
2001 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
2002 // On a 'real' member function type, these qualifiers are carried on the type
2003 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
2004 // tags around them. (But, in the raw function types with qualifiers, they have
2005 // to use wrapper types.)
2006
2007 // Add "this" pointer.
2008 const auto *OriginalFunc = cast<llvm::DISubroutineType>(
2009 getOrCreateType(CGM.getContext().getFunctionType(
2010 Func->getReturnType(), Func->getParamTypes(), EPI),
2011 Unit));
2012 llvm::DITypeRefArray Args = OriginalFunc->getTypeArray();
2013 assert(Args.size() && "Invalid number of arguments!");
2014
2016
2017 // First element is always return type. For 'void' functions it is NULL.
2018 Elts.push_back(Args[0]);
2019
2020 // "this" pointer is always first argument.
2021 // ThisPtr may be null if the member function has an explicit 'this'
2022 // parameter.
2023 if (!ThisPtr.isNull()) {
2024 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
2025 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2026 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
2027 Elts.push_back(ThisPtrType);
2028 }
2029
2030 // Copy rest of the arguments.
2031 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2032 Elts.push_back(Args[i]);
2033
2034 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2035
2036 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
2037 getDwarfCC(Func->getCallConv()));
2038}
2039
2040/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
2041/// inside a function.
2042static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
2043 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
2044 return isFunctionLocalClass(NRD);
2045 if (isa<FunctionDecl>(RD->getDeclContext()))
2046 return true;
2047 return false;
2048}
2049
2050llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
2051 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
2052 bool IsCtorOrDtor =
2053 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
2054
2055 StringRef MethodName = getFunctionName(Method);
2056 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
2057
2058 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
2059 // make sense to give a single ctor/dtor a linkage name.
2060 StringRef MethodLinkageName;
2061 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
2062 // property to use here. It may've been intended to model "is non-external
2063 // type" but misses cases of non-function-local but non-external classes such
2064 // as those in anonymous namespaces as well as the reverse - external types
2065 // that are function local, such as those in (non-local) inline functions.
2066 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
2067 MethodLinkageName = CGM.getMangledName(Method);
2068
2069 // Get the location for the method.
2070 llvm::DIFile *MethodDefUnit = nullptr;
2071 unsigned MethodLine = 0;
2072 if (!Method->isImplicit()) {
2073 MethodDefUnit = getOrCreateFile(Method->getLocation());
2074 MethodLine = getLineNumber(Method->getLocation());
2075 }
2076
2077 // Collect virtual method info.
2078 llvm::DIType *ContainingType = nullptr;
2079 unsigned VIndex = 0;
2080 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2081 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2082 int ThisAdjustment = 0;
2083
2085 if (Method->isPureVirtual())
2086 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2087 else
2088 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2089
2090 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2091 // It doesn't make sense to give a virtual destructor a vtable index,
2092 // since a single destructor has two entries in the vtable.
2093 if (!isa<CXXDestructorDecl>(Method))
2094 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2095 } else {
2096 // Emit MS ABI vftable information. There is only one entry for the
2097 // deleting dtor.
2098 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2099 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
2102 VIndex = ML.Index;
2103
2104 // CodeView only records the vftable offset in the class that introduces
2105 // the virtual method. This is possible because, unlike Itanium, the MS
2106 // C++ ABI does not include all virtual methods from non-primary bases in
2107 // the vtable for the most derived class. For example, if C inherits from
2108 // A and B, C's primary vftable will not include B's virtual methods.
2109 if (Method->size_overridden_methods() == 0)
2110 Flags |= llvm::DINode::FlagIntroducedVirtual;
2111
2112 // The 'this' adjustment accounts for both the virtual and non-virtual
2113 // portions of the adjustment. Presumably the debugger only uses it when
2114 // it knows the dynamic type of an object.
2117 .getQuantity();
2118 }
2119 ContainingType = RecordTy;
2120 }
2121
2122 if (Method->getCanonicalDecl()->isDeleted())
2123 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2124
2125 if (Method->isNoReturn())
2126 Flags |= llvm::DINode::FlagNoReturn;
2127
2128 if (Method->isStatic())
2129 Flags |= llvm::DINode::FlagStaticMember;
2130 if (Method->isImplicit())
2131 Flags |= llvm::DINode::FlagArtificial;
2132 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2133 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2134 if (CXXC->isExplicit())
2135 Flags |= llvm::DINode::FlagExplicit;
2136 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2137 if (CXXC->isExplicit())
2138 Flags |= llvm::DINode::FlagExplicit;
2139 }
2140 if (Method->hasPrototype())
2141 Flags |= llvm::DINode::FlagPrototyped;
2142 if (Method->getRefQualifier() == RQ_LValue)
2143 Flags |= llvm::DINode::FlagLValueReference;
2144 if (Method->getRefQualifier() == RQ_RValue)
2145 Flags |= llvm::DINode::FlagRValueReference;
2146 if (!Method->isExternallyVisible())
2147 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2148 if (CGM.getLangOpts().Optimize)
2149 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2150
2151 // In this debug mode, emit type info for a class when its constructor type
2152 // info is emitted.
2153 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2154 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2155 completeUnusedClass(*CD->getParent());
2156
2157 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2158 llvm::DISubprogram *SP = DBuilder.createMethod(
2159 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2160 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2161 TParamsArray.get());
2162
2163 SPCache[Method->getCanonicalDecl()].reset(SP);
2164
2165 return SP;
2166}
2167
2168void CGDebugInfo::CollectCXXMemberFunctions(
2169 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2170 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2171
2172 // Since we want more than just the individual member decls if we
2173 // have templated functions iterate over every declaration to gather
2174 // the functions.
2175 for (const auto *I : RD->decls()) {
2176 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2177 // If the member is implicit, don't add it to the member list. This avoids
2178 // the member being added to type units by LLVM, while still allowing it
2179 // to be emitted into the type declaration/reference inside the compile
2180 // unit.
2181 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2182 // FIXME: Handle Using(Shadow?)Decls here to create
2183 // DW_TAG_imported_declarations inside the class for base decls brought into
2184 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2185 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2186 // referenced)
2187 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2188 continue;
2189
2191 continue;
2192
2193 // Reuse the existing member function declaration if it exists.
2194 // It may be associated with the declaration of the type & should be
2195 // reused as we're building the definition.
2196 //
2197 // This situation can arise in the vtable-based debug info reduction where
2198 // implicit members are emitted in a non-vtable TU.
2199 auto MI = SPCache.find(Method->getCanonicalDecl());
2200 EltTys.push_back(MI == SPCache.end()
2201 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2202 : static_cast<llvm::Metadata *>(MI->second));
2203 }
2204}
2205
2206void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2208 llvm::DIType *RecordTy) {
2209 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
2210 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2211 llvm::DINode::FlagZero);
2212
2213 // If we are generating CodeView debug info, we also need to emit records for
2214 // indirect virtual base classes.
2215 if (CGM.getCodeGenOpts().EmitCodeView) {
2216 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2217 llvm::DINode::FlagIndirectVirtualBase);
2218 }
2219}
2220
2221void CGDebugInfo::CollectCXXBasesAux(
2222 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2223 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2225 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2226 llvm::DINode::DIFlags StartingFlags) {
2227 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2228 for (const auto &BI : Bases) {
2229 const auto *Base =
2230 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
2231 if (!SeenTypes.insert(Base).second)
2232 continue;
2233 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2234 llvm::DINode::DIFlags BFlags = StartingFlags;
2235 uint64_t BaseOffset;
2236 uint32_t VBPtrOffset = 0;
2237
2238 if (BI.isVirtual()) {
2239 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2240 // virtual base offset offset is -ve. The code generator emits dwarf
2241 // expression where it expects +ve number.
2242 BaseOffset = 0 - CGM.getItaniumVTableContext()
2244 .getQuantity();
2245 } else {
2246 // In the MS ABI, store the vbtable offset, which is analogous to the
2247 // vbase offset offset in Itanium.
2248 BaseOffset =
2250 VBPtrOffset = CGM.getContext()
2253 .getQuantity();
2254 }
2255 BFlags |= llvm::DINode::FlagVirtual;
2256 } else
2257 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2258 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2259 // BI->isVirtual() and bits when not.
2260
2261 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2262 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2263 VBPtrOffset, BFlags);
2264 EltTys.push_back(DTy);
2265 }
2266}
2267
2268llvm::DINodeArray
2269CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2270 llvm::DIFile *Unit) {
2271 if (!OArgs)
2272 return llvm::DINodeArray();
2273 TemplateArgs &Args = *OArgs;
2274 SmallVector<llvm::Metadata *, 16> TemplateParams;
2275 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2276 const TemplateArgument &TA = Args.Args[i];
2277 StringRef Name;
2278 const bool defaultParameter = TA.getIsDefaulted();
2279 if (Args.TList)
2280 Name = Args.TList->getParam(i)->getName();
2281
2282 switch (TA.getKind()) {
2284 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2285 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2286 TheCU, Name, TTy, defaultParameter));
2287
2288 } break;
2290 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2291 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2292 TheCU, Name, TTy, defaultParameter,
2293 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2294 } break;
2296 const ValueDecl *D = TA.getAsDecl();
2298 llvm::DIType *TTy = getOrCreateType(T, Unit);
2299 llvm::Constant *V = nullptr;
2300 // Skip retrieve the value if that template parameter has cuda device
2301 // attribute, i.e. that value is not available at the host side.
2302 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2303 !D->hasAttr<CUDADeviceAttr>()) {
2304 // Variable pointer template parameters have a value that is the address
2305 // of the variable.
2306 if (const auto *VD = dyn_cast<VarDecl>(D))
2307 V = CGM.GetAddrOfGlobalVar(VD);
2308 // Member function pointers have special support for building them,
2309 // though this is currently unsupported in LLVM CodeGen.
2310 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2311 MD && MD->isImplicitObjectMemberFunction())
2313 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2314 V = CGM.GetAddrOfFunction(FD);
2315 // Member data pointers have special handling too to compute the fixed
2316 // offset within the object.
2317 else if (const auto *MPT =
2318 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2319 // These five lines (& possibly the above member function pointer
2320 // handling) might be able to be refactored to use similar code in
2321 // CodeGenModule::getMemberPointerConstant
2322 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2323 CharUnits chars =
2324 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2325 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2326 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2327 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2328 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2329 if (T->isRecordType())
2331 SourceLocation(), TPO->getValue(), TPO->getType());
2332 else
2334 }
2335 assert(V && "Failed to find template parameter pointer");
2336 V = V->stripPointerCasts();
2337 }
2338 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2339 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2340 } break;
2342 QualType T = TA.getNullPtrType();
2343 llvm::DIType *TTy = getOrCreateType(T, Unit);
2344 llvm::Constant *V = nullptr;
2345 // Special case member data pointer null values since they're actually -1
2346 // instead of zero.
2347 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2348 // But treat member function pointers as simple zero integers because
2349 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2350 // CodeGen grows handling for values of non-null member function
2351 // pointers then perhaps we could remove this special case and rely on
2352 // EmitNullMemberPointer for member function pointers.
2353 if (MPT->isMemberDataPointer())
2354 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2355 if (!V)
2356 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2357 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2358 TheCU, Name, TTy, defaultParameter, V));
2359 } break;
2362 llvm::DIType *TTy = getOrCreateType(T, Unit);
2363 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2365 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2366 TheCU, Name, TTy, defaultParameter, V));
2367 } break;
2369 std::string QualName;
2370 llvm::raw_string_ostream OS(QualName);
2372 OS, getPrintingPolicy());
2373 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2374 TheCU, Name, nullptr, QualName, defaultParameter));
2375 break;
2376 }
2378 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2379 TheCU, Name, nullptr,
2380 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2381 break;
2383 const Expr *E = TA.getAsExpr();
2384 QualType T = E->getType();
2385 if (E->isGLValue())
2387 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2388 assert(V && "Expression in template argument isn't constant");
2389 llvm::DIType *TTy = getOrCreateType(T, Unit);
2390 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2391 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2392 } break;
2393 // And the following should never occur:
2396 llvm_unreachable(
2397 "These argument types shouldn't exist in concrete types");
2398 }
2399 }
2400 return DBuilder.getOrCreateArray(TemplateParams);
2401}
2402
2403std::optional<CGDebugInfo::TemplateArgs>
2404CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2405 if (FD->getTemplatedKind() ==
2408 ->getTemplate()
2410 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2411 }
2412 return std::nullopt;
2413}
2414std::optional<CGDebugInfo::TemplateArgs>
2415CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2416 // Always get the full list of parameters, not just the ones from the
2417 // specialization. A partial specialization may have fewer parameters than
2418 // there are arguments.
2419 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2420 if (!TS)
2421 return std::nullopt;
2422 VarTemplateDecl *T = TS->getSpecializedTemplate();
2423 const TemplateParameterList *TList = T->getTemplateParameters();
2424 auto TA = TS->getTemplateArgs().asArray();
2425 return {{TList, TA}};
2426}
2427std::optional<CGDebugInfo::TemplateArgs>
2428CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2429 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2430 // Always get the full list of parameters, not just the ones from the
2431 // specialization. A partial specialization may have fewer parameters than
2432 // there are arguments.
2433 TemplateParameterList *TPList =
2434 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2435 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2436 return {{TPList, TAList.asArray()}};
2437 }
2438 return std::nullopt;
2439}
2440
2441llvm::DINodeArray
2442CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2443 llvm::DIFile *Unit) {
2444 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2445}
2446
2447llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2448 llvm::DIFile *Unit) {
2449 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2450}
2451
2452llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2453 llvm::DIFile *Unit) {
2454 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2455}
2456
2457llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2458 if (!D->hasAttr<BTFDeclTagAttr>())
2459 return nullptr;
2460
2462 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2463 llvm::Metadata *Ops[2] = {
2464 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2465 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2466 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2467 }
2468 return DBuilder.getOrCreateArray(Annotations);
2469}
2470
2471llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2472 if (VTablePtrType)
2473 return VTablePtrType;
2474
2475 ASTContext &Context = CGM.getContext();
2476
2477 /* Function type */
2478 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2479 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
2480 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2481 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2482 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2483 std::optional<unsigned> DWARFAddressSpace =
2484 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2485
2486 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2487 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2488 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2489 return VTablePtrType;
2490}
2491
2492StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2493 // Copy the gdb compatible name on the side and use its reference.
2494 return internString("_vptr$", RD->getNameAsString());
2495}
2496
2497StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2498 DynamicInitKind StubKind,
2499 llvm::Function *InitFn) {
2500 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2501 // arbitrary.
2502 if (!CGM.getCodeGenOpts().EmitCodeView ||
2504 return InitFn->getName();
2505
2506 // Print the normal qualified name for the variable, then break off the last
2507 // NNS, and add the appropriate other text. Clang always prints the global
2508 // variable name without template arguments, so we can use rsplit("::") and
2509 // then recombine the pieces.
2510 SmallString<128> QualifiedGV;
2511 StringRef Quals;
2512 StringRef GVName;
2513 {
2514 llvm::raw_svector_ostream OS(QualifiedGV);
2515 VD->printQualifiedName(OS, getPrintingPolicy());
2516 std::tie(Quals, GVName) = OS.str().rsplit("::");
2517 if (GVName.empty())
2518 std::swap(Quals, GVName);
2519 }
2520
2521 SmallString<128> InitName;
2522 llvm::raw_svector_ostream OS(InitName);
2523 if (!Quals.empty())
2524 OS << Quals << "::";
2525
2526 switch (StubKind) {
2529 llvm_unreachable("not an initializer");
2531 OS << "`dynamic initializer for '";
2532 break;
2534 OS << "`dynamic atexit destructor for '";
2535 break;
2536 }
2537
2538 OS << GVName;
2539
2540 // Add any template specialization args.
2541 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2542 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
2543 getPrintingPolicy());
2544 }
2545
2546 OS << '\'';
2547
2548 return internString(OS.str());
2549}
2550
2551void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2553 // If this class is not dynamic then there is not any vtable info to collect.
2554 if (!RD->isDynamicClass())
2555 return;
2556
2557 // Don't emit any vtable shape or vptr info if this class doesn't have an
2558 // extendable vfptr. This can happen if the class doesn't have virtual
2559 // methods, or in the MS ABI if those virtual methods only come from virtually
2560 // inherited bases.
2561 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2562 if (!RL.hasExtendableVFPtr())
2563 return;
2564
2565 // CodeView needs to know how large the vtable of every dynamic class is, so
2566 // emit a special named pointer type into the element list. The vptr type
2567 // points to this type as well.
2568 llvm::DIType *VPtrTy = nullptr;
2569 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2571 if (NeedVTableShape) {
2572 uint64_t PtrWidth =
2574 const VTableLayout &VFTLayout =
2576 unsigned VSlotCount =
2577 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2578 unsigned VTableWidth = PtrWidth * VSlotCount;
2579 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2580 std::optional<unsigned> DWARFAddressSpace =
2581 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2582
2583 // Create a very wide void* type and insert it directly in the element list.
2584 llvm::DIType *VTableType = DBuilder.createPointerType(
2585 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2586 EltTys.push_back(VTableType);
2587
2588 // The vptr is a pointer to this special vtable type.
2589 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2590 }
2591
2592 // If there is a primary base then the artificial vptr member lives there.
2593 if (RL.getPrimaryBase())
2594 return;
2595
2596 if (!VPtrTy)
2597 VPtrTy = getOrCreateVTablePtrType(Unit);
2598
2599 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2600 llvm::DIType *VPtrMember =
2601 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2602 llvm::DINode::FlagArtificial, VPtrTy);
2603 EltTys.push_back(VPtrMember);
2604}
2605
2608 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2609 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2610 return T;
2611}
2612
2616}
2617
2620 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2621 assert(!D.isNull() && "null type");
2622 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2623 assert(T && "could not create debug info for type");
2624
2625 RetainedTypes.push_back(D.getAsOpaquePtr());
2626 return T;
2627}
2628
2630 QualType AllocatedTy,
2632 if (CGM.getCodeGenOpts().getDebugInfo() <=
2633 llvm::codegenoptions::DebugLineTablesOnly)
2634 return;
2635 llvm::MDNode *node;
2636 if (AllocatedTy->isVoidType())
2637 node = llvm::MDNode::get(CGM.getLLVMContext(), {});
2638 else
2639 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
2640
2641 CI->setMetadata("heapallocsite", node);
2642}
2643
2645 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2646 return;
2647 QualType Ty = CGM.getContext().getEnumType(ED);
2648 void *TyPtr = Ty.getAsOpaquePtr();
2649 auto I = TypeCache.find(TyPtr);
2650 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2651 return;
2652 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2653 assert(!Res->isForwardDecl());
2654 TypeCache[TyPtr].reset(Res);
2655}
2656
2658 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2659 !CGM.getLangOpts().CPlusPlus)
2661}
2662
2663/// Return true if the class or any of its methods are marked dllimport.
2665 if (RD->hasAttr<DLLImportAttr>())
2666 return true;
2667 for (const CXXMethodDecl *MD : RD->methods())
2668 if (MD->hasAttr<DLLImportAttr>())
2669 return true;
2670 return false;
2671}
2672
2673/// Does a type definition exist in an imported clang module?
2674static bool isDefinedInClangModule(const RecordDecl *RD) {
2675 // Only definitions that where imported from an AST file come from a module.
2676 if (!RD || !RD->isFromASTFile())
2677 return false;
2678 // Anonymous entities cannot be addressed. Treat them as not from module.
2679 if (!RD->isExternallyVisible() && RD->getName().empty())
2680 return false;
2681 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2682 if (!CXXDecl->isCompleteDefinition())
2683 return false;
2684 // Check wether RD is a template.
2685 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2686 if (TemplateKind != TSK_Undeclared) {
2687 // Unfortunately getOwningModule() isn't accurate enough to find the
2688 // owning module of a ClassTemplateSpecializationDecl that is inside a
2689 // namespace spanning multiple modules.
2690 bool Explicit = false;
2691 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2692 Explicit = TD->isExplicitInstantiationOrSpecialization();
2693 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2694 return false;
2695 // This is a template, check the origin of the first member.
2696 if (CXXDecl->field_begin() == CXXDecl->field_end())
2697 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2698 if (!CXXDecl->field_begin()->isFromASTFile())
2699 return false;
2700 }
2701 }
2702 return true;
2703}
2704
2706 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2707 if (CXXRD->isDynamicClass() &&
2708 CGM.getVTableLinkage(CXXRD) ==
2709 llvm::GlobalValue::AvailableExternallyLinkage &&
2711 return;
2712
2713 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2714 return;
2715
2716 completeClass(RD);
2717}
2718
2720 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2721 return;
2722 QualType Ty = CGM.getContext().getRecordType(RD);
2723 void *TyPtr = Ty.getAsOpaquePtr();
2724 auto I = TypeCache.find(TyPtr);
2725 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2726 return;
2727
2728 // We want the canonical definition of the structure to not
2729 // be the typedef. Since that would lead to circular typedef
2730 // metadata.
2731 auto [Res, PrefRes] = CreateTypeDefinition(Ty->castAs<RecordType>());
2732 assert(!Res->isForwardDecl());
2733 TypeCache[TyPtr].reset(Res);
2734}
2735
2738 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2740 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2741 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2742 return true;
2743 return false;
2744}
2745
2746static bool canUseCtorHoming(const CXXRecordDecl *RD) {
2747 // Constructor homing can be used for classes that cannnot be constructed
2748 // without emitting code for one of their constructors. This is classes that
2749 // don't have trivial or constexpr constructors, or can be created from
2750 // aggregate initialization. Also skip lambda objects because they don't call
2751 // constructors.
2752
2753 // Skip this optimization if the class or any of its methods are marked
2754 // dllimport.
2756 return false;
2757
2758 if (RD->isLambda() || RD->isAggregate() ||
2761 return false;
2762
2763 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
2764 if (Ctor->isCopyOrMoveConstructor())
2765 continue;
2766 if (!Ctor->isDeleted())
2767 return true;
2768 }
2769 return false;
2770}
2771
2772static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
2773 bool DebugTypeExtRefs, const RecordDecl *RD,
2774 const LangOptions &LangOpts) {
2775 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2776 return true;
2777
2778 if (auto *ES = RD->getASTContext().getExternalSource())
2779 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2780 return true;
2781
2782 // Only emit forward declarations in line tables only to keep debug info size
2783 // small. This only applies to CodeView, since we don't emit types in DWARF
2784 // line tables only.
2785 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
2786 return true;
2787
2788 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
2789 RD->hasAttr<StandaloneDebugAttr>())
2790 return false;
2791
2792 if (!LangOpts.CPlusPlus)
2793 return false;
2794
2796 return true;
2797
2798 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2799
2800 if (!CXXDecl)
2801 return false;
2802
2803 // Only emit complete debug info for a dynamic class when its vtable is
2804 // emitted. However, Microsoft debuggers don't resolve type information
2805 // across DLL boundaries, so skip this optimization if the class or any of its
2806 // methods are marked dllimport. This isn't a complete solution, since objects
2807 // without any dllimport methods can be used in one DLL and constructed in
2808 // another, but it is the current behavior of LimitedDebugInfo.
2809 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2810 !isClassOrMethodDLLImport(CXXDecl))
2811 return true;
2812
2814 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2815 Spec = SD->getSpecializationKind();
2816
2819 CXXDecl->method_end()))
2820 return true;
2821
2822 // In constructor homing mode, only emit complete debug info for a class
2823 // when its constructor is emitted.
2824 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
2825 canUseCtorHoming(CXXDecl))
2826 return true;
2827
2828 return false;
2829}
2830
2832 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2833 return;
2834
2835 QualType Ty = CGM.getContext().getRecordType(RD);
2836 llvm::DIType *T = getTypeOrNull(Ty);
2837 if (T && T->isForwardDecl())
2839}
2840
2841llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2842 RecordDecl *RD = Ty->getDecl();
2843 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2844 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2845 CGM.getLangOpts())) {
2846 if (!T)
2847 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2848 return T;
2849 }
2850
2851 auto [Def, Pref] = CreateTypeDefinition(Ty);
2852
2853 return Pref ? Pref : Def;
2854}
2855
2856llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
2857 llvm::DIFile *Unit) {
2858 if (!RD)
2859 return nullptr;
2860
2861 auto const *PNA = RD->getAttr<PreferredNameAttr>();
2862 if (!PNA)
2863 return nullptr;
2864
2865 return getOrCreateType(PNA->getTypedefType(), Unit);
2866}
2867
2868std::pair<llvm::DIType *, llvm::DIType *>
2869CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2870 RecordDecl *RD = Ty->getDecl();
2871
2872 // Get overall information about the record type for the debug info.
2873 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2874
2875 // Records and classes and unions can all be recursive. To handle them, we
2876 // first generate a debug descriptor for the struct as a forward declaration.
2877 // Then (if it is a definition) we go through and get debug info for all of
2878 // its members. Finally, we create a descriptor for the complete type (which
2879 // may refer to the forward decl if the struct is recursive) and replace all
2880 // uses of the forward declaration with the final definition.
2881 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
2882
2883 const RecordDecl *D = RD->getDefinition();
2884 if (!D || !D->isCompleteDefinition())
2885 return {FwdDecl, nullptr};
2886
2887 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2888 CollectContainingType(CXXDecl, FwdDecl);
2889
2890 // Push the struct on region stack.
2891 LexicalBlockStack.emplace_back(&*FwdDecl);
2892 RegionMap[Ty->getDecl()].reset(FwdDecl);
2893
2894 // Convert all the elements.
2896 // what about nested types?
2897
2898 // Note: The split of CXXDecl information here is intentional, the
2899 // gdb tests will depend on a certain ordering at printout. The debug
2900 // information offsets are still correct if we merge them all together
2901 // though.
2902 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2903 if (CXXDecl) {
2904 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2905 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
2906 }
2907
2908 // Collect data fields (including static variables and any initializers).
2909 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2910 if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)
2911 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2912
2913 LexicalBlockStack.pop_back();
2914 RegionMap.erase(Ty->getDecl());
2915
2916 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2917 DBuilder.replaceArrays(FwdDecl, Elements);
2918
2919 if (FwdDecl->isTemporary())
2920 FwdDecl =
2921 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2922
2923 RegionMap[Ty->getDecl()].reset(FwdDecl);
2924
2925 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
2926 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
2927 return {FwdDecl, PrefDI};
2928
2929 return {FwdDecl, nullptr};
2930}
2931
2932llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2933 llvm::DIFile *Unit) {
2934 // Ignore protocols.
2935 return getOrCreateType(Ty->getBaseType(), Unit);
2936}
2937
2938llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2939 llvm::DIFile *Unit) {
2940 // Ignore protocols.
2942
2943 // Use Typedefs to represent ObjCTypeParamType.
2944 return DBuilder.createTypedef(
2945 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2946 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2947 getDeclContextDescriptor(Ty->getDecl()));
2948}
2949
2950/// \return true if Getter has the default name for the property PD.
2952 const ObjCMethodDecl *Getter) {
2953 assert(PD);
2954 if (!Getter)
2955 return true;
2956
2957 assert(Getter->getDeclName().isObjCZeroArgSelector());
2958 return PD->getName() ==
2960}
2961
2962/// \return true if Setter has the default name for the property PD.
2964 const ObjCMethodDecl *Setter) {
2965 assert(PD);
2966 if (!Setter)
2967 return true;
2968
2969 assert(Setter->getDeclName().isObjCOneArgSelector());
2972}
2973
2974llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2975 llvm::DIFile *Unit) {
2976 ObjCInterfaceDecl *ID = Ty->getDecl();
2977 if (!ID)
2978 return nullptr;
2979
2980 auto RuntimeLang =
2981 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2982
2983 // Return a forward declaration if this type was imported from a clang module,
2984 // and this is not the compile unit with the implementation of the type (which
2985 // may contain hidden ivars).
2986 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2987 !ID->getImplementation())
2988 return DBuilder.createForwardDecl(
2989 llvm::dwarf::DW_TAG_structure_type, ID->getName(),
2990 getDeclContextDescriptor(ID), Unit, 0, RuntimeLang);
2991
2992 // Get overall information about the record type for the debug info.
2993 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2994 unsigned Line = getLineNumber(ID->getLocation());
2995
2996 // If this is just a forward declaration return a special forward-declaration
2997 // debug type since we won't be able to lay out the entire type.
2998 ObjCInterfaceDecl *Def = ID->getDefinition();
2999 if (!Def || !Def->getImplementation()) {
3000 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3001 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
3002 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
3003 DefUnit, Line, RuntimeLang);
3004 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
3005 return FwdDecl;
3006 }
3007
3008 return CreateTypeDefinition(Ty, Unit);
3009}
3010
3011llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
3012 bool CreateSkeletonCU) {
3013 // Use the Module pointer as the key into the cache. This is a
3014 // nullptr if the "Module" is a PCH, which is safe because we don't
3015 // support chained PCH debug info, so there can only be a single PCH.
3016 const Module *M = Mod.getModuleOrNull();
3017 auto ModRef = ModuleCache.find(M);
3018 if (ModRef != ModuleCache.end())
3019 return cast<llvm::DIModule>(ModRef->second);
3020
3021 // Macro definitions that were defined with "-D" on the command line.
3022 SmallString<128> ConfigMacros;
3023 {
3024 llvm::raw_svector_ostream OS(ConfigMacros);
3025 const auto &PPOpts = CGM.getPreprocessorOpts();
3026 unsigned I = 0;
3027 // Translate the macro definitions back into a command line.
3028 for (auto &M : PPOpts.Macros) {
3029 if (++I > 1)
3030 OS << " ";
3031 const std::string &Macro = M.first;
3032 bool Undef = M.second;
3033 OS << "\"-" << (Undef ? 'U' : 'D');
3034 for (char c : Macro)
3035 switch (c) {
3036 case '\\':
3037 OS << "\\\\";
3038 break;
3039 case '"':
3040 OS << "\\\"";
3041 break;
3042 default:
3043 OS << c;
3044 }
3045 OS << '\"';
3046 }
3047 }
3048
3049 bool IsRootModule = M ? !M->Parent : true;
3050 // When a module name is specified as -fmodule-name, that module gets a
3051 // clang::Module object, but it won't actually be built or imported; it will
3052 // be textual.
3053 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3054 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3055 "clang module without ASTFile must be specified by -fmodule-name");
3056
3057 // Return a StringRef to the remapped Path.
3058 auto RemapPath = [this](StringRef Path) -> std::string {
3059 std::string Remapped = remapDIPath(Path);
3060 StringRef Relative(Remapped);
3061 StringRef CompDir = TheCU->getDirectory();
3062 if (Relative.consume_front(CompDir))
3063 Relative.consume_front(llvm::sys::path::get_separator());
3064
3065 return Relative.str();
3066 };
3067
3068 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3069 // PCH files don't have a signature field in the control block,
3070 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3071 // We use the lower 64 bits for debug info.
3072
3073 uint64_t Signature = 0;
3074 if (const auto &ModSig = Mod.getSignature())
3075 Signature = ModSig.truncatedValue();
3076 else
3077 Signature = ~1ULL;
3078
3079 llvm::DIBuilder DIB(CGM.getModule());
3080 SmallString<0> PCM;
3081 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3083 PCM = getCurrentDirname();
3084 else
3085 PCM = Mod.getPath();
3086 }
3087 llvm::sys::path::append(PCM, Mod.getASTFile());
3088 DIB.createCompileUnit(
3089 TheCU->getSourceLanguage(),
3090 // TODO: Support "Source" from external AST providers?
3091 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3092 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3093 llvm::DICompileUnit::FullDebug, Signature);
3094 DIB.finalize();
3095 }
3096
3097 llvm::DIModule *Parent =
3098 IsRootModule ? nullptr
3099 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3100 CreateSkeletonCU);
3101 std::string IncludePath = Mod.getPath().str();
3102 llvm::DIModule *DIMod =
3103 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3104 RemapPath(IncludePath));
3105 ModuleCache[M].reset(DIMod);
3106 return DIMod;
3107}
3108
3109llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3110 llvm::DIFile *Unit) {
3111 ObjCInterfaceDecl *ID = Ty->getDecl();
3112 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3113 unsigned Line = getLineNumber(ID->getLocation());
3114 unsigned RuntimeLang = TheCU->getSourceLanguage();
3115
3116 // Bit size, align and offset of the type.
3117 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3118 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3119
3120 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3121 if (ID->getImplementation())
3122 Flags |= llvm::DINode::FlagObjcClassComplete;
3123
3124 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3125 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3126 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3127 nullptr, llvm::DINodeArray(), RuntimeLang);
3128
3129 QualType QTy(Ty, 0);
3130 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3131
3132 // Push the struct on region stack.
3133 LexicalBlockStack.emplace_back(RealDecl);
3134 RegionMap[Ty->getDecl()].reset(RealDecl);
3135
3136 // Convert all the elements.
3138
3139 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3140 if (SClass) {
3141 llvm::DIType *SClassTy =
3142 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3143 if (!SClassTy)
3144 return nullptr;
3145
3146 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3147 llvm::DINode::FlagZero);
3148 EltTys.push_back(InhTag);
3149 }
3150
3151 // Create entries for all of the properties.
3152 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3153 SourceLocation Loc = PD->getLocation();
3154 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3155 unsigned PLine = getLineNumber(Loc);
3156 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3157 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3158 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3159 PD->getName(), PUnit, PLine,
3160 hasDefaultGetterName(PD, Getter) ? ""
3161 : getSelectorName(PD->getGetterName()),
3162 hasDefaultSetterName(PD, Setter) ? ""
3163 : getSelectorName(PD->getSetterName()),
3164 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3165 EltTys.push_back(PropertyNode);
3166 };
3167 {
3168 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3169 // empty/tombstone keys in the data type (and bool is too small for that).
3170 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3171 /// List of already emitted properties. Two distinct class and instance
3172 /// properties can share the same identifier (but not two instance
3173 /// properties or two class properties).
3174 llvm::DenseSet<IsClassAndIdent> PropertySet;
3175 /// Returns the IsClassAndIdent key for the given property.
3176 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3177 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3178 };
3179 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3180 for (auto *PD : ClassExt->properties()) {
3181 PropertySet.insert(GetIsClassAndIdent(PD));
3182 AddProperty(PD);
3183 }
3184 for (const auto *PD : ID->properties()) {
3185 // Don't emit duplicate metadata for properties that were already in a
3186 // class extension.
3187 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3188 continue;
3189 AddProperty(PD);
3190 }
3191 }
3192
3194 unsigned FieldNo = 0;
3195 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3196 Field = Field->getNextIvar(), ++FieldNo) {
3197 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3198 if (!FieldTy)
3199 return nullptr;
3200
3201 StringRef FieldName = Field->getName();
3202
3203 // Ignore unnamed fields.
3204 if (FieldName.empty())
3205 continue;
3206
3207 // Get the location for the field.
3208 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3209 unsigned FieldLine = getLineNumber(Field->getLocation());
3210 QualType FType = Field->getType();
3211 uint64_t FieldSize = 0;
3212 uint32_t FieldAlign = 0;
3213
3214 if (!FType->isIncompleteArrayType()) {
3215
3216 // Bit size, align and offset of the type.
3217 FieldSize = Field->isBitField()
3218 ? Field->getBitWidthValue(CGM.getContext())
3219 : CGM.getContext().getTypeSize(FType);
3220 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3221 }
3222
3223 uint64_t FieldOffset;
3224 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3225 // We don't know the runtime offset of an ivar if we're using the
3226 // non-fragile ABI. For bitfields, use the bit offset into the first
3227 // byte of storage of the bitfield. For other fields, use zero.
3228 if (Field->isBitField()) {
3229 FieldOffset =
3230 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3231 FieldOffset %= CGM.getContext().getCharWidth();
3232 } else {
3233 FieldOffset = 0;
3234 }
3235 } else {
3236 FieldOffset = RL.getFieldOffset(FieldNo);
3237 }
3238
3239 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3240 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3241 Flags = llvm::DINode::FlagProtected;
3242 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3243 Flags = llvm::DINode::FlagPrivate;
3244 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3245 Flags = llvm::DINode::FlagPublic;
3246
3247 if (Field->isBitField())
3248 Flags |= llvm::DINode::FlagBitField;
3249
3250 llvm::MDNode *PropertyNode = nullptr;
3251 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3252 if (ObjCPropertyImplDecl *PImpD =
3253 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3254 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3255 SourceLocation Loc = PD->getLocation();
3256 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3257 unsigned PLine = getLineNumber(Loc);
3258 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3259 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3260 PropertyNode = DBuilder.createObjCProperty(
3261 PD->getName(), PUnit, PLine,
3262 hasDefaultGetterName(PD, Getter)
3263 ? ""
3264 : getSelectorName(PD->getGetterName()),
3265 hasDefaultSetterName(PD, Setter)
3266 ? ""
3267 : getSelectorName(PD->getSetterName()),
3268 PD->getPropertyAttributes(),
3269 getOrCreateType(PD->getType(), PUnit));
3270 }
3271 }
3272 }
3273 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3274 FieldSize, FieldAlign, FieldOffset, Flags,
3275 FieldTy, PropertyNode);
3276 EltTys.push_back(FieldTy);
3277 }
3278
3279 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3280 DBuilder.replaceArrays(RealDecl, Elements);
3281
3282 LexicalBlockStack.pop_back();
3283 return RealDecl;
3284}
3285
3286llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3287 llvm::DIFile *Unit) {
3288 if (Ty->isExtVectorBoolType()) {
3289 // Boolean ext_vector_type(N) are special because their real element type
3290 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3291 // For now, we pretend the boolean vector were actually a vector of bytes
3292 // (where each byte represents 8 bits of the actual vector).
3293 // FIXME Debug info should actually represent this proper as a vector mask
3294 // type.
3295 auto &Ctx = CGM.getContext();
3296 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3297 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3298
3299 // Construct the vector of 'char' type.
3300 QualType CharVecTy =
3301 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3302 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3303 }
3304
3305 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3306 int64_t Count = Ty->getNumElements();
3307
3308 llvm::Metadata *Subscript;
3309 QualType QTy(Ty, 0);
3310 auto SizeExpr = SizeExprCache.find(QTy);
3311 if (SizeExpr != SizeExprCache.end())
3312 Subscript = DBuilder.getOrCreateSubrange(
3313 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3314 nullptr /*upperBound*/, nullptr /*stride*/);
3315 else {
3316 auto *CountNode =
3317 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3318 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3319 Subscript = DBuilder.getOrCreateSubrange(
3320 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3321 nullptr /*stride*/);
3322 }
3323 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3324
3325 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3326 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3327
3328 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3329}
3330
3331llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3332 llvm::DIFile *Unit) {
3333 // FIXME: Create another debug type for matrices
3334 // For the time being, it treats it like a nested ArrayType.
3335
3336 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3337 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3338 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3339
3340 // Create ranges for both dimensions.
3342 auto *ColumnCountNode =
3343 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3344 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3345 auto *RowCountNode =
3346 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3347 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3348 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3349 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3350 nullptr /*stride*/));
3351 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3352 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3353 nullptr /*stride*/));
3354 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3355 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3356}
3357
3358llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3359 uint64_t Size;
3360 uint32_t Align;
3361
3362 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3363 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3364 Size = 0;
3366 CGM.getContext());
3367 } else if (Ty->isIncompleteArrayType()) {
3368 Size = 0;
3369 if (Ty->getElementType()->isIncompleteType())
3370 Align = 0;
3371 else
3372 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3373 } else if (Ty->isIncompleteType()) {
3374 Size = 0;
3375 Align = 0;
3376 } else {
3377 // Size and align of the whole array, not the element type.
3378 Size = CGM.getContext().getTypeSize(Ty);
3379 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3380 }
3381
3382 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3383 // interior arrays, do we care? Why aren't nested arrays represented the
3384 // obvious/recursive way?
3386 QualType EltTy(Ty, 0);
3387 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3388 // If the number of elements is known, then count is that number. Otherwise,
3389 // it's -1. This allows us to represent a subrange with an array of 0
3390 // elements, like this:
3391 //
3392 // struct foo {
3393 // int x[0];
3394 // };
3395 int64_t Count = -1; // Count == -1 is an unbounded array.
3396 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3397 Count = CAT->getZExtSize();
3398 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3399 if (Expr *Size = VAT->getSizeExpr()) {
3401 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3402 Count = Result.Val.getInt().getExtValue();
3403 }
3404 }
3405
3406 auto SizeNode = SizeExprCache.find(EltTy);
3407 if (SizeNode != SizeExprCache.end())
3408 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3409 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3410 nullptr /*upperBound*/, nullptr /*stride*/));
3411 else {
3412 auto *CountNode =
3413 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3414 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3415 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3416 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3417 nullptr /*stride*/));
3418 }
3419 EltTy = Ty->getElementType();
3420 }
3421
3422 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3423
3424 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3425 SubscriptArray);
3426}
3427
3428llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3429 llvm::DIFile *Unit) {
3430 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3431 Ty->getPointeeType(), Unit);
3432}
3433
3434llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3435 llvm::DIFile *Unit) {
3436 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3437 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3438 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3439 CGM.getCodeGenOpts().DwarfVersion < 4)
3440 Tag = llvm::dwarf::DW_TAG_reference_type;
3441
3442 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3443}
3444
3445llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3446 llvm::DIFile *U) {
3447 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3448 uint64_t Size = 0;
3449
3450 if (!Ty->isIncompleteType()) {
3451 Size = CGM.getContext().getTypeSize(Ty);
3452
3453 // Set the MS inheritance model. There is no flag for the unspecified model.
3454 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3457 Flags |= llvm::DINode::FlagSingleInheritance;
3458 break;
3460 Flags |= llvm::DINode::FlagMultipleInheritance;
3461 break;
3463 Flags |= llvm::DINode::FlagVirtualInheritance;
3464 break;
3466 break;
3467 }
3468 }
3469 }
3470
3471 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
3472 if (Ty->isMemberDataPointerType())
3473 return DBuilder.createMemberPointerType(
3474 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3475 Flags);
3476
3477 const FunctionProtoType *FPT =
3479 return DBuilder.createMemberPointerType(
3480 getOrCreateInstanceMethodType(
3482 FPT, U),
3483 ClassType, Size, /*Align=*/0, Flags);
3484}
3485
3486llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3487 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3488 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3489}
3490
3491llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3492 return getOrCreateType(Ty->getElementType(), U);
3493}
3494
3495llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
3496 const EnumDecl *ED = Ty->getDecl();
3497
3498 uint64_t Size = 0;
3499 uint32_t Align = 0;
3500 if (!ED->getTypeForDecl()->isIncompleteType()) {
3502 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3503 }
3504
3506
3507 bool isImportedFromModule =
3508 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
3509
3510 // If this is just a forward declaration, construct an appropriately
3511 // marked node and just return it.
3512 if (isImportedFromModule || !ED->getDefinition()) {
3513 // Note that it is possible for enums to be created as part of
3514 // their own declcontext. In this case a FwdDecl will be created
3515 // twice. This doesn't cause a problem because both FwdDecls are
3516 // entered into the ReplaceMap: finalize() will replace the first
3517 // FwdDecl with the second and then replace the second with
3518 // complete type.
3519 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
3520 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3521 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
3522 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
3523
3524 unsigned Line = getLineNumber(ED->getLocation());
3525 StringRef EDName = ED->getName();
3526 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
3527 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
3528 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
3529
3530 ReplaceMap.emplace_back(
3531 std::piecewise_construct, std::make_tuple(Ty),
3532 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
3533 return RetTy;
3534 }
3535
3536 return CreateTypeDefinition(Ty);
3537}
3538
3539llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
3540 const EnumDecl *ED = Ty->getDecl();
3541 uint64_t Size = 0;
3542 uint32_t Align = 0;
3543 if (!ED->getTypeForDecl()->isIncompleteType()) {
3545 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3546 }
3547
3549
3551 ED = ED->getDefinition();
3552 assert(ED && "An enumeration definition is required");
3553 for (const auto *Enum : ED->enumerators()) {
3554 Enumerators.push_back(
3555 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
3556 }
3557
3558 // Return a CompositeType for the enum itself.
3559 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
3560
3561 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
3562 unsigned Line = getLineNumber(ED->getLocation());
3563 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
3564 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
3565 return DBuilder.createEnumerationType(
3566 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
3567 /*RunTimeLang=*/0, Identifier, ED->isScoped());
3568}
3569
3570llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
3571 unsigned MType, SourceLocation LineLoc,
3572 StringRef Name, StringRef Value) {
3573 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3574 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
3575}
3576
3577llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
3578 SourceLocation LineLoc,
3579 SourceLocation FileLoc) {
3580 llvm::DIFile *FName = getOrCreateFile(FileLoc);
3581 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
3582 return DBuilder.createTempMacroFile(Parent, Line, FName);
3583}
3584
3586 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
3587 // Create a debug location from `TrapLocation` that adds an artificial inline
3588 // frame.
3590
3591 FuncName += "$";
3592 FuncName += Category;
3593 FuncName += "$";
3594 FuncName += FailureMsg;
3595
3596 llvm::DISubprogram *TrapSP =
3597 createInlinedTrapSubprogram(FuncName, TrapLocation->getFile());
3598 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
3599 /*Scope=*/TrapSP, /*InlinedAt=*/TrapLocation);
3600}
3601
3603 Qualifiers Quals;
3604 do {
3605 Qualifiers InnerQuals = T.getLocalQualifiers();
3606 // Qualifiers::operator+() doesn't like it if you add a Qualifier
3607 // that is already there.
3608 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
3609 Quals += InnerQuals;
3610 QualType LastT = T;
3611 switch (T->getTypeClass()) {
3612 default:
3613 return C.getQualifiedType(T.getTypePtr(), Quals);
3614 case Type::TemplateSpecialization: {
3615 const auto *Spec = cast<TemplateSpecializationType>(T);
3616 if (Spec->isTypeAlias())
3617 return C.getQualifiedType(T.getTypePtr(), Quals);
3618 T = Spec->desugar();
3619 break;
3620 }
3621 case Type::TypeOfExpr:
3622 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
3623 break;
3624 case Type::TypeOf:
3625 T = cast<TypeOfType>(T)->getUnmodifiedType();
3626 break;
3627 case Type::Decltype:
3628 T = cast<DecltypeType>(T)->getUnderlyingType();
3629 break;
3630 case Type::UnaryTransform:
3631 T = cast<UnaryTransformType>(T)->getUnderlyingType();
3632 break;
3633 case Type::Attributed:
3634 T = cast<AttributedType>(T)->getEquivalentType();
3635 break;
3636 case Type::BTFTagAttributed:
3637 T = cast<BTFTagAttributedType>(T)->getWrappedType();
3638 break;
3639 case Type::CountAttributed:
3640 T = cast<CountAttributedType>(T)->desugar();
3641 break;
3642 case Type::Elaborated:
3643 T = cast<ElaboratedType>(T)->getNamedType();
3644 break;
3645 case Type::Using:
3646 T = cast<UsingType>(T)->getUnderlyingType();
3647 break;
3648 case Type::Paren:
3649 T = cast<ParenType>(T)->getInnerType();
3650 break;
3651 case Type::MacroQualified:
3652 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
3653 break;
3654 case Type::SubstTemplateTypeParm:
3655 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
3656 break;
3657 case Type::Auto:
3658 case Type::DeducedTemplateSpecialization: {
3659 QualType DT = cast<DeducedType>(T)->getDeducedType();
3660 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
3661 T = DT;
3662 break;
3663 }
3664 case Type::PackIndexing: {
3665 T = cast<PackIndexingType>(T)->getSelectedType();
3666 break;
3667 }
3668 case Type::Adjusted:
3669 case Type::Decayed:
3670 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
3671 T = cast<AdjustedType>(T)->getAdjustedType();
3672 break;
3673 }
3674
3675 assert(T != LastT && "Type unwrapping failed to unwrap!");
3676 (void)LastT;
3677 } while (true);
3678}
3679
3680llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
3681 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
3682 auto It = TypeCache.find(Ty.getAsOpaquePtr());
3683 if (It != TypeCache.end()) {
3684 // Verify that the debug info still exists.
3685 if (llvm::Metadata *V = It->second)
3686 return cast<llvm::DIType>(V);
3687 }
3688
3689 return nullptr;
3690}
3691
3695}
3696
3698 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
3699 D.isDynamicClass())
3700 return;
3701
3703 // In case this type has no member function definitions being emitted, ensure
3704 // it is retained
3705 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
3706}
3707
3708llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
3709 if (Ty.isNull())
3710 return nullptr;
3711
3712 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
3713 std::string Name;
3714 llvm::raw_string_ostream OS(Name);
3715 Ty.print(OS, getPrintingPolicy());
3716 return Name;
3717 });
3718
3719 // Unwrap the type as needed for debug information.
3720 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
3721
3722 if (auto *T = getTypeOrNull(Ty))
3723 return T;
3724
3725 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
3726 void *TyPtr = Ty.getAsOpaquePtr();
3727
3728 // And update the type cache.
3729 TypeCache[TyPtr].reset(Res);
3730
3731 return Res;
3732}
3733
3734llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3735 // A forward declaration inside a module header does not belong to the module.
3736 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3737 return nullptr;
3738 if (DebugTypeExtRefs && D->isFromASTFile()) {
3739 // Record a reference to an imported clang module or precompiled header.
3740 auto *Reader = CGM.getContext().getExternalSource();
3741 auto Idx = D->getOwningModuleID();
3742 auto Info = Reader->getSourceDescriptor(Idx);
3743 if (Info)
3744 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3745 } else if (ClangModuleMap) {
3746 // We are building a clang module or a precompiled header.
3747 //
3748 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3749 // and it wouldn't be necessary to specify the parent scope
3750 // because the type is already unique by definition (it would look
3751 // like the output of -fno-standalone-debug). On the other hand,
3752 // the parent scope helps a consumer to quickly locate the object
3753 // file where the type's definition is located, so it might be
3754 // best to make this behavior a command line or debugger tuning
3755 // option.
3756 if (Module *M = D->getOwningModule()) {
3757 // This is a (sub-)module.
3758 auto Info = ASTSourceDescriptor(*M);
3759 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3760 } else {
3761 // This the precompiled header being built.
3762 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3763 }
3764 }
3765
3766 return nullptr;
3767}
3768
3769llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3770 // Handle qualifiers, which recursively handles what they refer to.
3771 if (Ty.hasLocalQualifiers())
3772 return CreateQualifiedType(Ty, Unit);
3773
3774 // Work out details of type.
3775 switch (Ty->getTypeClass()) {
3776#define TYPE(Class, Base)
3777#define ABSTRACT_TYPE(Class, Base)
3778#define NON_CANONICAL_TYPE(Class, Base)
3779#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3780#include "clang/AST/TypeNodes.inc"
3781 llvm_unreachable("Dependent types cannot show up in debug information");
3782
3783 case Type::ExtVector:
3784 case Type::Vector:
3785 return CreateType(cast<VectorType>(Ty), Unit);
3786 case Type::ConstantMatrix:
3787 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
3788 case Type::ObjCObjectPointer:
3789 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3790 case Type::ObjCObject:
3791 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3792 case Type::ObjCTypeParam:
3793 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3794 case Type::ObjCInterface:
3795 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3796 case Type::Builtin:
3797 return CreateType(cast<BuiltinType>(Ty));
3798 case Type::Complex:
3799 return CreateType(cast<ComplexType>(Ty));
3800 case Type::Pointer:
3801 return CreateType(cast<PointerType>(Ty), Unit);
3802 case Type::BlockPointer:
3803 return CreateType(cast<BlockPointerType>(Ty), Unit);
3804 case Type::Typedef:
3805 return CreateType(cast<TypedefType>(Ty), Unit);
3806 case Type::Record:
3807 return CreateType(cast<RecordType>(Ty));
3808 case Type::Enum:
3809 return CreateEnumType(cast<EnumType>(Ty));
3810 case Type::FunctionProto:
3811 case Type::FunctionNoProto:
3812 return CreateType(cast<FunctionType>(Ty), Unit);
3813 case Type::ConstantArray:
3814 case Type::VariableArray:
3815 case Type::IncompleteArray:
3816 case Type::ArrayParameter:
3817 return CreateType(cast<ArrayType>(Ty), Unit);
3818
3819 case Type::LValueReference:
3820 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3821 case Type::RValueReference:
3822 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3823
3824 case Type::MemberPointer:
3825 return CreateType(cast<MemberPointerType>(Ty), Unit);
3826
3827 case Type::Atomic:
3828 return CreateType(cast<AtomicType>(Ty), Unit);
3829
3830 case Type::BitInt:
3831 return CreateType(cast<BitIntType>(Ty));
3832 case Type::Pipe:
3833 return CreateType(cast<PipeType>(Ty), Unit);
3834
3835 case Type::TemplateSpecialization:
3836 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3837
3838 case Type::CountAttributed:
3839 case Type::Auto:
3840 case Type::Attributed:
3841 case Type::BTFTagAttributed:
3842 case Type::HLSLAttributedResource:
3843 case Type::Adjusted:
3844 case Type::Decayed:
3845 case Type::DeducedTemplateSpecialization:
3846 case Type::Elaborated:
3847 case Type::Using:
3848 case Type::Paren:
3849 case Type::MacroQualified:
3850 case Type::SubstTemplateTypeParm:
3851 case Type::TypeOfExpr:
3852 case Type::TypeOf:
3853 case Type::Decltype:
3854 case Type::PackIndexing:
3855 case Type::UnaryTransform:
3856 break;
3857 }
3858
3859 llvm_unreachable("type should have been unwrapped!");
3860}
3861
3862llvm::DICompositeType *
3863CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
3864 QualType QTy(Ty, 0);
3865
3866 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3867
3868 // We may have cached a forward decl when we could have created
3869 // a non-forward decl. Go ahead and create a non-forward decl
3870 // now.
3871 if (T && !T->isForwardDecl())
3872 return T;
3873
3874 // Otherwise create the type.
3875 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3876
3877 // Propagate members from the declaration to the definition
3878 // CreateType(const RecordType*) will overwrite this with the members in the
3879 // correct order if the full type is needed.
3880 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3881
3882 // And update the type cache.
3883 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3884 return Res;
3885}
3886
3887// TODO: Currently used for context chains when limiting debug info.
3888llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3889 RecordDecl *RD = Ty->getDecl();
3890
3891 // Get overall information about the record type for the debug info.
3892 StringRef RDName = getClassName(RD);
3893 const SourceLocation Loc = RD->getLocation();
3894 llvm::DIFile *DefUnit = nullptr;
3895 unsigned Line = 0;
3896 if (Loc.isValid()) {
3897 DefUnit = getOrCreateFile(Loc);
3898 Line = getLineNumber(Loc);
3899 }
3900
3901 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3902
3903 // If we ended up creating the type during the context chain construction,
3904 // just return that.
3905 auto *T = cast_or_null<llvm::DICompositeType>(
3906 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3907 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3908 return T;
3909
3910 // If this is just a forward or incomplete declaration, construct an
3911 // appropriately marked node and just return it.
3912 const RecordDecl *D = RD->getDefinition();
3913 if (!D || !D->isCompleteDefinition())
3914 return getOrCreateRecordFwdDecl(Ty, RDContext);
3915
3916 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3917 // __attribute__((aligned)) can increase or decrease alignment *except* on a
3918 // struct or struct member, where it only increases alignment unless 'packed'
3919 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
3920 // to be used.
3921 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3922
3924
3925 // Explicitly record the calling convention and export symbols for C++
3926 // records.
3927 auto Flags = llvm::DINode::FlagZero;
3928 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3930 Flags |= llvm::DINode::FlagTypePassByReference;
3931 else
3932 Flags |= llvm::DINode::FlagTypePassByValue;
3933
3934 // Record if a C++ record is non-trivial type.
3935 if (!CXXRD->isTrivial())
3936 Flags |= llvm::DINode::FlagNonTrivial;
3937
3938 // Record exports it symbols to the containing structure.
3939 if (CXXRD->isAnonymousStructOrUnion())
3940 Flags |= llvm::DINode::FlagExportSymbols;
3941
3942 Flags |= getAccessFlag(CXXRD->getAccess(),
3943 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
3944 }
3945
3946 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
3947 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3948 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3949 Flags, Identifier, Annotations);
3950
3951 // Elements of composite types usually have back to the type, creating
3952 // uniquing cycles. Distinct nodes are more efficient.
3953 switch (RealDecl->getTag()) {
3954 default:
3955 llvm_unreachable("invalid composite type tag");
3956
3957 case llvm::dwarf::DW_TAG_array_type:
3958 case llvm::dwarf::DW_TAG_enumeration_type:
3959 // Array elements and most enumeration elements don't have back references,
3960 // so they don't tend to be involved in uniquing cycles and there is some
3961 // chance of merging them when linking together two modules. Only make
3962 // them distinct if they are ODR-uniqued.
3963 if (Identifier.empty())
3964 break;
3965 [[fallthrough]];
3966
3967 case llvm::dwarf::DW_TAG_structure_type:
3968 case llvm::dwarf::DW_TAG_union_type:
3969 case llvm::dwarf::DW_TAG_class_type:
3970 // Immediately resolve to a distinct node.
3971 RealDecl =
3972 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3973 break;
3974 }
3975
3976 RegionMap[Ty->getDecl()].reset(RealDecl);
3977 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3978
3979 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3980 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3981 CollectCXXTemplateParams(TSpecial, DefUnit));
3982 return RealDecl;
3983}
3984
3985void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3986 llvm::DICompositeType *RealDecl) {
3987 // A class's primary base or the class itself contains the vtable.
3988 llvm::DIType *ContainingType = nullptr;
3989 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3990 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3991 // Seek non-virtual primary base root.
3992 while (true) {
3993 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3994 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3995 if (PBT && !BRL.isPrimaryBaseVirtual())
3996 PBase = PBT;
3997 else
3998 break;
3999 }
4000 ContainingType = getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
4001 getOrCreateFile(RD->getLocation()));
4002 } else if (RD->isDynamicClass())
4003 ContainingType = RealDecl;
4004
4005 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4006}
4007
4008llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4009 StringRef Name, uint64_t *Offset) {
4010 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4011 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4012 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4013 llvm::DIType *Ty =
4014 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4015 *Offset, llvm::DINode::FlagZero, FieldTy);
4016 *Offset += FieldSize;
4017 return Ty;
4018}
4019
4020void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4021 StringRef &Name,
4022 StringRef &LinkageName,
4023 llvm::DIScope *&FDContext,
4024 llvm::DINodeArray &TParamsArray,
4025 llvm::DINode::DIFlags &Flags) {
4026 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4027 Name = getFunctionName(FD);
4028 // Use mangled name as linkage name for C/C++ functions.
4029 if (FD->getType()->getAs<FunctionProtoType>())
4030 LinkageName = CGM.getMangledName(GD);
4031 if (FD->hasPrototype())
4032 Flags |= llvm::DINode::FlagPrototyped;
4033 // No need to replicate the linkage name if it isn't different from the
4034 // subprogram name, no need to have it at all unless coverage is enabled or
4035 // debug is set to more than just line tables or extra debug info is needed.
4036 if (LinkageName == Name ||
4037 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4038 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4039 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4040 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4041 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4042 LinkageName = StringRef();
4043
4044 // Emit the function scope in line tables only mode (if CodeView) to
4045 // differentiate between function names.
4046 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4047 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4048 CGM.getCodeGenOpts().EmitCodeView)) {
4049 if (const NamespaceDecl *NSDecl =
4050 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4051 FDContext = getOrCreateNamespace(NSDecl);
4052 else if (const RecordDecl *RDecl =
4053 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4054 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4055 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4056 }
4057 }
4058 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4059 // Check if it is a noreturn-marked function
4060 if (FD->isNoReturn())
4061 Flags |= llvm::DINode::FlagNoReturn;
4062 // Collect template parameters.
4063 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4064 }
4065}
4066
4067void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4068 unsigned &LineNo, QualType &T,
4069 StringRef &Name, StringRef &LinkageName,
4070 llvm::MDTuple *&TemplateParameters,
4071 llvm::DIScope *&VDContext) {
4072 Unit = getOrCreateFile(VD->getLocation());
4073 LineNo = getLineNumber(VD->getLocation());
4074
4075 setLocation(VD->getLocation());
4076
4077 T = VD->getType();
4078 if (T->isIncompleteArrayType()) {
4079 // CodeGen turns int[] into int[1] so we'll do the same here.
4080 llvm::APInt ConstVal(32, 1);
4082
4083 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4085 }
4086
4087 Name = VD->getName();
4088 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4089 !isa<ObjCMethodDecl>(VD->getDeclContext()))
4090 LinkageName = CGM.getMangledName(VD);
4091 if (LinkageName == Name)
4092 LinkageName = StringRef();
4093
4094 if (isa<VarTemplateSpecializationDecl>(VD)) {
4095 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4096 TemplateParameters = parameterNodes.get();
4097 } else {
4098 TemplateParameters = nullptr;
4099 }
4100
4101 // Since we emit declarations (DW_AT_members) for static members, place the
4102 // definition of those static members in the namespace they were declared in
4103 // in the source code (the lexical decl context).
4104 // FIXME: Generalize this for even non-member global variables where the
4105 // declaration and definition may have different lexical decl contexts, once
4106 // we have support for emitting declarations of (non-member) global variables.
4107 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4108 : VD->getDeclContext();
4109 // When a record type contains an in-line initialization of a static data
4110 // member, and the record type is marked as __declspec(dllexport), an implicit
4111 // definition of the member will be created in the record context. DWARF
4112 // doesn't seem to have a nice way to describe this in a form that consumers
4113 // are likely to understand, so fake the "normal" situation of a definition
4114 // outside the class by putting it in the global scope.
4115 if (DC->isRecord())
4117
4118 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4119 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4120}
4121
4122llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4123 bool Stub) {
4124 llvm::DINodeArray TParamsArray;
4125 StringRef Name, LinkageName;
4126 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4127 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4129 llvm::DIFile *Unit = getOrCreateFile(Loc);
4130 llvm::DIScope *DContext = Unit;
4131 unsigned Line = getLineNumber(Loc);
4132 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4133 Flags);
4134 auto *FD = cast<FunctionDecl>(GD.getDecl());
4135
4136 // Build function type.
4138 for (const ParmVarDecl *Parm : FD->parameters())
4139 ArgTypes.push_back(Parm->getType());
4140
4141 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4142 QualType FnType = CGM.getContext().getFunctionType(
4143 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4144 if (!FD->isExternallyVisible())
4145 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4146 if (CGM.getLangOpts().Optimize)
4147 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4148
4149 if (Stub) {
4150 Flags |= getCallSiteRelatedAttrs();
4151 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4152 return DBuilder.createFunction(
4153 DContext, Name, LinkageName, Unit, Line,
4154 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4155 TParamsArray.get(), getFunctionDeclaration(FD));
4156 }
4157
4158 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4159 DContext, Name, LinkageName, Unit, Line,
4160 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4161 TParamsArray.get(), getFunctionDeclaration(FD));
4162 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4163 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4164 std::make_tuple(CanonDecl),
4165 std::make_tuple(SP));
4166 return SP;
4167}
4168
4169llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4170 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4171}
4172
4173llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4174 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4175}
4176
4177llvm::DIGlobalVariable *
4178CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4179 QualType T;
4180 StringRef Name, LinkageName;
4182 llvm::DIFile *Unit = getOrCreateFile(Loc);
4183 llvm::DIScope *DContext = Unit;
4184 unsigned Line = getLineNumber(Loc);
4185 llvm::MDTuple *TemplateParameters = nullptr;
4186
4187 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4188 DContext);
4189 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4190 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4191 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4192 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4193 FwdDeclReplaceMap.emplace_back(
4194 std::piecewise_construct,
4195 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4196 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4197 return GV;
4198}
4199
4200llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4201 // We only need a declaration (not a definition) of the type - so use whatever
4202 // we would otherwise do to get a type for a pointee. (forward declarations in
4203 // limited debug info, full definitions (if the type definition is available)
4204 // in unlimited debug info)
4205 if (const auto *TD = dyn_cast<TypeDecl>(D))
4206 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
4207 getOrCreateFile(TD->getLocation()));
4208 auto I = DeclCache.find(D->getCanonicalDecl());
4209
4210 if (I != DeclCache.end()) {
4211 auto N = I->second;
4212 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4213 return GVE->getVariable();
4214 return cast<llvm::DINode>(N);
4215 }
4216
4217 // Search imported declaration cache if it is already defined
4218 // as imported declaration.
4219 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4220
4221 if (IE != ImportedDeclCache.end()) {
4222 auto N = IE->second;
4223 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4224 return cast<llvm::DINode>(GVE);
4225 return dyn_cast_or_null<llvm::DINode>(N);
4226 }
4227
4228 // No definition for now. Emit a forward definition that might be
4229 // merged with a potential upcoming definition.
4230 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4231 return getFunctionForwardDeclaration(FD);
4232 else if (const auto *VD = dyn_cast<VarDecl>(D))
4233 return getGlobalVariableForwardDeclaration(VD);
4234
4235 return nullptr;
4236}
4237
4238llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4239 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4240 return nullptr;
4241
4242 const auto *FD = dyn_cast<FunctionDecl>(D);
4243 if (!FD)
4244 return nullptr;
4245
4246 // Setup context.
4247 auto *S = getDeclContextDescriptor(D);
4248
4249 auto MI = SPCache.find(FD->getCanonicalDecl());
4250 if (MI == SPCache.end()) {
4251 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4252 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4253 cast<llvm::DICompositeType>(S));
4254 }
4255 }
4256 if (MI != SPCache.end()) {
4257 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4258 if (SP && !SP->isDefinition())
4259 return SP;
4260 }
4261
4262 for (auto *NextFD : FD->redecls()) {
4263 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4264 if (MI != SPCache.end()) {
4265 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4266 if (SP && !SP->isDefinition())
4267 return SP;
4268 }
4269 }
4270 return nullptr;
4271}
4272
4273llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4274 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4275 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4276 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4277 return nullptr;
4278
4279 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4280 if (!OMD)
4281 return nullptr;
4282
4283 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4284 return nullptr;
4285
4286 if (OMD->isDirectMethod())
4287 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4288
4289 // Starting with DWARF V5 method declarations are emitted as children of
4290 // the interface type.
4291 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4292 if (!ID)
4293 ID = OMD->getClassInterface();
4294 if (!ID)
4295 return nullptr;
4296 QualType QTy(ID->getTypeForDecl(), 0);
4297 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4298 if (It == TypeCache.end())
4299 return nullptr;
4300 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4301 llvm::DISubprogram *FD = DBuilder.createFunction(
4302 InterfaceType, getObjCMethodName(OMD), StringRef(),
4303 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4304 DBuilder.finalizeSubprogram(FD);
4305 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4306 return FD;
4307}
4308
4309// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4310// implicit parameter "this".
4311llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4312 QualType FnType,
4313 llvm::DIFile *F) {
4314 // In CodeView, we emit the function types in line tables only because the
4315 // only way to distinguish between functions is by display name and type.
4316 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4317 !CGM.getCodeGenOpts().EmitCodeView))
4318 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4319 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4320 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4321
4322 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4323 return getOrCreateMethodType(Method, F);
4324
4325 const auto *FTy = FnType->getAs<FunctionType>();
4326 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4327
4328 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4329 // Add "self" and "_cmd"
4331
4332 // First element is always return type. For 'void' functions it is NULL.
4333 QualType ResultTy = OMethod->getReturnType();
4334
4335 // Replace the instancetype keyword with the actual type.
4336 if (ResultTy == CGM.getContext().getObjCInstanceType())
4337 ResultTy = CGM.getContext().getPointerType(
4338 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4339
4340 Elts.push_back(getOrCreateType(ResultTy, F));
4341 // "self" pointer is always first argument.
4342 QualType SelfDeclTy;
4343 if (auto *SelfDecl = OMethod->getSelfDecl())
4344 SelfDeclTy = SelfDecl->getType();
4345 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4346 if (FPT->getNumParams() > 1)
4347 SelfDeclTy = FPT->getParamType(0);
4348 if (!SelfDeclTy.isNull())
4349 Elts.push_back(
4350 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4351 // "_cmd" pointer is always second argument.
4352 Elts.push_back(DBuilder.createArtificialType(
4353 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4354 // Get rest of the arguments.
4355 for (const auto *PI : OMethod->parameters())
4356 Elts.push_back(getOrCreateType(PI->getType(), F));
4357 // Variadic methods need a special marker at the end of the type list.
4358 if (OMethod->isVariadic())
4359 Elts.push_back(DBuilder.createUnspecifiedParameter());
4360
4361 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4362 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4363 getDwarfCC(CC));
4364 }
4365
4366 // Handle variadic function types; they need an additional
4367 // unspecified parameter.
4368 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4369 if (FD->isVariadic()) {
4371 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4372 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4373 for (QualType ParamType : FPT->param_types())
4374 EltTys.push_back(getOrCreateType(ParamType, F));
4375 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4376 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4377 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4378 getDwarfCC(CC));
4379 }
4380
4381 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4382}
4383
4388 if (FD)
4389 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4390 CC = SrcFnTy->getCallConv();
4392 for (const VarDecl *VD : Args)
4393 ArgTypes.push_back(VD->getType());
4394 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4396}
4397
4399 SourceLocation ScopeLoc, QualType FnType,
4400 llvm::Function *Fn, bool CurFuncIsThunk) {
4401 StringRef Name;
4402 StringRef LinkageName;
4403
4404 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4405
4406 const Decl *D = GD.getDecl();
4407 bool HasDecl = (D != nullptr);
4408
4409 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4410 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4411 llvm::DIFile *Unit = getOrCreateFile(Loc);
4412 llvm::DIScope *FDContext = Unit;
4413 llvm::DINodeArray TParamsArray;
4414 if (!HasDecl) {
4415 // Use llvm function name.
4416 LinkageName = Fn->getName();
4417 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4418 // If there is a subprogram for this function available then use it.
4419 auto FI = SPCache.find(FD->getCanonicalDecl());
4420 if (FI != SPCache.end()) {
4421 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4422 if (SP && SP->isDefinition()) {
4423 LexicalBlockStack.emplace_back(SP);
4424 RegionMap[D].reset(SP);
4425 return;
4426 }
4427 }
4428 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4429 TParamsArray, Flags);
4430 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4431 Name = getObjCMethodName(OMD);
4432 Flags |= llvm::DINode::FlagPrototyped;
4433 } else if (isa<VarDecl>(D) &&
4435 // This is a global initializer or atexit destructor for a global variable.
4436 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4437 Fn);
4438 } else {
4439 Name = Fn->getName();
4440
4441 if (isa<BlockDecl>(D))
4442 LinkageName = Name;
4443
4444 Flags |= llvm::DINode::FlagPrototyped;
4445 }
4446 if (Name.starts_with("\01"))
4447 Name = Name.substr(1);
4448
4449 assert((!D || !isa<VarDecl>(D) ||
4451 "Unexpected DynamicInitKind !");
4452
4453 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4454 isa<VarDecl>(D) || isa<CapturedDecl>(D)) {
4455 Flags |= llvm::DINode::FlagArtificial;
4456 // Artificial functions should not silently reuse CurLoc.
4457 CurLoc = SourceLocation();
4458 }
4459
4460 if (CurFuncIsThunk)
4461 Flags |= llvm::DINode::FlagThunk;
4462
4463 if (Fn->hasLocalLinkage())
4464 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4465 if (CGM.getLangOpts().Optimize)
4466 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4467
4468 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
4469 llvm::DISubprogram::DISPFlags SPFlagsForDef =
4470 SPFlags | llvm::DISubprogram::SPFlagDefinition;
4471
4472 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
4473 unsigned ScopeLine = getLineNumber(ScopeLoc);
4474 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
4475 llvm::DISubprogram *Decl = nullptr;
4476 llvm::DINodeArray Annotations = nullptr;
4477 if (D) {
4478 Decl = isa<ObjCMethodDecl>(D)
4479 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
4480 : getFunctionDeclaration(D);
4481 Annotations = CollectBTFDeclTagAnnotations(D);
4482 }
4483
4484 // FIXME: The function declaration we're constructing here is mostly reusing
4485 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
4486 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
4487 // all subprograms instead of the actual context since subprogram definitions
4488 // are emitted as CU level entities by the backend.
4489 llvm::DISubprogram *SP = DBuilder.createFunction(
4490 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
4491 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
4492 Annotations);
4493 Fn->setSubprogram(SP);
4494 // We might get here with a VarDecl in the case we're generating
4495 // code for the initialization of globals. Do not record these decls
4496 // as they will overwrite the actual VarDecl Decl in the cache.
4497 if (HasDecl && isa<FunctionDecl>(D))
4498 DeclCache[D->getCanonicalDecl()].reset(SP);
4499
4500 // Push the function onto the lexical block stack.
4501 LexicalBlockStack.emplace_back(SP);
4502
4503 if (HasDecl)
4504 RegionMap[D].reset(SP);
4505}
4506
4508 QualType FnType, llvm::Function *Fn) {
4509 StringRef Name;
4510 StringRef LinkageName;
4511
4512 const Decl *D = GD.getDecl();
4513 if (!D)
4514 return;
4515
4516 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
4517 return GetName(D, true);
4518 });
4519
4520 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4521 llvm::DIFile *Unit = getOrCreateFile(Loc);
4522 bool IsDeclForCallSite = Fn ? true : false;
4523 llvm::DIScope *FDContext =
4524 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
4525 llvm::DINodeArray TParamsArray;
4526 if (isa<FunctionDecl>(D)) {
4527 // If there is a DISubprogram for this function available then use it.
4528 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4529 TParamsArray, Flags);
4530 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4531 Name = getObjCMethodName(OMD);
4532 Flags |= llvm::DINode::FlagPrototyped;
4533 } else {
4534 llvm_unreachable("not a function or ObjC method");
4535 }
4536 if (!Name.empty() && Name[0] == '\01')
4537 Name = Name.substr(1);
4538
4539 if (D->isImplicit()) {
4540 Flags |= llvm::DINode::FlagArtificial;
4541 // Artificial functions without a location should not silently reuse CurLoc.
4542 if (Loc.isInvalid())
4543 CurLoc = SourceLocation();
4544 }
4545 unsigned LineNo = getLineNumber(Loc);
4546 unsigned ScopeLine = 0;
4547 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4548 if (CGM.getLangOpts().Optimize)
4549 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4550
4551 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4552 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
4553 llvm::DISubprogram *SP = DBuilder.createFunction(
4554 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
4555 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations);
4556
4557 // Preserve btf_decl_tag attributes for parameters of extern functions
4558 // for BPF target. The parameters created in this loop are attached as
4559 // DISubprogram's retainedNodes in the subsequent finalizeSubprogram call.
4560 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
4561 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
4562 llvm::DITypeRefArray ParamTypes = STy->getTypeArray();
4563 unsigned ArgNo = 1;
4564 for (ParmVarDecl *PD : FD->parameters()) {
4565 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
4566 DBuilder.createParameterVariable(
4567 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
4568 llvm::DINode::FlagZero, ParamAnnotations);
4569 ++ArgNo;
4570 }
4571 }
4572 }
4573
4574 if (IsDeclForCallSite)
4575 Fn->setSubprogram(SP);
4576
4577 DBuilder.finalizeSubprogram(SP);
4578}
4579
4580void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
4581 QualType CalleeType,
4582 const FunctionDecl *CalleeDecl) {
4583 if (!CallOrInvoke)
4584 return;
4585 auto *Func = CallOrInvoke->getCalledFunction();
4586 if (!Func)
4587 return;
4588 if (Func->getSubprogram())
4589 return;
4590
4591 // Do not emit a declaration subprogram for a function with nodebug
4592 // attribute, or if call site info isn't required.
4593 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
4594 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
4595 return;
4596
4597 // If there is no DISubprogram attached to the function being called,
4598 // create the one describing the function in order to have complete
4599 // call site debug info.
4600 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
4601 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
4602}
4603
4605 const auto *FD = cast<FunctionDecl>(GD.getDecl());
4606 // If there is a subprogram for this function available then use it.
4607 auto FI = SPCache.find(FD->getCanonicalDecl());
4608 llvm::DISubprogram *SP = nullptr;
4609 if (FI != SPCache.end())
4610 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4611 if (!SP || !SP->isDefinition())
4612 SP = getFunctionStub(GD);
4613 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4614 LexicalBlockStack.emplace_back(SP);
4615 setInlinedAt(Builder.getCurrentDebugLocation());
4616 EmitLocation(Builder, FD->getLocation());
4617}
4618
4620 assert(CurInlinedAt && "unbalanced inline scope stack");
4621 EmitFunctionEnd(Builder, nullptr);
4622 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
4623}
4624
4626 // Update our current location
4628
4629 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
4630 return;
4631
4632 llvm::MDNode *Scope = LexicalBlockStack.back();
4633 Builder.SetCurrentDebugLocation(
4634 llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(CurLoc),
4635 getColumnNumber(CurLoc), Scope, CurInlinedAt));
4636}
4637
4638void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
4639 llvm::MDNode *Back = nullptr;
4640 if (!LexicalBlockStack.empty())
4641 Back = LexicalBlockStack.back().get();
4642 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
4643 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
4644 getColumnNumber(CurLoc)));
4645}
4646
4647void CGDebugInfo::AppendAddressSpaceXDeref(
4648 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
4649 std::optional<unsigned> DWARFAddressSpace =
4650 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
4651 if (!DWARFAddressSpace)
4652 return;
4653
4654 Expr.push_back(llvm::dwarf::DW_OP_constu);
4655 Expr.push_back(*DWARFAddressSpace);
4656 Expr.push_back(llvm::dwarf::DW_OP_swap);
4657 Expr.push_back(llvm::dwarf::DW_OP_xderef);
4658}
4659
4662 // Set our current location.
4664
4665 // Emit a line table change for the current location inside the new scope.
4666 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
4667 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
4668 LexicalBlockStack.back(), CurInlinedAt));
4669
4670 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4671 return;
4672
4673 // Create a new lexical block and push it on the stack.
4674 CreateLexicalBlock(Loc);
4675}
4676
4679 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4680
4681 // Provide an entry in the line table for the end of the block.
4682 EmitLocation(Builder, Loc);
4683
4684 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4685 return;
4686
4687 LexicalBlockStack.pop_back();
4688}
4689
4690void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
4691 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4692 unsigned RCount = FnBeginRegionCount.back();
4693 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
4694
4695 // Pop all regions for this function.
4696 while (LexicalBlockStack.size() != RCount) {
4697 // Provide an entry in the line table for the end of the block.
4698 EmitLocation(Builder, CurLoc);
4699 LexicalBlockStack.pop_back();
4700 }
4701 FnBeginRegionCount.pop_back();
4702
4703 if (Fn && Fn->getSubprogram())
4704 DBuilder.finalizeSubprogram(Fn->getSubprogram());
4705}
4706
4707CGDebugInfo::BlockByRefType
4708CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
4709 uint64_t *XOffset) {
4711 QualType FType;
4712 uint64_t FieldSize, FieldOffset;
4713 uint32_t FieldAlign;
4714
4715 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4716 QualType Type = VD->getType();
4717
4718 FieldOffset = 0;
4719 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4720 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
4721 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
4722 FType = CGM.getContext().IntTy;
4723 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
4724 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
4725
4726 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
4727 if (HasCopyAndDispose) {
4728 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4729 EltTys.push_back(
4730 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
4731 EltTys.push_back(
4732 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
4733 }
4734 bool HasByrefExtendedLayout;
4735 Qualifiers::ObjCLifetime Lifetime;
4736 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
4737 HasByrefExtendedLayout) &&
4738 HasByrefExtendedLayout) {
4739 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
4740 EltTys.push_back(
4741 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
4742 }
4743
4744 CharUnits Align = CGM.getContext().getDeclAlign(VD);
4745 if (Align > CGM.getContext().toCharUnitsFromBits(
4747 CharUnits FieldOffsetInBytes =
4748 CGM.getContext().toCharUnitsFromBits(FieldOffset);
4749 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
4750 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
4751
4752 if (NumPaddingBytes.isPositive()) {
4753 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
4754 FType = CGM.getContext().getConstantArrayType(
4755 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
4756 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
4757 }
4758 }
4759
4760 FType = Type;
4761 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
4762 FieldSize = CGM.getContext().getTypeSize(FType);
4763 FieldAlign = CGM.getContext().toBits(Align);
4764
4765 *XOffset = FieldOffset;
4766 llvm::DIType *FieldTy = DBuilder.createMemberType(
4767 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
4768 llvm::DINode::FlagZero, WrappedTy);
4769 EltTys.push_back(FieldTy);
4770 FieldOffset += FieldSize;
4771
4772 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4773 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
4774 llvm::DINode::FlagZero, nullptr, Elements),
4775 WrappedTy};
4776}
4777
4778llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
4779 llvm::Value *Storage,
4780 std::optional<unsigned> ArgNo,
4781 CGBuilderTy &Builder,
4782 const bool UsePointerValue) {
4783 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4784 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4785 if (VD->hasAttr<NoDebugAttr>())
4786 return nullptr;
4787
4788 const bool VarIsArtificial = IsArtificial(VD);
4789
4790 llvm::DIFile *Unit = nullptr;
4791 if (!VarIsArtificial)
4792 Unit = getOrCreateFile(VD->getLocation());
4793 llvm::DIType *Ty;
4794 uint64_t XOffset = 0;
4795 if (VD->hasAttr<BlocksAttr>())
4796 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4797 else
4798 Ty = getOrCreateType(VD->getType(), Unit);
4799
4800 // If there is no debug info for this type then do not emit debug info
4801 // for this variable.
4802 if (!Ty)
4803 return nullptr;
4804
4805 // Get location information.
4806 unsigned Line = 0;
4807 unsigned Column = 0;
4808 if (!VarIsArtificial) {
4809 Line = getLineNumber(VD->getLocation());
4810 Column = getColumnNumber(VD->getLocation());
4811 }
4813 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4814 if (VarIsArtificial)
4815 Flags |= llvm::DINode::FlagArtificial;
4816
4817 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4818
4819 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
4820 AppendAddressSpaceXDeref(AddressSpace, Expr);
4821
4822 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4823 // object pointer flag.
4824 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4825 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
4826 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
4827 Flags |= llvm::DINode::FlagObjectPointer;
4828 }
4829
4830 // Note: Older versions of clang used to emit byval references with an extra
4831 // DW_OP_deref, because they referenced the IR arg directly instead of
4832 // referencing an alloca. Newer versions of LLVM don't treat allocas
4833 // differently from other function arguments when used in a dbg.declare.
4834 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4835 StringRef Name = VD->getName();
4836 if (!Name.empty()) {
4837 // __block vars are stored on the heap if they are captured by a block that
4838 // can escape the local scope.
4839 if (VD->isEscapingByref()) {
4840 // Here, we need an offset *into* the alloca.
4842 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4843 // offset of __forwarding field
4844 offset = CGM.getContext().toCharUnitsFromBits(
4846 Expr.push_back(offset.getQuantity());
4847 Expr.push_back(llvm::dwarf::DW_OP_deref);
4848 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4849 // offset of x field
4850 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4851 Expr.push_back(offset.getQuantity());
4852 }
4853 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4854 // If VD is an anonymous union then Storage represents value for
4855 // all union fields.
4856 const RecordDecl *RD = RT->getDecl();
4857 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4858 // GDB has trouble finding local variables in anonymous unions, so we emit
4859 // artificial local variables for each of the members.
4860 //
4861 // FIXME: Remove this code as soon as GDB supports this.
4862 // The debug info verifier in LLVM operates based on the assumption that a
4863 // variable has the same size as its storage and we had to disable the
4864 // check for artificial variables.
4865 for (const auto *Field : RD->fields()) {
4866 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4867 StringRef FieldName = Field->getName();
4868
4869 // Ignore unnamed fields. Do not ignore unnamed records.
4870 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4871 continue;
4872
4873 // Use VarDecl's Tag, Scope and Line number.
4874 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4875 auto *D = DBuilder.createAutoVariable(
4876 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4877 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4878
4879 // Insert an llvm.dbg.declare into the current block.
4880 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4881 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4882 Column, Scope,
4883 CurInlinedAt),
4884 Builder.GetInsertBlock());
4885 }
4886 }
4887 }
4888
4889 // Clang stores the sret pointer provided by the caller in a static alloca.
4890 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4891 // the address of the variable.
4892 if (UsePointerValue) {
4893 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4894 "Debug info already contains DW_OP_deref.");
4895 Expr.push_back(llvm::dwarf::DW_OP_deref);
4896 }
4897
4898 // Create the descriptor for the variable.
4899 llvm::DILocalVariable *D = nullptr;
4900 if (ArgNo) {
4901 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
4902 D = DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line, Ty,
4903 CGM.getLangOpts().Optimize, Flags,
4904 Annotations);
4905 } else {
4906 // For normal local variable, we will try to find out whether 'VD' is the
4907 // copy parameter of coroutine.
4908 // If yes, we are going to use DIVariable of the origin parameter instead
4909 // of creating the new one.
4910 // If no, it might be a normal alloc, we just create a new one for it.
4911
4912 // Check whether the VD is move parameters.
4913 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
4914 // The scope of parameter and move-parameter should be distinct
4915 // DISubprogram.
4916 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
4917 return nullptr;
4918
4919 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
4920 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
4921 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
4922 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
4923 Decl *Decl = DeclGroup.getSingleDecl();
4924 if (VD == dyn_cast_or_null<VarDecl>(Decl))
4925 return true;
4926 }
4927 return false;
4928 });
4929
4930 if (Iter != CoroutineParameterMappings.end()) {
4931 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
4932 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
4933 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
4934 });
4935 if (Iter2 != ParamDbgMappings.end())
4936 return const_cast<llvm::DILocalVariable *>(Iter2->second);
4937 }
4938 return nullptr;
4939 };
4940
4941 // If we couldn't find a move param DIVariable, create a new one.
4942 D = RemapCoroArgToLocalVar();
4943 // Or we will create a new DIVariable for this Decl if D dose not exists.
4944 if (!D)
4945 D = DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4946 CGM.getLangOpts().Optimize, Flags, Align);
4947 }
4948 // Insert an llvm.dbg.declare into the current block.
4949 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4950 llvm::DILocation::get(CGM.getLLVMContext(), Line,
4951 Column, Scope, CurInlinedAt),
4952 Builder.GetInsertBlock());
4953
4954 return D;
4955}
4956
4957llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
4958 llvm::Value *Storage,
4959 std::optional<unsigned> ArgNo,
4960 CGBuilderTy &Builder,
4961 const bool UsePointerValue) {
4962 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4963 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4964 if (BD->hasAttr<NoDebugAttr>())
4965 return nullptr;
4966
4967 // Skip the tuple like case, we don't handle that here
4968 if (isa<DeclRefExpr>(BD->getBinding()))
4969 return nullptr;
4970
4971 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
4972 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
4973
4974 // If there is no debug info for this type then do not emit debug info
4975 // for this variable.
4976 if (!Ty)
4977 return nullptr;
4978
4979 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
4980 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
4981
4983 AppendAddressSpaceXDeref(AddressSpace, Expr);
4984
4985 // Clang stores the sret pointer provided by the caller in a static alloca.
4986 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4987 // the address of the variable.
4988 if (UsePointerValue) {
4989 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
4990 "Debug info already contains DW_OP_deref.");
4991 Expr.push_back(llvm::dwarf::DW_OP_deref);
4992 }
4993
4994 unsigned Line = getLineNumber(BD->getLocation());
4995 unsigned Column = getColumnNumber(BD->getLocation());
4996 StringRef Name = BD->getName();
4997 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4998 // Create the descriptor for the variable.
4999 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5000 Scope, Name, Unit, Line, Ty, CGM.getLangOpts().Optimize,
5001 llvm::DINode::FlagZero, Align);
5002
5003 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5004 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5005 const unsigned fieldIndex = FD->getFieldIndex();
5006 const clang::CXXRecordDecl *parent =
5007 (const CXXRecordDecl *)FD->getParent();
5008 const ASTRecordLayout &layout =
5009 CGM.getContext().getASTRecordLayout(parent);
5010 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5011 if (FD->isBitField()) {
5012 const CGRecordLayout &RL =
5013 CGM.getTypes().getCGRecordLayout(FD->getParent());
5014 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5015 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5016 // storage.
5017 if (!Info.StorageOffset.isZero()) {
5018 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5019 Expr.push_back(Info.StorageOffset.getQuantity());
5020 }
5021 // Use LLVM_extract_bits to extract the appropriate bits from this
5022 // bitfield.
5023 Expr.push_back(Info.IsSigned
5024 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5025 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5026 Expr.push_back(Info.Offset);
5027 // If we have an oversized bitfield then the value won't be more than
5028 // the size of the type.
5029 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5030 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5031 } else if (fieldOffset != 0) {
5032 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5033 "Unexpected non-bitfield with non-byte-aligned offset");
5034 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5035 Expr.push_back(
5036 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5037 }
5038 }
5039 } else if (const ArraySubscriptExpr *ASE =
5040 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5041 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5042 const uint64_t value = IL->getValue().getZExtValue();
5043 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5044
5045 if (value != 0) {
5046 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5047 Expr.push_back(CGM.getContext()
5048 .toCharUnitsFromBits(value * typeSize)
5049 .getQuantity());
5050 }
5051 }
5052 }
5053
5054 // Insert an llvm.dbg.declare into the current block.
5055 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5056 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5057 Column, Scope, CurInlinedAt),
5058 Builder.GetInsertBlock());
5059
5060 return D;
5061}
5062
5063llvm::DILocalVariable *
5064CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5065 CGBuilderTy &Builder,
5066 const bool UsePointerValue) {
5067 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5068
5069 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5070 for (auto *B : DD->bindings()) {
5071 EmitDeclare(B, Storage, std::nullopt, Builder,
5072 VD->getType()->isReferenceType());
5073 }
5074 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5075 // correspond to a user variable.
5076 return nullptr;
5077 }
5078
5079 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5080}
5081
5083 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5084 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5085
5086 if (D->hasAttr<NoDebugAttr>())
5087 return;
5088
5089 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5090 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5091
5092 // Get location information.
5093 unsigned Line = getLineNumber(D->getLocation());
5094 unsigned Column = getColumnNumber(D->getLocation());
5095
5096 StringRef Name = D->getName();
5097
5098 // Create the descriptor for the label.
5099 auto *L =
5100 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
5101
5102 // Insert an llvm.dbg.label into the current block.
5103 DBuilder.insertLabel(L,
5104 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5105 Scope, CurInlinedAt),
5106 Builder.GetInsertBlock());
5107}
5108
5109llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5110 llvm::DIType *Ty) {
5111 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5112 if (CachedTy)
5113 Ty = CachedTy;
5114 return DBuilder.createObjectPointerType(Ty);
5115}
5116
5118 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5119 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5120 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5121 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5122
5123 if (Builder.GetInsertBlock() == nullptr)
5124 return;
5125 if (VD->hasAttr<NoDebugAttr>())
5126 return;
5127
5128 bool isByRef = VD->hasAttr<BlocksAttr>();
5129
5130 uint64_t XOffset = 0;
5131 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5132 llvm::DIType *Ty;
5133 if (isByRef)
5134 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5135 else
5136 Ty = getOrCreateType(VD->getType(), Unit);
5137
5138 // Self is passed along as an implicit non-arg variable in a
5139 // block. Mark it as the object pointer.
5140 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5141 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5142 Ty = CreateSelfType(VD->getType(), Ty);
5143
5144 // Get location information.
5145 const unsigned Line =
5146 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5147 unsigned Column = getColumnNumber(VD->getLocation());
5148
5149 const llvm::DataLayout &target = CGM.getDataLayout();
5150
5152 target.getStructLayout(blockInfo.StructureType)
5153 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5154
5156 addr.push_back(llvm::dwarf::DW_OP_deref);
5157 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5158 addr.push_back(offset.getQuantity());
5159 if (isByRef) {
5160 addr.push_back(llvm::dwarf::DW_OP_deref);
5161 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5162 // offset of __forwarding field
5163 offset =
5164 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5165 addr.push_back(offset.getQuantity());
5166 addr.push_back(llvm::dwarf::DW_OP_deref);
5167 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5168 // offset of x field
5169 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5170 addr.push_back(offset.getQuantity());
5171 }
5172
5173 // Create the descriptor for the variable.
5174 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5175 auto *D = DBuilder.createAutoVariable(
5176 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5177 Line, Ty, false, llvm::DINode::FlagZero, Align);
5178
5179 // Insert an llvm.dbg.declare into the current block.
5180 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5181 LexicalBlockStack.back(), CurInlinedAt);
5182 auto *Expr = DBuilder.createExpression(addr);
5183 if (InsertPoint)
5184 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
5185 else
5186 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5187}
5188
5189llvm::DILocalVariable *
5191 unsigned ArgNo, CGBuilderTy &Builder,
5192 bool UsePointerValue) {
5193 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5194 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5195}
5196
5197namespace {
5198struct BlockLayoutChunk {
5199 uint64_t OffsetInBits;
5201};
5202bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5203 return l.OffsetInBits < r.OffsetInBits;
5204}
5205} // namespace
5206
5207void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5208 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5209 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5211 // Blocks in OpenCL have unique constraints which make the standard fields
5212 // redundant while requiring size and align fields for enqueue_kernel. See
5213 // initializeForBlockHeader in CGBlocks.cpp
5214 if (CGM.getLangOpts().OpenCL) {
5215 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5216 BlockLayout.getElementOffsetInBits(0),
5217 Unit,