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