Thanks to visit codestin.com
Credit goes to clang.llvm.org

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