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