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
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 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1535 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) {
1536 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1537 Size, Align, DWARFAddressSpace);
1538 } else {
1539 SmallVector<llvm::Metadata *, 4> Annots;
1540 CollectBTFTypeTagAnnotations(PointeeTy, Annots);
1541
1542 llvm::DINodeArray Annotations = nullptr;
1543 if (Annots.size() > 0)
1544 Annotations = DBuilder.getOrCreateArray(Annots);
1545 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1546 Align, DWARFAddressSpace, StringRef(),
1547 Annotations);
1548 }
1549}
1550
1551llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1552 llvm::DIType *&Cache) {
1553 if (Cache)
1554 return Cache;
1555 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1556 TheCU, TheCU->getFile(), 0);
1557 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1558 Cache = DBuilder.createPointerType(Cache, Size);
1559 return Cache;
1560}
1561
1562uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1563 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1564 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1565 QualType FType;
1566
1567 // Advanced by calls to CreateMemberType in increments of FType, then
1568 // returned as the overall size of the default elements.
1569 uint64_t FieldOffset = 0;
1570
1571 // Blocks in OpenCL have unique constraints which make the standard fields
1572 // redundant while requiring size and align fields for enqueue_kernel. See
1573 // initializeForBlockHeader in CGBlocks.cpp
1574 if (CGM.getLangOpts().OpenCL) {
1575 FType = CGM.getContext().IntTy;
1576 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1577 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1578 } else {
1579 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1580 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1581 FType = CGM.getContext().IntTy;
1582 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1583 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1584 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1585 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1586 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1587 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1588 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1589 EltTys.push_back(DBuilder.createMemberType(
1590 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1591 FieldOffset, llvm::DINode::FlagZero, DescTy));
1592 FieldOffset += FieldSize;
1593 }
1594
1595 return FieldOffset;
1596}
1597
1598llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1599 llvm::DIFile *Unit) {
1600 SmallVector<llvm::Metadata *, 8> EltTys;
1601 QualType FType;
1602 uint64_t FieldOffset;
1603 llvm::DINodeArray Elements;
1604
1605 FieldOffset = 0;
1606 FType = CGM.getContext().UnsignedLongTy;
1607 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1608 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1609
1610 Elements = DBuilder.getOrCreateArray(EltTys);
1611 EltTys.clear();
1612
1613 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1614
1615 auto *EltTy =
1616 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1617 FieldOffset, 0, Flags, nullptr, Elements);
1618
1619 // Bit size, align and offset of the type.
1620 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1621
1622 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1623
1624 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1625 0, EltTys);
1626
1627 Elements = DBuilder.getOrCreateArray(EltTys);
1628
1629 // The __block_literal_generic structs are marked with a special
1630 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1631 // the debugger needs to know about. To allow type uniquing, emit
1632 // them without a name or a location.
1633 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1634 Flags, nullptr, Elements);
1635
1636 return DBuilder.createPointerType(EltTy, Size);
1637}
1638
1639static llvm::SmallVector<TemplateArgument>
1640GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) {
1641 assert(Ty->isTypeAlias());
1642 // TemplateSpecializationType doesn't know if its template args are
1643 // being substituted into a parameter pack. We can find out if that's
1644 // the case now by inspecting the TypeAliasTemplateDecl template
1645 // parameters. Insert Ty's template args into SpecArgs, bundling args
1646 // passed to a parameter pack into a TemplateArgument::Pack. It also
1647 // doesn't know the value of any defaulted args, so collect those now
1648 // too.
1650 ArrayRef SubstArgs = Ty->template_arguments();
1651 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1652 // If Param is a parameter pack, pack the remaining arguments.
1653 if (Param->isParameterPack()) {
1654 SpecArgs.push_back(TemplateArgument(SubstArgs));
1655 break;
1656 }
1657
1658 // Skip defaulted args.
1659 // FIXME: Ideally, we wouldn't do this. We can read the default values
1660 // for each parameter. However, defaulted arguments which are dependent
1661 // values or dependent types can't (easily?) be resolved here.
1662 if (SubstArgs.empty()) {
1663 // If SubstArgs is now empty (we're taking from it each iteration) and
1664 // this template parameter isn't a pack, then that should mean we're
1665 // using default values for the remaining template parameters (after
1666 // which there may be an empty pack too which we will ignore).
1667 break;
1668 }
1669
1670 // Take the next argument.
1671 SpecArgs.push_back(SubstArgs.front());
1672 SubstArgs = SubstArgs.drop_front();
1673 }
1674 return SpecArgs;
1675}
1676
1677llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1678 llvm::DIFile *Unit) {
1679 assert(Ty->isTypeAlias());
1680 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1681
1682 const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl();
1684 return Src;
1685
1686 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1687 if (AliasDecl->hasAttr<NoDebugAttr>())
1688 return Src;
1689
1690 SmallString<128> NS;
1691 llvm::raw_svector_ostream OS(NS);
1692
1693 auto PP = getPrintingPolicy();
1694 Ty->getTemplateName().print(OS, PP, TemplateName::Qualified::None);
1695
1696 SourceLocation Loc = AliasDecl->getLocation();
1697
1698 if (CGM.getCodeGenOpts().DebugTemplateAlias) {
1699 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1700 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1701
1702 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1703 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1704 // doesn't have instantiation information, so
1705 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1706 // template args.
1707 std::string Name;
1708 llvm::raw_string_ostream OS(Name);
1709 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1710 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1711 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1712 !HasReconstitutableArgs(Args.Args))
1713 printTemplateArgumentList(OS, Args.Args, PP);
1714
1715 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1716 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1717 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1718 return AliasTy;
1719 }
1720
1721 printTemplateArgumentList(OS, Ty->template_arguments(), PP,
1722 TD->getTemplateParameters());
1723 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1724 getLineNumber(Loc),
1725 getDeclContextDescriptor(AliasDecl));
1726}
1727
1728/// Convert an AccessSpecifier into the corresponding DINode flag.
1729/// As an optimization, return 0 if the access specifier equals the
1730/// default for the containing type.
1731static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1732 const RecordDecl *RD) {
1734 if (RD && RD->isClass())
1736 else if (RD && (RD->isStruct() || RD->isUnion()))
1738
1739 if (Access == Default)
1740 return llvm::DINode::FlagZero;
1741
1742 switch (Access) {
1743 case clang::AS_private:
1744 return llvm::DINode::FlagPrivate;
1746 return llvm::DINode::FlagProtected;
1747 case clang::AS_public:
1748 return llvm::DINode::FlagPublic;
1749 case clang::AS_none:
1750 return llvm::DINode::FlagZero;
1751 }
1752 llvm_unreachable("unexpected access enumerator");
1753}
1754
1755llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1756 llvm::DIFile *Unit) {
1757 llvm::DIType *Underlying =
1758 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1759
1760 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1761 return Underlying;
1762
1763 // We don't set size information, but do specify where the typedef was
1764 // declared.
1765 SourceLocation Loc = Ty->getDecl()->getLocation();
1766
1767 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1768
1769 // Typedefs are derived from some other type. Collect both btf_decl_tag
1770 // annotations on the typedef declaration and btf_type_tag annotations on
1771 // the (possibly non-pointer) underlying type, e.g.
1772 // typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1773 SmallVector<llvm::Metadata *, 4> Annots;
1774 llvm::DINodeArray Annotations;
1775 CollectBTFTypeTagAnnotations(Ty->getDecl()->getUnderlyingType(), Annots);
1776 CollectBTFDeclTagAnnotations(Ty->getDecl(), Annots);
1777 if (!Annots.empty())
1778 Annotations = DBuilder.getOrCreateArray(Annots);
1779
1780 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1781 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1782 if (isa<RecordDecl>(DC))
1783 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1784
1785 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1786 getOrCreateFile(Loc), getLineNumber(Loc),
1787 getDeclContextDescriptor(Ty->getDecl()), Align,
1788 Flags, Annotations);
1789}
1790
1791static unsigned getDwarfCC(CallingConv CC) {
1792 switch (CC) {
1793 case CC_C:
1794 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1795 return 0;
1796
1797 case CC_X86StdCall:
1798 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1799 case CC_X86FastCall:
1800 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1801 case CC_X86ThisCall:
1802 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1803 case CC_X86VectorCall:
1804 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1805 case CC_X86Pascal:
1806 return llvm::dwarf::DW_CC_BORLAND_pascal;
1807 case CC_Win64:
1808 return llvm::dwarf::DW_CC_LLVM_Win64;
1809 case CC_X86_64SysV:
1810 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1811 case CC_AAPCS:
1813 case CC_AArch64SVEPCS:
1814 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1815 case CC_AAPCS_VFP:
1816 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1817 case CC_IntelOclBicc:
1818 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1819 case CC_SpirFunction:
1820 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1821 case CC_DeviceKernel:
1822 return llvm::dwarf::DW_CC_LLVM_DeviceKernel;
1823 case CC_Swift:
1824 return llvm::dwarf::DW_CC_LLVM_Swift;
1825 case CC_SwiftAsync:
1826 return llvm::dwarf::DW_CC_LLVM_SwiftTail;
1827 case CC_PreserveMost:
1828 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1829 case CC_PreserveAll:
1830 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1831 case CC_X86RegCall:
1832 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1833 case CC_M68kRTD:
1834 return llvm::dwarf::DW_CC_LLVM_M68kRTD;
1835 case CC_PreserveNone:
1836 return llvm::dwarf::DW_CC_LLVM_PreserveNone;
1837 case CC_RISCVVectorCall:
1838 return llvm::dwarf::DW_CC_LLVM_RISCVVectorCall;
1839#define CC_VLS_CASE(ABI_VLEN) case CC_RISCVVLSCall_##ABI_VLEN:
1840 CC_VLS_CASE(32)
1841 CC_VLS_CASE(64)
1842 CC_VLS_CASE(128)
1843 CC_VLS_CASE(256)
1844 CC_VLS_CASE(512)
1845 CC_VLS_CASE(1024)
1846 CC_VLS_CASE(2048)
1847 CC_VLS_CASE(4096)
1848 CC_VLS_CASE(8192)
1849 CC_VLS_CASE(16384)
1850 CC_VLS_CASE(32768)
1851 CC_VLS_CASE(65536)
1852#undef CC_VLS_CASE
1853 return llvm::dwarf::DW_CC_LLVM_RISCVVLSCall;
1854 }
1855 return 0;
1856}
1857
1858static llvm::DINode::DIFlags getRefFlags(const FunctionProtoType *Func) {
1859 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1860 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1861 Flags |= llvm::DINode::FlagLValueReference;
1862 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1863 Flags |= llvm::DINode::FlagRValueReference;
1864 return Flags;
1865}
1866
1867llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1868 llvm::DIFile *Unit) {
1869 const auto *FPT = dyn_cast<FunctionProtoType>(Ty);
1870 if (FPT) {
1871 if (llvm::DIType *QTy = CreateQualifiedType(FPT, Unit))
1872 return QTy;
1873 }
1874
1875 // Create the type without any qualifiers
1876
1877 SmallVector<llvm::Metadata *, 16> EltTys;
1878
1879 // Add the result type at least.
1880 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1881
1882 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1883 // Set up remainder of arguments if there is a prototype.
1884 // otherwise emit it as a variadic function.
1885 if (!FPT) {
1886 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1887 } else {
1888 Flags = getRefFlags(FPT);
1889 for (const QualType &ParamType : FPT->param_types())
1890 EltTys.push_back(getOrCreateType(ParamType, Unit));
1891 if (FPT->isVariadic())
1892 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1893 }
1894
1895 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1896 llvm::DIType *F = DBuilder.createSubroutineType(
1897 EltTypeArray, Flags, getDwarfCC(Ty->getCallConv()));
1898 return F;
1899}
1900
1901llvm::DIDerivedType *
1902CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1903 llvm::DIScope *RecordTy, const RecordDecl *RD) {
1904 StringRef Name = BitFieldDecl->getName();
1905 QualType Ty = BitFieldDecl->getType();
1906 if (BitFieldDecl->hasAttr<PreferredTypeAttr>())
1907 Ty = BitFieldDecl->getAttr<PreferredTypeAttr>()->getType();
1908 SourceLocation Loc = BitFieldDecl->getLocation();
1909 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1910 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1911
1912 // Get the location for the field.
1913 llvm::DIFile *File = getOrCreateFile(Loc);
1914 unsigned Line = getLineNumber(Loc);
1915
1916 const CGBitFieldInfo &BitFieldInfo =
1917 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1918 uint64_t SizeInBits = BitFieldInfo.Size;
1919 assert(SizeInBits > 0 && "found named 0-width bitfield");
1920 uint64_t StorageOffsetInBits =
1921 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1922 uint64_t Offset = BitFieldInfo.Offset;
1923 // The bit offsets for big endian machines are reversed for big
1924 // endian target, compensate for that as the DIDerivedType requires
1925 // un-reversed offsets.
1926 if (CGM.getDataLayout().isBigEndian())
1927 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1928 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1929 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1930 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(BitFieldDecl);
1931 return DBuilder.createBitFieldMemberType(
1932 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1933 Flags, DebugType, Annotations);
1934}
1935
1936llvm::DIDerivedType *CGDebugInfo::createBitFieldSeparatorIfNeeded(
1937 const FieldDecl *BitFieldDecl, const llvm::DIDerivedType *BitFieldDI,
1938 llvm::ArrayRef<llvm::Metadata *> PreviousFieldsDI, const RecordDecl *RD) {
1939
1940 if (!CGM.getTargetCodeGenInfo().shouldEmitDWARFBitFieldSeparators())
1941 return nullptr;
1942
1943 /*
1944 Add a *single* zero-bitfield separator between two non-zero bitfields
1945 separated by one or more zero-bitfields. This is used to distinguish between
1946 structures such the ones below, where the memory layout is the same, but how
1947 the ABI assigns fields to registers differs.
1948
1949 struct foo {
1950 int space[4];
1951 char a : 8; // on amdgpu, passed on v4
1952 char b : 8;
1953 char x : 8;
1954 char y : 8;
1955 };
1956 struct bar {
1957 int space[4];
1958 char a : 8; // on amdgpu, passed on v4
1959 char b : 8;
1960 char : 0;
1961 char x : 8; // passed on v5
1962 char y : 8;
1963 };
1964 */
1965 if (PreviousFieldsDI.empty())
1966 return nullptr;
1967
1968 // If we already emitted metadata for a 0-length bitfield, nothing to do here.
1969 auto *PreviousMDEntry =
1970 PreviousFieldsDI.empty() ? nullptr : PreviousFieldsDI.back();
1971 auto *PreviousMDField =
1972 dyn_cast_or_null<llvm::DIDerivedType>(PreviousMDEntry);
1973 if (!PreviousMDField || !PreviousMDField->isBitField() ||
1974 PreviousMDField->getSizeInBits() == 0)
1975 return nullptr;
1976
1977 auto PreviousBitfield = RD->field_begin();
1978 std::advance(PreviousBitfield, BitFieldDecl->getFieldIndex() - 1);
1979
1980 assert(PreviousBitfield->isBitField());
1981
1982 if (!PreviousBitfield->isZeroLengthBitField())
1983 return nullptr;
1984
1985 QualType Ty = PreviousBitfield->getType();
1986 SourceLocation Loc = PreviousBitfield->getLocation();
1987 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1988 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1989 llvm::DIScope *RecordTy = BitFieldDI->getScope();
1990
1991 llvm::DIFile *File = getOrCreateFile(Loc);
1992 unsigned Line = getLineNumber(Loc);
1993
1994 uint64_t StorageOffsetInBits =
1995 cast<llvm::ConstantInt>(BitFieldDI->getStorageOffsetInBits())
1996 ->getZExtValue();
1997
1998 llvm::DINode::DIFlags Flags =
1999 getAccessFlag(PreviousBitfield->getAccess(), RD);
2000 llvm::DINodeArray Annotations =
2001 CollectBTFDeclTagAnnotations(*PreviousBitfield);
2002 return DBuilder.createBitFieldMemberType(
2003 RecordTy, "", File, Line, 0, StorageOffsetInBits, StorageOffsetInBits,
2004 Flags, DebugType, Annotations);
2005}
2006
2007llvm::DIType *CGDebugInfo::createFieldType(
2008 StringRef name, QualType type, SourceLocation loc, AccessSpecifier AS,
2009 uint64_t offsetInBits, uint32_t AlignInBits, llvm::DIFile *tunit,
2010 llvm::DIScope *scope, const RecordDecl *RD, llvm::DINodeArray Annotations) {
2011 llvm::DIType *debugType = getOrCreateType(type, tunit);
2012
2013 // Get the location for the field.
2014 llvm::DIFile *file = getOrCreateFile(loc);
2015 const unsigned line = getLineNumber(loc.isValid() ? loc : CurLoc);
2016
2017 uint64_t SizeInBits = 0;
2018 auto Align = AlignInBits;
2019 if (!type->isIncompleteArrayType()) {
2020 TypeInfo TI = CGM.getContext().getTypeInfo(type);
2021 SizeInBits = TI.Width;
2022 if (!Align)
2023 Align = getTypeAlignIfRequired(type, CGM.getContext());
2024 }
2025
2026 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
2027 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
2028 offsetInBits, flags, debugType, Annotations);
2029}
2030
2031llvm::DISubprogram *
2032CGDebugInfo::createInlinedSubprogram(StringRef FuncName,
2033 llvm::DIFile *FileScope) {
2034 // We are caching the subprogram because we don't want to duplicate
2035 // subprograms with the same message. Note that `SPFlagDefinition` prevents
2036 // subprograms from being uniqued.
2037 llvm::DISubprogram *&SP = InlinedSubprogramMap[FuncName];
2038
2039 if (!SP) {
2040 llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(nullptr);
2041 SP = DBuilder.createFunction(
2042 /*Scope=*/FileScope, /*Name=*/FuncName, /*LinkageName=*/StringRef(),
2043 /*File=*/FileScope, /*LineNo=*/0, /*Ty=*/DIFnTy,
2044 /*ScopeLine=*/0,
2045 /*Flags=*/llvm::DINode::FlagArtificial,
2046 /*SPFlags=*/llvm::DISubprogram::SPFlagDefinition,
2047 /*TParams=*/nullptr, /*Decl=*/nullptr, /*ThrownTypes=*/nullptr,
2048 /*Annotations=*/nullptr, /*TargetFuncName=*/StringRef(),
2049 /*UseKeyInstructions=*/CGM.getCodeGenOpts().DebugKeyInstructions);
2050 }
2051
2052 return SP;
2053}
2054
2055llvm::StringRef
2056CGDebugInfo::GetLambdaCaptureName(const LambdaCapture &Capture) {
2057 if (Capture.capturesThis())
2058 return CGM.getCodeGenOpts().EmitCodeView ? "__this" : "this";
2059
2060 assert(Capture.capturesVariable());
2061
2062 const ValueDecl *CaptureDecl = Capture.getCapturedVar();
2063 assert(CaptureDecl && "Expected valid decl for captured variable.");
2064
2065 return CaptureDecl->getName();
2066}
2067
2068void CGDebugInfo::CollectRecordLambdaFields(
2069 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
2070 llvm::DIType *RecordTy) {
2071 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
2072 // has the name and the location of the variable so we should iterate over
2073 // both concurrently.
2075 unsigned fieldno = 0;
2077 E = CXXDecl->captures_end();
2078 I != E; ++I, ++Field, ++fieldno) {
2079 const LambdaCapture &Capture = *I;
2080 const uint64_t FieldOffset =
2081 CGM.getContext().getASTRecordLayout(CXXDecl).getFieldOffset(fieldno);
2082
2083 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
2084
2085 SourceLocation Loc;
2086 uint32_t Align = 0;
2087
2088 if (Capture.capturesThis()) {
2089 // TODO: Need to handle 'this' in some way by probably renaming the
2090 // this of the lambda class and having a field member of 'this' or
2091 // by using AT_object_pointer for the function and having that be
2092 // used as 'this' for semantic references.
2093 Loc = Field->getLocation();
2094 } else if (Capture.capturesVariable()) {
2095 Loc = Capture.getLocation();
2096
2097 const ValueDecl *CaptureDecl = Capture.getCapturedVar();
2098 assert(CaptureDecl && "Expected valid decl for captured variable.");
2099
2100 Align = getDeclAlignIfRequired(CaptureDecl, CGM.getContext());
2101 } else {
2102 continue;
2103 }
2104
2105 llvm::DIFile *VUnit = getOrCreateFile(Loc);
2106
2107 elements.push_back(createFieldType(
2108 GetLambdaCaptureName(Capture), Field->getType(), Loc,
2109 Field->getAccess(), FieldOffset, Align, VUnit, RecordTy, CXXDecl));
2110 }
2111}
2112
2113/// Build an llvm::ConstantDataArray from the initialized elements of an
2114/// APValue array, using the narrowest integer type that fits the element width.
2115template <typename T>
2116static llvm::Constant *
2117buildConstantDataArrayFromElements(llvm::LLVMContext &Ctx, const APValue &Arr) {
2118 const unsigned NumElts = Arr.getArraySize();
2119 SmallVector<T, 64> Vals(
2120 NumElts,
2121 Arr.hasArrayFiller()
2122 ? static_cast<T>(Arr.getArrayFiller().getInt().getZExtValue())
2123 : 0);
2124 for (unsigned I : llvm::seq(Arr.getArrayInitializedElts()))
2125 Vals[I] =
2126 static_cast<T>(Arr.getArrayInitializedElt(I).getInt().getZExtValue());
2127 return llvm::ConstantDataArray::get(Ctx, Vals);
2128}
2129
2130/// Try to create an llvm::Constant for a constexpr array of integer elements.
2131/// Handles arrays of char, short, int, long with element width up to 64 bits.
2132/// Returns nullptr if the array cannot be represented.
2134 const VarDecl *Var,
2135 const APValue *Value) {
2136 const auto *ArrayTy = CGM.getContext().getAsConstantArrayType(Var->getType());
2137 if (!ArrayTy)
2138 return nullptr;
2139
2140 const QualType ElemQTy = ArrayTy->getElementType();
2141 if (ElemQTy.isNull() || !ElemQTy->isIntegerType())
2142 return nullptr;
2143
2144 const uint64_t ElemBitWidth = CGM.getContext().getTypeSize(ElemQTy);
2145
2146 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2147 switch (ElemBitWidth) {
2148 case 8:
2150 case 16:
2152 case 32:
2154 case 64:
2156 default:
2157 // ConstantDataArray only supports 8/16/32/64-bit elements.
2158 // Wider types (e.g. __int128) are not representable.
2159 return nullptr;
2160 }
2161}
2162
2163llvm::DIDerivedType *
2164CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
2165 const RecordDecl *RD) {
2166 // Create the descriptor for the static variable, with or without
2167 // constant initializers.
2168 Var = Var->getCanonicalDecl();
2169 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
2170 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
2171
2172 unsigned LineNumber = getLineNumber(Var->getLocation());
2173 StringRef VName = Var->getName();
2174
2175 // FIXME: to avoid complications with type merging we should
2176 // emit the constant on the definition instead of the declaration.
2177 llvm::Constant *C = nullptr;
2178 if (Var->getInit()) {
2179 const APValue *Value = Var->evaluateValue();
2180 if (Value) {
2181 if (Value->isInt())
2182 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
2183 if (Value->isFloat())
2184 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
2185 if (Value->isArray())
2187 }
2188 }
2189
2190 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
2191 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
2192 ? llvm::dwarf::DW_TAG_variable
2193 : llvm::dwarf::DW_TAG_member;
2194 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
2195 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
2196 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Tag, Align);
2197 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
2198 return GV;
2199}
2200
2201void CGDebugInfo::CollectRecordNormalField(
2202 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
2203 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
2204 const RecordDecl *RD) {
2205 StringRef name = field->getName();
2206 QualType type = field->getType();
2207
2208 // Ignore unnamed fields unless they're anonymous structs/unions.
2209 if (name.empty() && !type->isRecordType())
2210 return;
2211
2212 llvm::DIType *FieldType;
2213 if (field->isBitField()) {
2214 llvm::DIDerivedType *BitFieldType;
2215 FieldType = BitFieldType = createBitFieldType(field, RecordTy, RD);
2216 if (llvm::DIType *Separator =
2217 createBitFieldSeparatorIfNeeded(field, BitFieldType, elements, RD))
2218 elements.push_back(Separator);
2219 } else {
2220 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
2221 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(field);
2222 FieldType =
2223 createFieldType(name, type, field->getLocation(), field->getAccess(),
2224 OffsetInBits, Align, tunit, RecordTy, RD, Annotations);
2225 }
2226
2227 elements.push_back(FieldType);
2228}
2229
2230void CGDebugInfo::CollectRecordNestedType(
2231 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
2232 QualType Ty = CGM.getContext().getTypeDeclType(TD);
2233 // Injected class names are not considered nested records.
2234 // FIXME: Is this supposed to be testing for injected class name declarations
2235 // instead?
2237 return;
2238 SourceLocation Loc = TD->getLocation();
2239 if (llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc)))
2240 elements.push_back(nestedType);
2241}
2242
2243void CGDebugInfo::CollectRecordFields(
2244 const RecordDecl *record, llvm::DIFile *tunit,
2245 SmallVectorImpl<llvm::Metadata *> &elements,
2246 llvm::DICompositeType *RecordTy) {
2247 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
2248
2249 if (CXXDecl && CXXDecl->isLambda())
2250 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
2251 else {
2252 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
2253
2254 // Field number for non-static fields.
2255 unsigned fieldNo = 0;
2256
2257 // Static and non-static members should appear in the same order as
2258 // the corresponding declarations in the source program.
2259 for (const auto *I : record->decls())
2260 if (const auto *V = dyn_cast<VarDecl>(I)) {
2261 if (V->hasAttr<NoDebugAttr>())
2262 continue;
2263
2264 // Skip variable template specializations when emitting CodeView. MSVC
2265 // doesn't emit them.
2266 if (CGM.getCodeGenOpts().EmitCodeView &&
2268 continue;
2269
2271 continue;
2272
2273 // Reuse the existing static member declaration if one exists
2274 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
2275 if (MI != StaticDataMemberCache.end()) {
2276 assert(MI->second &&
2277 "Static data member declaration should still exist");
2278 elements.push_back(MI->second);
2279 } else {
2280 auto Field = CreateRecordStaticField(V, RecordTy, record);
2281 elements.push_back(Field);
2282 }
2283 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
2284 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
2285 elements, RecordTy, record);
2286
2287 // Bump field number for next field.
2288 ++fieldNo;
2289 } else if (CGM.getCodeGenOpts().EmitCodeView) {
2290 // Debug info for nested types is included in the member list only for
2291 // CodeView.
2292 if (const auto *nestedType = dyn_cast<TypeDecl>(I)) {
2293 // MSVC doesn't generate nested type for anonymous struct/union.
2294 if (isa<RecordDecl>(I) &&
2295 cast<RecordDecl>(I)->isAnonymousStructOrUnion())
2296 continue;
2297 if (!nestedType->isImplicit() &&
2298 nestedType->getDeclContext() == record)
2299 CollectRecordNestedType(nestedType, elements);
2300 }
2301 }
2302 }
2303}
2304
2305llvm::DISubroutineType *
2306CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
2307 llvm::DIFile *Unit) {
2308 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
2309 if (Method->isStatic())
2310 return cast_or_null<llvm::DISubroutineType>(
2311 getOrCreateType(QualType(Func, 0), Unit));
2312
2313 QualType ThisType;
2314 if (!Method->hasCXXExplicitFunctionObjectParameter())
2315 ThisType = Method->getThisType();
2316
2317 return getOrCreateInstanceMethodType(ThisType, Func, Unit);
2318}
2319
2320llvm::DISubroutineType *CGDebugInfo::getOrCreateMethodTypeForDestructor(
2321 const CXXMethodDecl *Method, llvm::DIFile *Unit, QualType FNType) {
2322 const FunctionProtoType *Func = FNType->getAs<FunctionProtoType>();
2323 // skip the first param since it is also this
2324 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit, true);
2325}
2326
2327llvm::DISubroutineType *
2328CGDebugInfo::getOrCreateInstanceMethodType(QualType ThisPtr,
2329 const FunctionProtoType *Func,
2330 llvm::DIFile *Unit, bool SkipFirst) {
2331 FunctionProtoType::ExtProtoInfo EPI = Func->getExtProtoInfo();
2332 Qualifiers &Qc = EPI.TypeQuals;
2333 Qc.removeConst();
2334 Qc.removeVolatile();
2335 Qc.removeRestrict();
2336 Qc.removeUnaligned();
2337 // Keep the removed qualifiers in sync with
2338 // CreateQualifiedType(const FunctionPrototype*, DIFile *Unit)
2339 // On a 'real' member function type, these qualifiers are carried on the type
2340 // of the first parameter, not as separate DW_TAG_const_type (etc) decorator
2341 // tags around them. (But, in the raw function types with qualifiers, they have
2342 // to use wrapper types.)
2343
2344 // Add "this" pointer.
2345 const auto *OriginalFunc = cast<llvm::DISubroutineType>(
2346 getOrCreateType(CGM.getContext().getFunctionType(
2347 Func->getReturnType(), Func->getParamTypes(), EPI),
2348 Unit));
2349 llvm::DITypeArray Args = OriginalFunc->getTypeArray();
2350 assert(Args.size() && "Invalid number of arguments!");
2351
2352 SmallVector<llvm::Metadata *, 16> Elts;
2353
2354 // First element is always return type. For 'void' functions it is NULL.
2355 Elts.push_back(Args[0]);
2356
2357 const bool HasExplicitObjectParameter = ThisPtr.isNull();
2358
2359 // "this" pointer is always first argument. For explicit "this"
2360 // parameters, it will already be in Args[1].
2361 if (!HasExplicitObjectParameter) {
2362 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
2363 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
2364 ThisPtrType =
2365 DBuilder.createObjectPointerType(ThisPtrType, /*Implicit=*/true);
2366 Elts.push_back(ThisPtrType);
2367 }
2368
2369 // Copy rest of the arguments.
2370 for (unsigned i = (SkipFirst ? 2 : 1), e = Args.size(); i < e; ++i)
2371 Elts.push_back(Args[i]);
2372
2373 // Attach FlagObjectPointer to the explicit "this" parameter.
2374 if (HasExplicitObjectParameter) {
2375 assert(Elts.size() >= 2 && Args.size() >= 2 &&
2376 "Expected at least return type and object parameter.");
2377 Elts[1] = DBuilder.createObjectPointerType(Args[1], /*Implicit=*/false);
2378 }
2379
2380 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2381
2382 return DBuilder.createSubroutineType(EltTypeArray, OriginalFunc->getFlags(),
2383 getDwarfCC(Func->getCallConv()));
2384}
2385
2386/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
2387/// inside a function.
2388static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
2389 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
2390 return isFunctionLocalClass(NRD);
2392 return true;
2393 return false;
2394}
2395
2396llvm::StringRef
2397CGDebugInfo::GetMethodLinkageName(const CXXMethodDecl *Method) const {
2398 assert(Method);
2399
2400 const bool IsCtorOrDtor =
2402
2403 if (IsCtorOrDtor && !CGM.getCodeGenOpts().DebugStructorDeclLinkageNames)
2404 return {};
2405
2406 // In some ABIs (particularly Itanium) a single ctor/dtor
2407 // corresponds to multiple functions. Attach a "unified"
2408 // linkage name for those (which is the convention GCC uses).
2409 // Otherwise, attach no linkage name.
2410 if (IsCtorOrDtor && !CGM.getTarget().getCXXABI().hasConstructorVariants())
2411 return {};
2412
2413 if (const auto *Ctor = llvm::dyn_cast<CXXConstructorDecl>(Method))
2414 return CGM.getMangledName(GlobalDecl(Ctor, CXXCtorType::Ctor_Unified));
2415
2416 if (const auto *Dtor = llvm::dyn_cast<CXXDestructorDecl>(Method))
2417 return CGM.getMangledName(GlobalDecl(Dtor, CXXDtorType::Dtor_Unified));
2418
2419 return CGM.getMangledName(Method);
2420}
2421
2422bool CGDebugInfo::shouldGenerateVirtualCallSite() const {
2423 // Check general conditions for call site generation.
2424 return ((getCallSiteRelatedAttrs() != llvm::DINode::FlagZero) &&
2425 (CGM.getCodeGenOpts().DwarfVersion >= 5));
2426}
2427
2428llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
2429 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
2430 assert(Method);
2431
2432 StringRef MethodName = getFunctionName(Method);
2433 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
2434
2435 StringRef MethodLinkageName;
2436 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
2437 // property to use here. It may've been intended to model "is non-external
2438 // type" but misses cases of non-function-local but non-external classes such
2439 // as those in anonymous namespaces as well as the reverse - external types
2440 // that are function local, such as those in (non-local) inline functions.
2441 if (!isFunctionLocalClass(Method->getParent()))
2442 MethodLinkageName = GetMethodLinkageName(Method);
2443
2444 // Get the location for the method.
2445 llvm::DIFile *MethodDefUnit = nullptr;
2446 unsigned MethodLine = 0;
2447 if (!Method->isImplicit()) {
2448 MethodDefUnit = getOrCreateFile(Method->getLocation());
2449 MethodLine = getLineNumber(Method->getLocation());
2450 }
2451
2452 // Collect virtual method info.
2453 llvm::DIType *ContainingType = nullptr;
2454 unsigned VIndex = 0;
2455 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2456 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
2457 int ThisAdjustment = 0;
2458
2460 if (Method->isPureVirtual())
2461 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
2462 else
2463 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
2464
2465 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2466 // It doesn't make sense to give a virtual destructor a vtable index,
2467 // since a single destructor has two entries in the vtable.
2469 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
2470 } else {
2471 // Emit MS ABI vftable information. There is only one entry for the
2472 // deleting dtor.
2473 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
2474 GlobalDecl GD =
2475 DD ? GlobalDecl(
2476 DD, CGM.getContext().getTargetInfo().emitVectorDeletingDtors(
2477 CGM.getContext().getLangOpts())
2479 : Dtor_Deleting)
2480 : GlobalDecl(Method);
2481 MethodVFTableLocation ML =
2482 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
2483 VIndex = ML.Index;
2484
2485 // CodeView only records the vftable offset in the class that introduces
2486 // the virtual method. This is possible because, unlike Itanium, the MS
2487 // C++ ABI does not include all virtual methods from non-primary bases in
2488 // the vtable for the most derived class. For example, if C inherits from
2489 // A and B, C's primary vftable will not include B's virtual methods.
2490 if (Method->size_overridden_methods() == 0)
2491 Flags |= llvm::DINode::FlagIntroducedVirtual;
2492
2493 // The 'this' adjustment accounts for both the virtual and non-virtual
2494 // portions of the adjustment. Presumably the debugger only uses it when
2495 // it knows the dynamic type of an object.
2496 ThisAdjustment = CGM.getCXXABI()
2497 .getVirtualFunctionPrologueThisAdjustment(GD)
2498 .getQuantity();
2499 }
2500 ContainingType = RecordTy;
2501 }
2502
2503 if (Method->getCanonicalDecl()->isDeleted())
2504 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
2505
2506 if (Method->isNoReturn())
2507 Flags |= llvm::DINode::FlagNoReturn;
2508
2509 if (Method->isStatic())
2510 Flags |= llvm::DINode::FlagStaticMember;
2511 if (Method->isImplicit())
2512 Flags |= llvm::DINode::FlagArtificial;
2513 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
2514 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
2515 if (CXXC->isExplicit())
2516 Flags |= llvm::DINode::FlagExplicit;
2517 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
2518 if (CXXC->isExplicit())
2519 Flags |= llvm::DINode::FlagExplicit;
2520 }
2521 if (Method->hasPrototype())
2522 Flags |= llvm::DINode::FlagPrototyped;
2523 if (Method->getRefQualifier() == RQ_LValue)
2524 Flags |= llvm::DINode::FlagLValueReference;
2525 if (Method->getRefQualifier() == RQ_RValue)
2526 Flags |= llvm::DINode::FlagRValueReference;
2527 if (!Method->isExternallyVisible())
2528 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
2529 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
2530 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
2531
2532 // In this debug mode, emit type info for a class when its constructor type
2533 // info is emitted.
2534 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor)
2535 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
2536 completeUnusedClass(*CD->getParent());
2537
2538 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2539 llvm::DISubprogram *SP = DBuilder.createMethod(
2540 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2541 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2542 TParamsArray.get(), /*ThrownTypes*/ nullptr,
2543 CGM.getCodeGenOpts().DebugKeyInstructions);
2544
2545 SPCache[Method->getCanonicalDecl()].reset(SP);
2546
2547 return SP;
2548}
2549
2550void CGDebugInfo::CollectCXXMemberFunctions(
2551 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2552 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2553
2554 // Since we want more than just the individual member decls if we
2555 // have templated functions iterate over every declaration to gather
2556 // the functions.
2557 for (const auto *I : RD->decls()) {
2558 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2559 // If the member is implicit, don't add it to the member list. This avoids
2560 // the member being added to type units by LLVM, while still allowing it
2561 // to be emitted into the type declaration/reference inside the compile
2562 // unit.
2563 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2564 // FIXME: Handle Using(Shadow?)Decls here to create
2565 // DW_TAG_imported_declarations inside the class for base decls brought into
2566 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2567 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2568 // referenced)
2569 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2570 continue;
2571
2572 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
2573 continue;
2574
2575 // Reuse the existing member function declaration if it exists.
2576 // It may be associated with the declaration of the type & should be
2577 // reused as we're building the definition.
2578 //
2579 // This situation can arise in the vtable-based debug info reduction where
2580 // implicit members are emitted in a non-vtable TU.
2581 auto MI = SPCache.find(Method->getCanonicalDecl());
2582 EltTys.push_back(MI == SPCache.end()
2583 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2584 : static_cast<llvm::Metadata *>(MI->second));
2585 }
2586}
2587
2588void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2589 SmallVectorImpl<llvm::Metadata *> &EltTys,
2590 llvm::DIType *RecordTy) {
2591 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
2592 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2593 llvm::DINode::FlagZero);
2594
2595 // If we are generating CodeView debug info, we also need to emit records for
2596 // indirect virtual base classes.
2597 if (CGM.getCodeGenOpts().EmitCodeView) {
2598 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2599 llvm::DINode::FlagIndirectVirtualBase);
2600 }
2601}
2602
2603void CGDebugInfo::CollectCXXBasesAux(
2604 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2605 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2607 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2608 llvm::DINode::DIFlags StartingFlags) {
2609 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2610 for (const auto &BI : Bases) {
2611 const auto *Base =
2613 BI.getType()->castAsCanonical<RecordType>()->getDecl())
2614 ->getDefinition();
2615 if (!SeenTypes.insert(Base).second)
2616 continue;
2617 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2618 llvm::DINode::DIFlags BFlags = StartingFlags;
2619 uint64_t BaseOffset;
2620 uint32_t VBPtrOffset = 0;
2621
2622 if (BI.isVirtual()) {
2623 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2624 // virtual base offset offset is -ve. The code generator emits dwarf
2625 // expression where it expects +ve number.
2626 BaseOffset = 0 - CGM.getItaniumVTableContext()
2627 .getVirtualBaseOffsetOffset(RD, Base)
2628 .getQuantity();
2629 } else {
2630 // In the MS ABI, store the vbtable offset, which is analogous to the
2631 // vbase offset offset in Itanium.
2632 BaseOffset =
2633 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
2634 VBPtrOffset = CGM.getContext()
2635 .getASTRecordLayout(RD)
2636 .getVBPtrOffset()
2637 .getQuantity();
2638 }
2639 BFlags |= llvm::DINode::FlagVirtual;
2640 } else
2641 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2642 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2643 // BI->isVirtual() and bits when not.
2644
2645 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2646 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2647 VBPtrOffset, BFlags);
2648 EltTys.push_back(DTy);
2649 }
2650}
2651
2652llvm::DINodeArray
2653CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2654 llvm::DIFile *Unit) {
2655 if (!OArgs)
2656 return llvm::DINodeArray();
2657 TemplateArgs &Args = *OArgs;
2658 SmallVector<llvm::Metadata *, 16> TemplateParams;
2659 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2660 const TemplateArgument &TA = Args.Args[i];
2661 StringRef Name;
2662 const bool defaultParameter = TA.getIsDefaulted();
2663 if (Args.TList)
2664 Name = Args.TList->getParam(i)->getName();
2665
2666 switch (TA.getKind()) {
2668 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2669 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2670 TheCU, Name, TTy, defaultParameter));
2671
2672 } break;
2674 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2675 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2676 TheCU, Name, TTy, defaultParameter,
2677 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2678 } break;
2680 const ValueDecl *D = TA.getAsDecl();
2681 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2682 llvm::DIType *TTy = getOrCreateType(T, Unit);
2683 llvm::Constant *V = nullptr;
2684 // Skip retrieve the value if that template parameter has cuda device
2685 // attribute, i.e. that value is not available at the host side.
2686 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2687 !D->hasAttr<CUDADeviceAttr>()) {
2688 // Variable pointer template parameters have a value that is the address
2689 // of the variable.
2690 if (const auto *VD = dyn_cast<VarDecl>(D))
2691 V = CGM.GetAddrOfGlobalVar(VD);
2692 // Member function pointers have special support for building them,
2693 // though this is currently unsupported in LLVM CodeGen.
2694 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2695 MD && MD->isImplicitObjectMemberFunction())
2696 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2697 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2698 V = CGM.GetAddrOfFunction(FD);
2699 // Member data pointers have special handling too to compute the fixed
2700 // offset within the object.
2701 else if (const auto *MPT =
2702 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2703 // These five lines (& possibly the above member function pointer
2704 // handling) might be able to be refactored to use similar code in
2705 // CodeGenModule::getMemberPointerConstant
2706 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2707 CharUnits chars =
2708 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2709 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2710 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2711 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2712 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2713 if (T->isRecordType())
2714 V = ConstantEmitter(CGM).emitAbstract(
2715 SourceLocation(), TPO->getValue(), TPO->getType());
2716 else
2717 V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2718 }
2719 assert(V && "Failed to find template parameter pointer");
2720 V = V->stripPointerCasts();
2721 }
2722 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2723 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2724 } break;
2726 QualType T = TA.getNullPtrType();
2727 llvm::DIType *TTy = getOrCreateType(T, Unit);
2728 llvm::Constant *V = nullptr;
2729 // Special case member data pointer null values since they're actually -1
2730 // instead of zero.
2731 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2732 // But treat member function pointers as simple zero integers because
2733 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2734 // CodeGen grows handling for values of non-null member function
2735 // pointers then perhaps we could remove this special case and rely on
2736 // EmitNullMemberPointer for member function pointers.
2737 if (MPT->isMemberDataPointer())
2738 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2739 if (!V)
2740 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2741 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2742 TheCU, Name, TTy, defaultParameter, V));
2743 } break;
2745 QualType T = TA.getStructuralValueType();
2746 llvm::DIType *TTy = getOrCreateType(T, Unit);
2747 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2748 SourceLocation(), TA.getAsStructuralValue(), T);
2749 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2750 TheCU, Name, TTy, defaultParameter, V));
2751 } break;
2753 std::string QualName;
2754 llvm::raw_string_ostream OS(QualName);
2756 OS, getPrintingPolicy());
2757 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2758 TheCU, Name, nullptr, QualName, defaultParameter));
2759 break;
2760 }
2762 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2763 TheCU, Name, nullptr,
2764 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2765 break;
2767 const Expr *E = TA.getAsExpr();
2768 QualType T = E->getType();
2769 if (E->isGLValue())
2770 T = CGM.getContext().getLValueReferenceType(T);
2771 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2772 assert(V && "Expression in template argument isn't constant");
2773 llvm::DIType *TTy = getOrCreateType(T, Unit);
2774 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2775 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2776 } break;
2777 // And the following should never occur:
2780 llvm_unreachable(
2781 "These argument types shouldn't exist in concrete types");
2782 }
2783 }
2784 return DBuilder.getOrCreateArray(TemplateParams);
2785}
2786
2787std::optional<CGDebugInfo::TemplateArgs>
2788CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2789 if (FD->getTemplatedKind() ==
2791 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2792 ->getTemplate()
2794 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2795 }
2796 return std::nullopt;
2797}
2798std::optional<CGDebugInfo::TemplateArgs>
2799CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2800 // Always get the full list of parameters, not just the ones from the
2801 // specialization. A partial specialization may have fewer parameters than
2802 // there are arguments.
2803 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2804 if (!TS)
2805 return std::nullopt;
2806 VarTemplateDecl *T = TS->getSpecializedTemplate();
2807 const TemplateParameterList *TList = T->getTemplateParameters();
2808 auto TA = TS->getTemplateArgs().asArray();
2809 return {{TList, TA}};
2810}
2811std::optional<CGDebugInfo::TemplateArgs>
2812CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2813 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2814 // Always get the full list of parameters, not just the ones from the
2815 // specialization. A partial specialization may have fewer parameters than
2816 // there are arguments.
2817 TemplateParameterList *TPList =
2818 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2819 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2820 return {{TPList, TAList.asArray()}};
2821 }
2822 return std::nullopt;
2823}
2824
2825llvm::DINodeArray
2826CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2827 llvm::DIFile *Unit) {
2828 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2829}
2830
2831llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2832 llvm::DIFile *Unit) {
2833 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2834}
2835
2836llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2837 llvm::DIFile *Unit) {
2838 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2839}
2840
2841void CGDebugInfo::CollectBTFDeclTagAnnotations(
2842 const Decl *D, SmallVectorImpl<llvm::Metadata *> &Annotations) {
2843 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2844 llvm::Metadata *Ops[2] = {
2845 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2846 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2847 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2848 }
2849}
2850
2851llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2852 if (!D->hasAttr<BTFDeclTagAttr>())
2853 return nullptr;
2854
2855 SmallVector<llvm::Metadata *, 4> Annotations;
2856 CollectBTFDeclTagAnnotations(D, Annotations);
2857 return DBuilder.getOrCreateArray(Annotations);
2858}
2859
2860void CGDebugInfo::CollectBTFTypeTagAnnotations(
2861 QualType Ty, SmallVectorImpl<llvm::Metadata *> &Annotations) {
2862 const BTFTagAttributedType *BTFAttrTy;
2863 if (auto *Atomic = Ty->getAs<AtomicType>())
2864 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Atomic->getValueType());
2865 else
2866 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Ty);
2867
2868 while (BTFAttrTy) {
2869 StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
2870 if (!Tag.empty()) {
2871 llvm::Metadata *Ops[2] = {
2872 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
2873 llvm::MDString::get(CGM.getLLVMContext(), Tag)};
2874 Annotations.insert(Annotations.begin(),
2875 llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2876 }
2877 BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
2878 }
2879}
2880
2881llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2882 if (VTablePtrType)
2883 return VTablePtrType;
2884
2885 ASTContext &Context = CGM.getContext();
2886
2887 /* Function type */
2888 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2889 llvm::DITypeArray SElements = DBuilder.getOrCreateTypeArray(STy);
2890 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2891 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2892 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2893 std::optional<unsigned> DWARFAddressSpace =
2894 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2895
2896 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2897 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2898 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2899 return VTablePtrType;
2900}
2901
2902StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2903 // Copy the gdb compatible name on the side and use its reference.
2904 return internString("_vptr$", RD->getNameAsString());
2905}
2906
2907// Emit symbol for the debugger that points to the vtable address for
2908// the given class. The symbol is named as '__clang_vtable'.
2909// The debugger does not need to know any details about the contents of the
2910// vtable as it can work this out using its knowledge of the ABI and the
2911// existing information in the DWARF. The type is assumed to be 'void *'.
2912void CGDebugInfo::emitVTableSymbol(llvm::GlobalVariable *VTable,
2913 const CXXRecordDecl *RD) {
2914 if (!CGM.getTarget().getCXXABI().isItaniumFamily())
2915 return;
2916 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2917 return;
2918
2919 // On COFF platform, we shouldn't emit a reference to an external entity (i.e.
2920 // VTable) into debug info, which is constructed within a discardable section.
2921 // If that entity ends up implicitly dllimported from another DLL, the linker
2922 // may produce a runtime pseudo-relocation for it (BFD-ld only. LLD prohibits
2923 // to emit such relocation). If the debug section is stripped, the runtime
2924 // pseudo-relocation points to memory space outside of the module, causing an
2925 // access violation.
2926 if (CGM.getTarget().getTriple().isOSBinFormatCOFF() &&
2927 VTable->isDeclarationForLinker())
2928 return;
2929
2930 ASTContext &Context = CGM.getContext();
2931 StringRef SymbolName = "__clang_vtable";
2932 SourceLocation Loc;
2933 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2934
2935 // We deal with two different contexts:
2936 // - The type for the variable, which is part of the class that has the
2937 // vtable, is placed in the context of the DICompositeType metadata.
2938 // - The DIGlobalVariable for the vtable is put in the DICompileUnitScope.
2939
2940 // The created non-member should be mark as 'artificial'. It will be
2941 // placed inside the scope of the C++ class/structure.
2942 llvm::DIScope *DContext = getContextDescriptor(RD, TheCU);
2943 auto *Ctxt = cast<llvm::DICompositeType>(DContext);
2944 llvm::DIFile *Unit = getOrCreateFile(Loc);
2945 llvm::DIType *VTy = getOrCreateType(VoidPtr, Unit);
2946 llvm::DINode::DIFlags Flags = getAccessFlag(AccessSpecifier::AS_private, RD) |
2947 llvm::DINode::FlagArtificial;
2948 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
2949 ? llvm::dwarf::DW_TAG_variable
2950 : llvm::dwarf::DW_TAG_member;
2951 llvm::DIDerivedType *DT = DBuilder.createStaticMemberType(
2952 Ctxt, SymbolName, Unit, /*LineNumber=*/0, VTy, Flags,
2953 /*Val=*/nullptr, Tag);
2954
2955 // Use the same vtable pointer to global alignment for the symbol.
2956 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2957
2958 // The global variable is in the CU scope, and links back to the type it's
2959 // "within" via the declaration field.
2960 llvm::DIGlobalVariableExpression *GVE =
2961 DBuilder.createGlobalVariableExpression(
2962 TheCU, SymbolName, VTable->getName(), Unit, /*LineNo=*/0,
2963 getOrCreateType(VoidPtr, Unit), VTable->hasLocalLinkage(),
2964 /*isDefined=*/true, nullptr, DT, /*TemplateParameters=*/nullptr,
2965 PAlign);
2966 VTable->addDebugInfo(GVE);
2967}
2968
2969StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2970 DynamicInitKind StubKind,
2971 llvm::Function *InitFn) {
2972 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2973 // arbitrary.
2974 if (!CGM.getCodeGenOpts().EmitCodeView ||
2976 return InitFn->getName();
2977
2978 // Print the normal qualified name for the variable, then break off the last
2979 // NNS, and add the appropriate other text. Clang always prints the global
2980 // variable name without template arguments, so we can use rsplit("::") and
2981 // then recombine the pieces.
2982 SmallString<128> QualifiedGV;
2983 StringRef Quals;
2984 StringRef GVName;
2985 {
2986 llvm::raw_svector_ostream OS(QualifiedGV);
2987 VD->printQualifiedName(OS, getPrintingPolicy());
2988 std::tie(Quals, GVName) = OS.str().rsplit("::");
2989 if (GVName.empty())
2990 std::swap(Quals, GVName);
2991 }
2992
2993 SmallString<128> InitName;
2994 llvm::raw_svector_ostream OS(InitName);
2995 if (!Quals.empty())
2996 OS << Quals << "::";
2997
2998 switch (StubKind) {
3001 llvm_unreachable("not an initializer");
3003 OS << "`dynamic initializer for '";
3004 break;
3006 OS << "`dynamic atexit destructor for '";
3007 break;
3008 }
3009
3010 OS << GVName;
3011
3012 // Add any template specialization args.
3013 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3014 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
3015 getPrintingPolicy());
3016 }
3017
3018 OS << '\'';
3019
3020 return internString(OS.str());
3021}
3022
3023void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
3024 SmallVectorImpl<llvm::Metadata *> &EltTys) {
3025 // If this class is not dynamic then there is not any vtable info to collect.
3026 if (!RD->isDynamicClass())
3027 return;
3028
3029 // Don't emit any vtable shape or vptr info if this class doesn't have an
3030 // extendable vfptr. This can happen if the class doesn't have virtual
3031 // methods, or in the MS ABI if those virtual methods only come from virtually
3032 // inherited bases.
3033 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3034 if (!RL.hasExtendableVFPtr())
3035 return;
3036
3037 // CodeView needs to know how large the vtable of every dynamic class is, so
3038 // emit a special named pointer type into the element list. The vptr type
3039 // points to this type as well.
3040 llvm::DIType *VPtrTy = nullptr;
3041 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
3042 CGM.getTarget().getCXXABI().isMicrosoft();
3043 if (NeedVTableShape) {
3044 uint64_t PtrWidth =
3045 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
3046 const VTableLayout &VFTLayout =
3047 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
3048 unsigned VSlotCount =
3049 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
3050 unsigned VTableWidth = PtrWidth * VSlotCount;
3051 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
3052 std::optional<unsigned> DWARFAddressSpace =
3053 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
3054
3055 // Create a very wide void* type and insert it directly in the element list.
3056 llvm::DIType *VTableType = DBuilder.createPointerType(
3057 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
3058 EltTys.push_back(VTableType);
3059
3060 // The vptr is a pointer to this special vtable type.
3061 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
3062 }
3063
3064 // If there is a primary base then the artificial vptr member lives there.
3065 if (RL.getPrimaryBase())
3066 return;
3067
3068 if (!VPtrTy)
3069 VPtrTy = getOrCreateVTablePtrType(Unit);
3070
3071 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
3072 llvm::DIType *VPtrMember =
3073 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
3074 llvm::DINode::FlagArtificial, VPtrTy);
3075 EltTys.push_back(VPtrMember);
3076}
3077
3079 SourceLocation Loc) {
3080 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3081 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
3082 return T;
3083}
3084
3086 SourceLocation Loc) {
3087 return getOrCreateStandaloneType(D, Loc);
3088}
3089
3091 SourceLocation Loc) {
3092 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3093 assert(!D.isNull() && "null type");
3094 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
3095 assert(T && "could not create debug info for type");
3096
3097 RetainedTypes.push_back(D.getAsOpaquePtr());
3098 return T;
3099}
3100
3102 QualType AllocatedTy,
3103 SourceLocation Loc) {
3104 if (CGM.getCodeGenOpts().getDebugInfo() <=
3105 llvm::codegenoptions::DebugLineTablesOnly)
3106 return;
3107 llvm::MDNode *node;
3108 if (AllocatedTy->isVoidType())
3109 node = llvm::MDNode::get(CGM.getLLVMContext(), {});
3110 else
3111 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
3112
3113 CI->setMetadata("heapallocsite", node);
3114}
3115
3117 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
3118 return;
3119 CanQualType Ty = CGM.getContext().getCanonicalTagType(ED);
3120 void *TyPtr = Ty.getAsOpaquePtr();
3121 auto I = TypeCache.find(TyPtr);
3122 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
3123 return;
3124 llvm::DIType *Res = CreateTypeDefinition(dyn_cast<EnumType>(Ty));
3125 assert(!Res->isForwardDecl());
3126 TypeCache[TyPtr].reset(Res);
3127}
3128
3130 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3131 !CGM.getLangOpts().CPlusPlus)
3133}
3134
3135/// Return true if the class or any of its methods are marked dllimport.
3137 if (RD->hasAttr<DLLImportAttr>())
3138 return true;
3139 for (const CXXMethodDecl *MD : RD->methods())
3140 if (MD->hasAttr<DLLImportAttr>())
3141 return true;
3142 return false;
3143}
3144
3145/// Does a type definition exist in an imported clang module?
3146static bool isDefinedInClangModule(const RecordDecl *RD) {
3147 // Only definitions that where imported from an AST file come from a module.
3148 if (!RD || !RD->isFromASTFile())
3149 return false;
3150 // Anonymous entities cannot be addressed. Treat them as not from module.
3151 if (!RD->isExternallyVisible() && RD->getName().empty())
3152 return false;
3153 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
3154 if (!CXXDecl->isCompleteDefinition())
3155 return false;
3156 // Check wether RD is a template.
3157 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
3158 if (TemplateKind != TSK_Undeclared) {
3159 // Unfortunately getOwningModule() isn't accurate enough to find the
3160 // owning module of a ClassTemplateSpecializationDecl that is inside a
3161 // namespace spanning multiple modules.
3162 bool Explicit = false;
3163 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
3164 Explicit = TD->isExplicitInstantiationOrSpecialization();
3165 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
3166 return false;
3167 // This is a template, check the origin of the first member.
3168 if (CXXDecl->fields().empty())
3169 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
3170 if (!CXXDecl->field_begin()->isFromASTFile())
3171 return false;
3172 }
3173 }
3174 return true;
3175}
3176
3178 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3179 if (CXXRD->isDynamicClass() &&
3180 CGM.getVTableLinkage(CXXRD) ==
3181 llvm::GlobalValue::AvailableExternallyLinkage &&
3183 return;
3184
3185 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3186 return;
3187
3188 completeClass(RD);
3189}
3190
3192 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
3193 return;
3194 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3195 void *TyPtr = Ty.getAsOpaquePtr();
3196 auto I = TypeCache.find(TyPtr);
3197 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
3198 return;
3199
3200 // We want the canonical definition of the structure to not
3201 // be the typedef. Since that would lead to circular typedef
3202 // metadata.
3203 auto [Res, PrefRes] = CreateTypeDefinition(dyn_cast<RecordType>(Ty));
3204 assert(!Res->isForwardDecl());
3205 TypeCache[TyPtr].reset(Res);
3206}
3207
3210 for (CXXMethodDecl *MD : llvm::make_range(I, End))
3212 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
3213 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
3214 return true;
3215 return false;
3216}
3217
3218static bool canUseCtorHoming(const CXXRecordDecl *RD) {
3219 // Constructor homing can be used for classes that cannnot be constructed
3220 // without emitting code for one of their constructors. This is classes that
3221 // don't have trivial or constexpr constructors, or can be created from
3222 // aggregate initialization. Also skip lambda objects because they don't call
3223 // constructors.
3224
3225 // Skip this optimization if the class or any of its methods are marked
3226 // dllimport.
3228 return false;
3229
3230 if (RD->isLambda() || RD->isAggregate() ||
3233 return false;
3234
3235 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
3236 if (Ctor->isCopyOrMoveConstructor())
3237 continue;
3238 if (!Ctor->isDeleted())
3239 return true;
3240 }
3241 return false;
3242}
3243
3244static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
3245 bool DebugTypeExtRefs, const RecordDecl *RD,
3246 const LangOptions &LangOpts) {
3247 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3248 return true;
3249
3250 if (auto *ES = RD->getASTContext().getExternalSource())
3251 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
3252 return true;
3253
3254 // Only emit forward declarations in line tables only to keep debug info size
3255 // small. This only applies to CodeView, since we don't emit types in DWARF
3256 // line tables only.
3257 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
3258 return true;
3259
3260 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3261 RD->hasAttr<StandaloneDebugAttr>())
3262 return false;
3263
3264 if (!LangOpts.CPlusPlus)
3265 return false;
3266
3268 return true;
3269
3270 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3271
3272 if (!CXXDecl)
3273 return false;
3274
3275 // Only emit complete debug info for a dynamic class when its vtable is
3276 // emitted. However, Microsoft debuggers don't resolve type information
3277 // across DLL boundaries, so skip this optimization if the class or any of its
3278 // methods are marked dllimport. This isn't a complete solution, since objects
3279 // without any dllimport methods can be used in one DLL and constructed in
3280 // another, but it is the current behavior of LimitedDebugInfo.
3281 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
3282 !isClassOrMethodDLLImport(CXXDecl) && !CXXDecl->hasAttr<MSNoVTableAttr>())
3283 return true;
3284
3286 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3287 Spec = SD->getSpecializationKind();
3288
3291 CXXDecl->method_end()))
3292 return true;
3293
3294 // In constructor homing mode, only emit complete debug info for a class
3295 // when its constructor is emitted.
3296 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
3297 canUseCtorHoming(CXXDecl))
3298 return true;
3299
3300 return false;
3301}
3302
3304 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
3305 return;
3306
3307 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3308 llvm::DIType *T = getTypeOrNull(Ty);
3309 if (T && T->isForwardDecl())
3311}
3312
3313llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
3314 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3315 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
3316 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
3317 CGM.getLangOpts())) {
3318 if (!T)
3319 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
3320 return T;
3321 }
3322
3323 auto [Def, Pref] = CreateTypeDefinition(Ty);
3324
3325 return Pref ? Pref : Def;
3326}
3327
3328llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
3329 llvm::DIFile *Unit) {
3330 if (!RD)
3331 return nullptr;
3332
3333 auto const *PNA = RD->getAttr<PreferredNameAttr>();
3334 if (!PNA)
3335 return nullptr;
3336
3337 return getOrCreateType(PNA->getTypedefType(), Unit);
3338}
3339
3340std::pair<llvm::DIType *, llvm::DIType *>
3341CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
3342 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3343
3344 // Get overall information about the record type for the debug info.
3345 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3346
3347 // Records and classes and unions can all be recursive. To handle them, we
3348 // first generate a debug descriptor for the struct as a forward declaration.
3349 // Then (if it is a definition) we go through and get debug info for all of
3350 // its members. Finally, we create a descriptor for the complete type (which
3351 // may refer to the forward decl if the struct is recursive) and replace all
3352 // uses of the forward declaration with the final definition.
3353 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
3354
3355 const RecordDecl *D = RD->getDefinition();
3356 if (!D || !D->isCompleteDefinition())
3357 return {FwdDecl, nullptr};
3358
3359 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
3360 CollectContainingType(CXXDecl, FwdDecl);
3361
3362 // Push the struct on region stack.
3363 LexicalBlockStack.emplace_back(&*FwdDecl);
3364 RegionMap[RD].reset(FwdDecl);
3365
3366 // Convert all the elements.
3367 SmallVector<llvm::Metadata *, 16> EltTys;
3368 // what about nested types?
3369
3370 // Note: The split of CXXDecl information here is intentional, the
3371 // gdb tests will depend on a certain ordering at printout. The debug
3372 // information offsets are still correct if we merge them all together
3373 // though.
3374 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3375 if (CXXDecl) {
3376 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
3377 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
3378 }
3379
3380 // Collect data fields (including static variables and any initializers).
3381 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
3382 if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)
3383 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
3384
3385 LexicalBlockStack.pop_back();
3386 RegionMap.erase(RD);
3387
3388 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3389 DBuilder.replaceArrays(FwdDecl, Elements);
3390
3391 if (FwdDecl->isTemporary())
3392 FwdDecl =
3393 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
3394
3395 RegionMap[RD].reset(FwdDecl);
3396
3397 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
3398 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
3399 return {FwdDecl, PrefDI};
3400
3401 return {FwdDecl, nullptr};
3402}
3403
3404llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
3405 llvm::DIFile *Unit) {
3406 // Ignore protocols.
3407 return getOrCreateType(Ty->getBaseType(), Unit);
3408}
3409
3410llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
3411 llvm::DIFile *Unit) {
3412 // Ignore protocols.
3413 SourceLocation Loc = Ty->getDecl()->getLocation();
3414
3415 // Use Typedefs to represent ObjCTypeParamType.
3416 return DBuilder.createTypedef(
3417 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
3418 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
3419 getDeclContextDescriptor(Ty->getDecl()));
3420}
3421
3422/// \return true if Getter has the default name for the property PD.
3424 const ObjCMethodDecl *Getter) {
3425 assert(PD);
3426 if (!Getter)
3427 return true;
3428
3429 assert(Getter->getDeclName().isObjCZeroArgSelector());
3430 return PD->getName() ==
3432}
3433
3434/// \return true if Setter has the default name for the property PD.
3436 const ObjCMethodDecl *Setter) {
3437 assert(PD);
3438 if (!Setter)
3439 return true;
3440
3441 assert(Setter->getDeclName().isObjCOneArgSelector());
3444}
3445
3446llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
3447 llvm::DIFile *Unit) {
3448 ObjCInterfaceDecl *ID = Ty->getDecl();
3449 if (!ID)
3450 return nullptr;
3451
3452 auto RuntimeLang = static_cast<llvm::dwarf::SourceLanguage>(
3453 TheCU->getSourceLanguage().getUnversionedName());
3454
3455 // Return a forward declaration if this type was imported from a clang module,
3456 // and this is not the compile unit with the implementation of the type (which
3457 // may contain hidden ivars).
3458 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
3459 !ID->getImplementation())
3460 return DBuilder.createForwardDecl(
3461 llvm::dwarf::DW_TAG_structure_type, ID->getName(),
3462 getDeclContextDescriptor(ID), Unit, 0, RuntimeLang);
3463
3464 // Get overall information about the record type for the debug info.
3465 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3466 unsigned Line = getLineNumber(ID->getLocation());
3467
3468 // If this is just a forward declaration return a special forward-declaration
3469 // debug type since we won't be able to lay out the entire type.
3470 ObjCInterfaceDecl *Def = ID->getDefinition();
3471 if (!Def || !Def->getImplementation()) {
3472 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3473 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
3474 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
3475 DefUnit, Line, RuntimeLang);
3476 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
3477 return FwdDecl;
3478 }
3479
3480 return CreateTypeDefinition(Ty, Unit);
3481}
3482
3483llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
3484 bool CreateSkeletonCU) {
3485 // Use the Module pointer as the key into the cache. This is a
3486 // nullptr if the "Module" is a PCH, which is safe because we don't
3487 // support chained PCH debug info, so there can only be a single PCH.
3488 const Module *M = Mod.getModuleOrNull();
3489 auto ModRef = ModuleCache.find(M);
3490 if (ModRef != ModuleCache.end())
3491 return cast<llvm::DIModule>(ModRef->second);
3492
3493 // Macro definitions that were defined with "-D" on the command line.
3494 SmallString<128> ConfigMacros;
3495 {
3496 llvm::raw_svector_ostream OS(ConfigMacros);
3497 const auto &PPOpts = CGM.getPreprocessorOpts();
3498 unsigned I = 0;
3499 // Translate the macro definitions back into a command line.
3500 for (auto &M : PPOpts.Macros) {
3501 if (++I > 1)
3502 OS << " ";
3503 const std::string &Macro = M.first;
3504 bool Undef = M.second;
3505 OS << "\"-" << (Undef ? 'U' : 'D');
3506 for (char c : Macro)
3507 switch (c) {
3508 case '\\':
3509 OS << "\\\\";
3510 break;
3511 case '"':
3512 OS << "\\\"";
3513 break;
3514 default:
3515 OS << c;
3516 }
3517 OS << '\"';
3518 }
3519 }
3520
3521 bool IsRootModule = M ? !M->Parent : true;
3522 // When a module name is specified as -fmodule-name, that module gets a
3523 // clang::Module object, but it won't actually be built or imported; it will
3524 // be textual.
3525 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3526 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3527 "clang module without ASTFile must be specified by -fmodule-name");
3528
3529 // Return a StringRef to the remapped Path.
3530 auto RemapPath = [this](StringRef Path) -> std::string {
3531 std::string Remapped = remapDIPath(Path);
3532 StringRef Relative(Remapped);
3533 StringRef CompDir = TheCU->getDirectory();
3534 if (CompDir.empty())
3535 return Remapped;
3536
3537 if (Relative.consume_front(CompDir))
3538 Relative.consume_front(llvm::sys::path::get_separator());
3539
3540 return Relative.str();
3541 };
3542
3543 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3544 // PCH files don't have a signature field in the control block,
3545 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3546 // We use the lower 64 bits for debug info.
3547
3548 uint64_t Signature = 0;
3549 if (const auto &ModSig = Mod.getSignature())
3550 Signature = ModSig.truncatedValue();
3551 else
3552 Signature = ~1ULL;
3553
3554 llvm::DIBuilder DIB(CGM.getModule());
3555 SmallString<0> PCM;
3556 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3557 if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd)
3558 PCM = getCurrentDirname();
3559 else
3560 PCM = Mod.getPath();
3561 }
3562 llvm::sys::path::append(PCM, Mod.getASTFile());
3563 DIB.createCompileUnit(
3564 TheCU->getSourceLanguage(),
3565 // TODO: Support "Source" from external AST providers?
3566 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3567 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3568 llvm::DICompileUnit::FullDebug, Signature);
3569 DIB.finalize();
3570 }
3571
3572 llvm::DIModule *Parent =
3573 IsRootModule ? nullptr
3574 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3575 CreateSkeletonCU);
3576 StringRef IncludePath = Mod.getPath();
3577 if (!CGM.getCodeGenOpts().DebugRecordSysroot) {
3578 StringRef Sysroot = CGM.getHeaderSearchOpts().Sysroot;
3579 if (!Sysroot.empty() && IncludePath.starts_with(Sysroot))
3580 IncludePath = "";
3581 }
3582 llvm::DIModule *DIMod =
3583 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3584 RemapPath(IncludePath));
3585 ModuleCache[M].reset(DIMod);
3586 return DIMod;
3587}
3588
3589llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3590 llvm::DIFile *Unit) {
3591 ObjCInterfaceDecl *ID = Ty->getDecl();
3592 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3593 unsigned Line = getLineNumber(ID->getLocation());
3594
3595 unsigned RuntimeLang = TheCU->getSourceLanguage().getUnversionedName();
3596
3597 // Bit size, align and offset of the type.
3598 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3599 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3600
3601 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3602 if (ID->getImplementation())
3603 Flags |= llvm::DINode::FlagObjcClassComplete;
3604
3605 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3606 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3607 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3608 nullptr, llvm::DINodeArray(), RuntimeLang);
3609
3610 QualType QTy(Ty, 0);
3611 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3612
3613 // Push the struct on region stack.
3614 LexicalBlockStack.emplace_back(RealDecl);
3615 RegionMap[Ty->getDecl()].reset(RealDecl);
3616
3617 // Convert all the elements.
3618 SmallVector<llvm::Metadata *, 16> EltTys;
3619
3620 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3621 if (SClass) {
3622 llvm::DIType *SClassTy =
3623 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3624 if (!SClassTy)
3625 return nullptr;
3626
3627 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3628 llvm::DINode::FlagZero);
3629 EltTys.push_back(InhTag);
3630 }
3631
3632 // Create entries for all of the properties.
3633 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3634 SourceLocation Loc = PD->getLocation();
3635 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3636 unsigned PLine = getLineNumber(Loc);
3637 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3638 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3639 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3640 PD->getName(), PUnit, PLine,
3641 hasDefaultGetterName(PD, Getter) ? ""
3642 : getSelectorName(PD->getGetterName()),
3643 hasDefaultSetterName(PD, Setter) ? ""
3644 : getSelectorName(PD->getSetterName()),
3645 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3646 EltTys.push_back(PropertyNode);
3647 };
3648 {
3649 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3650 // the empty key in the data type (and bool is too small for that).
3651 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3652 /// List of already emitted properties. Two distinct class and instance
3653 /// properties can share the same identifier (but not two instance
3654 /// properties or two class properties).
3655 llvm::DenseSet<IsClassAndIdent> PropertySet;
3656 /// Returns the IsClassAndIdent key for the given property.
3657 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3658 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3659 };
3660 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3661 for (auto *PD : ClassExt->properties()) {
3662 PropertySet.insert(GetIsClassAndIdent(PD));
3663 AddProperty(PD);
3664 }
3665 for (const auto *PD : ID->properties()) {
3666 // Don't emit duplicate metadata for properties that were already in a
3667 // class extension.
3668 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3669 continue;
3670 AddProperty(PD);
3671 }
3672 }
3673
3674 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
3675 unsigned FieldNo = 0;
3676 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3677 Field = Field->getNextIvar(), ++FieldNo) {
3678 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3679 if (!FieldTy)
3680 return nullptr;
3681
3682 StringRef FieldName = Field->getName();
3683
3684 // Ignore unnamed fields.
3685 if (FieldName.empty())
3686 continue;
3687
3688 // Get the location for the field.
3689 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3690 unsigned FieldLine = getLineNumber(Field->getLocation());
3691 QualType FType = Field->getType();
3692 uint64_t FieldSize = 0;
3693 uint32_t FieldAlign = 0;
3694
3695 if (!FType->isIncompleteArrayType()) {
3696
3697 // Bit size, align and offset of the type.
3698 FieldSize = Field->isBitField() ? Field->getBitWidthValue()
3699 : CGM.getContext().getTypeSize(FType);
3700 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3701 }
3702
3703 uint64_t FieldOffset;
3704 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3705 // We don't know the runtime offset of an ivar if we're using the
3706 // non-fragile ABI. For bitfields, use the bit offset into the first
3707 // byte of storage of the bitfield. For other fields, use zero.
3708 if (Field->isBitField()) {
3709 FieldOffset =
3710 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3711 FieldOffset %= CGM.getContext().getCharWidth();
3712 } else {
3713 FieldOffset = 0;
3714 }
3715 } else {
3716 FieldOffset = RL.getFieldOffset(FieldNo);
3717 }
3718
3719 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3720 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3721 Flags = llvm::DINode::FlagProtected;
3722 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3723 Flags = llvm::DINode::FlagPrivate;
3724 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3725 Flags = llvm::DINode::FlagPublic;
3726
3727 if (Field->isBitField())
3728 Flags |= llvm::DINode::FlagBitField;
3729
3730 llvm::MDNode *PropertyNode = nullptr;
3731 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3732 if (ObjCPropertyImplDecl *PImpD =
3733 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3734 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3735 SourceLocation Loc = PD->getLocation();
3736 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3737 unsigned PLine = getLineNumber(Loc);
3738 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3739 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3740 PropertyNode = DBuilder.createObjCProperty(
3741 PD->getName(), PUnit, PLine,
3742 hasDefaultGetterName(PD, Getter)
3743 ? ""
3744 : getSelectorName(PD->getGetterName()),
3745 hasDefaultSetterName(PD, Setter)
3746 ? ""
3747 : getSelectorName(PD->getSetterName()),
3748 PD->getPropertyAttributes(),
3749 getOrCreateType(PD->getType(), PUnit));
3750 }
3751 }
3752 }
3753 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3754 FieldSize, FieldAlign, FieldOffset, Flags,
3755 FieldTy, PropertyNode);
3756 EltTys.push_back(FieldTy);
3757 }
3758
3759 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3760 DBuilder.replaceArrays(RealDecl, Elements);
3761
3762 LexicalBlockStack.pop_back();
3763 return RealDecl;
3764}
3765
3766llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3767 llvm::DIFile *Unit) {
3768 if (Ty->isPackedVectorBoolType(CGM.getContext())) {
3769 // Boolean ext_vector_type(N) are special because their real element type
3770 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3771 // For now, we pretend the boolean vector were actually a vector of bytes
3772 // (where each byte represents 8 bits of the actual vector).
3773 // FIXME Debug info should actually represent this proper as a vector mask
3774 // type.
3775 auto &Ctx = CGM.getContext();
3776 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3777 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3778
3779 // Construct the vector of 'char' type.
3780 QualType CharVecTy =
3781 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3782 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3783 }
3784
3785 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3786 int64_t Count = Ty->getNumElements();
3787
3788 llvm::Metadata *Subscript;
3789 QualType QTy(Ty, 0);
3790 auto SizeExpr = SizeExprCache.find(QTy);
3791 if (SizeExpr != SizeExprCache.end())
3792 Subscript = DBuilder.getOrCreateSubrange(
3793 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3794 nullptr /*upperBound*/, nullptr /*stride*/);
3795 else {
3796 auto *CountNode =
3797 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3798 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3799 Subscript = DBuilder.getOrCreateSubrange(
3800 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3801 nullptr /*stride*/);
3802 }
3803 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3804
3805 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3806 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3807
3808 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3809}
3810
3811llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3812 llvm::DIFile *Unit) {
3813 // FIXME: Create another debug type for matrices
3814 // For the time being, it treats it like a nested ArrayType.
3815
3816 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3817 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3818 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3819
3820 // Create ranges for both dimensions.
3821 llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3822 auto *ColumnCountNode =
3823 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3824 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3825 auto *RowCountNode =
3826 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3827 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3828 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3829 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3830 nullptr /*stride*/));
3831 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3832 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3833 nullptr /*stride*/));
3834 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3835 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3836}
3837
3838llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3839 uint64_t Size;
3840 uint32_t Align;
3841
3842 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3843 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3844 Size = 0;
3845 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3846 CGM.getContext());
3847 } else if (Ty->isIncompleteArrayType()) {
3848 Size = 0;
3849 if (Ty->getElementType()->isIncompleteType())
3850 Align = 0;
3851 else
3852 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3853 } else if (Ty->isIncompleteType()) {
3854 Size = 0;
3855 Align = 0;
3856 } else {
3857 // Size and align of the whole array, not the element type.
3858 Size = CGM.getContext().getTypeSize(Ty);
3859 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3860 }
3861
3862 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3863 // interior arrays, do we care? Why aren't nested arrays represented the
3864 // obvious/recursive way?
3865 SmallVector<llvm::Metadata *, 8> Subscripts;
3866 QualType EltTy(Ty, 0);
3867 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3868 // If the number of elements is known, then count is that number. Otherwise,
3869 // it's -1. This allows us to represent a subrange with an array of 0
3870 // elements, like this:
3871 //
3872 // struct foo {
3873 // int x[0];
3874 // };
3875 int64_t Count = -1; // Count == -1 is an unbounded array.
3876 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3877 Count = CAT->getZExtSize();
3878 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3879 if (Expr *Size = VAT->getSizeExpr()) {
3880 Expr::EvalResult Result;
3881 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3882 Count = Result.Val.getInt().getExtValue();
3883 }
3884 }
3885
3886 auto SizeNode = SizeExprCache.find(EltTy);
3887 if (SizeNode != SizeExprCache.end())
3888 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3889 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3890 nullptr /*upperBound*/, nullptr /*stride*/));
3891 else {
3892 auto *CountNode =
3893 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3894 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3895 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3896 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3897 nullptr /*stride*/));
3898 }
3899 EltTy = Ty->getElementType();
3900 }
3901
3902 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3903
3904 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
3905 SubscriptArray);
3906}
3907
3908llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
3909 llvm::DIFile *Unit) {
3910 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
3911 Ty->getPointeeType(), Unit);
3912}
3913
3914llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
3915 llvm::DIFile *Unit) {
3916 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
3917 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
3918 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
3919 CGM.getCodeGenOpts().DwarfVersion < 4)
3920 Tag = llvm::dwarf::DW_TAG_reference_type;
3921
3922 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
3923}
3924
3925llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
3926 llvm::DIFile *U) {
3927 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3928 uint64_t Size = 0;
3929
3930 if (!Ty->isIncompleteType()) {
3931 Size = CGM.getContext().getTypeSize(Ty);
3932
3933 // Set the MS inheritance model. There is no flag for the unspecified model.
3934 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
3937 Flags |= llvm::DINode::FlagSingleInheritance;
3938 break;
3940 Flags |= llvm::DINode::FlagMultipleInheritance;
3941 break;
3943 Flags |= llvm::DINode::FlagVirtualInheritance;
3944 break;
3946 break;
3947 }
3948 }
3949 }
3950
3951 CanQualType T =
3952 CGM.getContext().getCanonicalTagType(Ty->getMostRecentCXXRecordDecl());
3953 llvm::DIType *ClassType = getOrCreateType(T, U);
3954 if (Ty->isMemberDataPointerType())
3955 return DBuilder.createMemberPointerType(
3956 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
3957 Flags);
3958
3959 const FunctionProtoType *FPT =
3960 Ty->getPointeeType()->castAs<FunctionProtoType>();
3961 return DBuilder.createMemberPointerType(
3962 getOrCreateInstanceMethodType(
3964 FPT, U),
3965 ClassType, Size, /*Align=*/0, Flags);
3966}
3967
3968llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
3969 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
3970 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
3971}
3972
3973llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
3974 return getOrCreateType(Ty->getElementType(), U);
3975}
3976
3977llvm::DIType *CGDebugInfo::CreateType(const HLSLAttributedResourceType *Ty,
3978 llvm::DIFile *U) {
3979 return getOrCreateType(Ty->getWrappedType(), U);
3980}
3981
3982llvm::DIType *CGDebugInfo::CreateType(const HLSLInlineSpirvType *Ty,
3983 llvm::DIFile *U) {
3984 // Debug information unneeded.
3985 return nullptr;
3986}
3987
3988static auto getEnumInfo(CodeGenModule &CGM, llvm::DICompileUnit *TheCU,
3989 const EnumType *Ty) {
3990 const EnumDecl *ED = Ty->getDecl()->getDefinitionOrSelf();
3991
3992 uint64_t Size = 0;
3993 uint32_t Align = 0;
3994 if (ED->isComplete()) {
3995 Size = CGM.getContext().getTypeSize(QualType(Ty, 0));
3996 Align = getDeclAlignIfRequired(ED, CGM.getContext());
3997 }
3998 return std::make_tuple(ED, Size, Align, getTypeIdentifier(Ty, CGM, TheCU));
3999}
4000
4001llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
4002 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
4003
4004 bool isImportedFromModule =
4005 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
4006
4007 // If this is just a forward declaration, construct an appropriately
4008 // marked node and just return it.
4009 if (isImportedFromModule || !ED->getDefinition()) {
4010 // Note that it is possible for enums to be created as part of
4011 // their own declcontext. In this case a FwdDecl will be created
4012 // twice. This doesn't cause a problem because both FwdDecls are
4013 // entered into the ReplaceMap: finalize() will replace the first
4014 // FwdDecl with the second and then replace the second with
4015 // complete type.
4016 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
4017 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
4018 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
4019 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
4020
4021 unsigned Line = getLineNumber(ED->getLocation());
4022 StringRef EDName = ED->getName();
4023 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
4024 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
4025 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
4026
4027 ReplaceMap.emplace_back(
4028 std::piecewise_construct, std::make_tuple(Ty),
4029 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
4030 return RetTy;
4031 }
4032
4033 return CreateTypeDefinition(Ty);
4034}
4035
4036llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
4037 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
4038
4039 SmallVector<llvm::Metadata *, 16> Enumerators;
4040 ED = ED->getDefinition();
4041 assert(ED && "An enumeration definition is required");
4042 for (const auto *Enum : ED->enumerators()) {
4043 Enumerators.push_back(
4044 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
4045 }
4046
4047 std::optional<EnumExtensibilityAttr::Kind> EnumKind;
4048 if (auto *Attr = ED->getAttr<EnumExtensibilityAttr>())
4049 EnumKind = Attr->getExtensibility();
4050
4051 // Return a CompositeType for the enum itself.
4052 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
4053
4054 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
4055 unsigned Line = getLineNumber(ED->getLocation());
4056 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
4057 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
4058 return DBuilder.createEnumerationType(
4059 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
4060 /*RunTimeLang=*/0, Identifier, ED->isScoped(), EnumKind);
4061}
4062
4063llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
4064 unsigned MType, SourceLocation LineLoc,
4065 StringRef Name, StringRef Value) {
4066 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
4067 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
4068}
4069
4070llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
4071 SourceLocation LineLoc,
4072 SourceLocation FileLoc) {
4073 llvm::DIFile *FName = getOrCreateFile(FileLoc);
4074 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
4075 return DBuilder.createTempMacroFile(Parent, Line, FName);
4076}
4077
4078llvm::DILocation *
4079CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc ParentLocation,
4080 llvm::DISubprogram *SynthSubprogram) {
4081 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
4082 SynthSubprogram, ParentLocation);
4083}
4084
4085llvm::DILocation *
4086CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc ParentLocation,
4087 StringRef SynthFuncName,
4088 llvm::DIFile *SynthFile) {
4089 llvm::DISubprogram *SP = createInlinedSubprogram(SynthFuncName, SynthFile);
4090 return CreateSyntheticInlineAt(ParentLocation, SP);
4091}
4092
4094 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
4095 // Create a debug location from `TrapLocation` that adds an artificial inline
4096 // frame.
4098
4099 FuncName += "$";
4100 FuncName += Category;
4101 FuncName += "$";
4102 FuncName += FailureMsg;
4103
4104 return CreateSyntheticInlineAt(TrapLocation, FuncName,
4105 TrapLocation->getFile());
4106}
4107
4109 Qualifiers Quals;
4110 do {
4111 Qualifiers InnerQuals = T.getLocalQualifiers();
4112 // Qualifiers::operator+() doesn't like it if you add a Qualifier
4113 // that is already there.
4114 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
4115 Quals += InnerQuals;
4116 QualType LastT = T;
4117 switch (T->getTypeClass()) {
4118 default:
4119 return C.getQualifiedType(T.getTypePtr(), Quals);
4120 case Type::Enum:
4121 case Type::Record:
4122 case Type::InjectedClassName:
4123 return C.getQualifiedType(T->getCanonicalTypeUnqualified().getTypePtr(),
4124 Quals);
4125 case Type::TemplateSpecialization: {
4126 const auto *Spec = cast<TemplateSpecializationType>(T);
4127 if (Spec->isTypeAlias())
4128 return C.getQualifiedType(T.getTypePtr(), Quals);
4129 T = Spec->desugar();
4130 break;
4131 }
4132 case Type::TypeOfExpr:
4133 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
4134 break;
4135 case Type::TypeOf:
4136 T = cast<TypeOfType>(T)->getUnmodifiedType();
4137 break;
4138 case Type::Decltype:
4139 T = cast<DecltypeType>(T)->getUnderlyingType();
4140 break;
4141 case Type::UnaryTransform:
4142 T = cast<UnaryTransformType>(T)->getUnderlyingType();
4143 break;
4144 case Type::Attributed:
4145 T = cast<AttributedType>(T)->getEquivalentType();
4146 break;
4147 case Type::BTFTagAttributed:
4148 T = cast<BTFTagAttributedType>(T)->getWrappedType();
4149 break;
4150 case Type::CountAttributed:
4151 T = cast<CountAttributedType>(T)->desugar();
4152 break;
4153 case Type::Using:
4154 T = cast<UsingType>(T)->desugar();
4155 break;
4156 case Type::Paren:
4157 T = cast<ParenType>(T)->getInnerType();
4158 break;
4159 case Type::MacroQualified:
4160 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
4161 break;
4162 case Type::SubstTemplateTypeParm:
4163 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
4164 break;
4165 case Type::Auto:
4166 case Type::DeducedTemplateSpecialization: {
4167 QualType DT = cast<DeducedType>(T)->getDeducedType();
4168 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
4169 T = DT;
4170 break;
4171 }
4172 case Type::PackIndexing: {
4173 T = cast<PackIndexingType>(T)->getSelectedType();
4174 break;
4175 }
4176 case Type::Adjusted:
4177 case Type::Decayed:
4178 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
4179 T = cast<AdjustedType>(T)->getAdjustedType();
4180 break;
4181 }
4182
4183 assert(T != LastT && "Type unwrapping failed to unwrap!");
4184 (void)LastT;
4185 } while (true);
4186}
4187
4188llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
4189 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
4190 auto It = TypeCache.find(Ty.getAsOpaquePtr());
4191 if (It != TypeCache.end()) {
4192 // Verify that the debug info still exists.
4193 if (llvm::Metadata *V = It->second)
4194 return cast<llvm::DIType>(V);
4195 }
4196
4197 return nullptr;
4198}
4199
4204
4206 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
4207 D.isDynamicClass())
4208 return;
4209
4211 // In case this type has no member function definitions being emitted, ensure
4212 // it is retained
4213 RetainedTypes.push_back(
4214 CGM.getContext().getCanonicalTagType(&D).getAsOpaquePtr());
4215}
4216
4217llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
4218 if (Ty.isNull())
4219 return nullptr;
4220
4221 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
4222 std::string Name;
4223 llvm::raw_string_ostream OS(Name);
4224 Ty.print(OS, getPrintingPolicy());
4225 return Name;
4226 });
4227
4228 // Unwrap the type as needed for debug information.
4229 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
4230
4231 if (auto *T = getTypeOrNull(Ty))
4232 return T;
4233
4234 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
4235 void *TyPtr = Ty.getAsOpaquePtr();
4236
4237 // And update the type cache.
4238 TypeCache[TyPtr].reset(Res);
4239
4240 return Res;
4241}
4242
4243llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
4244 // A forward declaration inside a module header does not belong to the module.
4246 return nullptr;
4247 if (DebugTypeExtRefs && D->isFromASTFile()) {
4248 // Record a reference to an imported clang module or precompiled header.
4249 auto *Reader = CGM.getContext().getExternalSource();
4250 auto Idx = D->getOwningModuleID();
4251 auto Info = Reader->getSourceDescriptor(Idx);
4252 if (Info)
4253 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
4254 } else if (ClangModuleMap) {
4255 // We are building a clang module or a precompiled header.
4256 //
4257 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
4258 // and it wouldn't be necessary to specify the parent scope
4259 // because the type is already unique by definition (it would look
4260 // like the output of -fno-standalone-debug). On the other hand,
4261 // the parent scope helps a consumer to quickly locate the object
4262 // file where the type's definition is located, so it might be
4263 // best to make this behavior a command line or debugger tuning
4264 // option.
4265 if (Module *M = D->getOwningModule()) {
4266 // This is a (sub-)module.
4267 auto Info = ASTSourceDescriptor(*M);
4268 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
4269 } else {
4270 // This the precompiled header being built.
4271 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
4272 }
4273 }
4274
4275 return nullptr;
4276}
4277
4278llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
4279 // Handle qualifiers, which recursively handles what they refer to.
4280 if (Ty.hasLocalQualifiers())
4281 return CreateQualifiedType(Ty, Unit);
4282
4283 // Work out details of type.
4284 switch (Ty->getTypeClass()) {
4285#define TYPE(Class, Base)
4286#define ABSTRACT_TYPE(Class, Base)
4287#define NON_CANONICAL_TYPE(Class, Base)
4288#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4289#include "clang/AST/TypeNodes.inc"
4290 llvm_unreachable("Dependent types cannot show up in debug information");
4291
4292 case Type::ExtVector:
4293 case Type::Vector:
4294 return CreateType(cast<VectorType>(Ty), Unit);
4295 case Type::ConstantMatrix:
4296 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
4297 case Type::ObjCObjectPointer:
4298 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
4299 case Type::ObjCObject:
4300 return CreateType(cast<ObjCObjectType>(Ty), Unit);
4301 case Type::ObjCTypeParam:
4302 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
4303 case Type::ObjCInterface:
4304 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
4305 case Type::Builtin:
4306 return CreateType(cast<BuiltinType>(Ty));
4307 case Type::Complex:
4308 return CreateType(cast<ComplexType>(Ty));
4309 case Type::Pointer:
4310 return CreateType(cast<PointerType>(Ty), Unit);
4311 case Type::BlockPointer:
4312 return CreateType(cast<BlockPointerType>(Ty), Unit);
4313 case Type::Typedef:
4314 return CreateType(cast<TypedefType>(Ty), Unit);
4315 case Type::Record:
4316 return CreateType(cast<RecordType>(Ty));
4317 case Type::Enum:
4318 return CreateEnumType(cast<EnumType>(Ty));
4319 case Type::FunctionProto:
4320 case Type::FunctionNoProto:
4321 return CreateType(cast<FunctionType>(Ty), Unit);
4322 case Type::ConstantArray:
4323 case Type::VariableArray:
4324 case Type::IncompleteArray:
4325 case Type::ArrayParameter:
4326 return CreateType(cast<ArrayType>(Ty), Unit);
4327
4328 case Type::LValueReference:
4329 return CreateType(cast<LValueReferenceType>(Ty), Unit);
4330 case Type::RValueReference:
4331 return CreateType(cast<RValueReferenceType>(Ty), Unit);
4332
4333 case Type::MemberPointer:
4334 return CreateType(cast<MemberPointerType>(Ty), Unit);
4335
4336 case Type::Atomic:
4337 return CreateType(cast<AtomicType>(Ty), Unit);
4338
4339 case Type::BitInt:
4340 return CreateType(cast<BitIntType>(Ty));
4341 case Type::OverflowBehavior:
4342 return CreateType(cast<OverflowBehaviorType>(Ty), Unit);
4343 case Type::Pipe:
4344 return CreateType(cast<PipeType>(Ty), Unit);
4345
4346 case Type::TemplateSpecialization:
4347 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
4348 case Type::HLSLAttributedResource:
4349 return CreateType(cast<HLSLAttributedResourceType>(Ty), Unit);
4350 case Type::HLSLInlineSpirv:
4351 return CreateType(cast<HLSLInlineSpirvType>(Ty), Unit);
4352 case Type::PredefinedSugar:
4353 return getOrCreateType(cast<PredefinedSugarType>(Ty)->desugar(), Unit);
4354 case Type::CountAttributed:
4355 case Type::Auto:
4356 case Type::Attributed:
4357 case Type::BTFTagAttributed:
4358 case Type::Adjusted:
4359 case Type::Decayed:
4360 case Type::DeducedTemplateSpecialization:
4361 case Type::Using:
4362 case Type::Paren:
4363 case Type::MacroQualified:
4364 case Type::SubstTemplateTypeParm:
4365 case Type::TypeOfExpr:
4366 case Type::TypeOf:
4367 case Type::Decltype:
4368 case Type::PackIndexing:
4369 case Type::UnaryTransform:
4370 break;
4371 }
4372
4373 llvm_unreachable("type should have been unwrapped!");
4374}
4375
4376llvm::DICompositeType *
4377CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
4378 QualType QTy(Ty, 0);
4379
4380 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
4381
4382 // We may have cached a forward decl when we could have created
4383 // a non-forward decl. Go ahead and create a non-forward decl
4384 // now.
4385 if (T && !T->isForwardDecl())
4386 return T;
4387
4388 // Otherwise create the type.
4389 llvm::DICompositeType *Res = CreateLimitedType(Ty);
4390
4391 // Propagate members from the declaration to the definition
4392 // CreateType(const RecordType*) will overwrite this with the members in the
4393 // correct order if the full type is needed.
4394 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
4395
4396 // And update the type cache.
4397 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
4398 return Res;
4399}
4400
4401// TODO: Currently used for context chains when limiting debug info.
4402llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
4403 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
4404 bool NameIsSimplified = false;
4405
4406 // Get overall information about the record type for the debug info.
4407 StringRef RDName = getClassName(RD, &NameIsSimplified);
4408 const SourceLocation Loc = RD->getLocation();
4409 llvm::DIFile *DefUnit = nullptr;
4410 unsigned Line = 0;
4411 if (Loc.isValid()) {
4412 DefUnit = getOrCreateFile(Loc);
4413 Line = getLineNumber(Loc);
4414 }
4415
4416 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
4417
4418 // If we ended up creating the type during the context chain construction,
4419 // just return that.
4420 auto *T = cast_or_null<llvm::DICompositeType>(
4421 getTypeOrNull(CGM.getContext().getCanonicalTagType(RD)));
4422 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
4423 return T;
4424
4425 // If this is just a forward or incomplete declaration, construct an
4426 // appropriately marked node and just return it.
4427 const RecordDecl *D = RD->getDefinition();
4428 if (!D || !D->isCompleteDefinition())
4429 return getOrCreateRecordFwdDecl(Ty, RDContext);
4430
4431 uint64_t Size = CGM.getContext().getTypeSize(Ty);
4432 // __attribute__((aligned)) can increase or decrease alignment *except* on a
4433 // struct or struct member, where it only increases alignment unless 'packed'
4434 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
4435 // to be used.
4436 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
4437
4438 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
4439
4440 // Explicitly record the calling convention and export symbols for C++
4441 // records.
4442 auto Flags = llvm::DINode::FlagZero;
4443 if (NameIsSimplified)
4444 Flags |= llvm::DINode::FlagNameIsSimplified;
4445 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4446 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
4447 Flags |= llvm::DINode::FlagTypePassByReference;
4448 else
4449 Flags |= llvm::DINode::FlagTypePassByValue;
4450
4451 // Record if a C++ record is non-trivial type.
4452 if (!CXXRD->isTrivial())
4453 Flags |= llvm::DINode::FlagNonTrivial;
4454
4455 // Record exports it symbols to the containing structure.
4456 if (CXXRD->isAnonymousStructOrUnion())
4457 Flags |= llvm::DINode::FlagExportSymbols;
4458
4459 Flags |= getAccessFlag(CXXRD->getAccess(),
4460 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
4461 }
4462
4463 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4464 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
4465 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
4466 Flags, Identifier, Annotations);
4467
4468 // Elements of composite types usually have back to the type, creating
4469 // uniquing cycles. Distinct nodes are more efficient.
4470 switch (RealDecl->getTag()) {
4471 default:
4472 llvm_unreachable("invalid composite type tag");
4473
4474 case llvm::dwarf::DW_TAG_array_type:
4475 case llvm::dwarf::DW_TAG_enumeration_type:
4476 // Array elements and most enumeration elements don't have back references,
4477 // so they don't tend to be involved in uniquing cycles and there is some
4478 // chance of merging them when linking together two modules. Only make
4479 // them distinct if they are ODR-uniqued.
4480 if (Identifier.empty())
4481 break;
4482 [[fallthrough]];
4483
4484 case llvm::dwarf::DW_TAG_structure_type:
4485 case llvm::dwarf::DW_TAG_union_type:
4486 case llvm::dwarf::DW_TAG_class_type:
4487 // Immediately resolve to a distinct node.
4488 RealDecl =
4489 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
4490 break;
4491 }
4492
4493 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Ty->getDecl())) {
4494 CXXRecordDecl *TemplateDecl =
4495 CTSD->getSpecializedTemplate()->getTemplatedDecl();
4496 RegionMap[TemplateDecl].reset(RealDecl);
4497 } else {
4498 RegionMap[RD].reset(RealDecl);
4499 }
4500 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
4501
4502 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
4503 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
4504 CollectCXXTemplateParams(TSpecial, DefUnit));
4505 return RealDecl;
4506}
4507
4508void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
4509 llvm::DICompositeType *RealDecl) {
4510 // A class's primary base or the class itself contains the vtable.
4511 llvm::DIType *ContainingType = nullptr;
4512 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
4513 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
4514 // Seek non-virtual primary base root.
4515 while (true) {
4516 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
4517 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
4518 if (PBT && !BRL.isPrimaryBaseVirtual())
4519 PBase = PBT;
4520 else
4521 break;
4522 }
4523 CanQualType T = CGM.getContext().getCanonicalTagType(PBase);
4524 ContainingType = getOrCreateType(T, getOrCreateFile(RD->getLocation()));
4525 } else if (RD->isDynamicClass())
4526 ContainingType = RealDecl;
4527
4528 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4529}
4530
4531llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4532 StringRef Name, uint64_t *Offset) {
4533 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4534 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4535 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4536 llvm::DIType *Ty =
4537 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4538 *Offset, llvm::DINode::FlagZero, FieldTy);
4539 *Offset += FieldSize;
4540 return Ty;
4541}
4542
4543void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4544 StringRef &Name,
4545 StringRef &LinkageName,
4546 llvm::DIScope *&FDContext,
4547 llvm::DINodeArray &TParamsArray,
4548 llvm::DINode::DIFlags &Flags) {
4549 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4550 bool NameIsSimplified = false;
4551 Name = getFunctionName(FD, &NameIsSimplified);
4552 if (NameIsSimplified)
4553 Flags |= llvm::DINode::FlagNameIsSimplified;
4554 Name = getFunctionName(FD);
4555 // Use mangled name as linkage name for C/C++ functions.
4556 if (FD->getType()->getAs<FunctionProtoType>())
4557 LinkageName = CGM.getMangledName(GD);
4558 if (FD->hasPrototype())
4559 Flags |= llvm::DINode::FlagPrototyped;
4560 // No need to replicate the linkage name if it isn't different from the
4561 // subprogram name, no need to have it at all unless coverage is enabled or
4562 // debug is set to more than just line tables or extra debug info is needed.
4563 if (LinkageName == Name ||
4564 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4565 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4566 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4567 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4568 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4569 LinkageName = StringRef();
4570
4571 // Emit the function scope in line tables only mode (if CodeView) to
4572 // differentiate between function names.
4573 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4574 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4575 CGM.getCodeGenOpts().EmitCodeView)) {
4576 if (const NamespaceDecl *NSDecl =
4577 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4578 FDContext = getOrCreateNamespace(NSDecl);
4579 else if (const RecordDecl *RDecl =
4580 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4581 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4582 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4583 }
4584 }
4585 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4586 // Check if it is a noreturn-marked function
4587 if (FD->isNoReturn())
4588 Flags |= llvm::DINode::FlagNoReturn;
4589 // Collect template parameters.
4590 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4591 }
4592}
4593
4594void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4595 unsigned &LineNo, QualType &T,
4596 StringRef &Name, StringRef &LinkageName,
4597 llvm::MDTuple *&TemplateParameters,
4598 llvm::DIScope *&VDContext) {
4599 Unit = getOrCreateFile(VD->getLocation());
4600 LineNo = getLineNumber(VD->getLocation());
4601
4602 setLocation(VD->getLocation());
4603
4604 T = VD->getType();
4605 if (T->isIncompleteArrayType()) {
4606 // CodeGen turns int[] into int[1] so we'll do the same here.
4607 llvm::APInt ConstVal(32, 1);
4608 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
4609
4610 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4612 }
4613
4614 Name = VD->getName();
4615 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4617 LinkageName = CGM.getMangledName(VD);
4618 if (LinkageName == Name)
4619 LinkageName = StringRef();
4620
4622 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4623 TemplateParameters = parameterNodes.get();
4624 } else {
4625 TemplateParameters = nullptr;
4626 }
4627
4628 // Since we emit declarations (DW_AT_members) for static members, place the
4629 // definition of those static members in the namespace they were declared in
4630 // in the source code (the lexical decl context).
4631 // FIXME: Generalize this for even non-member global variables where the
4632 // declaration and definition may have different lexical decl contexts, once
4633 // we have support for emitting declarations of (non-member) global variables.
4634 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4635 : VD->getDeclContext();
4636 // When a record type contains an in-line initialization of a static data
4637 // member, and the record type is marked as __declspec(dllexport), an implicit
4638 // definition of the member will be created in the record context. DWARF
4639 // doesn't seem to have a nice way to describe this in a form that consumers
4640 // are likely to understand, so fake the "normal" situation of a definition
4641 // outside the class by putting it in the global scope.
4642 if (DC->isRecord())
4643 DC = CGM.getContext().getTranslationUnitDecl();
4644
4645 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4646 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4647}
4648
4649llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4650 bool Stub) {
4651 llvm::DINodeArray TParamsArray;
4652 StringRef Name, LinkageName;
4653 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4654 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4655 SourceLocation Loc = GD.getDecl()->getLocation();
4656 llvm::DIFile *Unit = getOrCreateFile(Loc);
4657 llvm::DIScope *DContext = Unit;
4658 unsigned Line = getLineNumber(Loc);
4659 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4660 Flags);
4661 auto *FD = cast<FunctionDecl>(GD.getDecl());
4662
4663 // Build function type.
4664 SmallVector<QualType, 16> ArgTypes;
4665 for (const ParmVarDecl *Parm : FD->parameters())
4666 ArgTypes.push_back(Parm->getType());
4667
4668 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4669 QualType FnType = CGM.getContext().getFunctionType(
4670 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4671 if (!FD->isExternallyVisible())
4672 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4673 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
4674 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4675
4676 if (Stub) {
4677 Flags |= getCallSiteRelatedAttrs();
4678 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4679 return DBuilder.createFunction(
4680 DContext, Name, LinkageName, Unit, Line,
4681 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4682 TParamsArray.get(), getFunctionDeclaration(FD), /*ThrownTypes*/ nullptr,
4683 /*Annotations*/ nullptr, /*TargetFuncName*/ "",
4684 CGM.getCodeGenOpts().DebugKeyInstructions);
4685 }
4686
4687 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4688 DContext, Name, LinkageName, Unit, Line,
4689 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4690 TParamsArray.get(), getFunctionDeclaration(FD));
4691 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4692 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4693 std::make_tuple(CanonDecl),
4694 std::make_tuple(SP));
4695 return SP;
4696}
4697
4698llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4699 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4700}
4701
4702llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4703 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4704}
4705
4706llvm::DIGlobalVariable *
4707CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4708 QualType T;
4709 StringRef Name, LinkageName;
4710 SourceLocation Loc = VD->getLocation();
4711 llvm::DIFile *Unit = getOrCreateFile(Loc);
4712 llvm::DIScope *DContext = Unit;
4713 unsigned Line = getLineNumber(Loc);
4714 llvm::MDTuple *TemplateParameters = nullptr;
4715
4716 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4717 DContext);
4718 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4719 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4720 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4721 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4722 FwdDeclReplaceMap.emplace_back(
4723 std::piecewise_construct,
4724 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4725 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4726 return GV;
4727}
4728
4729llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4730 // We only need a declaration (not a definition) of the type - so use whatever
4731 // we would otherwise do to get a type for a pointee. (forward declarations in
4732 // limited debug info, full definitions (if the type definition is available)
4733 // in unlimited debug info)
4734 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
4735 QualType Ty = CGM.getContext().getTypeDeclType(TD);
4736 return getOrCreateType(Ty, getOrCreateFile(TD->getLocation()));
4737 }
4738 auto I = DeclCache.find(D->getCanonicalDecl());
4739
4740 if (I != DeclCache.end()) {
4741 auto N = I->second;
4742 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4743 return GVE->getVariable();
4744 return cast<llvm::DINode>(N);
4745 }
4746
4747 // Search imported declaration cache if it is already defined
4748 // as imported declaration.
4749 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4750
4751 if (IE != ImportedDeclCache.end()) {
4752 auto N = IE->second;
4753 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4754 return cast<llvm::DINode>(GVE);
4755 return dyn_cast_or_null<llvm::DINode>(N);
4756 }
4757
4758 // No definition for now. Emit a forward definition that might be
4759 // merged with a potential upcoming definition.
4760 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4761 return getFunctionForwardDeclaration(FD);
4762 else if (const auto *VD = dyn_cast<VarDecl>(D))
4763 return getGlobalVariableForwardDeclaration(VD);
4764
4765 return nullptr;
4766}
4767
4768llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4769 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4770 return nullptr;
4771
4772 const auto *FD = dyn_cast<FunctionDecl>(D);
4773 if (!FD)
4774 return nullptr;
4775
4776 // Setup context.
4777 auto *S = getDeclContextDescriptor(D);
4778
4779 auto MI = SPCache.find(FD->getCanonicalDecl());
4780 if (MI == SPCache.end()) {
4781 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4782 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4784 }
4785 }
4786 if (MI != SPCache.end()) {
4787 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4788 if (SP && !SP->isDefinition())
4789 return SP;
4790 }
4791
4792 for (auto *NextFD : FD->redecls()) {
4793 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4794 if (MI != SPCache.end()) {
4795 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4796 if (SP && !SP->isDefinition())
4797 return SP;
4798 }
4799 }
4800 return nullptr;
4801}
4802
4803llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4804 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4805 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4806 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4807 return nullptr;
4808
4809 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4810 if (!OMD)
4811 return nullptr;
4812
4813 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4814 return nullptr;
4815
4816 if (OMD->isDirectMethod())
4817 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4818
4819 // Starting with DWARF V5 method declarations are emitted as children of
4820 // the interface type.
4821 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4822 if (!ID)
4823 ID = OMD->getClassInterface();
4824 if (!ID)
4825 return nullptr;
4826 QualType QTy(ID->getTypeForDecl(), 0);
4827 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4828 if (It == TypeCache.end())
4829 return nullptr;
4830 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4831 llvm::DISubprogram *FD = DBuilder.createFunction(
4832 InterfaceType, getObjCMethodName(OMD), StringRef(),
4833 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4834 DBuilder.finalizeSubprogram(FD);
4835 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4836 return FD;
4837}
4838
4839// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4840// implicit parameter "this".
4841llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4842 QualType FnType,
4843 llvm::DIFile *F) {
4844 // In CodeView, we emit the function types in line tables only because the
4845 // only way to distinguish between functions is by display name and type.
4846 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4847 !CGM.getCodeGenOpts().EmitCodeView))
4848 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4849 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4850 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4851
4852 if (const auto *Method = dyn_cast<CXXDestructorDecl>(D)) {
4853 // Read method type from 'FnType' because 'D.getType()' does not cover
4854 // implicit arguments for destructors.
4855 return getOrCreateMethodTypeForDestructor(Method, F, FnType);
4856 }
4857
4858 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4859 return getOrCreateMethodType(Method, F);
4860
4861 const auto *FTy = FnType->getAs<FunctionType>();
4862 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4863
4864 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4865 // Add "self" and "_cmd"
4866 SmallVector<llvm::Metadata *, 16> Elts;
4867
4868 // First element is always return type. For 'void' functions it is NULL.
4869 QualType ResultTy = OMethod->getReturnType();
4870
4871 // Replace the instancetype keyword with the actual type.
4872 if (ResultTy == CGM.getContext().getObjCInstanceType())
4873 ResultTy = CGM.getContext().getPointerType(
4874 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4875
4876 Elts.push_back(getOrCreateType(ResultTy, F));
4877 // "self" pointer is always first argument.
4878 QualType SelfDeclTy;
4879 if (auto *SelfDecl = OMethod->getSelfDecl())
4880 SelfDeclTy = SelfDecl->getType();
4881 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4882 if (FPT->getNumParams() > 1)
4883 SelfDeclTy = FPT->getParamType(0);
4884 if (!SelfDeclTy.isNull())
4885 Elts.push_back(
4886 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4887 // "_cmd" pointer is always second argument.
4888 Elts.push_back(DBuilder.createArtificialType(
4889 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
4890 // Get rest of the arguments.
4891 for (const auto *PI : OMethod->parameters())
4892 Elts.push_back(getOrCreateType(PI->getType(), F));
4893 // Variadic methods need a special marker at the end of the type list.
4894 if (OMethod->isVariadic())
4895 Elts.push_back(DBuilder.createUnspecifiedParameter());
4896
4897 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
4898 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4899 getDwarfCC(CC));
4900 }
4901
4902 // Handle variadic function types; they need an additional
4903 // unspecified parameter.
4904 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4905 if (FD->isVariadic()) {
4906 SmallVector<llvm::Metadata *, 16> EltTys;
4907 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
4908 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4909 for (QualType ParamType : FPT->param_types())
4910 EltTys.push_back(getOrCreateType(ParamType, F));
4911 EltTys.push_back(DBuilder.createUnspecifiedParameter());
4912 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
4913 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
4914 getDwarfCC(CC));
4915 }
4916
4917 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
4918}
4919
4920QualType
4924 if (FD)
4925 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
4926 CC = SrcFnTy->getCallConv();
4928 for (const VarDecl *VD : Args)
4929 ArgTypes.push_back(VD->getType());
4930 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
4932}
4933
4935 SourceLocation ScopeLoc, QualType FnType,
4936 llvm::Function *Fn, bool CurFuncIsThunk) {
4937 StringRef Name;
4938 StringRef LinkageName;
4939
4940 FnBeginRegionCount.push_back(LexicalBlockStack.size());
4941
4942 const Decl *D = GD.getDecl();
4943 bool HasDecl = (D != nullptr);
4944
4945 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4946 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4947 llvm::DIFile *Unit = getOrCreateFile(Loc);
4948 llvm::DIScope *FDContext = Unit;
4949 llvm::DINodeArray TParamsArray;
4950 bool KeyInstructions = CGM.getCodeGenOpts().DebugKeyInstructions;
4951 if (!HasDecl) {
4952 // Use llvm function name.
4953 LinkageName = Fn->getName();
4954 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
4955 // If there is a subprogram for this function available then use it.
4956 auto FI = SPCache.find(FD->getCanonicalDecl());
4957 if (FI != SPCache.end()) {
4958 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
4959 if (SP && SP->isDefinition()) {
4960 LexicalBlockStack.emplace_back(SP);
4961 RegionMap[D].reset(SP);
4962 return;
4963 }
4964 }
4965 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
4966 TParamsArray, Flags);
4967 // Disable KIs if this is a coroutine.
4968 KeyInstructions =
4969 KeyInstructions && !isa_and_present<CoroutineBodyStmt>(FD->getBody());
4970 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
4971 Name = getObjCMethodName(OMD);
4972 Flags |= llvm::DINode::FlagPrototyped;
4973 } else if (isa<VarDecl>(D) &&
4975 // This is a global initializer or atexit destructor for a global variable.
4976 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
4977 Fn);
4978 if (Name != Fn->getName())
4979 LinkageName = Fn->getName();
4980 } else {
4981 Name = Fn->getName();
4982
4983 if (isa<BlockDecl>(D))
4984 LinkageName = Name;
4985
4986 Flags |= llvm::DINode::FlagPrototyped;
4987 }
4988 Name.consume_front("\01");
4989
4990 assert((!D || !isa<VarDecl>(D) ||
4992 "Unexpected DynamicInitKind !");
4993
4994 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
4996 Flags |= llvm::DINode::FlagArtificial;
4997 // Artificial functions should not silently reuse CurLoc.
4998 clearCurLoc();
4999 }
5000
5001 if (CurFuncIsThunk)
5002 Flags |= llvm::DINode::FlagThunk;
5003
5004 if (Fn->hasLocalLinkage())
5005 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
5006 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
5007 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
5008
5009 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
5010 llvm::DISubprogram::DISPFlags SPFlagsForDef =
5011 SPFlags | llvm::DISubprogram::SPFlagDefinition;
5012
5013 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
5014 unsigned ScopeLine = getLineNumber(ScopeLoc);
5015 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
5016 llvm::DISubprogram *Decl = nullptr;
5017 llvm::DINodeArray Annotations = nullptr;
5018 if (D) {
5020 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
5021 : getFunctionDeclaration(D);
5022 Annotations = CollectBTFDeclTagAnnotations(D);
5023 }
5024
5025 // FIXME: The function declaration we're constructing here is mostly reusing
5026 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
5027 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
5028 // all subprograms instead of the actual context since subprogram definitions
5029 // are emitted as CU level entities by the backend.
5030 llvm::DISubprogram *SP = DBuilder.createFunction(
5031 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
5032 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
5033 Annotations, "", KeyInstructions);
5034 Fn->setSubprogram(SP);
5035
5036 // We might get here with a VarDecl in the case we're generating
5037 // code for the initialization of globals. Do not record these decls
5038 // as they will overwrite the actual VarDecl Decl in the cache.
5039 if (HasDecl && isa<FunctionDecl>(D))
5040 DeclCache[D->getCanonicalDecl()].reset(SP);
5041
5042 // Push the function onto the lexical block stack.
5043 LexicalBlockStack.emplace_back(SP);
5044
5045 if (HasDecl)
5046 RegionMap[D].reset(SP);
5047}
5048
5050 QualType FnType, llvm::Function *Fn) {
5051 StringRef Name;
5052 StringRef LinkageName;
5053
5054 const Decl *D = GD.getDecl();
5055 if (!D)
5056 return;
5057
5058 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
5059 return GetName(D, true);
5060 });
5061
5062 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5063 llvm::DIFile *Unit = getOrCreateFile(Loc);
5064 bool IsDeclForCallSite = Fn ? true : false;
5065 llvm::DIScope *FDContext =
5066 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
5067 llvm::DINodeArray TParamsArray;
5068 if (isa<FunctionDecl>(D)) {
5069 // If there is a DISubprogram for this function available then use it.
5070 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
5071 TParamsArray, Flags);
5072 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
5073 Name = getObjCMethodName(OMD);
5074 Flags |= llvm::DINode::FlagPrototyped;
5075 } else {
5076 llvm_unreachable("not a function or ObjC method");
5077 }
5078 Name.consume_front("\01");
5079
5080 if (D->isImplicit()) {
5081 Flags |= llvm::DINode::FlagArtificial;
5082 // Artificial functions without a location should not silently reuse CurLoc.
5083 if (Loc.isInvalid())
5084 clearCurLoc();
5085 }
5086 unsigned LineNo = getLineNumber(Loc);
5087 unsigned ScopeLine = 0;
5088 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
5089 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
5090 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
5091
5092 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5093 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
5094 // Key Instructions: Don't set flag on declarations.
5095 assert(~SPFlags & llvm::DISubprogram::SPFlagDefinition);
5096 llvm::DISubprogram *SP = DBuilder.createFunction(
5097 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
5098 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations,
5099 /*TargetFunctionName*/ "", /*UseKeyInstructions*/ false);
5100
5101 // Preserve btf_decl_tag attributes for parameters of extern functions
5102 // for BPF target. The parameters created in this loop are attached as
5103 // DISubprogram's retainedNodes in the DIBuilder::finalize() call.
5104 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
5105 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5106 llvm::DITypeArray ParamTypes = STy->getTypeArray();
5107 unsigned ArgNo = 1;
5108 for (ParmVarDecl *PD : FD->parameters()) {
5109 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
5110 DBuilder.createParameterVariable(
5111 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
5112 llvm::DINode::FlagZero, ParamAnnotations);
5113 ++ArgNo;
5114 }
5115 }
5116 }
5117
5118 if (IsDeclForCallSite)
5119 Fn->setSubprogram(SP);
5120}
5121
5123 llvm::CallBase *CI) {
5124 if (!shouldGenerateVirtualCallSite())
5125 return;
5126
5127 if (!FD)
5128 return;
5129
5130 assert(CI && "Invalid Call Instruction.");
5131 if (!CI->isIndirectCall())
5132 return;
5133
5134 // Always get the method declaration.
5135 if (llvm::DISubprogram *MD = getFunctionDeclaration(FD))
5136 CI->setMetadata(llvm::LLVMContext::MD_call_target, MD);
5137}
5138
5139void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
5140 QualType CalleeType,
5141 GlobalDecl CalleeGlobalDecl) {
5142 if (!CallOrInvoke)
5143 return;
5144 auto *Func = dyn_cast<llvm::Function>(CallOrInvoke->getCalledOperand());
5145 if (!Func)
5146 return;
5147 if (Func->getSubprogram())
5148 return;
5149
5150 const FunctionDecl *CalleeDecl =
5151 cast<FunctionDecl>(CalleeGlobalDecl.getDecl());
5152
5153 // Do not emit a declaration subprogram for a function with nodebug
5154 // attribute, or if call site info isn't required.
5155 if (CalleeDecl->hasAttr<NoDebugAttr>() ||
5156 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
5157 return;
5158
5159 // If there is no DISubprogram attached to the function being called,
5160 // create the one describing the function in order to have complete
5161 // call site debug info.
5162 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
5163 EmitFunctionDecl(CalleeGlobalDecl, CalleeDecl->getLocation(), CalleeType,
5164 Func);
5165}
5166
5168 const auto *FD = cast<FunctionDecl>(GD.getDecl());
5169 // If there is a subprogram for this function available then use it.
5170 auto FI = SPCache.find(FD->getCanonicalDecl());
5171 llvm::DISubprogram *SP = nullptr;
5172 if (FI != SPCache.end())
5173 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
5174 if (!SP || !SP->isDefinition())
5175 SP = getFunctionStub(GD);
5176 FnBeginRegionCount.push_back(LexicalBlockStack.size());
5177 LexicalBlockStack.emplace_back(SP);
5178 setInlinedAt(Builder.getCurrentDebugLocation());
5179 EmitLocation(Builder, FD->getLocation());
5180}
5181
5183 assert(CurInlinedAt && "unbalanced inline scope stack");
5184 EmitFunctionEnd(Builder, nullptr);
5185 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
5186}
5187
5189 // Update our current location
5190 setLocation(Loc);
5191
5192 if (CurLoc.isInvalid() ||
5193 (CGM.getCodeGenOpts().DebugInfoMacroExpansionLoc && CurLoc.isMacroID()) ||
5194 LexicalBlockStack.empty())
5195 return;
5196
5197 llvm::MDNode *Scope = LexicalBlockStack.back();
5198 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
5199 CGM.getLLVMContext(), CurLocLine, CurLocColumn, Scope, CurInlinedAt));
5200}
5201
5202void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
5203 llvm::MDNode *Back = nullptr;
5204 if (!LexicalBlockStack.empty())
5205 Back = LexicalBlockStack.back().get();
5206 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
5207 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
5208 getColumnNumber(CurLoc)));
5209}
5210
5211void CGDebugInfo::AppendAddressSpaceXDeref(
5212 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
5213 std::optional<unsigned> DWARFAddressSpace =
5214 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
5215 if (!DWARFAddressSpace)
5216 return;
5217
5218 Expr.push_back(llvm::dwarf::DW_OP_constu);
5219 Expr.push_back(*DWARFAddressSpace);
5220 Expr.push_back(llvm::dwarf::DW_OP_swap);
5221 Expr.push_back(llvm::dwarf::DW_OP_xderef);
5222}
5223
5225 SourceLocation Loc) {
5226 // Set our current location.
5227 setLocation(Loc);
5228
5229 // Emit a line table change for the current location inside the new scope.
5230 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
5231 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
5232 LexicalBlockStack.back(), CurInlinedAt));
5233
5234 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5235 return;
5236
5237 // Create a new lexical block and push it on the stack.
5238 CreateLexicalBlock(Loc);
5239}
5240
5242 SourceLocation Loc) {
5243 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5244
5245 // Provide an entry in the line table for the end of the block.
5246 EmitLocation(Builder, Loc);
5247
5248 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5249 return;
5250
5251 LexicalBlockStack.pop_back();
5252}
5253
5254void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
5255 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5256 unsigned RCount = FnBeginRegionCount.back();
5257 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
5258
5259 // Pop all regions for this function.
5260 while (LexicalBlockStack.size() != RCount) {
5261 // Provide an entry in the line table for the end of the block.
5262 EmitLocation(Builder, CurLoc);
5263 LexicalBlockStack.pop_back();
5264 }
5265 FnBeginRegionCount.pop_back();
5266
5267 if (Fn && Fn->getSubprogram())
5268 DBuilder.finalizeSubprogram(Fn->getSubprogram());
5269}
5270
5271CGDebugInfo::BlockByRefType
5272CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
5273 uint64_t *XOffset) {
5275 QualType FType;
5276 uint64_t FieldSize, FieldOffset;
5277 uint32_t FieldAlign;
5278
5279 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5280 QualType Type = VD->getType();
5281
5282 FieldOffset = 0;
5283 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5284 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
5285 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
5286 FType = CGM.getContext().IntTy;
5287 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
5288 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
5289
5290 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
5291 if (HasCopyAndDispose) {
5292 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5293 EltTys.push_back(
5294 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
5295 EltTys.push_back(
5296 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
5297 }
5298 bool HasByrefExtendedLayout;
5299 Qualifiers::ObjCLifetime Lifetime;
5300 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
5301 HasByrefExtendedLayout) &&
5302 HasByrefExtendedLayout) {
5303 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5304 EltTys.push_back(
5305 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
5306 }
5307
5308 CharUnits Align = CGM.getContext().getDeclAlign(VD);
5309 if (Align > CGM.getContext().toCharUnitsFromBits(
5311 CharUnits FieldOffsetInBytes =
5312 CGM.getContext().toCharUnitsFromBits(FieldOffset);
5313 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
5314 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
5315
5316 if (NumPaddingBytes.isPositive()) {
5317 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
5318 FType = CGM.getContext().getConstantArrayType(
5319 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
5320 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
5321 }
5322 }
5323
5324 FType = Type;
5325 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
5326 FieldSize = CGM.getContext().getTypeSize(FType);
5327 FieldAlign = CGM.getContext().toBits(Align);
5328
5329 *XOffset = FieldOffset;
5330 llvm::DIType *FieldTy = DBuilder.createMemberType(
5331 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
5332 llvm::DINode::FlagZero, WrappedTy);
5333 EltTys.push_back(FieldTy);
5334 FieldOffset += FieldSize;
5335
5336 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5337 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
5338 llvm::DINode::FlagZero, nullptr, Elements),
5339 WrappedTy};
5340}
5341
5342llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
5343 llvm::Value *Storage,
5344 std::optional<unsigned> ArgNo,
5345 CGBuilderTy &Builder,
5346 const bool UsePointerValue) {
5347 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5348 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5349 if (VD->hasAttr<NoDebugAttr>())
5350 return nullptr;
5351
5352 const bool VarIsArtificial = IsArtificial(VD);
5353
5354 llvm::DIFile *Unit = nullptr;
5355 if (!VarIsArtificial)
5356 Unit = getOrCreateFile(VD->getLocation());
5357 llvm::DIType *Ty;
5358 uint64_t XOffset = 0;
5359 if (VD->hasAttr<BlocksAttr>())
5360 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5361 else
5362 Ty = getOrCreateType(VD->getType(), Unit);
5363
5364 // If there is no debug info for this type then do not emit debug info
5365 // for this variable.
5366 if (!Ty)
5367 return nullptr;
5368
5369 // Get location information.
5370 unsigned Line = 0;
5371 unsigned Column = 0;
5372 if (!VarIsArtificial) {
5373 Line = getLineNumber(VD->getLocation());
5374 Column = getColumnNumber(VD->getLocation());
5375 }
5376 SmallVector<uint64_t, 13> Expr;
5377 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5378
5379 // While synthesized Objective-C property setters are "artificial" (i.e., they
5380 // are not spelled out in source), we want to pretend they are just like a
5381 // regular non-compiler generated method. Hence, don't mark explicitly passed
5382 // parameters of such methods as artificial.
5383 if (VarIsArtificial && !IsObjCSynthesizedPropertyExplicitParameter(VD))
5384 Flags |= llvm::DINode::FlagArtificial;
5385
5386 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5387
5388 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
5389 AppendAddressSpaceXDeref(AddressSpace, Expr);
5390
5391 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
5392 // object pointer flag.
5393 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
5394 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
5395 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5396 Flags |= llvm::DINode::FlagObjectPointer;
5397 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5398 if (PVD->isExplicitObjectParameter())
5399 Flags |= llvm::DINode::FlagObjectPointer;
5400 }
5401
5402 // Note: Older versions of clang used to emit byval references with an extra
5403 // DW_OP_deref, because they referenced the IR arg directly instead of
5404 // referencing an alloca. Newer versions of LLVM don't treat allocas
5405 // differently from other function arguments when used in a dbg.declare.
5406 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5407 StringRef Name = VD->getName();
5408 if (!Name.empty()) {
5409 // __block vars are stored on the heap if they are captured by a block that
5410 // can escape the local scope.
5411 if (VD->isEscapingByref()) {
5412 // Here, we need an offset *into* the alloca.
5413 CharUnits offset = CharUnits::fromQuantity(32);
5414 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5415 // offset of __forwarding field
5416 offset = CGM.getContext().toCharUnitsFromBits(
5417 CGM.getTarget().getPointerWidth(LangAS::Default));
5418 Expr.push_back(offset.getQuantity());
5419 Expr.push_back(llvm::dwarf::DW_OP_deref);
5420 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5421 // offset of x field
5422 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5423 Expr.push_back(offset.getQuantity());
5424 }
5425 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
5426 // If VD is an anonymous union then Storage represents value for
5427 // all union fields.
5428 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
5429 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
5430 // GDB has trouble finding local variables in anonymous unions, so we emit
5431 // artificial local variables for each of the members.
5432 //
5433 // FIXME: Remove this code as soon as GDB supports this.
5434 // The debug info verifier in LLVM operates based on the assumption that a
5435 // variable has the same size as its storage and we had to disable the
5436 // check for artificial variables.
5437 for (const auto *Field : RD->fields()) {
5438 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5439 StringRef FieldName = Field->getName();
5440
5441 // Ignore unnamed fields. Do not ignore unnamed records.
5442 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
5443 continue;
5444
5445 // Use VarDecl's Tag, Scope and Line number.
5446 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
5447 auto *D = DBuilder.createAutoVariable(
5448 Scope, FieldName, Unit, Line, FieldTy,
5449 CGM.getCodeGenOpts().OptimizationLevel != 0,
5450 Flags | llvm::DINode::FlagArtificial, FieldAlign);
5451
5452 // Insert an llvm.dbg.declare into the current block.
5453 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5454 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5455 Column, Scope,
5456 CurInlinedAt),
5457 Builder.GetInsertBlock());
5458 }
5459 }
5460 }
5461
5462 // Clang stores the sret pointer provided by the caller in a static alloca.
5463 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5464 // the address of the variable.
5465 if (UsePointerValue) {
5466 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5467 "Debug info already contains DW_OP_deref.");
5468 Expr.push_back(llvm::dwarf::DW_OP_deref);
5469 }
5470
5471 // Create the descriptor for the variable.
5472 llvm::DILocalVariable *D = nullptr;
5473 if (ArgNo) {
5474 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
5475 D = DBuilder.createParameterVariable(
5476 Scope, Name, *ArgNo, Unit, Line, Ty,
5477 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Annotations);
5478 } else {
5479 // For normal local variable, we will try to find out whether 'VD' is the
5480 // copy parameter of coroutine.
5481 // If yes, we are going to use DIVariable of the origin parameter instead
5482 // of creating the new one.
5483 // If no, it might be a normal alloc, we just create a new one for it.
5484
5485 // Check whether the VD is move parameters.
5486 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
5487 // The scope of parameter and move-parameter should be distinct
5488 // DISubprogram.
5489 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
5490 return nullptr;
5491
5492 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
5493 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
5494 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
5495 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
5496 Decl *Decl = DeclGroup.getSingleDecl();
5497 if (VD == dyn_cast_or_null<VarDecl>(Decl))
5498 return true;
5499 }
5500 return false;
5501 });
5502
5503 if (Iter != CoroutineParameterMappings.end()) {
5504 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
5505 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
5506 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
5507 });
5508 if (Iter2 != ParamDbgMappings.end())
5509 return const_cast<llvm::DILocalVariable *>(Iter2->second);
5510 }
5511 return nullptr;
5512 };
5513
5514 // If we couldn't find a move param DIVariable, create a new one.
5515 D = RemapCoroArgToLocalVar();
5516 // Or we will create a new DIVariable for this Decl if D dose not exists.
5517 if (!D)
5518 D = DBuilder.createAutoVariable(
5519 Scope, Name, Unit, Line, Ty,
5520 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Align);
5521 }
5522 // Insert an llvm.dbg.declare into the current block.
5523 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5524 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5525 Column, Scope, CurInlinedAt),
5526 Builder.GetInsertBlock());
5527
5528 return D;
5529}
5530
5531llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
5532 llvm::Value *Storage,
5533 std::optional<unsigned> ArgNo,
5534 CGBuilderTy &Builder,
5535 const bool UsePointerValue) {
5536 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5537 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5538 if (BD->hasAttr<NoDebugAttr>())
5539 return nullptr;
5540
5541 // Skip the tuple like case, we don't handle that here
5542 if (isa<DeclRefExpr>(BD->getBinding()))
5543 return nullptr;
5544
5545 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
5546 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
5547
5548 // If there is no debug info for this type then do not emit debug info
5549 // for this variable.
5550 if (!Ty)
5551 return nullptr;
5552
5553 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
5554 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
5555
5556 SmallVector<uint64_t, 3> Expr;
5557 AppendAddressSpaceXDeref(AddressSpace, Expr);
5558
5559 // Clang stores the sret pointer provided by the caller in a static alloca.
5560 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5561 // the address of the variable.
5562 if (UsePointerValue) {
5563 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5564 "Debug info already contains DW_OP_deref.");
5565 Expr.push_back(llvm::dwarf::DW_OP_deref);
5566 }
5567
5568 unsigned Line = getLineNumber(BD->getLocation());
5569 unsigned Column = getColumnNumber(BD->getLocation());
5570 StringRef Name = BD->getName();
5571 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5572 // Create the descriptor for the variable.
5573 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5574 Scope, Name, Unit, Line, Ty, CGM.getCodeGenOpts().OptimizationLevel != 0,
5575 llvm::DINode::FlagZero, Align);
5576
5577 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5578 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5579 const unsigned fieldIndex = FD->getFieldIndex();
5580 const clang::CXXRecordDecl *parent =
5581 (const CXXRecordDecl *)FD->getParent();
5582 const ASTRecordLayout &layout =
5583 CGM.getContext().getASTRecordLayout(parent);
5584 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5585 if (FD->isBitField()) {
5586 const CGRecordLayout &RL =
5587 CGM.getTypes().getCGRecordLayout(FD->getParent());
5588 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5589 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5590 // storage.
5591 if (!Info.StorageOffset.isZero()) {
5592 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5593 Expr.push_back(Info.StorageOffset.getQuantity());
5594 }
5595 // Use LLVM_extract_bits to extract the appropriate bits from this
5596 // bitfield.
5597 Expr.push_back(Info.IsSigned
5598 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5599 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5600 Expr.push_back(Info.Offset);
5601 // If we have an oversized bitfield then the value won't be more than
5602 // the size of the type.
5603 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5604 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5605 } else if (fieldOffset != 0) {
5606 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5607 "Unexpected non-bitfield with non-byte-aligned offset");
5608 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5609 Expr.push_back(
5610 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5611 }
5612 }
5613 } else if (const ArraySubscriptExpr *ASE =
5614 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5615 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5616 const uint64_t value = IL->getValue().getZExtValue();
5617 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5618
5619 if (value != 0) {
5620 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5621 Expr.push_back(CGM.getContext()
5622 .toCharUnitsFromBits(value * typeSize)
5623 .getQuantity());
5624 }
5625 }
5626 }
5627
5628 // Insert an llvm.dbg.declare into the current block.
5629 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5630 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5631 Column, Scope, CurInlinedAt),
5632 Builder.GetInsertBlock());
5633
5634 return D;
5635}
5636
5637llvm::DILocalVariable *
5638CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5639 CGBuilderTy &Builder,
5640 const bool UsePointerValue) {
5641 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5642
5643 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5644 for (BindingDecl *B : DD->flat_bindings())
5645 EmitDeclare(B, Storage, std::nullopt, Builder,
5646 VD->getType()->isReferenceType());
5647 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5648 // correspond to a user variable.
5649 return nullptr;
5650 }
5651
5652 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5653}
5654
5656 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5657 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5658
5659 if (D->hasAttr<NoDebugAttr>())
5660 return;
5661
5662 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5663 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5664
5665 // Get location information.
5666 unsigned Line = getLineNumber(D->getLocation());
5667 unsigned Column = getColumnNumber(D->getLocation());
5668
5669 StringRef Name = D->getName();
5670
5671 // Create the descriptor for the label.
5672 auto *L = DBuilder.createLabel(Scope, Name, Unit, Line, Column,
5673 /*IsArtificial=*/false,
5674 /*CoroSuspendIdx=*/std::nullopt,
5675 CGM.getCodeGenOpts().OptimizationLevel != 0);
5676
5677 // Insert an llvm.dbg.label into the current block.
5678 DBuilder.insertLabel(L,
5679 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5680 Scope, CurInlinedAt),
5681 Builder.GetInsertBlock()->end());
5682}
5683
5684llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5685 llvm::DIType *Ty) {
5686 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5687 if (CachedTy)
5688 Ty = CachedTy;
5689 return DBuilder.createObjectPointerType(Ty, /*Implicit=*/true);
5690}
5691
5693 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5694 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5695 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5696 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5697
5698 if (Builder.GetInsertBlock() == nullptr)
5699 return;
5700 if (VD->hasAttr<NoDebugAttr>())
5701 return;
5702
5703 bool isByRef = VD->hasAttr<BlocksAttr>();
5704
5705 uint64_t XOffset = 0;
5706 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5707 llvm::DIType *Ty;
5708 if (isByRef)
5709 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5710 else
5711 Ty = getOrCreateType(VD->getType(), Unit);
5712
5713 // Self is passed along as an implicit non-arg variable in a
5714 // block. Mark it as the object pointer.
5715 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5716 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5717 Ty = CreateSelfType(VD->getType(), Ty);
5718
5719 // Get location information.
5720 const unsigned Line =
5721 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5722 unsigned Column = getColumnNumber(VD->getLocation());
5723
5724 const llvm::DataLayout &target = CGM.getDataLayout();
5725
5727 target.getStructLayout(blockInfo.StructureType)
5728 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5729
5731 addr.push_back(llvm::dwarf::DW_OP_deref);
5732 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5733 addr.push_back(offset.getQuantity());
5734 if (isByRef) {
5735 addr.push_back(llvm::dwarf::DW_OP_deref);
5736 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5737 // offset of __forwarding field
5738 offset =
5739 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5740 addr.push_back(offset.getQuantity());
5741 addr.push_back(llvm::dwarf::DW_OP_deref);
5742 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5743 // offset of x field
5744 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5745 addr.push_back(offset.getQuantity());
5746 }
5747
5748 // Create the descriptor for the variable.
5749 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5750 auto *D = DBuilder.createAutoVariable(
5751 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5752 Line, Ty, false, llvm::DINode::FlagZero, Align);
5753
5754 // Insert an llvm.dbg.declare into the current block.
5755 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5756 LexicalBlockStack.back(), CurInlinedAt);
5757 auto *Expr = DBuilder.createExpression(addr);
5758 if (InsertPoint)
5759 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint->getIterator());
5760 else
5761 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5762}
5763
5764llvm::DILocalVariable *
5766 unsigned ArgNo, CGBuilderTy &Builder,
5767 bool UsePointerValue) {
5768 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5769 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5770}
5771
5772namespace {
5773struct BlockLayoutChunk {
5774 uint64_t OffsetInBits;
5776};
5777bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5778 return l.OffsetInBits < r.OffsetInBits;
5779}
5780} // namespace
5781
5782void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5783 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5784 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5785 SmallVectorImpl<llvm::Metadata *> &Fields) {
5786 // Blocks in OpenCL have unique constraints which make the standard fields
5787 // redundant while requiring size and align fields for enqueue_kernel. See
5788 // initializeForBlockHeader in CGBlocks.cpp
5789 if (CGM.getLangOpts().OpenCL) {
5790 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5791 BlockLayout.getElementOffsetInBits(0),
5792 Unit, Unit));
5793 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5794 BlockLayout.getElementOffsetInBits(1),
5795 Unit, Unit));
5796 } else {
5797 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5798 BlockLayout.getElementOffsetInBits(0),
5799 Unit, Unit));
5800 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5801 BlockLayout.getElementOffsetInBits(1),
5802 Unit, Unit));
5803 Fields.push_back(
5804 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5805 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5806 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5807 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5808 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5809 BlockLayout.getElementOffsetInBits(3),
5810 Unit, Unit));
5811 Fields.push_back(createFieldType(
5812 "__descriptor",
5813 Context.getPointerType(Block.NeedsCopyDispose
5815 : Context.getBlockDescriptorType()),
5816 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5817 }
5818}
5819
5821 StringRef Name,
5822 unsigned ArgNo,
5823 llvm::AllocaInst *Alloca,
5824 CGBuilderTy &Builder) {
5825 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5826 ASTContext &C = CGM.getContext();
5827 const BlockDecl *blockDecl = block.getBlockDecl();
5828
5829 // Collect some general information about the block's location.
5830 SourceLocation loc = blockDecl->getCaretLocation();
5831 llvm::DIFile *tunit = getOrCreateFile(loc);
5832 unsigned line = getLineNumber(loc);
5833 unsigned column = getColumnNumber(loc);
5834
5835 // Build the debug-info type for the block literal.
5836 getDeclContextDescriptor(blockDecl);
5837
5838 const llvm::StructLayout *blockLayout =
5839 CGM.getDataLayout().getStructLayout(block.StructureType);
5840
5842 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5843 fields);
5844
5845 // We want to sort the captures by offset, not because DWARF
5846 // requires this, but because we're paranoid about debuggers.
5848
5849 // 'this' capture.
5850 if (blockDecl->capturesCXXThis()) {
5851 BlockLayoutChunk chunk;
5852 chunk.OffsetInBits =
5853 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5854 chunk.Capture = nullptr;
5855 chunks.push_back(chunk);
5856 }
5857
5858 // Variable captures.
5859 for (const auto &capture : blockDecl->captures()) {
5860 const VarDecl *variable = capture.getVariable();
5861 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5862
5863 // Ignore constant captures.
5864 if (captureInfo.isConstant())
5865 continue;
5866
5867 BlockLayoutChunk chunk;
5868 chunk.OffsetInBits =
5869 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
5870 chunk.Capture = &capture;
5871 chunks.push_back(chunk);
5872 }
5873
5874 // Sort by offset.
5875 llvm::array_pod_sort(chunks.begin(), chunks.end());
5876
5877 for (const BlockLayoutChunk &Chunk : chunks) {
5878 uint64_t offsetInBits = Chunk.OffsetInBits;
5879 const BlockDecl::Capture *capture = Chunk.Capture;
5880
5881 // If we have a null capture, this must be the C++ 'this' capture.
5882 if (!capture) {
5883 QualType type;
5884 if (auto *Method =
5885 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
5886 type = Method->getThisType();
5887 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
5888 type = CGM.getContext().getCanonicalTagType(RDecl);
5889 else
5890 llvm_unreachable("unexpected block declcontext");
5891
5892 fields.push_back(createFieldType("this", type, loc, AS_public,
5893 offsetInBits, tunit, tunit));
5894 continue;
5895 }
5896
5897 const VarDecl *variable = capture->getVariable();
5898 StringRef name = variable->getName();
5899
5900 llvm::DIType *fieldType;
5901 if (capture->isByRef()) {
5902 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
5903 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
5904 // FIXME: This recomputes the layout of the BlockByRefWrapper.
5905 uint64_t xoffset;
5906 fieldType =
5907 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
5908 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
5909 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
5910 PtrInfo.Width, Align, offsetInBits,
5911 llvm::DINode::FlagZero, fieldType);
5912 } else {
5913 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
5914 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
5915 offsetInBits, Align, tunit, tunit);
5916 }
5917 fields.push_back(fieldType);
5918 }
5919
5920 SmallString<36> typeName;
5921 llvm::raw_svector_ostream(typeName)
5922 << "__block_literal_" << CGM.getUniqueBlockCount();
5923
5924 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
5925
5926 llvm::DIType *type =
5927 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
5928 CGM.getContext().toBits(block.BlockSize), 0,
5929 llvm::DINode::FlagZero, nullptr, fieldsArray);
5930 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
5931
5932 // Get overall information about the block.
5933 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
5934 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
5935
5936 // Create the descriptor for the parameter.
5937 auto *debugVar = DBuilder.createParameterVariable(
5938 scope, Name, ArgNo, tunit, line, type,
5939 CGM.getCodeGenOpts().OptimizationLevel != 0, flags);
5940
5941 // Insert an llvm.dbg.declare into the current block.
5942 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
5943 llvm::DILocation::get(CGM.getLLVMContext(), line,
5944 column, scope, CurInlinedAt),
5945 Builder.GetInsertBlock());
5946}
5947
5948llvm::DIDerivedType *
5949CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
5950 if (!D || !D->isStaticDataMember())
5951 return nullptr;
5952
5953 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
5954 if (MI != StaticDataMemberCache.end()) {
5955 assert(MI->second && "Static data member declaration should still exist");
5956 return MI->second;
5957 }
5958
5959 // If the member wasn't found in the cache, lazily construct and add it to the
5960 // type (used when a limited form of the type is emitted).
5961 auto DC = D->getDeclContext();
5962 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
5963 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
5964}
5965
5966llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
5967 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
5968 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
5969 llvm::DIGlobalVariableExpression *GVE = nullptr;
5970
5971 for (const auto *Field : RD->fields()) {
5972 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5973 StringRef FieldName = Field->getName();
5974
5975 // Ignore unnamed fields, but recurse into anonymous records.
5976 if (FieldName.empty()) {
5977 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
5978 GVE = CollectAnonRecordDecls(RT->getDecl()->getDefinitionOrSelf(), Unit,
5979 LineNo, LinkageName, Var, DContext);
5980 continue;
5981 }
5982 // Use VarDecl's Tag, Scope and Line number.
5983 GVE = DBuilder.createGlobalVariableExpression(
5984 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
5985 Var->hasLocalLinkage());
5986 Var->addDebugInfo(GVE);
5987 }
5988 return GVE;
5989}
5990
5991static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);
5992static bool ReferencesAnonymousEntity(RecordType *RT) {
5993 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
5994 // info we produce in the DWARF, so we can't get Clang's full name back.
5995 // But so long as it's not one of those, it doesn't matter if some sub-type
5996 // of the record (a template parameter) can't be reconstituted - because the
5997 // un-reconstitutable type itself will carry its own name.
5998 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5999 if (!RD)
6000 return false;
6001 if (!RD->getIdentifier())
6002 return true;
6003 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
6004 if (!TSpecial)
6005 return false;
6006 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
6007}
6009 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
6010 switch (TA.getKind()) {
6014 struct ReferencesAnonymous
6015 : public RecursiveASTVisitor<ReferencesAnonymous> {
6016 bool RefAnon = false;
6017 bool VisitRecordType(RecordType *RT) {
6018 if (ReferencesAnonymousEntity(RT)) {
6019 RefAnon = true;
6020 return false;
6021 }
6022 return true;
6023 }
6024 };
6025 ReferencesAnonymous RT;
6026 RT.TraverseType(TA.getAsType());
6027 if (RT.RefAnon)
6028 return true;
6029 break;
6030 }
6031 default:
6032 break;
6033 }
6034 return false;
6035 });
6036}
6037namespace {
6038struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
6039 bool Reconstitutable = true;
6040 bool VisitVectorType(VectorType *FT) {
6041 Reconstitutable = false;
6042 return false;
6043 }
6044 bool VisitAtomicType(AtomicType *FT) {
6045 Reconstitutable = false;
6046 return false;
6047 }
6048 bool TraverseEnumType(EnumType *ET, bool = false) {
6049 // Unnamed enums can't be reconstituted due to a lack of column info we
6050 // produce in the DWARF, so we can't get Clang's full name back.
6051 const EnumDecl *ED = ET->getDecl();
6052 if (!ED->getIdentifier()) {
6053 Reconstitutable = false;
6054 return false;
6055 }
6057 Reconstitutable = false;
6058 return false;
6059 }
6060 return true;
6061 }
6062 bool VisitFunctionProtoType(FunctionProtoType *FT) {
6063 // noexcept is not encoded in DWARF, so the reversi
6064 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
6065 Reconstitutable &= !FT->getNoReturnAttr();
6066 return Reconstitutable;
6067 }
6068 bool VisitRecordType(RecordType *RT, bool = false) {
6069 if (ReferencesAnonymousEntity(RT)) {
6070 Reconstitutable = false;
6071 return false;
6072 }
6073 return true;
6074 }
6075};
6076} // anonymous namespace
6077
6078// Test whether a type name could be rebuilt from emitted debug info.
6080 ReconstitutableType T;
6081 T.TraverseType(QT);
6082 return T.Reconstitutable;
6083}
6084
6085bool CGDebugInfo::HasReconstitutableArgs(
6086 ArrayRef<TemplateArgument> Args) const {
6087 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
6088 switch (TA.getKind()) {
6090 // Easy to reconstitute - the value of the parameter in the debug
6091 // info is the string name of the template. The template name
6092 // itself won't benefit from any name rebuilding, but that's a
6093 // representational limitation - maybe DWARF could be
6094 // changed/improved to use some more structural representation.
6095 return true;
6097 // Reference and pointer non-type template parameters point to
6098 // variables, functions, etc and their value is, at best (for
6099 // variables) represented as an address - not a reference to the
6100 // DWARF describing the variable/function/etc. This makes it hard,
6101 // possibly impossible to rebuild the original name - looking up
6102 // the address in the executable file's symbol table would be
6103 // needed.
6104 return false;
6106 // These could be rebuilt, but figured they're close enough to the
6107 // declaration case, and not worth rebuilding.
6108 return false;
6110 // A pack is invalid if any of the elements of the pack are
6111 // invalid.
6112 return HasReconstitutableArgs(TA.getPackAsArray());
6114 // Larger integers get encoded as DWARF blocks which are a bit
6115 // harder to parse back into a large integer, etc - so punting on
6116 // this for now. Re-parsing the integers back into APInt is
6117 // probably feasible some day.
6118 return TA.getAsIntegral().getBitWidth() <= 64 &&
6121 return false;
6123 return IsReconstitutableType(TA.getAsType());
6125 return IsReconstitutableType(TA.getAsExpr()->getType());
6126 default:
6127 llvm_unreachable("Other, unresolved, template arguments should "
6128 "not be seen here");
6129 }
6130 });
6131}
6132
6133std::string CGDebugInfo::GetName(const Decl *D, bool Qualified,
6134 bool *NameIsSimplified) const {
6135 std::string Name;
6136 llvm::raw_string_ostream OS(Name);
6137 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
6138 if (!ND)
6139 return Name;
6140 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
6141 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
6142
6143 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6144 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
6145
6146 std::optional<TemplateArgs> Args;
6147
6148 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
6149 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
6150 Args = GetTemplateArgs(RD);
6151 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
6152 Args = GetTemplateArgs(FD);
6153 auto NameKind = ND->getDeclName().getNameKind();
6154 IsOperatorOverload |=
6157 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
6158 Args = GetTemplateArgs(VD);
6159 }
6160
6161 // A conversion operator presents complications/ambiguity if there's a
6162 // conversion to class template that is itself a template, eg:
6163 // template<typename T>
6164 // operator ns::t1<T, int>();
6165 // This should be named, eg: "operator ns::t1<float, int><float>"
6166 // (ignoring clang bug that means this is currently "operator t1<float>")
6167 // but if the arguments were stripped, the consumer couldn't differentiate
6168 // whether the template argument list for the conversion type was the
6169 // function's argument list (& no reconstitution was needed) or not.
6170 // This could be handled if reconstitutable names had a separate attribute
6171 // annotating them as such - this would remove the ambiguity.
6172 //
6173 // Alternatively the template argument list could be parsed enough to check
6174 // whether there's one list or two, then compare that with the DWARF
6175 // description of the return type and the template argument lists to determine
6176 // how many lists there should be and if one is missing it could be assumed(?)
6177 // to be the function's template argument list & then be rebuilt.
6178 //
6179 // Other operator overloads that aren't conversion operators could be
6180 // reconstituted but would require a bit more nuance about detecting the
6181 // difference between these different operators during that rebuilding.
6182 bool Reconstitutable =
6183 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
6184
6185 PrintingPolicy PP = getPrintingPolicy();
6186
6187 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
6188 !Reconstitutable) {
6189 ND->getNameForDiagnostic(OS, PP, Qualified);
6190 } else {
6191 // Treat both "simple" and "mangled" as simplified.
6192 if (NameIsSimplified)
6193 *NameIsSimplified = true;
6194 bool Mangled = TemplateNamesKind ==
6195 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
6196 // check if it's a template
6197 if (Mangled)
6198 OS << "_STN|";
6199
6200 OS << ND->getDeclName();
6201 std::string EncodedOriginalName;
6202 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
6203 EncodedOriginalNameOS << ND->getDeclName();
6204
6205 if (Mangled) {
6206 OS << "|";
6207 printTemplateArgumentList(OS, Args->Args, PP);
6208 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
6209#ifndef NDEBUG
6210 std::string CanonicalOriginalName;
6211 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
6212 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
6213 assert(EncodedOriginalName == CanonicalOriginalName);
6214#endif
6215 }
6216 }
6217 return Name;
6218}
6219
6220void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
6221 const VarDecl *D) {
6222 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6223 if (D->hasAttr<NoDebugAttr>())
6224 return;
6225
6226 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
6227 return GetName(D, true);
6228 });
6229
6230 // If we already created a DIGlobalVariable for this declaration, just attach
6231 // it to the llvm::GlobalVariable.
6232 auto Cached = DeclCache.find(D->getCanonicalDecl());
6233 if (Cached != DeclCache.end())
6234 return Var->addDebugInfo(
6236
6237 // Create global variable debug descriptor.
6238 llvm::DIFile *Unit = nullptr;
6239 llvm::DIScope *DContext = nullptr;
6240 unsigned LineNo;
6241 StringRef DeclName, LinkageName;
6242 QualType T;
6243 llvm::MDTuple *TemplateParameters = nullptr;
6244 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
6245 TemplateParameters, DContext);
6246
6247 // Attempt to store one global variable for the declaration - even if we
6248 // emit a lot of fields.
6249 llvm::DIGlobalVariableExpression *GVE = nullptr;
6250
6251 // If this is an anonymous union then we'll want to emit a global
6252 // variable for each member of the anonymous union so that it's possible
6253 // to find the name of any field in the union.
6254 if (T->isUnionType() && DeclName.empty()) {
6255 const auto *RD = T->castAsRecordDecl();
6256 assert(RD->isAnonymousStructOrUnion() &&
6257 "unnamed non-anonymous struct or union?");
6258 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
6259 } else {
6260 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6261
6263 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
6264 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
6265 if (D->hasAttr<CUDASharedAttr>())
6266 AddressSpace =
6267 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
6268 else if (D->hasAttr<CUDAConstantAttr>())
6269 AddressSpace =
6270 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
6271 }
6272 AppendAddressSpaceXDeref(AddressSpace, Expr);
6273
6274 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
6275 GVE = DBuilder.createGlobalVariableExpression(
6276 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
6277 Var->hasLocalLinkage(), true,
6278 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
6279 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
6280 Align, Annotations);
6281 Var->addDebugInfo(GVE);
6282 }
6283 DeclCache[D->getCanonicalDecl()].reset(GVE);
6284}
6285
6287 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6288 if (VD->hasAttr<NoDebugAttr>())
6289 return;
6290 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
6291 return GetName(VD, true);
6292 });
6293
6294 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
6295 // Create the descriptor for the variable.
6296 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
6297 StringRef Name = VD->getName();
6298 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
6299
6300 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
6301 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
6302 if (CGM.getCodeGenOpts().EmitCodeView) {
6303 // If CodeView, emit enums as global variables, unless they are defined
6304 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
6305 // enums in classes, and because it is difficult to attach this scope
6306 // information to the global variable.
6308 return;
6309 } else {
6310 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
6311 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
6312 // first time `ZERO` is referenced in a function.
6313 CanQualType T = CGM.getContext().getCanonicalTagType(ED);
6314 [[maybe_unused]] llvm::DIType *EDTy = getOrCreateType(T, Unit);
6315 assert(EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
6316 return;
6317 }
6318 }
6319
6320 // Do not emit separate definitions for function local consts.
6322 return;
6323
6325 auto *VarD = dyn_cast<VarDecl>(VD);
6326 if (VarD && VarD->isStaticDataMember()) {
6327 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
6328 getDeclContextDescriptor(VarD);
6329 // Ensure that the type is retained even though it's otherwise unreferenced.
6330 //
6331 // FIXME: This is probably unnecessary, since Ty should reference RD
6332 // through its scope.
6333 RetainedTypes.push_back(
6334 CGM.getContext().getCanonicalTagType(RD).getAsOpaquePtr());
6335
6336 return;
6337 }
6338 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
6339
6340 auto &GV = DeclCache[VD];
6341 if (GV)
6342 return;
6343
6344 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
6345 llvm::MDTuple *TemplateParameters = nullptr;
6346
6348 if (VarD) {
6349 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
6350 TemplateParameters = parameterNodes.get();
6351 }
6352
6353 GV.reset(DBuilder.createGlobalVariableExpression(
6354 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
6355 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
6356 TemplateParameters, Align));
6357}
6358
6359void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
6360 const VarDecl *D) {
6361 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6362 if (D->hasAttr<NoDebugAttr>())
6363 return;
6364
6365 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6366 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
6367 StringRef Name = D->getName();
6368 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
6369
6370 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6371 llvm::DIGlobalVariableExpression *GVE =
6372 DBuilder.createGlobalVariableExpression(
6373 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
6374 Ty, false, false, nullptr, nullptr, nullptr, Align);
6375 Var->addDebugInfo(GVE);
6376}
6377
6379 llvm::Instruction *Value, QualType Ty) {
6380 // Only when -g2 or above is specified, debug info for variables will be
6381 // generated.
6382 if (CGM.getCodeGenOpts().getDebugInfo() <=
6383 llvm::codegenoptions::DebugLineTablesOnly)
6384 return;
6385
6386 llvm::DILocation *DIL = Value->getDebugLoc().get();
6387 if (!DIL)
6388 return;
6389
6390 llvm::DIFile *Unit = DIL->getFile();
6391 llvm::DIType *Type = getOrCreateType(Ty, Unit);
6392
6393 // Check if Value is already a declared variable and has debug info, in this
6394 // case we have nothing to do. Clang emits a declared variable as alloca, and
6395 // it is loaded upon use, so we identify such pattern here.
6396 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
6397 llvm::Value *Var = Load->getPointerOperand();
6398 // There can be implicit type cast applied on a variable if it is an opaque
6399 // ptr, in this case its debug info may not match the actual type of object
6400 // being used as in the next instruction, so we will need to emit a pseudo
6401 // variable for type-casted value.
6402 auto DeclareTypeMatches = [&](llvm::DbgVariableRecord *DbgDeclare) {
6403 return DbgDeclare->getVariable()->getType() == Type;
6404 };
6405 if (any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
6406 return;
6407 }
6408
6409 llvm::DILocalVariable *D =
6410 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
6411 Type, false, llvm::DINode::FlagArtificial);
6412
6413 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
6414 DBuilder.insertDbgValueIntrinsic(Value, D, DBuilder.createExpression(), DIL,
6415 *InsertPoint);
6416 }
6417}
6418
6419void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
6420 const GlobalDecl GD) {
6421
6422 assert(GV);
6423
6424 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6425 return;
6426
6427 const auto *D = cast<ValueDecl>(GD.getDecl());
6428 if (D->hasAttr<NoDebugAttr>())
6429 return;
6430
6431 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
6432 llvm::DINode *DI;
6433
6434 if (!AliaseeDecl)
6435 // FIXME: Aliasee not declared yet - possibly declared later
6436 // For example,
6437 //
6438 // 1 extern int newname __attribute__((alias("oldname")));
6439 // 2 int oldname = 1;
6440 //
6441 // No debug info would be generated for 'newname' in this case.
6442 //
6443 // Fix compiler to generate "newname" as imported_declaration
6444 // pointing to the DIE of "oldname".
6445 return;
6446 if (!(DI = getDeclarationOrDefinition(
6447 AliaseeDecl.getCanonicalDecl().getDecl())))
6448 return;
6449
6450 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6451 auto Loc = D->getLocation();
6452
6453 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
6454 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
6455
6456 // Record this DIE in the cache for nested declaration reference.
6457 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
6458}
6459
6460void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
6461 const StringLiteral *S) {
6462 SourceLocation Loc = S->getStrTokenLoc(0);
6463 SourceManager &SM = CGM.getContext().getSourceManager();
6464 PresumedLoc PLoc = SM.getPresumedLoc(getMacroDebugLoc(CGM, Loc));
6465 if (!PLoc.isValid())
6466 return;
6467
6468 llvm::DIFile *File = getOrCreateFile(Loc);
6469 llvm::DIGlobalVariableExpression *Debug =
6470 DBuilder.createGlobalVariableExpression(
6471 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
6472 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
6473 GV->addDebugInfo(Debug);
6474}
6475
6476llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
6477 if (!LexicalBlockStack.empty())
6478 return LexicalBlockStack.back();
6479 llvm::DIScope *Mod = getParentModuleOrNull(D);
6480 return getContextDescriptor(D, Mod ? Mod : TheCU);
6481}
6482
6484 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6485 return;
6486 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
6487 if (!NSDecl->isAnonymousNamespace() ||
6488 CGM.getCodeGenOpts().DebugExplicitImport) {
6489 auto Loc = UD.getLocation();
6490 if (!Loc.isValid())
6491 Loc = CurLoc;
6492 DBuilder.createImportedModule(
6493 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
6494 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
6495 }
6496}
6497
6499 if (llvm::DINode *Target =
6500 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
6501 auto Loc = USD.getLocation();
6502 DBuilder.createImportedDeclaration(
6503 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
6504 getOrCreateFile(Loc), getLineNumber(Loc));
6505 }
6506}
6507
6509 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6510 return;
6511 assert(UD.shadow_size() &&
6512 "We shouldn't be codegening an invalid UsingDecl containing no decls");
6513
6514 for (const auto *USD : UD.shadows()) {
6515 // FIXME: Skip functions with undeduced auto return type for now since we
6516 // don't currently have the plumbing for separate declarations & definitions
6517 // of free functions and mismatched types (auto in the declaration, concrete
6518 // return type in the definition)
6519 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
6520 if (const auto *AT = FD->getType()
6521 ->castAs<FunctionProtoType>()
6523 if (AT->getDeducedType().isNull())
6524 continue;
6525
6526 EmitUsingShadowDecl(*USD);
6527 // Emitting one decl is sufficient - debuggers can detect that this is an
6528 // overloaded name & provide lookup for all the overloads.
6529 break;
6530 }
6531}
6532
6534 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6535 return;
6536 assert(UD.shadow_size() &&
6537 "We shouldn't be codegening an invalid UsingEnumDecl"
6538 " containing no decls");
6539
6540 for (const auto *USD : UD.shadows())
6541 EmitUsingShadowDecl(*USD);
6542}
6543
6545 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
6546 return;
6547 if (Module *M = ID.getImportedModule()) {
6548 auto Info = ASTSourceDescriptor(*M);
6549 auto Loc = ID.getLocation();
6550 DBuilder.createImportedDeclaration(
6551 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
6552 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
6553 getLineNumber(Loc));
6554 }
6555}
6556
6557llvm::DIImportedEntity *
6559 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6560 return nullptr;
6561 auto &VH = NamespaceAliasCache[&NA];
6562 if (VH)
6564 llvm::DIImportedEntity *R;
6565 auto Loc = NA.getLocation();
6566 if (const auto *Underlying =
6567 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6568 // This could cache & dedup here rather than relying on metadata deduping.
6569 R = DBuilder.createImportedDeclaration(
6570 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6571 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6572 getLineNumber(Loc), NA.getName());
6573 else
6574 R = DBuilder.createImportedDeclaration(
6575 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6576 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6577 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6578 VH.reset(R);
6579 return R;
6580}
6581
6582llvm::DINamespace *
6583CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6584 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6585 // if necessary, and this way multiple declarations of the same namespace in
6586 // different parent modules stay distinct.
6587 auto I = NamespaceCache.find(NSDecl);
6588 if (I != NamespaceCache.end())
6589 return cast<llvm::DINamespace>(I->second);
6590
6591 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6592 // Don't trust the context if it is a DIModule (see comment above).
6593 llvm::DINamespace *NS =
6594 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6595 NamespaceCache[NSDecl].reset(NS);
6596 return NS;
6597}
6598
6599void CGDebugInfo::setDwoId(uint64_t Signature) {
6600 assert(TheCU && "no main compile unit");
6601 TheCU->setDWOId(Signature);
6602}
6603
6605 // Creating types might create further types - invalidating the current
6606 // element and the size(), so don't cache/reference them.
6607 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6608 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6609 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6610 ? CreateTypeDefinition(E.Type, E.Unit)
6611 : E.Decl;
6612 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6613 }
6614
6615 // Add methods to interface.
6616 for (const auto &P : ObjCMethodCache) {
6617 if (P.second.empty())
6618 continue;
6619
6620 QualType QTy(P.first->getTypeForDecl(), 0);
6621 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6622 assert(It != TypeCache.end());
6623
6624 llvm::DICompositeType *InterfaceDecl =
6625 cast<llvm::DICompositeType>(It->second);
6626
6627 auto CurElts = InterfaceDecl->getElements();
6628 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6629
6630 // For DWARF v4 or earlier, only add objc_direct methods.
6631 for (auto &SubprogramDirect : P.second)
6632 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6633 EltTys.push_back(SubprogramDirect.getPointer());
6634
6635 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6636 DBuilder.replaceArrays(InterfaceDecl, Elements);
6637 }
6638
6639 for (const auto &P : ReplaceMap) {
6640 assert(P.second);
6641 auto *Ty = cast<llvm::DIType>(P.second);
6642 assert(Ty->isForwardDecl());
6643
6644 auto It = TypeCache.find(P.first);
6645 assert(It != TypeCache.end());
6646 assert(It->second);
6647
6648 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6649 cast<llvm::DIType>(It->second));
6650 }
6651
6652 for (const auto &P : FwdDeclReplaceMap) {
6653 assert(P.second);
6654 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6655 llvm::Metadata *Repl;
6656
6657 auto It = DeclCache.find(P.first);
6658 // If there has been no definition for the declaration, call RAUW
6659 // with ourselves, that will destroy the temporary MDNode and
6660 // replace it with a standard one, avoiding leaking memory.
6661 if (It == DeclCache.end())
6662 Repl = P.second;
6663 else
6664 Repl = It->second;
6665
6666 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6667 Repl = GVE->getVariable();
6668 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6669 }
6670
6671 // We keep our own list of retained types, because we need to look
6672 // up the final type in the type cache.
6673 for (auto &RT : RetainedTypes)
6674 if (auto MD = TypeCache[RT])
6675 DBuilder.retainType(cast<llvm::DIType>(MD));
6676
6677 DBuilder.finalize();
6678}
6679
6680// Don't ignore in case of explicit cast where it is referenced indirectly.
6682 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
6683 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6684 DBuilder.retainType(DieTy);
6685}
6686
6688 if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
6689 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6690 DBuilder.retainType(DieTy);
6691}
6692
6694 if (LexicalBlockStack.empty())
6695 return llvm::DebugLoc();
6696
6697 llvm::MDNode *Scope = LexicalBlockStack.back();
6698 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6699 getColumnNumber(Loc), Scope);
6700}
6701
6702llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6703 // Call site-related attributes are only useful in optimized programs, and
6704 // when there's a possibility of debugging backtraces.
6705 if (CGM.getCodeGenOpts().OptimizationLevel == 0 ||
6706 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6707 DebugKind == llvm::codegenoptions::LocTrackingOnly ||
6708 !CGM.getCodeGenOpts().DebugCallSiteInfo)
6709 return llvm::DINode::FlagZero;
6710
6711 // Call site-related attributes are available in DWARF v5. Some debuggers,
6712 // while not fully DWARF v5-compliant, may accept these attributes as if they
6713 // were part of DWARF v4.
6714 bool SupportsDWARFv4Ext =
6715 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6716 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6717 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6718
6719 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6720 return llvm::DINode::FlagZero;
6721
6722 return llvm::DINode::FlagAllCallsDescribed;
6723}
6724
6725llvm::DIExpression *
6726CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6727 const APValue &Val) {
6728 // FIXME: Add a representation for integer constants wider than 64 bits.
6729 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6730 return nullptr;
6731
6732 if (Val.isFloat())
6733 return DBuilder.createConstantValueExpression(
6734 Val.getFloat().bitcastToAPInt().getZExtValue());
6735
6736 if (!Val.isInt())
6737 return nullptr;
6738
6739 llvm::APSInt const &ValInt = Val.getInt();
6740 std::optional<uint64_t> ValIntOpt;
6741 if (ValInt.isUnsigned())
6742 ValIntOpt = ValInt.tryZExtValue();
6743 else if (auto tmp = ValInt.trySExtValue())
6744 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6745 // use std::optional::transform
6746 ValIntOpt = static_cast<uint64_t>(*tmp);
6747
6748 if (ValIntOpt)
6749 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6750
6751 return nullptr;
6752}
6753
6754CodeGenFunction::LexicalScope::LexicalScope(CodeGenFunction &CGF,
6755 SourceRange Range)
6756 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
6757 CGF.CurLexicalScope = this;
6758 if (CGDebugInfo *DI = CGF.getDebugInfo())
6759 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
6760}
6761
6763 if (CGDebugInfo *DI = CGF.getDebugInfo())
6764 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
6765
6766 // If we should perform a cleanup, force them now. Note that
6767 // this ends the cleanup scope before rescoping any labels.
6768 if (PerformCleanup) {
6769 ApplyDebugLocation DL(CGF, Range.getEnd());
6770 ForceCleanup();
6771 }
6772}
6773
6775 std::string Label;
6776 switch (Handler) {
6777#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
6778 case Enum: \
6779 Label = "__ubsan_check_" #Name; \
6780 break;
6781
6783#undef SANITIZER_CHECK
6784 };
6785
6786 // Label doesn't require sanitization
6787 return Label;
6788}
6789
6790static std::string
6792 std::string Label;
6793 switch (Ordinal) {
6794#define SANITIZER(NAME, ID) \
6795 case SanitizerKind::SO_##ID: \
6796 Label = "__ubsan_check_" NAME; \
6797 break;
6798#include "clang/Basic/Sanitizers.def"
6799 default:
6800 llvm_unreachable("unexpected sanitizer kind");
6801 }
6802
6803 // Sanitize label (convert hyphens to underscores; also futureproof against
6804 // non-alpha)
6805 for (unsigned int i = 0; i < Label.length(); i++)
6806 if (!std::isalpha(Label[i]))
6807 Label[i] = '_';
6808
6809 return Label;
6810}
6811
6814 SanitizerHandler Handler) {
6815 llvm::DILocation *CheckDebugLoc = Builder.getCurrentDebugLocation();
6816 auto *DI = getDebugInfo();
6817 if (!DI || !CheckDebugLoc)
6818 return CheckDebugLoc;
6819 const auto &AnnotateDebugInfo =
6820 CGM.getCodeGenOpts().SanitizeAnnotateDebugInfo;
6821 if (AnnotateDebugInfo.empty())
6822 return CheckDebugLoc;
6823
6824 std::string Label;
6825 if (Ordinals.size() == 1)
6826 Label = SanitizerOrdinalToCheckLabel(Ordinals[0]);
6827 else
6828 Label = SanitizerHandlerToCheckLabel(Handler);
6829
6830 if (any_of(Ordinals, [&](auto Ord) { return AnnotateDebugInfo.has(Ord); })) {
6831 // Use ubsan header file to have the same filename for all checks. There is
6832 // nothing special in that file, we just want to make tools to count all
6833 // syntetic functions of a check as the same.
6834 llvm::DIFile *File = llvm::DIFile::get(CGM.getLLVMContext(),
6835 /*Filename=*/"ubsan_interface.h",
6836 /*Directory=*/"sanitizer");
6837 return DI->CreateSyntheticInlineAt(CheckDebugLoc, Label, File);
6838 }
6839
6840 return CheckDebugLoc;
6841}
6842
6845 SanitizerHandler Handler)
6846 : CGF(CGF),
6847 Apply(*CGF, CGF->SanitizerAnnotateDebugInfo(Ordinals, Handler)) {
6848 assert(!CGF->IsSanitizerScope);
6849 CGF->IsSanitizerScope = true;
6850}
6851
6853 assert(CGF->IsSanitizerScope);
6854 CGF->IsSanitizerScope = false;
6855}
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.
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:223
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
SourceManager & getSourceManager()
Definition ASTContext.h:863
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:3798
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3592
shadow_range shadows() const
Definition DeclCXX.h:3580
A binding in a decomposition declaration.
Definition DeclCXX.h:4203
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition DeclCXX.h:4229
bool isUnsigned() const
Definition TypeBase.h:8309
unsigned getNumBits() const
Definition TypeBase.h:8311
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:3618
Kind getKind() const
Definition TypeBase.h:3276
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3490
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
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:1148
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1251
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:1023
capture_const_iterator captures_end() const
Definition DeclCXX.h:1112
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:1266
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:1099
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:1106
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
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 completeUnusedClass(const CXXRecordDecl &D)
void setInlinedAt(llvm::DILocation *InlinedAt)
Update the current inline scope.
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 * getInlinedAt() const
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:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
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:283
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:5371
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4915
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
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:4415
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5643
QualType getPointeeType() const
Definition TypeBase.h:3735
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:3219
NamespaceBaseDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition DeclCXX.h:3312
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:989
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:8140
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8077
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:8276
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:3402
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:8447
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:8394
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4793
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
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4535
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:3655
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:9050
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:456
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
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:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2963
bool isMemberDataPointerType() const
Definition TypeBase.h:8776
bool isComplexIntegerType() const
Definition Type.cpp:768
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2528
TypeClass getTypeClass() const
Definition TypeBase.h:2445
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
QualType getUnderlyingType() const
Definition Decl.h:3639
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6216
Represents a C++ using-declaration.
Definition DeclCXX.h:3609
Represents C++ using-directive.
Definition DeclCXX.h:3114
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3345
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3810
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3417
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:4254
QualType getElementType() const
Definition TypeBase.h:4253
@ 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:196
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:4200
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
@ 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
int line
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#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:5456
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:197