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