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