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