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) {
2222 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
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,
2238 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
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).
3186 llvm::DenseSet<IsClassAndIdent> PropertySet;
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,
5227 BlockLayout.getElementOffsetInBits(0),
5228 Unit, Unit));
5229 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5230 BlockLayout.getElementOffsetInBits(1),
5231 Unit, Unit));
5232 } else {
5233 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5234 BlockLayout.getElementOffsetInBits(0),
5235 Unit, Unit));
5236 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5237 BlockLayout.getElementOffsetInBits(1),
5238 Unit, Unit));
5239 Fields.push_back(
5240 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5241 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5242 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5243 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5244 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5245 BlockLayout.getElementOffsetInBits(3),
5246 Unit, Unit));
5247 Fields.push_back(createFieldType(
5248 "__descriptor",
5249 Context.getPointerType(Block.NeedsCopyDispose
5251 : Context.getBlockDescriptorType()),
5252 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5253 }
5254}
5255
5257 StringRef Name,
5258 unsigned ArgNo,
5259 llvm::AllocaInst *Alloca,
5260 CGBuilderTy &Builder) {
5261 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5262 ASTContext &C = CGM.getContext();
5263 const BlockDecl *blockDecl = block.getBlockDecl();
5264
5265 // Collect some general information about the block's location.
5266 SourceLocation loc = blockDecl->getCaretLocation();
5267 llvm::DIFile *tunit = getOrCreateFile(loc);
5268 unsigned line = getLineNumber(loc);
5269 unsigned column = getColumnNumber(loc);
5270
5271 // Build the debug-info type for the block literal.
5272 getDeclContextDescriptor(blockDecl);
5273
5274 const llvm::StructLayout *blockLayout =
5275 CGM.getDataLayout().getStructLayout(block.StructureType);
5276
5278 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5279 fields);
5280
5281 // We want to sort the captures by offset, not because DWARF
5282 // requires this, but because we're paranoid about debuggers.
5284
5285 // 'this' capture.
5286 if (blockDecl->capturesCXXThis()) {
5287 BlockLayoutChunk chunk;
5288 chunk.OffsetInBits =
5289 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5290 chunk.Capture = nullptr;
5291 chunks.push_back(chunk);
5292 }
5293
5294 // Variable captures.
5295 for (const auto &capture : blockDecl->captures()) {
5296 const VarDecl *variable = capture.getVariable();
5297 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5298
5299 // Ignore constant captures.
5300 if (captureInfo.isConstant())
5301 continue;
5302
5303 BlockLayoutChunk chunk;
5304 chunk.OffsetInBits =
5305 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5306 chunk.Capture = &capture;
5307 chunks.push_back(chunk);
5308 }
5309
5310 // Sort by offset.
5311 llvm::array_pod_sort(chunks.begin(), chunks.end());
5312
5313 for (const BlockLayoutChunk &Chunk : chunks) {
5314 uint64_t offsetInBits = Chunk.OffsetInBits;
5315 const BlockDecl::Capture *capture = Chunk.Capture;
5316
5317 // If we have a null capture, this must be the C++ 'this' capture.
5318 if (!capture) {
5319 QualType type;
5320 if (auto *Method =
5321 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5322 type = Method->getThisType();
5323 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5324 type = QualType(RDecl->getTypeForDecl(), 0);
5325 else
5326 llvm_unreachable("unexpected block declcontext");
5327
5328 fields.push_back(createFieldType("this", type, loc, AS_public,
5329 offsetInBits, tunit, tunit));
5330 continue;
5331 }
5332
5333 const VarDecl *variable = capture->getVariable();
5334 StringRef name = variable->getName();
5335
5336 llvm::DIType *fieldType;
5337 if (capture->isByRef()) {
5338 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5339 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5340 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5341 uint64_t xoffset;
5342 fieldType =
5343 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5344 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5345 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5346 PtrInfo.Width, Align, offsetInBits,
5347 llvm::DINode::FlagZero, fieldType);
5348 } else {
5349 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5350 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5351 offsetInBits, Align, tunit, tunit);
5352 }
5353 fields.push_back(fieldType);
5354 }
5355
5356 SmallString<36> typeName;
5357 llvm::raw_svector_ostream(typeName)
5358 << "__block_literal_" << CGM.getUniqueBlockCount();
5359
5360 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5361
5362 llvm::DIType *type =
5363 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5364 CGM.getContext().toBits(block.BlockSize), 0,
5365 llvm::DINode::FlagZero, nullptr, fieldsArray);
5366 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5367
5368 // Get overall information about the block.
5369 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5370 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5371
5372 // Create the descriptor for the parameter.
5373 auto *debugVar = DBuilder.createParameterVariable(
5374 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
5375
5376 // Insert an llvm.dbg.declare into the current block.
5377 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5378 llvm::DILocation::get(CGM.getLLVMContext(), line,
5379 column, scope, CurInlinedAt),
5380 Builder.GetInsertBlock());
5381}
5382
5383llvm::DIDerivedType *
5384CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5385 if (!D || !D->isStaticDataMember())
5386 return nullptr;
5387
5388 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5389 if (MI != StaticDataMemberCache.end()) {
5390 assert(MI->second && "Static data member declaration should still exist");
5391 return MI->second;
5392 }
5393
5394 // If the member wasn't found in the cache, lazily construct and add it to the
5395 // type (used when a limited form of the type is emitted).
5396 auto DC = D->getDeclContext();
5397 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5398 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5399}
5400
5401llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5402 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5403 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5404 llvm::DIGlobalVariableExpression *GVE = nullptr;
5405
5406 for (const auto *Field : RD->fields()) {
5407 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5408 StringRef FieldName = Field->getName();
5409
5410 // Ignore unnamed fields, but recurse into anonymous records.
5411 if (FieldName.empty()) {
5412 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5413 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
5414 Var, DContext);
5415 continue;
5416 }
5417 // Use VarDecl's Tag, Scope and Line number.
5418 GVE = DBuilder.createGlobalVariableExpression(
5419 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5420 Var->hasLocalLinkage());
5421 Var->addDebugInfo(GVE);
5422 }
5423 return GVE;
5424}
5425
5428 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5429 // info we produce in the DWARF, so we can't get Clang's full name back.
5430 // But so long as it's not one of those, it doesn't matter if some sub-type
5431 // of the record (a template parameter) can't be reconstituted - because the
5432 // un-reconstitutable type itself will carry its own name.
5433 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5434 if (!RD)
5435 return false;
5436 if (!RD->getIdentifier())
5437 return true;
5438 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
5439 if (!TSpecial)
5440 return false;
5441 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
5442}
5444 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
5445 switch (TA.getKind()) {
5446 case TemplateArgument::Pack:
5447 return ReferencesAnonymousEntity(TA.getPackAsArray());
5448 case TemplateArgument::Type: {
5449 struct ReferencesAnonymous
5450 : public RecursiveASTVisitor<ReferencesAnonymous> {
5451 bool RefAnon = false;
5452 bool VisitRecordType(RecordType *RT) {
5453 if (ReferencesAnonymousEntity(RT)) {
5454 RefAnon = true;
5455 return false;
5456 }
5457 return true;
5458 }
5459 };
5460 ReferencesAnonymous RT;
5461 RT.TraverseType(TA.getAsType());
5462 if (RT.RefAnon)
5463 return true;
5464 break;
5465 }
5466 default:
5467 break;
5468 }
5469 return false;
5470 });
5471}
5472namespace {
5473struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
5474 bool Reconstitutable = true;
5475 bool VisitVectorType(VectorType *FT) {
5476 Reconstitutable = false;
5477 return false;
5478 }
5479 bool VisitAtomicType(AtomicType *FT) {
5480 Reconstitutable = false;
5481 return false;
5482 }
5483 bool VisitType(Type *T) {
5484 // _BitInt(N) isn't reconstitutable because the bit width isn't encoded in
5485 // the DWARF, only the byte width.
5486 if (T->isBitIntType()) {
5487 Reconstitutable = false;
5488 return false;
5489 }
5490 return true;
5491 }
5492 bool TraverseEnumType(EnumType *ET) {
5493 // Unnamed enums can't be reconstituted due to a lack of column info we
5494 // produce in the DWARF, so we can't get Clang's full name back.
5495 if (const auto *ED = dyn_cast<EnumDecl>(ET->getDecl())) {
5496 if (!ED->getIdentifier()) {
5497 Reconstitutable = false;
5498 return false;
5499 }
5500 if (!ED->isExternallyVisible()) {
5501 Reconstitutable = false;
5502 return false;
5503 }
5504 }
5505 return true;
5506 }
5507 bool VisitFunctionProtoType(FunctionProtoType *FT) {
5508 // noexcept is not encoded in DWARF, so the reversi
5509 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
5510 Reconstitutable &= !FT->getNoReturnAttr();
5511 return Reconstitutable;
5512 }
5513 bool VisitRecordType(RecordType *RT) {
5514 if (ReferencesAnonymousEntity(RT)) {
5515 Reconstitutable = false;
5516 return false;
5517 }
5518 return true;
5519 }
5520};
5521} // anonymous namespace
5522
5523// Test whether a type name could be rebuilt from emitted debug info.
5525 ReconstitutableType T;
5526 T.TraverseType(QT);
5527 return T.Reconstitutable;
5528}
5529
5530bool CGDebugInfo::HasReconstitutableArgs(
5531 ArrayRef<TemplateArgument> Args) const {
5532 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
5533 switch (TA.getKind()) {
5534 case TemplateArgument::Template:
5535 // Easy to reconstitute - the value of the parameter in the debug
5536 // info is the string name of the template. The template name
5537 // itself won't benefit from any name rebuilding, but that's a
5538 // representational limitation - maybe DWARF could be
5539 // changed/improved to use some more structural representation.
5540 return true;
5541 case TemplateArgument::Declaration:
5542 // Reference and pointer non-type template parameters point to
5543 // variables, functions, etc and their value is, at best (for
5544 // variables) represented as an address - not a reference to the
5545 // DWARF describing the variable/function/etc. This makes it hard,
5546 // possibly impossible to rebuild the original name - looking up
5547 // the address in the executable file's symbol table would be
5548 // needed.
5549 return false;
5550 case TemplateArgument::NullPtr:
5551 // These could be rebuilt, but figured they're close enough to the
5552 // declaration case, and not worth rebuilding.
5553 return false;
5554 case TemplateArgument::Pack:
5555 // A pack is invalid if any of the elements of the pack are
5556 // invalid.
5557 return HasReconstitutableArgs(TA.getPackAsArray());
5558 case TemplateArgument::Integral:
5559 // Larger integers get encoded as DWARF blocks which are a bit
5560 // harder to parse back into a large integer, etc - so punting on
5561 // this for now. Re-parsing the integers back into APInt is
5562 // probably feasible some day.
5563 return TA.getAsIntegral().getBitWidth() <= 64 &&
5564 IsReconstitutableType(TA.getIntegralType());
5565 case TemplateArgument::StructuralValue:
5566 return false;
5567 case TemplateArgument::Type:
5568 return IsReconstitutableType(TA.getAsType());
5569 case TemplateArgument::Expression:
5570 return IsReconstitutableType(TA.getAsExpr()->getType());
5571 default:
5572 llvm_unreachable("Other, unresolved, template arguments should "
5573 "not be seen here");
5574 }
5575 });
5576}
5577
5578std::string CGDebugInfo::GetName(const Decl *D, bool Qualified) const {
5579 std::string Name;
5580 llvm::raw_string_ostream OS(Name);
5581 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
5582 if (!ND)
5583 return Name;
5584 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
5585 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
5586
5588 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
5589
5590 std::optional<TemplateArgs> Args;
5591
5592 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
5593 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
5594 Args = GetTemplateArgs(RD);
5595 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
5596 Args = GetTemplateArgs(FD);
5597 auto NameKind = ND->getDeclName().getNameKind();
5598 IsOperatorOverload |=
5601 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
5602 Args = GetTemplateArgs(VD);
5603 }
5604
5605 // A conversion operator presents complications/ambiguity if there's a
5606 // conversion to class template that is itself a template, eg:
5607 // template<typename T>
5608 // operator ns::t1<T, int>();
5609 // This should be named, eg: "operator ns::t1<float, int><float>"
5610 // (ignoring clang bug that means this is currently "operator t1<float>")
5611 // but if the arguments were stripped, the consumer couldn't differentiate
5612 // whether the template argument list for the conversion type was the
5613 // function's argument list (& no reconstitution was needed) or not.
5614 // This could be handled if reconstitutable names had a separate attribute
5615 // annotating them as such - this would remove the ambiguity.
5616 //
5617 // Alternatively the template argument list could be parsed enough to check
5618 // whether there's one list or two, then compare that with the DWARF
5619 // description of the return type and the template argument lists to determine
5620 // how many lists there should be and if one is missing it could be assumed(?)
5621 // to be the function's template argument list & then be rebuilt.
5622 //
5623 // Other operator overloads that aren't conversion operators could be
5624 // reconstituted but would require a bit more nuance about detecting the
5625 // difference between these different operators during that rebuilding.
5626 bool Reconstitutable =
5627 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
5628
5629 PrintingPolicy PP = getPrintingPolicy();
5630
5631 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
5632 !Reconstitutable) {
5633 ND->getNameForDiagnostic(OS, PP, Qualified);
5634 } else {
5635 bool Mangled = TemplateNamesKind ==
5636 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
5637 // check if it's a template
5638 if (Mangled)
5639 OS << "_STN|";
5640
5641 OS << ND->getDeclName();
5642 std::string EncodedOriginalName;
5643 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
5644 EncodedOriginalNameOS << ND->getDeclName();
5645
5646 if (Mangled) {
5647 OS << "|";
5648 printTemplateArgumentList(OS, Args->Args, PP);
5649 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
5650#ifndef NDEBUG
5651 std::string CanonicalOriginalName;
5652 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
5653 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
5654 assert(EncodedOriginalNameOS.str() == OriginalOS.str());
5655#endif
5656 }
5657 }
5658 return Name;
5659}
5660
5661void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
5662 const VarDecl *D) {
5663 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5664 if (D->hasAttr<NoDebugAttr>())
5665 return;
5666
5667 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
5668 return GetName(D, true);
5669 });
5670
5671 // If we already created a DIGlobalVariable for this declaration, just attach
5672 // it to the llvm::GlobalVariable.
5673 auto Cached = DeclCache.find(D->getCanonicalDecl());
5674 if (Cached != DeclCache.end())
5675 return Var->addDebugInfo(
5676 cast<llvm::DIGlobalVariableExpression>(Cached->second));
5677
5678 // Create global variable debug descriptor.
5679 llvm::DIFile *Unit = nullptr;
5680 llvm::DIScope *DContext = nullptr;
5681 unsigned LineNo;
5682 StringRef DeclName, LinkageName;
5683 QualType T;
5684 llvm::MDTuple *TemplateParameters = nullptr;
5685 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
5686 TemplateParameters, DContext);
5687
5688 // Attempt to store one global variable for the declaration - even if we
5689 // emit a lot of fields.
5690 llvm::DIGlobalVariableExpression *GVE = nullptr;
5691
5692 // If this is an anonymous union then we'll want to emit a global
5693 // variable for each member of the anonymous union so that it's possible
5694 // to find the name of any field in the union.
5695 if (T->isUnionType() && DeclName.empty()) {
5696 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
5697 assert(RD->isAnonymousStructOrUnion() &&
5698 "unnamed non-anonymous struct or union?");
5699 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
5700 } else {
5701 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5702
5704 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
5705 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
5706 if (D->hasAttr<CUDASharedAttr>())
5707 AddressSpace =
5709 else if (D->hasAttr<CUDAConstantAttr>())
5710 AddressSpace =
5712 }
5713 AppendAddressSpaceXDeref(AddressSpace, Expr);
5714
5715 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5716 GVE = DBuilder.createGlobalVariableExpression(
5717 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
5718 Var->hasLocalLinkage(), true,
5719 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
5720 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
5721 Align, Annotations);
5722 Var->addDebugInfo(GVE);
5723 }
5724 DeclCache[D->getCanonicalDecl()].reset(GVE);
5725}
5726
5728 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5729 if (VD->hasAttr<NoDebugAttr>())
5730 return;
5731 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
5732 return GetName(VD, true);
5733 });
5734
5735 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5736 // Create the descriptor for the variable.
5737 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5738 StringRef Name = VD->getName();
5739 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
5740
5741 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
5742 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
5743 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
5744
5745 if (CGM.getCodeGenOpts().EmitCodeView) {
5746 // If CodeView, emit enums as global variables, unless they are defined
5747 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
5748 // enums in classes, and because it is difficult to attach this scope
5749 // information to the global variable.
5750 if (isa<RecordDecl>(ED->getDeclContext()))
5751 return;
5752 } else {
5753 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
5754 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
5755 // first time `ZERO` is referenced in a function.
5756 llvm::DIType *EDTy =
5757 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
5758 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
5759 (void)EDTy;
5760 return;
5761 }
5762 }
5763
5764 // Do not emit separate definitions for function local consts.
5765 if (isa<FunctionDecl>(VD->getDeclContext()))
5766 return;
5767
5768 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5769 auto *VarD = dyn_cast<VarDecl>(VD);
5770 if (VarD && VarD->isStaticDataMember()) {
5771 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
5772 getDeclContextDescriptor(VarD);
5773 // Ensure that the type is retained even though it's otherwise unreferenced.
5774 //
5775 // FIXME: This is probably unnecessary, since Ty should reference RD
5776 // through its scope.
5777 RetainedTypes.push_back(
5779
5780 return;
5781 }
5782 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
5783
5784 auto &GV = DeclCache[VD];
5785 if (GV)
5786 return;
5787
5788 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
5789 llvm::MDTuple *TemplateParameters = nullptr;
5790
5791 if (isa<VarTemplateSpecializationDecl>(VD))
5792 if (VarD) {
5793 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
5794 TemplateParameters = parameterNodes.get();
5795 }
5796
5797 GV.reset(DBuilder.createGlobalVariableExpression(
5798 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
5799 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
5800 TemplateParameters, Align));
5801}
5802
5803void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
5804 const VarDecl *D) {
5805 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5806 if (D->hasAttr<NoDebugAttr>())
5807 return;
5808
5809 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
5810 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5811 StringRef Name = D->getName();
5812 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
5813
5814 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5815 llvm::DIGlobalVariableExpression *GVE =
5816 DBuilder.createGlobalVariableExpression(
5817 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
5818 Ty, false, false, nullptr, nullptr, nullptr, Align);
5819 Var->addDebugInfo(GVE);
5820}
5821
5823 llvm::Instruction *Value, QualType Ty) {
5824 // Only when -g2 or above is specified, debug info for variables will be
5825 // generated.
5826 if (CGM.getCodeGenOpts().getDebugInfo() <=
5827 llvm::codegenoptions::DebugLineTablesOnly)
5828 return;
5829
5830 llvm::DILocation *DIL = Value->getDebugLoc().get();
5831 if (!DIL)
5832 return;
5833
5834 llvm::DIFile *Unit = DIL->getFile();
5835 llvm::DIType *Type = getOrCreateType(Ty, Unit);
5836
5837 // Check if Value is already a declared variable and has debug info, in this
5838 // case we have nothing to do. Clang emits a declared variable as alloca, and
5839 // it is loaded upon use, so we identify such pattern here.
5840 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
5841 llvm::Value *Var = Load->getPointerOperand();
5842 // There can be implicit type cast applied on a variable if it is an opaque
5843 // ptr, in this case its debug info may not match the actual type of object
5844 // being used as in the next instruction, so we will need to emit a pseudo
5845 // variable for type-casted value.
5846 auto DeclareTypeMatches = [&](auto *DbgDeclare) {
5847 return DbgDeclare->getVariable()->getType() == Type;
5848 };
5849 if (any_of(llvm::findDbgDeclares(Var), DeclareTypeMatches) ||
5850 any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
5851 return;
5852 }
5853
5854 llvm::DILocalVariable *D =
5855 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
5856 Type, false, llvm::DINode::FlagArtificial);
5857
5858 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
5859 DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,
5860 &**InsertPoint);
5861 }
5862}
5863
5864void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
5865 const GlobalDecl GD) {
5866
5867 assert(GV);
5868
5870 return;
5871
5872 const auto *D = cast<ValueDecl>(GD.getDecl());
5873 if (D->hasAttr<NoDebugAttr>())
5874 return;
5875
5876 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
5877 llvm::DINode *DI;
5878
5879 if (!AliaseeDecl)
5880 // FIXME: Aliasee not declared yet - possibly declared later
5881 // For example,
5882 //
5883 // 1 extern int newname __attribute__((alias("oldname")));
5884 // 2 int oldname = 1;
5885 //
5886 // No debug info would be generated for 'newname' in this case.
5887 //
5888 // Fix compiler to generate "newname" as imported_declaration
5889 // pointing to the DIE of "oldname".
5890 return;
5891 if (!(DI = getDeclarationOrDefinition(
5892 AliaseeDecl.getCanonicalDecl().getDecl())))
5893 return;
5894
5895 llvm::DIScope *DContext = getDeclContextDescriptor(D);
5896 auto Loc = D->getLocation();
5897
5898 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
5899 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
5900
5901 // Record this DIE in the cache for nested declaration reference.
5902 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
5903}
5904
5905void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
5906 const StringLiteral *S) {
5907 SourceLocation Loc = S->getStrTokenLoc(0);
5909 if (!PLoc.isValid())
5910 return;
5911
5912 llvm::DIFile *File = getOrCreateFile(Loc);
5913 llvm::DIGlobalVariableExpression *Debug =
5914 DBuilder.createGlobalVariableExpression(
5915 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
5916 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
5917 GV->addDebugInfo(Debug);
5918}
5919
5920llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
5921 if (!LexicalBlockStack.empty())
5922 return LexicalBlockStack.back();
5923 llvm::DIScope *Mod = getParentModuleOrNull(D);
5924 return getContextDescriptor(D, Mod ? Mod : TheCU);
5925}
5926
5929 return;
5930 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
5931 if (!NSDecl->isAnonymousNamespace() ||
5932 CGM.getCodeGenOpts().DebugExplicitImport) {
5933 auto Loc = UD.getLocation();
5934 if (!Loc.isValid())
5935 Loc = CurLoc;
5936 DBuilder.createImportedModule(
5937 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
5938 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
5939 }
5940}
5941
5943 if (llvm::DINode *Target =
5944 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
5945 auto Loc = USD.getLocation();
5946 DBuilder.createImportedDeclaration(
5947 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
5948 getOrCreateFile(Loc), getLineNumber(Loc));
5949 }
5950}
5951
5954 return;
5955 assert(UD.shadow_size() &&
5956 "We shouldn't be codegening an invalid UsingDecl containing no decls");
5957
5958 for (const auto *USD : UD.shadows()) {
5959 // FIXME: Skip functions with undeduced auto return type for now since we
5960 // don't currently have the plumbing for separate declarations & definitions
5961 // of free functions and mismatched types (auto in the declaration, concrete
5962 // return type in the definition)
5963 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
5964 if (const auto *AT = FD->getType()
5965 ->castAs<FunctionProtoType>()
5967 if (AT->getDeducedType().isNull())
5968 continue;
5969
5970 EmitUsingShadowDecl(*USD);
5971 // Emitting one decl is sufficient - debuggers can detect that this is an
5972 // overloaded name & provide lookup for all the overloads.
5973 break;
5974 }
5975}
5976
5979 return;
5980 assert(UD.shadow_size() &&
5981 "We shouldn't be codegening an invalid UsingEnumDecl"
5982 " containing no decls");
5983
5984 for (const auto *USD : UD.shadows())
5985 EmitUsingShadowDecl(*USD);
5986}
5987
5989 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
5990 return;
5991 if (Module *M = ID.getImportedModule()) {
5992 auto Info = ASTSourceDescriptor(*M);
5993 auto Loc = ID.getLocation();
5994 DBuilder.createImportedDeclaration(
5995 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
5996 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
5997 getLineNumber(Loc));
5998 }
5999}
6000
6001llvm::DIImportedEntity *
6004 return nullptr;
6005 auto &VH = NamespaceAliasCache[&NA];
6006 if (VH)
6007 return cast<llvm::DIImportedEntity>(VH);
6008 llvm::DIImportedEntity *R;
6009 auto Loc = NA.getLocation();
6010 if (const auto *Underlying =
6011 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6012 // This could cache & dedup here rather than relying on metadata deduping.
6013 R = DBuilder.createImportedDeclaration(
6014 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6015 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6016 getLineNumber(Loc), NA.getName());
6017 else
6018 R = DBuilder.createImportedDeclaration(
6019 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6020 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6021 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6022 VH.reset(R);
6023 return R;
6024}
6025
6026llvm::DINamespace *
6027CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6028 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6029 // if necessary, and this way multiple declarations of the same namespace in
6030 // different parent modules stay distinct.
6031 auto I = NamespaceCache.find(NSDecl);
6032 if (I != NamespaceCache.end())
6033 return cast<llvm::DINamespace>(I->second);
6034
6035 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6036 // Don't trust the context if it is a DIModule (see comment above).
6037 llvm::DINamespace *NS =
6038 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6039 NamespaceCache[NSDecl].reset(NS);
6040 return NS;
6041}
6042
6043void CGDebugInfo::setDwoId(uint64_t Signature) {
6044 assert(TheCU && "no main compile unit");
6045 TheCU->setDWOId(Signature);
6046}
6047
6049 // Creating types might create further types - invalidating the current
6050 // element and the size(), so don't cache/reference them.
6051 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6052 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6053 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6054 ? CreateTypeDefinition(E.Type, E.Unit)
6055 : E.Decl;
6056 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6057 }
6058
6059 // Add methods to interface.
6060 for (const auto &P : ObjCMethodCache) {
6061 if (P.second.empty())
6062 continue;
6063
6064 QualType QTy(P.first->getTypeForDecl(), 0);
6065 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6066 assert(It != TypeCache.end());
6067
6068 llvm::DICompositeType *InterfaceDecl =
6069 cast<llvm::DICompositeType>(It->second);
6070
6071 auto CurElts = InterfaceDecl->getElements();
6072 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6073
6074 // For DWARF v4 or earlier, only add objc_direct methods.
6075 for (auto &SubprogramDirect : P.second)
6076 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6077 EltTys.push_back(SubprogramDirect.getPointer());
6078
6079 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6080 DBuilder.replaceArrays(InterfaceDecl, Elements);
6081 }
6082
6083 for (const auto &P : ReplaceMap) {
6084 assert(P.second);
6085 auto *Ty = cast<llvm::DIType>(P.second);
6086 assert(Ty->isForwardDecl());
6087
6088 auto It = TypeCache.find(P.first);
6089 assert(It != TypeCache.end());
6090 assert(It->second);
6091
6092 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6093 cast<llvm::DIType>(It->second));
6094 }
6095
6096 for (const auto &P : FwdDeclReplaceMap) {
6097 assert(P.second);
6098 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6099 llvm::Metadata *Repl;
6100
6101 auto It = DeclCache.find(P.first);
6102 // If there has been no definition for the declaration, call RAUW
6103 // with ourselves, that will destroy the temporary MDNode and
6104 // replace it with a standard one, avoiding leaking memory.
6105 if (It == DeclCache.end())
6106 Repl = P.second;
6107 else
6108 Repl = It->second;
6109
6110 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6111 Repl = GVE->getVariable();
6112 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6113 }
6114
6115 // We keep our own list of retained types, because we need to look
6116 // up the final type in the type cache.
6117 for (auto &RT : RetainedTypes)
6118 if (auto MD = TypeCache[RT])
6119 DBuilder.retainType(cast<llvm::DIType>(MD));
6120
6121 DBuilder.finalize();
6122}
6123
6124// Don't ignore in case of explicit cast where it is referenced indirectly.
6127 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6128 DBuilder.retainType(DieTy);
6129}
6130
6133 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6134 DBuilder.retainType(DieTy);
6135}
6136
6138 if (LexicalBlockStack.empty())
6139 return llvm::DebugLoc();
6140
6141 llvm::MDNode *Scope = LexicalBlockStack.back();
6142 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6143 getColumnNumber(Loc), Scope);
6144}
6145
6146llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6147 // Call site-related attributes are only useful in optimized programs, and
6148 // when there's a possibility of debugging backtraces.
6149 if (!CGM.getLangOpts().Optimize ||
6150 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6151 DebugKind == llvm::codegenoptions::LocTrackingOnly)
6152 return llvm::DINode::FlagZero;
6153
6154 // Call site-related attributes are available in DWARF v5. Some debuggers,
6155 // while not fully DWARF v5-compliant, may accept these attributes as if they
6156 // were part of DWARF v4.
6157 bool SupportsDWARFv4Ext =
6158 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6159 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6160 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6161
6162 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6163 return llvm::DINode::FlagZero;
6164
6165 return llvm::DINode::FlagAllCallsDescribed;
6166}
6167
6168llvm::DIExpression *
6169CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6170 const APValue &Val) {
6171 // FIXME: Add a representation for integer constants wider than 64 bits.
6172 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6173 return nullptr;
6174
6175 if (Val.isFloat())
6176 return DBuilder.createConstantValueExpression(
6177 Val.getFloat().bitcastToAPInt().getZExtValue());
6178
6179 if (!Val.isInt())
6180 return nullptr;
6181
6182 llvm::APSInt const &ValInt = Val.getInt();
6183 std::optional<uint64_t> ValIntOpt;
6184 if (ValInt.isUnsigned())
6185 ValIntOpt = ValInt.tryZExtValue();
6186 else if (auto tmp = ValInt.trySExtValue())
6187 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6188 // use std::optional::transform
6189 ValIntOpt = static_cast<uint64_t>(*tmp);
6190
6191 if (ValIntOpt)
6192 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6193
6194 return nullptr;
6195}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
#define SM(sm)
Definition: Cuda.cpp:83
static bool IsReconstitutableType(QualType QT)
static void stripUnusedQualifiers(Qualifiers &Q)
static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU)
static bool IsArtificial(VarDecl const *VD)
Returns true if VD is a compiler-generated variable and should be treated as artificial for the purpo...
static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind, bool DebugTypeExtRefs, const RecordDecl *RD, const LangOptions &LangOpts)
static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access, const RecordDecl *RD)
Convert an AccessSpecifier into the corresponding DINode flag.
static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func)
static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C)
static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD)
static llvm::SmallVector< TemplateArgument > GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty)
static bool isFunctionLocalClass(const CXXRecordDecl *RD)
isFunctionLocalClass - Return true if CXXRecordDecl is defined inside a function.
static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:79
static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I, CXXRecordDecl::method_iterator End)
static bool canUseCtorHoming(const CXXRecordDecl *RD)
static bool hasDefaultGetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Getter)
static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD)
Return true if the class or any of its methods are marked dllimport.
static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx)
Definition: CGDebugInfo.cpp:61
static bool hasDefaultSetterName(const ObjCPropertyDecl *PD, const ObjCMethodDecl *Setter)
static bool isDefinedInClangModule(const RecordDecl *RD)
Does a type definition exist in an imported clang module?
static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q)
static bool IsDecomposedVarDecl(VarDecl const *VD)
Returns true if VD is a a holding variable (aka a VarDecl retrieved using BindingDecl::getHoldingVar)...
Definition: CGDebugInfo.cpp:85
static SmallString< 256 > getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM, llvm::DICompileUnit *TheCU)
static unsigned getDwarfCC(CallingConv CC)
static bool ReferencesAnonymousEntity(ArrayRef< TemplateArgument > Args)
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the clang::FileManager interface and associated types.
int Category
Definition: Format.cpp:3004
StringRef Identifier
Definition: Format.cpp:3009
unsigned Iter
Definition: HTMLLogger.cpp:154
llvm::MachO::Target Target
Definition: MachO.h:51
constexpr llvm::StringRef ClangTrapPrefix
Definition: ModuleBuilder.h:32
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2885
SourceLocation Loc
Definition: SemaObjC.cpp:759
Defines the SourceManager interface.
Defines version macros and version-related utility functions for Clang.
__device__ __2f16 float c
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool isFloat() const
Definition: APValue.h:402
bool isInt() const
Definition: APValue.h:401
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
SourceManager & getSourceManager()
Definition: ASTContext.h:721
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
TypedefNameDecl * getTypedefNameForUnnamedTagDecl(const TagDecl *TD)
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getRecordType(const RecordDecl *Decl) const
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getEnumType(const EnumDecl *Decl) const
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
QualType getBlockDescriptorExtendedType() const
Gets the struct used to keep track of the extended descriptor for pointer to blocks.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
bool BlockRequiresCopying(QualType Ty, const VarDecl *D)
Returns true iff we need copy/dispose helpers for the given type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;.
Definition: ASTContext.h:1998
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1120
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2127
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType CharTy
Definition: ASTContext.h:1121
QualType getBlockDescriptorType() const
Gets the struct used to keep track of the descriptor for pointer to blocks.
CanQualType IntTy
Definition: ASTContext.h:1128
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
DeclaratorDecl * getDeclaratorForUnnamedTagDecl(const TagDecl *TD)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
unsigned getTargetAddressSpace(LangAS AS) const
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2425
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:200
CharUnits getVBPtrOffset() const
getVBPtrOffset - Get the offset for virtual base table pointer.
Definition: RecordLayout.h:324
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:234
bool hasExtendableVFPtr() const
hasVFPtr - Does this class have a virtual function table pointer that can be extended by a derived cl...
Definition: RecordLayout.h:288
bool isPrimaryBaseVirtual() const
isPrimaryBaseVirtual - Get whether the primary base for this record is virtual or not.
Definition: RecordLayout.h:242
Abstracts clang modules and precompiled header files and holds everything needed to generate debug in...
ASTFileSignature getSignature() const
std::string getModuleName() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7580
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition: DeclCXX.h:3499
shadow_range shadows() const
Definition: DeclCXX.h:3487
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition: DeclCXX.h:4135
A fixed int type of a specified bitwidth.
Definition: Type.h:7633
bool isUnsigned() const
Definition: Type.h:7643
A class which contains all the information about a particular captured value.
Definition: Decl.h:4477
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition: Decl.h:4502
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition: Decl.h:4492
VarDecl * getVariable() const
The variable being captured.
Definition: Decl.h:4498
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
Pointer to a block type.
Definition: Type.h:3397
QualType getPointeeType() const
Definition: Type.h:3409
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Kind getKind() const
Definition: Type.h:3071
StringRef getName(const PrintingPolicy &Policy) const
Definition: Type.cpp:3283
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
unsigned size_overridden_methods() const
Definition: DeclCXX.cpp:2566
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this method.
Definition: DeclCXX.h:2240
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
QualType getThisType() const
Return the type of the this pointer.
Definition: DeclCXX.cpp:2603
bool isStatic() const
Definition: DeclCXX.cpp:2224
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2160
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1148
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1245
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1023
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1112
method_range methods() const
Definition: DeclCXX.h:662
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1260
method_iterator method_begin() const
Method begin iterator.
Definition: DeclCXX.h:668
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1944
base_class_range vbases()
Definition: DeclCXX.h:637
ctor_range ctors() const
Definition: DeclCXX.h:682
bool isDynamicClass() const
Definition: DeclCXX.h:586
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool hasDefinition() const
Definition: DeclCXX.h:572
method_iterator method_end() const
Method past-the-end iterator.
Definition: DeclCXX.h:673
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1106
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition: DeclCXX.h:618
A wrapper class around a pointer that always points to its canonical declaration.
Definition: Redeclarable.h:350
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isPositive() const
isPositive - Test whether the quantity is greater than zero.
Definition: CharUnits.h:128
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
CharUnits alignTo(const CharUnits &Align) const
alignTo - Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is ...
Definition: CharUnits.h:201
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
Represents a class template specialization, which refers to a class template with a given set of temp...
llvm::SmallVector< std::pair< std::string, std::string >, 0 > DebugPrefixMap
std::string CoverageNotesFile
The filename with path we use for coverage notes files.
std::string CoverageDataFile
The filename with path we use for coverage data files.
std::string DebugCompilationDir
The string to embed in debug information as the current working directory.
bool hasReducedDebugInfo() const
Check if type and variable info should be emitted.
bool hasMaybeUnusedDebugInfo() const
Check if maybe unused type info should be emitted.
ApplyInlineDebugLocation(CodeGenFunction &CGF, GlobalDecl InlinedFn)
Set up the CodeGenFunction's DebugInfo to produce inline locations for the function InlinedFn.
~ApplyInlineDebugLocation()
Restore everything back to the original state.
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:156
unsigned CXXThisIndex
The field index of 'this' within the block, if there is one.
Definition: CGBlocks.h:162
const BlockDecl * getBlockDecl() const
Definition: CGBlocks.h:305
llvm::StructType * StructureType
Definition: CGBlocks.h:276
const Capture & getCapture(const VarDecl *var) const
Definition: CGBlocks.h:296
virtual CharUnits getVirtualFunctionPrologueThisAdjustment(GlobalDecl GD)
Get the ABI-specific "this" parameter adjustment to apply in the prologue of a virtual function.
Definition: CGCXXABI.h:415
@ RAA_Indirect
Pass it as a pointer to temporary memory.
Definition: CGCXXABI.h:161
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Definition: CGCXXABI.cpp:105
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Definition: CGCXXABI.cpp:114
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Definition: CGCXXABI.cpp:109
MangleContext & getMangleContext()
Gets the mangle context.
Definition: CGCXXABI.h:113
llvm::MDNode * getInlinedAt() const
Definition: CGDebugInfo.h:457
llvm::DIType * getOrCreateStandaloneType(QualType Ty, SourceLocation Loc)
Emit standalone debug info for a type.
void EmitLocation(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate a change in line/column information in the source file.
void EmitGlobalAlias(const llvm::GlobalValue *GV, const GlobalDecl Decl)
Emit information about global variable alias.
void EmitLabel(const LabelDecl *D, CGBuilderTy &Builder)
Emit call to llvm.dbg.label for an label.
void EmitGlobalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about a global variable.
void setInlinedAt(llvm::MDNode *InlinedAt)
Update the current inline scope.
Definition: CGDebugInfo.h:454
void completeUnusedClass(const CXXRecordDecl &D)
void EmitUsingShadowDecl(const UsingShadowDecl &USD)
Emit a shadow decl brought in by a using or using-enum.
void EmitUsingEnumDecl(const UsingEnumDecl &UD)
Emit C++ using-enum declaration.
void EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn)
Constructs the debug code for exiting a function.
void EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke, QualType CalleeType, const FunctionDecl *CalleeDecl)
Emit debug info for an extern function being called.
void EmitUsingDecl(const UsingDecl &UD)
Emit C++ using declaration.
llvm::DIMacroFile * CreateTempMacroFile(llvm::DIMacroFile *Parent, SourceLocation LineLoc, SourceLocation FileLoc)
Create debug info for a file referenced by an #include directive.
void completeTemplateDefinition(const ClassTemplateSpecializationDecl &SD)
void EmitExternalVariable(llvm::GlobalVariable *GV, const VarDecl *Decl)
Emit information about an external variable.
void emitFunctionStart(GlobalDecl GD, SourceLocation Loc, SourceLocation ScopeLoc, QualType FnType, llvm::Function *Fn, bool CurFnIsThunk)
Emit a call to llvm.dbg.function.start to indicate start of a new function.
llvm::DILocalVariable * EmitDeclareOfArgVariable(const VarDecl *Decl, llvm::Value *AI, unsigned ArgNo, CGBuilderTy &Builder, bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an argument variable declaration.
void EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the end of a new lexical block and pop the current block.
void EmitUsingDirective(const UsingDirectiveDecl &UD)
Emit C++ using directive.
void completeRequiredType(const RecordDecl *RD)
void EmitAndRetainType(QualType Ty)
Emit the type even if it might not be used.
void EmitInlineFunctionEnd(CGBuilderTy &Builder)
End an inlined function scope.
void EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc, QualType FnType, llvm::Function *Fn=nullptr)
Emit debug info for a function declaration.
void AddStringLiteralDebugInfo(llvm::GlobalVariable *GV, const StringLiteral *S)
DebugInfo isn't attached to string literals by default.
llvm::DILocalVariable * EmitDeclareOfAutoVariable(const VarDecl *Decl, llvm::Value *AI, CGBuilderTy &Builder, const bool UsePointerValue=false)
Emit call to llvm.dbg.declare for an automatic variable declaration.
void completeClassData(const RecordDecl *RD)
void EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD)
Start a new scope for an inlined function.
void EmitImportDecl(const ImportDecl &ID)
Emit an @import declaration.
void EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block, StringRef Name, unsigned ArgNo, llvm::AllocaInst *LocalAddr, CGBuilderTy &Builder)
Emit call to llvm.dbg.declare for the block-literal argument to a block invocation function.
llvm::DebugLoc SourceLocToDebugLoc(SourceLocation Loc)
CGDebugInfo(CodeGenModule &CGM)
void completeClass(const RecordDecl *RD)
void EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc)
Emit metadata to indicate the beginning of a new lexical block and push the block onto the stack.
void setLocation(SourceLocation Loc)
Update the current source location.
llvm::DIMacro * CreateMacro(llvm::DIMacroFile *Parent, unsigned MType, SourceLocation LineLoc, StringRef Name, StringRef Value)
Create debug info for a macro defined by a #define directive or a macro undefined by a #undef directi...
llvm::DILocation * CreateTrapFailureMessageFor(llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg)
Create a debug location from TrapLocation that adds an artificial inline frame where the frame name i...
llvm::DIType * getOrCreateRecordType(QualType Ty, SourceLocation L)
Emit record type's standalone debug info.
void EmitPseudoVariable(CGBuilderTy &Builder, llvm::Instruction *Value, QualType Ty)
Emit a pseudo variable and debug info for an intermediate value if it does not correspond to a variab...
std::string remapDIPath(StringRef) const
Remap a given path with the current debug prefix map.
void EmitExplicitCastType(QualType Ty)
Emit the type explicitly casted to.
void addHeapAllocSiteMetadata(llvm::CallBase *CallSite, QualType AllocatedTy, SourceLocation Loc)
Add heapallocsite metadata for MSAllocator calls.
void setDwoId(uint64_t Signature)
Module debugging: Support for building PCMs.
QualType getFunctionType(const FunctionDecl *FD, QualType RetTy, const SmallVectorImpl< const VarDecl * > &Args)
llvm::DIType * getOrCreateInterfaceType(QualType Ty, SourceLocation Loc)
Emit an Objective-C interface type standalone debug info.
void completeType(const EnumDecl *ED)
void EmitDeclareOfBlockDeclRefVariable(const VarDecl *variable, llvm::Value *storage, CGBuilderTy &Builder, const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint=nullptr)
Emit call to llvm.dbg.declare for an imported variable declaration in a block.
llvm::DIImportedEntity * EmitNamespaceAlias(const NamespaceAliasDecl &NA)
Emit C++ namespace alias.
unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM, const ObjCInterfaceDecl *ID, const ObjCIvarDecl *Ivar)
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
This class organizes the cross-function state that is used while generating LLVM code.
const PreprocessorOptions & getPreprocessorOpts() const
ConstantAddress GetAddrOfMSGuidDecl(const MSGuidDecl *GD)
Get the address of a GUID.
llvm::Module & getModule() const
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=nullptr, bool ForVTable=false, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the given function.
const IntrusiveRefCntPtr< llvm::vfs::FileSystem > & getFileSystem() const
const LangOptions & getLangOpts() const
int getUniqueBlockCount()
Fetches the global unique block count.
const TargetInfo & getTarget() const
const llvm::DataLayout & getDataLayout() const
CGCXXABI & getCXXABI() const
ItaniumVTableContext & getItaniumVTableContext()
ASTContext & getContext() const
ConstantAddress GetAddrOfTemplateParamObject(const TemplateParamObjectDecl *TPO)
Get the address of a template parameter object.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr, ForDefinition_t IsForDefinition=NotForDefinition)
Return the llvm::Constant for the address of the given global variable.
MicrosoftVTableContext & getMicrosoftVTableContext()
const HeaderSearchOptions & getHeaderSearchOpts() const
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
llvm::LLVMContext & getLLVMContext()
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
llvm::GlobalVariable::LinkageTypes getVTableLinkage(const CXXRecordDecl *RD)
Return the appropriate linkage for the vtable, VTT, and type information of the given class.
Definition: CGVTables.cpp:1081
const GlobalDecl getMangledNameDecl(StringRef)
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
unsigned getTargetAddressSpace(QualType T) const
llvm::Constant * getPointer() const
Definition: Address.h:306
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
virtual bool shouldEmitDWARFBitFieldSeparators() const
Definition: TargetInfo.h:380
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4219
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4240
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4237
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2370
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:2006
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1502
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:580
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
Definition: DeclBase.cpp:537
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:836
bool isFromASTFile() const
Determine whether this declaration came from an AST file (such as a precompiled header or module) rat...
Definition: DeclBase.h:787
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:566
SourceLocation getLocation() const
Definition: DeclBase.h:446
DeclContext * getDeclContext()
Definition: DeclBase.h:455
AccessSpecifier getAccess() const
Definition: DeclBase.h:514
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
unsigned getOwningModuleID() const
Retrieve the global ID of the module that owns this particular declaration.
Definition: DeclBase.cpp:121
bool isObjCZeroArgSelector() const
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
bool isObjCOneArgSelector() const
NameKind getNameKind() const
Determine what kind of name this is.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:731
Represents an enum.
Definition: Decl.h:3844
enumerator_range enumerators() const
Definition: Decl.h:3977
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:4049
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:4004
EnumDecl * getDefinition() const
Definition: Decl.h:3947
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EnumDecl * getDecl() const
Definition: Type.h:5998
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition: Decl.cpp:4630
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Represents a function declaration or definition.
Definition: Decl.h:1932
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3717
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition: Decl.cpp:3511
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2368
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4158
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3603
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition: Decl.cpp:4164
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1948
bool isStatic() const
Definition: Decl.h:2801
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2285
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
QualType desugar() const
Definition: Type.h:5546
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5282
unsigned getNumParams() const
Definition: Type.h:5255
QualType getParamType(unsigned i) const
Definition: Type.h:5257
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
ArrayRef< QualType > param_types() const
Definition: Type.h:5411
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:522
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4638
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
GlobalDecl getCanonicalDecl() const
Definition: GlobalDecl.h:94
DynamicInitKind getDynamicInitKind() const
Definition: GlobalDecl.h:115
const Decl * getDecl() const
Definition: GlobalDecl.h:103
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
unsigned ModuleFileHomeIsCwd
Set the base path of a built module file to be the current working directory.
One of these records is kept for each identifier that is lexed.
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4783
bool isPreprocessed() const
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
CharUnits getVirtualBaseOffsetOffset(const CXXRecordDecl *RD, const CXXRecordDecl *VBase)
Return the offset in chars (relative to the vtable address point) where the offset of the virtual bas...
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3472
Represents the declaration of a label.
Definition: Decl.h:499
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
std::string ModuleName
The module currently being compiled as specified by -fmodule-name.
Definition: LangOptions.h:524
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
bool UseTargetPathSeparator
Indicates whether to use target's platform-specific file separator when FILE macro is used and when c...
Definition: LangOptions.h:587
virtual std::string getLambdaString(const CXXRecordDecl *Lambda)=0
virtual void mangleCXXRTTIName(QualType T, raw_ostream &, bool NormalizeIntegers=false)=0
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4197
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Definition: Type.cpp:5056
QualType getPointeeType() const
Definition: Type.h:3524
const Type * getClass() const
Definition: Type.h:3538
unsigned getVBTableIndex(const CXXRecordDecl *Derived, const CXXRecordDecl *VBase)
Returns the index of VBase in the vbtable of Derived.
MethodVFTableLocation getMethodVFTableLocation(GlobalDecl GD)
const VTableLayout & getVFTableLayout(const CXXRecordDecl *RD, CharUnits VFPtrOffset)
Describes a module or submodule.
Definition: Module.h:105
Module * Parent
The parent of this module.
Definition: Module.h:154
std::string Name
The name of this module.
Definition: Module.h:108
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition: Decl.cpp:1811
void printQualifiedName(raw_ostream &OS) const
Returns a human-readable qualified name for this declaration, like A::B::i, for i being member of nam...
Definition: Decl.cpp:1675
bool isExternallyVisible() const
Definition: Decl.h:408
Represents a C++ namespace alias.
Definition: DeclCXX.h:3124
NamedDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition: DeclCXX.h:3219
Represent a C++ namespace.
Definition: Decl.h:547
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:598
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition: Decl.h:603
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2328
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2596
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7343
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:871
Selector getSelector() const
Definition: DeclObjC.h:327
bool isInstanceMethod() const
Definition: DeclObjC.h:426
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7399
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:7474
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7411
Represents a class type in Objective C.
Definition: Type.h:7145
QualType getBaseType() const
Gets the base type of this object type.
Definition: Type.h:7207
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2804
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
Represents a type parameter type in Objective C.
Definition: Type.h:7071
ObjCTypeParamDecl * getDecl() const
Definition: Type.h:7113
Represents a parameter to a function.
Definition: Decl.h:1722
PipeType - OpenCL20.
Definition: Type.h:7599
QualType getElementType() const
Definition: Type.h:7610
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
Represents an unpacked "presumed" location which can be presented to the user.
unsigned getColumn() const
Return the presumed column number of this location.
const char * getFilename() const
Return the presumed filename of this location.
bool isValid() const
bool isInvalid() const
Return true if this object is invalid or uninitialized.
FileID getFileID() const
A (possibly-)qualified type.
Definition: Type.h:941
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool hasLocalQualifiers() const
Determine whether this particular QualType instance has any qualifiers, without looking through any t...
Definition: Type.h:1068
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
void * getAsOpaquePtr() const
Definition: Type.h:988
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:7690
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:7697
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:4356
The collection of all-type qualifiers we support.
Definition: Type.h:319
static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R)
Returns the common set of qualifiers while removing them from the given sets.
Definition: Type.h:371
void removeObjCLifetime()
Definition: Type.h:538
bool hasConst() const
Definition: Type.h:444
bool hasRestrict() const
Definition: Type.h:464
void removeObjCGCAttr()
Definition: Type.h:510
void removeUnaligned()
Definition: Type.h:502
void removeConst()
Definition: Type.h:446
void removeRestrict()
Definition: Type.h:466
void removeAddressSpace()
Definition: Type.h:583
bool hasVolatile() const
Definition: Type.h:454
bool empty() const
Definition: Type.h:634
void removeVolatile()
Definition: Type.h:456
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3490
Represents a struct/union/class.
Definition: Decl.h:4145
field_iterator field_end() const
Definition: Decl.h:4354
field_range fields() const
Definition: Decl.h:4351
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4336
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:4197
field_iterator field_begin() const
Definition: Decl.cpp:5068
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:297
QualType getPointeeType() const
Definition: Type.h:3446
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
static SmallString< 64 > constructSetterName(StringRef Name)
Return the default setter name for the given identifier.
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
std::string getAsString() const
Derive the full selector name (e.g.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
This class handles loading and caching of source files into memory.
PresumedLoc getPresumedLoc(SourceLocation Loc, bool UseLineDirectives=true) const
Returns the "presumed" location of a SourceLocation specifies.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
Stmt - This represents one statement.
Definition: Stmt.h:84
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
bool isStruct() const
Definition: Decl.h:3764
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3789
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition: Decl.h:3673
bool isUnion() const
Definition: Decl.h:3767
bool isInterface() const
Definition: Decl.h:3765
bool isClass() const
Definition: Decl.h:3766
TagDecl * getDecl() const
Definition: Type.cpp:4076
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
virtual std::optional< unsigned > getDWARFAddressSpace(unsigned AddressSpace) const
Definition: TargetInfo.h:1788
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
virtual unsigned getVtblPtrAddressSpace() const
Definition: TargetInfo.h:1778
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition: TargetInfo.h:476
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
llvm::APSInt getAsIntegral() const
Retrieve the template argument as an integral value.
Definition: TemplateBase.h:363
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
void print(raw_ostream &OS, const PrintingPolicy &Policy, Qualified Qual=Qualified::AsWritten) const
Print the template name.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6480
QualType getAliasedType() const
Get the aliased type, if this is a specialization of a type alias template.
Definition: Type.cpp:4333
ArrayRef< TemplateArgument > template_arguments() const
Definition: Type.h:6548
TemplateName getTemplateName() const
Retrieve the name of the template that we are specializing.
Definition: Type.h:6546
bool isTypeAlias() const
Determine if this template specialization type is for a type alias template that has been substituted...
Definition: Type.h:6539
Represents a declaration of a type.
Definition: Decl.h:3367
const Type * getTypeForDecl() const
Definition: Decl.h:3391
The type-property cache.
Definition: Type.cpp:4437
The base class of the type hierarchy.
Definition: Type.h:1829
bool isVoidType() const
Definition: Type.h:8319
bool isIncompleteArrayType() const
Definition: Type.h:8083
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
Definition: Type.cpp:1867
bool isExtVectorBoolType() const
Definition: Type.h:8123
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2800
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2703
bool isMemberDataPointerType() const
Definition: Type.h:8068
bool isBitIntType() const
Definition: Type.h:8241
bool isComplexIntegerType() const
Definition: Type.cpp:683
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
TypeClass getTypeClass() const
Definition: Type.h:2334
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isRecordType() const
Definition: Type.h:8103
bool isUnionType() const
Definition: Type.cpp:671
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
QualType getUnderlyingType() const
Definition: Decl.h:3464
TypedefNameDecl * getDecl() const
Definition: Type.h:5640
Represents a C++ using-declaration.
Definition: DeclCXX.h:3516
Represents C++ using-directive.
Definition: DeclCXX.h:3019
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition: DeclCXX.cpp:2996
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3717
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3324
static bool hasVtableSlot(const CXXMethodDecl *MD)
Determine whether this function should be assigned a vtable slot.
ArrayRef< VTableComponent > vtable_components() const
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2539
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
const Expr * getInit() const
Definition: Decl.h:1316
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2663
Declaration of a variable template.
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
QualType getElementType() const
Definition: Type.h:4035
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, BlockDecl > blockDecl
Matches block declarations.
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1781
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
@ Result
The result type of a method or function.
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
DynamicInitKind
Definition: GlobalDecl.h:32
@ Dtor_Deleting
Deleting dtor.
Definition: ABI.h:34
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86Pascal
Definition: Specifiers.h:284
@ CC_Swift
Definition: Specifiers.h:293
@ CC_IntelOclBicc
Definition: Specifiers.h:290
@ CC_OpenCLKernel
Definition: Specifiers.h:292
@ CC_PreserveMost
Definition: Specifiers.h:295
@ CC_Win64
Definition: Specifiers.h:285
@ CC_X86ThisCall
Definition: Specifiers.h:282
@ CC_AArch64VectorCall
Definition: Specifiers.h:297
@ CC_AAPCS
Definition: Specifiers.h:288
@ CC_PreserveNone
Definition: Specifiers.h:301
@ CC_C
Definition: Specifiers.h:279
@ CC_AMDGPUKernelCall
Definition: Specifiers.h:299
@ CC_M68kRTD
Definition: Specifiers.h:300
@ CC_SwiftAsync
Definition: Specifiers.h:294
@ CC_X86RegCall
Definition: Specifiers.h:287
@ CC_RISCVVectorCall
Definition: Specifiers.h:302
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_SpirFunction
Definition: Specifiers.h:291
@ CC_AArch64SVEPCS
Definition: Specifiers.h:298
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86_64SysV
Definition: Specifiers.h:286
@ CC_PreserveAll
Definition: Specifiers.h:296
@ CC_X86FastCall
Definition: Specifiers.h:281
@ CC_AAPCS_VFP
Definition: Specifiers.h:289
@ Generic
not a target-specific vector type
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ CXXThis
Parameter for C++ 'this' argument.
@ ObjCSelf
Parameter for Objective-C 'self' argument.
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number,...
Definition: Version.cpp:96
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:123
@ AS_public
Definition: Specifiers.h:124
@ AS_protected
Definition: Specifiers.h:125
@ AS_none
Definition: Specifiers.h:127
@ AS_private
Definition: Specifiers.h:126
unsigned long uint64_t
long int64_t
unsigned int uint32_t
#define true
Definition: stdbool.h:25
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
unsigned IsSigned
Whether the bit-field is signed.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
unsigned char PointerWidthInBits
The width of a pointer into the generic address space.
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
Extra information about a function prototype.
Definition: Type.h:5087
uint64_t Index
Method's index in the vftable.
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned MSVCFormatting
Use whitespace and punctuation like MSVC does.
unsigned SplitTemplateClosers
Whether nested templates must be closed like 'a<b<c> >' rather than 'a<b<c>>'.
unsigned PrintCanonicalTypes
Whether to print types as written or canonically.
unsigned AlwaysIncludeTypeForTemplateArgument
Whether to use type suffixes (eg: 1U) on integral non-type template parameters.
unsigned UsePreferredNames
Whether to use C++ template preferred_name attributes when printing templates.
unsigned UseEnumerators
Whether to print enumerator non-type template parameters with a matching enumerator name or via cast ...
unsigned SuppressInlineNamespace
Suppress printing parts of scope specifiers that correspond to inline namespaces, where the name is u...
const PrintingCallbacks * Callbacks
Callbacks to use to allow the behavior of printing to be customized.
A this pointer adjustment.
Definition: Thunk.h:92
bool isAlignRequired()
Definition: ASTContext.h:166
uint64_t Width
Definition: ASTContext.h:158
unsigned Align
Definition: ASTContext.h:159