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