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