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;
444 PP.AlwaysIncludeTypeForTemplateArgument = true;
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 return CGM.getCodeGenOpts().remapDebugPathPrefix(Path);
676}
677
678unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
679 if (Loc.isInvalid())
680 return 0;
682 SourceLocation DebugLoc = getMacroDebugLoc(CGM, Loc);
683 if (DebugLoc == CurLoc)
684 return CurLocLine;
685 return SM.getPresumedLoc(DebugLoc).getLine();
686}
687
688unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
689 // We may not want column information at all.
690 if (!CGM.getCodeGenOpts().DebugColumnInfo)
691 return 0;
692
693 // If the location is invalid then use the current column.
694 if (Loc.isInvalid() && CurLoc.isInvalid())
695 return 0;
697 SourceLocation DebugLoc = Loc.isValid() ? getMacroDebugLoc(CGM, Loc) : CurLoc;
698 if (DebugLoc == CurLoc)
699 return CurLocColumn;
700 PresumedLoc PLoc = SM.getPresumedLoc(DebugLoc);
701 return PLoc.isValid() ? PLoc.getColumn() : 0;
702}
703
704StringRef CGDebugInfo::getCurrentDirname() {
706}
707
708static llvm::dwarf::SourceLanguage GetSourceLanguage(const CodeGenModule &CGM) {
709 const CodeGenOptions &CGO = CGM.getCodeGenOpts();
710 const LangOptions &LO = CGM.getLangOpts();
711
712 assert(CGO.DwarfVersion <= 5);
713
714 llvm::dwarf::SourceLanguage LangTag;
715 if (LO.CPlusPlus) {
716 if (LO.HLSL)
717 LangTag = llvm::dwarf::DW_LANG_HLSL;
718 else if (LO.HIP)
719 LangTag = llvm::dwarf::DW_LANG_HIP;
720 else if (LO.ObjC)
721 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
722 else if (CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)
723 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
724 else if (LO.CPlusPlus14)
725 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
726 else if (LO.CPlusPlus11)
727 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
728 else
729 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
730 } else if (LO.ObjC) {
731 LangTag = llvm::dwarf::DW_LANG_ObjC;
732 } else if (LO.OpenCL && (!CGO.DebugStrictDwarf || CGO.DwarfVersion >= 5)) {
733 LangTag = llvm::dwarf::DW_LANG_OpenCL;
734 } else if (LO.C11 && !(CGO.DebugStrictDwarf && CGO.DwarfVersion < 5)) {
735 LangTag = llvm::dwarf::DW_LANG_C11;
736 } else if (LO.C99) {
737 LangTag = llvm::dwarf::DW_LANG_C99;
738 } else {
739 LangTag = llvm::dwarf::DW_LANG_C89;
740 }
741
742 return LangTag;
743}
744
745static llvm::DISourceLanguageName
747 // Emit pre-DWARFv6 language codes.
748 if (CGM.getCodeGenOpts().DwarfVersion < 6)
749 return llvm::DISourceLanguageName(GetSourceLanguage(CGM));
750
751 const LangOptions &LO = CGM.getLangOpts();
752
753 uint32_t LangVersion = 0;
754 llvm::dwarf::SourceLanguageName LangTag;
755 if (LO.CPlusPlus) {
756 if (LO.HLSL) {
757 LangTag = llvm::dwarf::DW_LNAME_HLSL;
758 } else if (LO.HIP) {
759 LangTag = llvm::dwarf::DW_LNAME_HIP;
760 } else if (LO.ObjC) {
761 LangTag = llvm::dwarf::DW_LNAME_ObjC_plus_plus;
762 } else {
763 LangTag = llvm::dwarf::DW_LNAME_C_plus_plus;
764 LangVersion = LO.getCPlusPlusLangStd().value_or(0);
765 }
766 } else if (LO.ObjC) {
767 LangTag = llvm::dwarf::DW_LNAME_ObjC;
768 } else if (LO.OpenCL) {
769 LangTag = llvm::dwarf::DW_LNAME_OpenCL_C;
770 } else {
771 LangTag = llvm::dwarf::DW_LNAME_C;
772 LangVersion = LO.getCLangStd().value_or(0);
773 }
774
775 return llvm::DISourceLanguageName(LangTag, LangVersion);
776}
777
778void CGDebugInfo::CreateCompileUnit() {
779 SmallString<64> Checksum;
780 std::optional<llvm::DIFile::ChecksumKind> CSKind;
781 std::optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
782
783 // Should we be asking the SourceManager for the main file name, instead of
784 // accepting it as an argument? This just causes the main file name to
785 // mismatch with source locations and create extra lexical scopes or
786 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
787 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
788 // because that's what the SourceManager says)
789
790 // Get absolute path name.
791 SourceManager &SM = CGM.getContext().getSourceManager();
792 auto &CGO = CGM.getCodeGenOpts();
793 const LangOptions &LO = CGM.getLangOpts();
794 std::string MainFileName = CGO.MainFileName;
795 if (MainFileName.empty())
796 MainFileName = "<stdin>";
797
798 // The main file name provided via the "-main-file-name" option contains just
799 // the file name itself with no path information. This file name may have had
800 // a relative path, so we look into the actual file entry for the main
801 // file to determine the real absolute path for the file.
802 std::string MainFileDir;
803 if (OptionalFileEntryRef MainFile =
805 MainFileDir = std::string(MainFile->getDir().getName());
806 if (!llvm::sys::path::is_absolute(MainFileName)) {
807 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
808 llvm::sys::path::Style Style =
810 ? (CGM.getTarget().getTriple().isOSWindows()
811 ? llvm::sys::path::Style::windows_backslash
812 : llvm::sys::path::Style::posix)
813 : llvm::sys::path::Style::native;
814 llvm::sys::path::append(MainFileDirSS, Style, MainFileName);
815 MainFileName = std::string(
816 llvm::sys::path::remove_leading_dotslash(MainFileDirSS, Style));
817 }
818 // If the main file name provided is identical to the input file name, and
819 // if the input file is a preprocessed source, use the module name for
820 // debug info. The module name comes from the name specified in the first
821 // linemarker if the input is a preprocessed source. In this case we don't
822 // know the content to compute a checksum.
823 if (MainFile->getName() == MainFileName &&
825 MainFile->getName().rsplit('.').second)
826 .isPreprocessed()) {
827 MainFileName = CGM.getModule().getName().str();
828 } else {
829 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
830 }
831 }
832
833 std::string Producer = getClangFullVersion();
834
835 // Figure out which version of the ObjC runtime we have.
836 unsigned RuntimeVers = 0;
837 if (LO.ObjC)
838 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
839
840 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
841 switch (DebugKind) {
842 case llvm::codegenoptions::NoDebugInfo:
843 case llvm::codegenoptions::LocTrackingOnly:
844 EmissionKind = llvm::DICompileUnit::NoDebug;
845 break;
846 case llvm::codegenoptions::DebugLineTablesOnly:
847 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
848 break;
849 case llvm::codegenoptions::DebugDirectivesOnly:
850 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
851 break;
852 case llvm::codegenoptions::DebugInfoConstructor:
853 case llvm::codegenoptions::LimitedDebugInfo:
854 case llvm::codegenoptions::FullDebugInfo:
855 case llvm::codegenoptions::UnusedTypeInfo:
856 EmissionKind = llvm::DICompileUnit::FullDebug;
857 break;
858 }
859
860 uint64_t DwoId = 0;
861 auto &CGOpts = CGM.getCodeGenOpts();
862 // The DIFile used by the CU is distinct from the main source
863 // file. Its directory part specifies what becomes the
864 // DW_AT_comp_dir (the compilation directory), even if the source
865 // file was specified with an absolute path.
866 if (CSKind)
867 CSInfo.emplace(*CSKind, Checksum);
868 llvm::DIFile *CUFile = DBuilder.createFile(
869 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
870 getSource(SM, SM.getMainFileID()));
871
872 StringRef Sysroot, SDK;
873 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB) {
874 StringRef FullSysroot = CGM.getHeaderSearchOpts().Sysroot;
875 if (CGM.getCodeGenOpts().DebugRecordSysroot)
876 Sysroot = FullSysroot;
877 auto B = llvm::sys::path::rbegin(FullSysroot);
878 auto E = llvm::sys::path::rend(FullSysroot);
879 auto It =
880 std::find_if(B, E, [](auto SDK) { return SDK.ends_with(".sdk"); });
881 if (It != E)
882 SDK = *It;
883 }
884
885 llvm::DICompileUnit::DebugNameTableKind NameTableKind =
886 static_cast<llvm::DICompileUnit::DebugNameTableKind>(
887 CGOpts.DebugNameTable);
888 if (CGM.getTarget().getTriple().isNVPTX())
889 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::None;
890 else if (CGM.getTarget().getTriple().getVendor() == llvm::Triple::Apple)
891 NameTableKind = llvm::DICompileUnit::DebugNameTableKind::Apple;
892
893 // Create new compile unit.
894 TheCU = DBuilder.createCompileUnit(
895 GetDISourceLanguageName(CGM), CUFile,
896 CGOpts.EmitVersionIdentMetadata ? Producer : "",
897 CGOpts.OptimizationLevel != 0 || CGOpts.PrepareForLTO ||
898 CGOpts.PrepareForThinLTO,
899 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
900 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
901 NameTableKind, CGOpts.DebugRangesBaseAddress, remapDIPath(Sysroot), SDK);
902}
903
904llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
905 llvm::dwarf::TypeKind Encoding;
906 StringRef BTName;
907 switch (BT->getKind()) {
908#define BUILTIN_TYPE(Id, SingletonId)
909#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
910#include "clang/AST/BuiltinTypes.def"
911 case BuiltinType::Dependent:
912 llvm_unreachable("Unexpected builtin type");
913 case BuiltinType::NullPtr:
914 return DBuilder.createNullPtrType();
915 case BuiltinType::Void:
916 return nullptr;
917 case BuiltinType::ObjCClass:
918 if (!ClassTy)
919 ClassTy =
920 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
921 "objc_class", TheCU, TheCU->getFile(), 0);
922 return ClassTy;
923 case BuiltinType::ObjCId: {
924 // typedef struct objc_class *Class;
925 // typedef struct objc_object {
926 // Class isa;
927 // } *id;
928
929 if (ObjTy)
930 return ObjTy;
931
932 if (!ClassTy)
933 ClassTy =
934 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
935 "objc_class", TheCU, TheCU->getFile(), 0);
936
937 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
938
939 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
940
941 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
942 (uint64_t)0, 0, llvm::DINode::FlagZero,
943 nullptr, llvm::DINodeArray());
944
945 DBuilder.replaceArrays(
946 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
947 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
948 llvm::DINode::FlagZero, ISATy)));
949 return ObjTy;
950 }
951 case BuiltinType::ObjCSel: {
952 if (!SelTy)
953 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
954 "objc_selector", TheCU,
955 TheCU->getFile(), 0);
956 return SelTy;
957 }
958
959#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
960 case BuiltinType::Id: \
961 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
962 SingletonId);
963#include "clang/Basic/OpenCLImageTypes.def"
964 case BuiltinType::OCLSampler:
965 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
966 case BuiltinType::OCLEvent:
967 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
968 case BuiltinType::OCLClkEvent:
969 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
970 case BuiltinType::OCLQueue:
971 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
972 case BuiltinType::OCLReserveID:
973 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
974#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
975 case BuiltinType::Id: \
976 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
977#include "clang/Basic/OpenCLExtensionTypes.def"
978#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
979 case BuiltinType::Id: \
980 return getOrCreateStructPtrType(#Name, SingletonId);
981#include "clang/Basic/HLSLIntangibleTypes.def"
982#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
983 case BuiltinType::Id: \
984 return DBuilder.createBasicType(#Name, 32, llvm::dwarf::DW_ATE_unsigned);
985#include "clang/Basic/HLSLPackedTypes.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 case BuiltinType::MetaInfo:
1225 llvm_unreachable("std::meta::info is consteval-only type");
1226 }
1227
1228 BTName = BT->getName(CGM.getLangOpts());
1229 // Bit size and offset of the type.
1230 uint64_t Size = CGM.getContext().getTypeSize(BT);
1231 return DBuilder.createBasicType(BTName, Size, Encoding);
1232}
1233
1234llvm::DIType *CGDebugInfo::CreateType(const BitIntType *Ty) {
1235 SmallString<32> Name;
1236 llvm::raw_svector_ostream OS(Name);
1237 OS << (Ty->isUnsigned() ? "unsigned _BitInt(" : "_BitInt(")
1238 << Ty->getNumBits() << ")";
1239 llvm::dwarf::TypeKind Encoding = Ty->isUnsigned()
1240 ? llvm::dwarf::DW_ATE_unsigned
1241 : llvm::dwarf::DW_ATE_signed;
1242 return DBuilder.createBasicType(Name, CGM.getContext().getTypeSize(Ty),
1243 Encoding, llvm::DINode::FlagZero, 0,
1244 Ty->getNumBits());
1245}
1246
1247llvm::DIType *CGDebugInfo::CreateType(const OverflowBehaviorType *Ty,
1248 llvm::DIFile *U) {
1249 return getOrCreateType(Ty->getUnderlyingType(), U);
1250}
1251
1252llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
1253 // Bit size and offset of the type.
1254 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
1255 if (Ty->isComplexIntegerType())
1256 Encoding = llvm::dwarf::DW_ATE_lo_user;
1257
1258 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1259 return DBuilder.createBasicType("complex", Size, Encoding);
1260}
1261
1263 // Ignore these qualifiers for now.
1264 Q.removeObjCGCAttr();
1267 Q.removeUnaligned();
1268}
1269
1270static llvm::dwarf::Tag getNextQualifier(Qualifiers &Q) {
1271 if (Q.hasConst()) {
1272 Q.removeConst();
1273 return llvm::dwarf::DW_TAG_const_type;
1274 }
1275 if (Q.hasVolatile()) {
1276 Q.removeVolatile();
1277 return llvm::dwarf::DW_TAG_volatile_type;
1278 }
1279 if (Q.hasRestrict()) {
1280 Q.removeRestrict();
1281 return llvm::dwarf::DW_TAG_restrict_type;
1282 }
1283 return (llvm::dwarf::Tag)0;
1284}
1285
1286llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
1287 llvm::DIFile *Unit) {
1288 QualifierCollector Qc;
1289 const Type *T = Qc.strip(Ty);
1290
1292
1293 // We will create one Derived type for one qualifier and recurse to handle any
1294 // additional ones.
1295 llvm::dwarf::Tag Tag = getNextQualifier(Qc);
1296 if (!Tag) {
1297 if (Qc.getPointerAuth()) {
1298 unsigned Key = Qc.getPointerAuth().getKey();
1299 bool IsDiscr = Qc.getPointerAuth().isAddressDiscriminated();
1300 unsigned ExtraDiscr = Qc.getPointerAuth().getExtraDiscriminator();
1301 bool IsaPointer = Qc.getPointerAuth().isIsaPointer();
1302 bool AuthenticatesNullValues =
1304 Qc.removePointerAuth();
1305 assert(Qc.empty() && "Unknown type qualifier for debug info");
1306 llvm::DIType *FromTy = getOrCreateType(QualType(T, 0), Unit);
1307 return DBuilder.createPtrAuthQualifiedType(FromTy, Key, IsDiscr,
1308 ExtraDiscr, IsaPointer,
1309 AuthenticatesNullValues);
1310 } else {
1311 assert(Qc.empty() && "Unknown type qualifier for debug info");
1312 return getOrCreateType(QualType(T, 0), Unit);
1313 }
1314 }
1315
1316 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
1317
1318 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1319 // CVR derived types.
1320 return DBuilder.createQualifiedType(Tag, FromTy);
1321}
1322
1323llvm::DIType *CGDebugInfo::CreateQualifiedType(const FunctionProtoType *F,
1324 llvm::DIFile *Unit) {
1325 FunctionProtoType::ExtProtoInfo EPI = F->getExtProtoInfo();
1326 Qualifiers &Q = EPI.TypeQuals;
1328
1329 // We will create one Derived type for one qualifier and recurse to handle any
1330 // additional ones.
1331 llvm::dwarf::Tag Tag = getNextQualifier(Q);
1332 if (!Tag) {
1333 assert(Q.empty() && "Unknown type qualifier for debug info");
1334 return nullptr;
1335 }
1336
1337 auto *FromTy =
1338 getOrCreateType(CGM.getContext().getFunctionType(F->getReturnType(),
1339 F->getParamTypes(), EPI),
1340 Unit);
1341
1342 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
1343 // CVR derived types.
1344 return DBuilder.createQualifiedType(Tag, FromTy);
1345}
1346
1347llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
1348 llvm::DIFile *Unit) {
1349
1350 // The frontend treats 'id' as a typedef to an ObjCObjectType,
1351 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
1352 // debug info, we want to emit 'id' in both cases.
1353 if (Ty->isObjCQualifiedIdType())
1354 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
1355
1356 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1357 Ty->getPointeeType(), Unit);
1358}
1359
1360llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
1361 llvm::DIFile *Unit) {
1362 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
1363 Ty->getPointeeType(), Unit);
1364}
1365
1366static bool hasCXXMangling(llvm::dwarf::SourceLanguage Lang, bool IsTagDecl) {
1367 switch (Lang) {
1368 case llvm::dwarf::DW_LANG_C_plus_plus:
1369 case llvm::dwarf::DW_LANG_C_plus_plus_11:
1370 case llvm::dwarf::DW_LANG_C_plus_plus_14:
1371 case llvm::dwarf::DW_LANG_HIP:
1372 return true;
1373 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
1374 return IsTagDecl;
1375 default:
1376 return false;
1377 }
1378}
1379
1380static bool hasCXXMangling(llvm::dwarf::SourceLanguageName Lang,
1381 bool IsTagDecl) {
1382 switch (Lang) {
1383 case llvm::dwarf::DW_LNAME_C_plus_plus:
1384 case llvm::dwarf::DW_LNAME_HIP:
1385 return true;
1386 case llvm::dwarf::DW_LNAME_ObjC_plus_plus:
1387 return IsTagDecl;
1388 default:
1389 return false;
1390 }
1391}
1392
1393/// \return whether a C++ mangling exists for the type defined by TD.
1394static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
1395 const bool IsTagDecl = isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
1396
1397 if (llvm::DISourceLanguageName SourceLang = TheCU->getSourceLanguage();
1398 SourceLang.hasVersionedName())
1399 return hasCXXMangling(
1400 static_cast<llvm::dwarf::SourceLanguageName>(SourceLang.getName()),
1401 IsTagDecl);
1402 else
1403 return hasCXXMangling(
1404 static_cast<llvm::dwarf::SourceLanguage>(SourceLang.getName()),
1405 IsTagDecl);
1406}
1407
1408// Determines if the debug info for this tag declaration needs a type
1409// identifier. The purpose of the unique identifier is to deduplicate type
1410// information for identical types across TUs. Because of the C++ one definition
1411// rule (ODR), it is valid to assume that the type is defined the same way in
1412// every TU and its debug info is equivalent.
1413//
1414// C does not have the ODR, and it is common for codebases to contain multiple
1415// different definitions of a struct with the same name in different TUs.
1416// Therefore, if the type doesn't have a C++ mangling, don't give it an
1417// identifer. Type information in C is smaller and simpler than C++ type
1418// information, so the increase in debug info size is negligible.
1419//
1420// If the type is not externally visible, it should be unique to the current TU,
1421// and should not need an identifier to participate in type deduplication.
1422// However, when emitting CodeView, the format internally uses these
1423// unique type name identifers for references between debug info. For example,
1424// the method of a class in an anonymous namespace uses the identifer to refer
1425// to its parent class. The Microsoft C++ ABI attempts to provide unique names
1426// for such types, so when emitting CodeView, always use identifiers for C++
1427// types. This may create problems when attempting to emit CodeView when the MS
1428// C++ ABI is not in use.
1429static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
1430 llvm::DICompileUnit *TheCU) {
1431 // We only add a type identifier for types with C++ name mangling.
1432 if (!hasCXXMangling(TD, TheCU))
1433 return false;
1434
1435 // Externally visible types with C++ mangling need a type identifier.
1436 if (TD->isExternallyVisible())
1437 return true;
1438
1439 // CodeView types with C++ mangling need a type identifier.
1440 if (CGM.getCodeGenOpts().EmitCodeView)
1441 return true;
1442
1443 return false;
1444}
1445
1446// Returns a unique type identifier string if one exists, or an empty string.
1447static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
1448 llvm::DICompileUnit *TheCU) {
1449 SmallString<256> Identifier;
1450 const TagDecl *TD = Ty->getDecl()->getDefinitionOrSelf();
1451
1452 if (!needsTypeIdentifier(TD, CGM, TheCU))
1453 return Identifier;
1454 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
1455 if (RD->getDefinition())
1456 if (RD->isDynamicClass() &&
1457 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
1458 return Identifier;
1459
1460 // TODO: This is using the RTTI name. Is there a better way to get
1461 // a unique string for a type?
1462 llvm::raw_svector_ostream Out(Identifier);
1464 return Identifier;
1465}
1466
1467/// \return the appropriate DWARF tag for a composite type.
1468static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
1469 llvm::dwarf::Tag Tag;
1470 if (RD->isStruct() || RD->isInterface())
1471 Tag = llvm::dwarf::DW_TAG_structure_type;
1472 else if (RD->isUnion())
1473 Tag = llvm::dwarf::DW_TAG_union_type;
1474 else {
1475 // FIXME: This could be a struct type giving a default visibility different
1476 // than C++ class type, but needs llvm metadata changes first.
1477 assert(RD->isClass());
1478 Tag = llvm::dwarf::DW_TAG_class_type;
1479 }
1480 return Tag;
1481}
1482
1483llvm::DICompositeType *
1484CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
1485 llvm::DIScope *Ctx) {
1486 const RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
1487 if (llvm::DIType *T = getTypeOrNull(QualType(Ty, 0)))
1489 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1490 const unsigned Line =
1491 getLineNumber(RD->getLocation().isValid() ? RD->getLocation() : CurLoc);
1492 StringRef RDName = getClassName(RD);
1493
1494 uint64_t Size = 0;
1495 uint32_t Align = 0;
1496
1497 const RecordDecl *D = RD->getDefinition();
1498 if (D && D->isCompleteDefinition())
1499 Size = CGM.getContext().getTypeSize(Ty);
1500
1501 llvm::DINode::DIFlags Flags = llvm::DINode::FlagFwdDecl;
1502
1503 // Add flag to nontrivial forward declarations. To be consistent with MSVC,
1504 // add the flag if a record has no definition because we don't know whether
1505 // it will be trivial or not.
1506 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1507 if (!CXXRD->hasDefinition() ||
1508 (CXXRD->hasDefinition() && !CXXRD->isTrivial()))
1509 Flags |= llvm::DINode::FlagNonTrivial;
1510
1511 // Create the type.
1512 SmallString<256> Identifier;
1513 // Don't include a linkage name in line tables only.
1514 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
1515 Identifier = getTypeIdentifier(Ty, CGM, TheCU);
1516 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
1517 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align, Flags,
1518 Identifier);
1519 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
1520 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1521 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
1522 CollectCXXTemplateParams(TSpecial, DefUnit));
1523 ReplaceMap.emplace_back(
1524 std::piecewise_construct, std::make_tuple(Ty),
1525 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1526 return RetTy;
1527}
1528
1529llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
1530 const Type *Ty,
1531 QualType PointeeTy,
1532 llvm::DIFile *Unit) {
1533 // Bit size, align and offset of the type.
1534 // Size is always the size of a pointer.
1535 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1536 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1537 std::optional<unsigned> DWARFAddressSpace =
1538 CGM.getTarget().getDWARFAddressSpace(
1539 CGM.getTypes().getTargetAddressSpace(PointeeTy));
1540
1541 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1542 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type) {
1543 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1544 Size, Align, DWARFAddressSpace);
1545 } else {
1546 SmallVector<llvm::Metadata *, 4> Annots;
1547 CollectBTFTypeTagAnnotations(PointeeTy, Annots);
1548
1549 llvm::DINodeArray Annotations = nullptr;
1550 if (Annots.size() > 0)
1551 Annotations = DBuilder.getOrCreateArray(Annots);
1552 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1553 Align, DWARFAddressSpace, StringRef(),
1554 Annotations);
1555 }
1556}
1557
1558llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1559 llvm::DIType *&Cache) {
1560 if (Cache)
1561 return Cache;
1562 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1563 TheCU, TheCU->getFile(), 0);
1564 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1565 Cache = DBuilder.createPointerType(Cache, Size);
1566 return Cache;
1567}
1568
1569uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1570 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1571 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1572 QualType FType;
1573
1574 // Advanced by calls to CreateMemberType in increments of FType, then
1575 // returned as the overall size of the default elements.
1576 uint64_t FieldOffset = 0;
1577
1578 // Blocks in OpenCL have unique constraints which make the standard fields
1579 // redundant while requiring size and align fields for enqueue_kernel. See
1580 // initializeForBlockHeader in CGBlocks.cpp
1581 if (CGM.getLangOpts().OpenCL) {
1582 FType = CGM.getContext().IntTy;
1583 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1584 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1585 } else {
1586 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1587 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1588 FType = CGM.getContext().IntTy;
1589 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1590 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1591 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1592 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1593 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1594 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1595 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1596 EltTys.push_back(DBuilder.createMemberType(
1597 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1598 FieldOffset, llvm::DINode::FlagZero, DescTy));
1599 FieldOffset += FieldSize;
1600 }
1601
1602 return FieldOffset;
1603}
1604
1605llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1606 llvm::DIFile *Unit) {
1607 SmallVector<llvm::Metadata *, 8> EltTys;
1608 QualType FType;
1609 uint64_t FieldOffset;
1610 llvm::DINodeArray Elements;
1611
1612 FieldOffset = 0;
1613 FType = CGM.getContext().UnsignedLongTy;
1614 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1615 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1616
1617 Elements = DBuilder.getOrCreateArray(EltTys);
1618 EltTys.clear();
1619
1620 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1621
1622 auto *EltTy =
1623 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1624 FieldOffset, 0, Flags, nullptr, Elements);
1625
1626 // Bit size, align and offset of the type.
1627 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1628
1629 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1630
1631 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1632 0, EltTys);
1633
1634 Elements = DBuilder.getOrCreateArray(EltTys);
1635
1636 // The __block_literal_generic structs are marked with a special
1637 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1638 // the debugger needs to know about. To allow type uniquing, emit
1639 // them without a name or a location.
1640 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1641 Flags, nullptr, Elements);
1642
1643 return DBuilder.createPointerType(EltTy, Size);
1644}
1645
1646static llvm::SmallVector<TemplateArgument>
1647GetTemplateArgs(const TemplateDecl *TD, const TemplateSpecializationType *Ty) {
1648 assert(Ty->isTypeAlias());
1649 // TemplateSpecializationType doesn't know if its template args are
1650 // being substituted into a parameter pack. We can find out if that's
1651 // the case now by inspecting the TypeAliasTemplateDecl template
1652 // parameters. Insert Ty's template args into SpecArgs, bundling args
1653 // passed to a parameter pack into a TemplateArgument::Pack. It also
1654 // doesn't know the value of any defaulted args, so collect those now
1655 // too.
1657 ArrayRef SubstArgs = Ty->template_arguments();
1658 for (const NamedDecl *Param : TD->getTemplateParameters()->asArray()) {
1659 // If Param is a parameter pack, pack the remaining arguments.
1660 if (Param->isParameterPack()) {
1661 SpecArgs.push_back(TemplateArgument(SubstArgs));
1662 break;
1663 }
1664
1665 // Skip defaulted args.
1666 // FIXME: Ideally, we wouldn't do this. We can read the default values
1667 // for each parameter. However, defaulted arguments which are dependent
1668 // values or dependent types can't (easily?) be resolved here.
1669 if (SubstArgs.empty()) {
1670 // If SubstArgs is now empty (we're taking from it each iteration) and
1671 // this template parameter isn't a pack, then that should mean we're
1672 // using default values for the remaining template parameters (after
1673 // which there may be an empty pack too which we will ignore).
1674 break;
1675 }
1676
1677 // Take the next argument.
1678 SpecArgs.push_back(SubstArgs.front());
1679 SubstArgs = SubstArgs.drop_front();
1680 }
1681 return SpecArgs;
1682}
1683
1684llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1685 llvm::DIFile *Unit) {
1686 assert(Ty->isTypeAlias());
1687 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1688
1689 const TemplateDecl *TD = Ty->getTemplateName().getAsTemplateDecl();
1691 return Src;
1692
1693 const auto *AliasDecl = cast<TypeAliasTemplateDecl>(TD)->getTemplatedDecl();
1694 if (AliasDecl->hasAttr<NoDebugAttr>())
1695 return Src;
1696
1697 SmallString<128> NS;
1698 llvm::raw_svector_ostream OS(NS);
1699
1700 auto PP = getPrintingPolicy();
1701 Ty->getTemplateName().print(OS, PP, TemplateName::Qualified::None);
1702
1703 SourceLocation Loc = AliasDecl->getLocation();
1704
1705 if (CGM.getCodeGenOpts().DebugTemplateAlias) {
1706 auto ArgVector = ::GetTemplateArgs(TD, Ty);
1707 TemplateArgs Args = {TD->getTemplateParameters(), ArgVector};
1708
1709 // FIXME: Respect DebugTemplateNameKind::Mangled, e.g. by using GetName.
1710 // Note we can't use GetName without additional work: TypeAliasTemplateDecl
1711 // doesn't have instantiation information, so
1712 // TypeAliasTemplateDecl::getNameForDiagnostic wouldn't have access to the
1713 // template args.
1714 std::string Name;
1715 llvm::raw_string_ostream OS(Name);
1716 TD->getNameForDiagnostic(OS, PP, /*Qualified=*/false);
1717 if (CGM.getCodeGenOpts().getDebugSimpleTemplateNames() !=
1718 llvm::codegenoptions::DebugTemplateNamesKind::Simple ||
1719 !HasReconstitutableArgs(Args.Args))
1720 printTemplateArgumentList(OS, Args.Args, PP);
1721
1722 llvm::DIDerivedType *AliasTy = DBuilder.createTemplateAlias(
1723 Src, Name, getOrCreateFile(Loc), getLineNumber(Loc),
1724 getDeclContextDescriptor(AliasDecl), CollectTemplateParams(Args, Unit));
1725 return AliasTy;
1726 }
1727
1728 printTemplateArgumentList(OS, Ty->template_arguments(), PP,
1729 TD->getTemplateParameters());
1730 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1731 getLineNumber(Loc),
1732 getDeclContextDescriptor(AliasDecl));
1733}
1734
1735/// Convert an AccessSpecifier into the corresponding DINode flag.
1736/// As an optimization, return 0 if the access specifier equals the
1737/// default for the containing type.
1738static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1739 const RecordDecl *RD) {
1741 if (RD && RD->isClass())
1743 else if (RD && (RD->isStruct() || RD->isUnion()))
1745
1746 if (Access == Default)
1747 return llvm::DINode::FlagZero;
1748
1749 switch (Access) {
1750 case clang::AS_private:
1751 return llvm::DINode::FlagPrivate;
1753 return llvm::DINode::FlagProtected;
1754 case clang::AS_public:
1755 return llvm::DINode::FlagPublic;
1756 case clang::AS_none:
1757 return llvm::DINode::FlagZero;
1758 }
1759 llvm_unreachable("unexpected access enumerator");
1760}
1761
1762llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1763 llvm::DIFile *Unit) {
1764 llvm::DIType *Underlying =
1765 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1766
1767 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1768 return Underlying;
1769
1770 // We don't set size information, but do specify where the typedef was
1771 // declared.
1772 SourceLocation Loc = Ty->getDecl()->getLocation();
1773
1774 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1775
1776 // Typedefs are derived from some other type. Collect both btf_decl_tag
1777 // annotations on the typedef declaration and btf_type_tag annotations on
1778 // the (possibly non-pointer) underlying type, e.g.
1779 // typedef struct foo __attribute__((btf_type_tag("tag"))) foo_t;
1780 SmallVector<llvm::Metadata *, 4> Annots;
1781 llvm::DINodeArray Annotations;
1782 CollectBTFTypeTagAnnotations(Ty->getDecl()->getUnderlyingType(), Annots);
1783 CollectBTFDeclTagAnnotations(Ty->getDecl(), Annots);
1784 if (!Annots.empty())
1785 Annotations = DBuilder.getOrCreateArray(Annots);
1786
1787 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1788 const DeclContext *DC = Ty->getDecl()->getDeclContext();
1789 if (isa<RecordDecl>(DC))
1790 Flags = getAccessFlag(Ty->getDecl()->getAccess(), cast<RecordDecl>(DC));
1791
1792 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1793 getOrCreateFile(Loc), getLineNumber(Loc),
1794 getDeclContextDescriptor(Ty->getDecl()), Align,
1795 Flags, Annotations);
1796}
1797
1798static unsigned getDwarfCC(CallingConv CC, const llvm::Triple &T) {
1799 switch (CC) {
1800 case CC_C:
1801 // On SPIR/SPIR-V, CC_C is the target default calling convention and lowers
1802 // to spir_func, so describe it that way.
1803 if (T.isSPIROrSPIRV())
1804 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1805 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1806 return 0;
1807
1808 case CC_X86StdCall:
1809 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1810 case CC_X86FastCall:
1811 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1812 case CC_X86ThisCall:
1813 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1814 case CC_X86VectorCall:
1815 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1816 case CC_X86Pascal:
1817 return llvm::dwarf::DW_CC_BORLAND_pascal;
1818 case CC_Win64:
1819 return llvm::dwarf::DW_CC_LLVM_Win64;
1820 case CC_X86_64SysV:
1821 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1822 case CC_AAPCS:
1824 case CC_AArch64SVEPCS:
1825 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1826 case CC_AAPCS_VFP:
1827 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1828 case CC_IntelOclBicc:
1829 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
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. Delegating constructors are ignored because the target
2545 // constructor's definition will emit the type info.
2546 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor) {
2547 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method)) {
2548 if (const auto *Def =
2549 dyn_cast_or_null<CXXConstructorDecl>(CD->getDefinition());
2550 Def && !Def->isDelegatingConstructor()) {
2551 completeUnusedClass(*CD->getParent());
2552 }
2553 }
2554 }
2555
2556 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
2557 llvm::DISubprogram *SP = DBuilder.createMethod(
2558 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
2559 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
2560 TParamsArray.get(), /*ThrownTypes*/ nullptr,
2561 CGM.getCodeGenOpts().DebugKeyInstructions);
2562
2563 SPCache[Method->getCanonicalDecl()].reset(SP);
2564
2565 return SP;
2566}
2567
2568void CGDebugInfo::CollectCXXMemberFunctions(
2569 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2570 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
2571
2572 // Since we want more than just the individual member decls if we
2573 // have templated functions iterate over every declaration to gather
2574 // the functions.
2575 for (const auto *I : RD->decls()) {
2576 const auto *Method = dyn_cast<CXXMethodDecl>(I);
2577 // If the member is implicit, don't add it to the member list. This avoids
2578 // the member being added to type units by LLVM, while still allowing it
2579 // to be emitted into the type declaration/reference inside the compile
2580 // unit.
2581 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
2582 // FIXME: Handle Using(Shadow?)Decls here to create
2583 // DW_TAG_imported_declarations inside the class for base decls brought into
2584 // derived classes. GDB doesn't seem to notice/leverage these when I tried
2585 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
2586 // referenced)
2587 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
2588 continue;
2589
2590 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
2591 continue;
2592
2593 // Reuse the existing member function declaration if it exists.
2594 // It may be associated with the declaration of the type & should be
2595 // reused as we're building the definition.
2596 //
2597 // This situation can arise in the vtable-based debug info reduction where
2598 // implicit members are emitted in a non-vtable TU.
2599 auto MI = SPCache.find(Method->getCanonicalDecl());
2600 EltTys.push_back(MI == SPCache.end()
2601 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
2602 : static_cast<llvm::Metadata *>(MI->second));
2603 }
2604}
2605
2606void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
2607 SmallVectorImpl<llvm::Metadata *> &EltTys,
2608 llvm::DIType *RecordTy) {
2609 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
2610 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
2611 llvm::DINode::FlagZero);
2612
2613 // If we are generating CodeView debug info, we also need to emit records for
2614 // indirect virtual base classes.
2615 if (CGM.getCodeGenOpts().EmitCodeView) {
2616 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
2617 llvm::DINode::FlagIndirectVirtualBase);
2618 }
2619}
2620
2621void CGDebugInfo::CollectCXXBasesAux(
2622 const CXXRecordDecl *RD, llvm::DIFile *Unit,
2623 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
2625 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
2626 llvm::DINode::DIFlags StartingFlags) {
2627 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2628 for (const auto &BI : Bases) {
2629 const auto *Base =
2631 BI.getType()->castAsCanonical<RecordType>()->getDecl())
2632 ->getDefinition();
2633 if (!SeenTypes.insert(Base).second)
2634 continue;
2635 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
2636 llvm::DINode::DIFlags BFlags = StartingFlags;
2637 uint64_t BaseOffset;
2638 uint32_t VBPtrOffset = 0;
2639
2640 if (BI.isVirtual()) {
2641 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
2642 // virtual base offset offset is -ve. The code generator emits dwarf
2643 // expression where it expects +ve number.
2644 BaseOffset = 0 - CGM.getItaniumVTableContext()
2645 .getVirtualBaseOffsetOffset(RD, Base)
2646 .getQuantity();
2647 } else {
2648 // In the MS ABI, store the vbtable offset, which is analogous to the
2649 // vbase offset offset in Itanium.
2650 BaseOffset =
2651 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
2652 VBPtrOffset = CGM.getContext()
2653 .getASTRecordLayout(RD)
2654 .getVBPtrOffset()
2655 .getQuantity();
2656 }
2657 BFlags |= llvm::DINode::FlagVirtual;
2658 } else
2659 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
2660 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
2661 // BI->isVirtual() and bits when not.
2662
2663 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
2664 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
2665 VBPtrOffset, BFlags);
2666 EltTys.push_back(DTy);
2667 }
2668}
2669
2670llvm::DINodeArray
2671CGDebugInfo::CollectTemplateParams(std::optional<TemplateArgs> OArgs,
2672 llvm::DIFile *Unit) {
2673 if (!OArgs)
2674 return llvm::DINodeArray();
2675 TemplateArgs &Args = *OArgs;
2676 SmallVector<llvm::Metadata *, 16> TemplateParams;
2677 for (unsigned i = 0, e = Args.Args.size(); i != e; ++i) {
2678 const TemplateArgument &TA = Args.Args[i];
2679 StringRef Name;
2680 const bool defaultParameter = TA.getIsDefaulted();
2681 if (Args.TList)
2682 Name = Args.TList->getParam(i)->getName();
2683
2684 switch (TA.getKind()) {
2686 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
2687 TemplateParams.push_back(DBuilder.createTemplateTypeParameter(
2688 TheCU, Name, TTy, defaultParameter));
2689
2690 } break;
2692 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
2693 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2694 TheCU, Name, TTy, defaultParameter,
2695 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
2696 } break;
2698 const ValueDecl *D = TA.getAsDecl();
2699 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
2700 llvm::DIType *TTy = getOrCreateType(T, Unit);
2701 llvm::Constant *V = nullptr;
2702 // Skip retrieve the value if that template parameter has cuda device
2703 // attribute, i.e. that value is not available at the host side.
2704 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
2705 !D->hasAttr<CUDADeviceAttr>()) {
2706 // Variable pointer template parameters have a value that is the address
2707 // of the variable.
2708 if (const auto *VD = dyn_cast<VarDecl>(D))
2709 V = CGM.GetAddrOfGlobalVar(VD);
2710 // Member function pointers have special support for building them,
2711 // though this is currently unsupported in LLVM CodeGen.
2712 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D);
2713 MD && MD->isImplicitObjectMemberFunction())
2714 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
2715 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
2716 V = CGM.GetAddrOfFunction(FD);
2717 // Member data pointers have special handling too to compute the fixed
2718 // offset within the object.
2719 else if (const auto *MPT =
2720 dyn_cast<MemberPointerType>(T.getTypePtr())) {
2721 // These five lines (& possibly the above member function pointer
2722 // handling) might be able to be refactored to use similar code in
2723 // CodeGenModule::getMemberPointerConstant
2724 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
2725 CharUnits chars =
2726 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
2727 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
2728 } else if (const auto *GD = dyn_cast<MSGuidDecl>(D)) {
2729 V = CGM.GetAddrOfMSGuidDecl(GD).getPointer();
2730 } else if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
2731 if (T->isRecordType())
2732 V = ConstantEmitter(CGM).emitAbstract(
2733 SourceLocation(), TPO->getValue(), TPO->getType());
2734 else
2735 V = CGM.GetAddrOfTemplateParamObject(TPO).getPointer();
2736 }
2737 assert(V && "Failed to find template parameter pointer");
2738 V = V->stripPointerCasts();
2739 }
2740 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2741 TheCU, Name, TTy, defaultParameter, cast_or_null<llvm::Constant>(V)));
2742 } break;
2744 QualType T = TA.getNullPtrType();
2745 llvm::DIType *TTy = getOrCreateType(T, Unit);
2746 llvm::Constant *V = nullptr;
2747 // Special case member data pointer null values since they're actually -1
2748 // instead of zero.
2749 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
2750 // But treat member function pointers as simple zero integers because
2751 // it's easier than having a special case in LLVM's CodeGen. If LLVM
2752 // CodeGen grows handling for values of non-null member function
2753 // pointers then perhaps we could remove this special case and rely on
2754 // EmitNullMemberPointer for member function pointers.
2755 if (MPT->isMemberDataPointer())
2756 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
2757 if (!V)
2758 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
2759 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2760 TheCU, Name, TTy, defaultParameter, V));
2761 } break;
2763 QualType T = TA.getStructuralValueType();
2764 llvm::DIType *TTy = getOrCreateType(T, Unit);
2765 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(
2766 SourceLocation(), TA.getAsStructuralValue(), T);
2767 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2768 TheCU, Name, TTy, defaultParameter, V));
2769 } break;
2771 std::string QualName;
2772 llvm::raw_string_ostream OS(QualName);
2774 OS, getPrintingPolicy());
2775 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
2776 TheCU, Name, nullptr, QualName, defaultParameter));
2777 break;
2778 }
2780 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
2781 TheCU, Name, nullptr,
2782 CollectTemplateParams({{nullptr, TA.getPackAsArray()}}, Unit)));
2783 break;
2785 const Expr *E = TA.getAsExpr();
2786 QualType T = E->getType();
2787 if (E->isGLValue())
2788 T = CGM.getContext().getLValueReferenceType(T);
2789 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
2790 assert(V && "Expression in template argument isn't constant");
2791 llvm::DIType *TTy = getOrCreateType(T, Unit);
2792 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
2793 TheCU, Name, TTy, defaultParameter, V->stripPointerCasts()));
2794 } break;
2795 // And the following should never occur:
2798 llvm_unreachable(
2799 "These argument types shouldn't exist in concrete types");
2800 }
2801 }
2802 return DBuilder.getOrCreateArray(TemplateParams);
2803}
2804
2805std::optional<CGDebugInfo::TemplateArgs>
2806CGDebugInfo::GetTemplateArgs(const FunctionDecl *FD) const {
2807 if (FD->getTemplatedKind() ==
2809 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
2810 ->getTemplate()
2812 return {{TList, FD->getTemplateSpecializationArgs()->asArray()}};
2813 }
2814 return std::nullopt;
2815}
2816std::optional<CGDebugInfo::TemplateArgs>
2817CGDebugInfo::GetTemplateArgs(const VarDecl *VD) const {
2818 // Always get the full list of parameters, not just the ones from the
2819 // specialization. A partial specialization may have fewer parameters than
2820 // there are arguments.
2821 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VD);
2822 if (!TS)
2823 return std::nullopt;
2824 VarTemplateDecl *T = TS->getSpecializedTemplate();
2825 const TemplateParameterList *TList = T->getTemplateParameters();
2826 auto TA = TS->getTemplateArgs().asArray();
2827 return {{TList, TA}};
2828}
2829std::optional<CGDebugInfo::TemplateArgs>
2830CGDebugInfo::GetTemplateArgs(const RecordDecl *RD) const {
2831 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
2832 // Always get the full list of parameters, not just the ones from the
2833 // specialization. A partial specialization may have fewer parameters than
2834 // there are arguments.
2835 TemplateParameterList *TPList =
2836 TSpecial->getSpecializedTemplate()->getTemplateParameters();
2837 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
2838 return {{TPList, TAList.asArray()}};
2839 }
2840 return std::nullopt;
2841}
2842
2843llvm::DINodeArray
2844CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
2845 llvm::DIFile *Unit) {
2846 return CollectTemplateParams(GetTemplateArgs(FD), Unit);
2847}
2848
2849llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
2850 llvm::DIFile *Unit) {
2851 return CollectTemplateParams(GetTemplateArgs(VL), Unit);
2852}
2853
2854llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(const RecordDecl *RD,
2855 llvm::DIFile *Unit) {
2856 return CollectTemplateParams(GetTemplateArgs(RD), Unit);
2857}
2858
2859void CGDebugInfo::CollectBTFDeclTagAnnotations(
2860 const Decl *D, SmallVectorImpl<llvm::Metadata *> &Annotations) {
2861 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) {
2862 llvm::Metadata *Ops[2] = {
2863 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_decl_tag")),
2864 llvm::MDString::get(CGM.getLLVMContext(), I->getBTFDeclTag())};
2865 Annotations.push_back(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2866 }
2867}
2868
2869llvm::DINodeArray CGDebugInfo::CollectBTFDeclTagAnnotations(const Decl *D) {
2870 if (!D->hasAttr<BTFDeclTagAttr>())
2871 return nullptr;
2872
2873 SmallVector<llvm::Metadata *, 4> Annotations;
2874 CollectBTFDeclTagAnnotations(D, Annotations);
2875 return DBuilder.getOrCreateArray(Annotations);
2876}
2877
2878void CGDebugInfo::CollectBTFTypeTagAnnotations(
2879 QualType Ty, SmallVectorImpl<llvm::Metadata *> &Annotations) {
2880 const BTFTagAttributedType *BTFAttrTy;
2881 if (auto *Atomic = Ty->getAs<AtomicType>())
2882 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Atomic->getValueType());
2883 else
2884 BTFAttrTy = dyn_cast<BTFTagAttributedType>(Ty);
2885
2886 while (BTFAttrTy) {
2887 StringRef Tag = BTFAttrTy->getAttr()->getBTFTypeTag();
2888 if (!Tag.empty()) {
2889 llvm::Metadata *Ops[2] = {
2890 llvm::MDString::get(CGM.getLLVMContext(), StringRef("btf_type_tag")),
2891 llvm::MDString::get(CGM.getLLVMContext(), Tag)};
2892 Annotations.insert(Annotations.begin(),
2893 llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2894 }
2895 BTFAttrTy = dyn_cast<BTFTagAttributedType>(BTFAttrTy->getWrappedType());
2896 }
2897}
2898
2899llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
2900 if (VTablePtrType)
2901 return VTablePtrType;
2902
2903 ASTContext &Context = CGM.getContext();
2904
2905 /* Function type */
2906 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
2907 llvm::DITypeArray SElements = DBuilder.getOrCreateTypeArray(STy);
2908 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
2909 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
2910 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2911 std::optional<unsigned> DWARFAddressSpace =
2912 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2913
2914 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
2915 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2916 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
2917 return VTablePtrType;
2918}
2919
2920StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
2921 // Copy the gdb compatible name on the side and use its reference.
2922 return internString("_vptr$", RD->getNameAsString());
2923}
2924
2925// Emit symbol for the debugger that points to the vtable address for
2926// the given class. The symbol is named as '__clang_vtable'.
2927// The debugger does not need to know any details about the contents of the
2928// vtable as it can work this out using its knowledge of the ABI and the
2929// existing information in the DWARF. The type is assumed to be 'void *'.
2930void CGDebugInfo::emitVTableSymbol(llvm::GlobalVariable *VTable,
2931 const CXXRecordDecl *RD) {
2932 if (!CGM.getTarget().getCXXABI().isItaniumFamily())
2933 return;
2934 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
2935 return;
2936
2937 // On COFF platform, we shouldn't emit a reference to an external entity (i.e.
2938 // VTable) into debug info, which is constructed within a discardable section.
2939 // If that entity ends up implicitly dllimported from another DLL, the linker
2940 // may produce a runtime pseudo-relocation for it (BFD-ld only. LLD prohibits
2941 // to emit such relocation). If the debug section is stripped, the runtime
2942 // pseudo-relocation points to memory space outside of the module, causing an
2943 // access violation.
2944 if (CGM.getTarget().getTriple().isOSBinFormatCOFF() &&
2945 VTable->isDeclarationForLinker())
2946 return;
2947
2948 ASTContext &Context = CGM.getContext();
2949 StringRef SymbolName = "__clang_vtable";
2950 SourceLocation Loc;
2951 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2952
2953 // We deal with two different contexts:
2954 // - The type for the variable, which is part of the class that has the
2955 // vtable, is placed in the context of the DICompositeType metadata.
2956 // - The DIGlobalVariable for the vtable is put in the DICompileUnitScope.
2957
2958 // The created non-member should be mark as 'artificial'. It will be
2959 // placed inside the scope of the C++ class/structure.
2960 llvm::DIScope *DContext = getContextDescriptor(RD, TheCU);
2961 auto *Ctxt = cast<llvm::DICompositeType>(DContext);
2962 llvm::DIFile *Unit = getOrCreateFile(Loc);
2963 llvm::DIType *VTy = getOrCreateType(VoidPtr, Unit);
2964 llvm::DINode::DIFlags Flags = getAccessFlag(AccessSpecifier::AS_private, RD) |
2965 llvm::DINode::FlagArtificial;
2966 auto Tag = CGM.getCodeGenOpts().DwarfVersion >= 5
2967 ? llvm::dwarf::DW_TAG_variable
2968 : llvm::dwarf::DW_TAG_member;
2969 llvm::DIDerivedType *DT = DBuilder.createStaticMemberType(
2970 Ctxt, SymbolName, Unit, /*LineNumber=*/0, VTy, Flags,
2971 /*Val=*/nullptr, Tag);
2972
2973 // Use the same vtable pointer to global alignment for the symbol.
2974 unsigned PAlign = CGM.getVtableGlobalVarAlignment();
2975
2976 // The global variable is in the CU scope, and links back to the type it's
2977 // "within" via the declaration field.
2978 llvm::DIGlobalVariableExpression *GVE =
2979 DBuilder.createGlobalVariableExpression(
2980 TheCU, SymbolName, VTable->getName(), Unit, /*LineNo=*/0,
2981 getOrCreateType(VoidPtr, Unit), VTable->hasLocalLinkage(),
2982 /*isDefined=*/true, nullptr, DT, /*TemplateParameters=*/nullptr,
2983 PAlign);
2984 VTable->addDebugInfo(GVE);
2985}
2986
2987StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
2988 DynamicInitKind StubKind,
2989 llvm::Function *InitFn) {
2990 // If we're not emitting codeview, use the mangled name. For Itanium, this is
2991 // arbitrary.
2992 if (!CGM.getCodeGenOpts().EmitCodeView ||
2994 return InitFn->getName();
2995
2996 // Print the normal qualified name for the variable, then break off the last
2997 // NNS, and add the appropriate other text. Clang always prints the global
2998 // variable name without template arguments, so we can use rsplit("::") and
2999 // then recombine the pieces.
3000 SmallString<128> QualifiedGV;
3001 StringRef Quals;
3002 StringRef GVName;
3003 {
3004 llvm::raw_svector_ostream OS(QualifiedGV);
3005 VD->printQualifiedName(OS, getPrintingPolicy());
3006 std::tie(Quals, GVName) = OS.str().rsplit("::");
3007 if (GVName.empty())
3008 std::swap(Quals, GVName);
3009 }
3010
3011 SmallString<128> InitName;
3012 llvm::raw_svector_ostream OS(InitName);
3013 if (!Quals.empty())
3014 OS << Quals << "::";
3015
3016 switch (StubKind) {
3019 llvm_unreachable("not an initializer");
3021 OS << "`dynamic initializer for '";
3022 break;
3024 OS << "`dynamic atexit destructor for '";
3025 break;
3026 }
3027
3028 OS << GVName;
3029
3030 // Add any template specialization args.
3031 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3032 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
3033 getPrintingPolicy());
3034 }
3035
3036 OS << '\'';
3037
3038 return internString(OS.str());
3039}
3040
3041void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
3042 SmallVectorImpl<llvm::Metadata *> &EltTys) {
3043 // If this class is not dynamic then there is not any vtable info to collect.
3044 if (!RD->isDynamicClass())
3045 return;
3046
3047 // Don't emit any vtable shape or vptr info if this class doesn't have an
3048 // extendable vfptr. This can happen if the class doesn't have virtual
3049 // methods, or in the MS ABI if those virtual methods only come from virtually
3050 // inherited bases.
3051 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3052 if (!RL.hasExtendableVFPtr())
3053 return;
3054
3055 // CodeView needs to know how large the vtable of every dynamic class is, so
3056 // emit a special named pointer type into the element list. The vptr type
3057 // points to this type as well.
3058 llvm::DIType *VPtrTy = nullptr;
3059 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
3060 CGM.getTarget().getCXXABI().isMicrosoft();
3061 if (NeedVTableShape) {
3062 uint64_t PtrWidth =
3063 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
3064 const VTableLayout &VFTLayout =
3065 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
3066 unsigned VSlotCount =
3067 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
3068 unsigned VTableWidth = PtrWidth * VSlotCount;
3069 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
3070 std::optional<unsigned> DWARFAddressSpace =
3071 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
3072
3073 // Create a very wide void* type and insert it directly in the element list.
3074 llvm::DIType *VTableType = DBuilder.createPointerType(
3075 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
3076 EltTys.push_back(VTableType);
3077
3078 // The vptr is a pointer to this special vtable type.
3079 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
3080 }
3081
3082 // If there is a primary base then the artificial vptr member lives there.
3083 if (RL.getPrimaryBase())
3084 return;
3085
3086 if (!VPtrTy)
3087 VPtrTy = getOrCreateVTablePtrType(Unit);
3088
3089 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
3090 llvm::DIType *VPtrMember =
3091 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
3092 llvm::DINode::FlagArtificial, VPtrTy);
3093 EltTys.push_back(VPtrMember);
3094}
3095
3097 SourceLocation Loc) {
3098 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3099 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
3100 return T;
3101}
3102
3104 SourceLocation Loc) {
3105 return getOrCreateStandaloneType(D, Loc);
3106}
3107
3109 SourceLocation Loc) {
3110 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3111 assert(!D.isNull() && "null type");
3112 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
3113 assert(T && "could not create debug info for type");
3114
3115 RetainedTypes.push_back(D.getAsOpaquePtr());
3116 return T;
3117}
3118
3120 QualType AllocatedTy,
3121 SourceLocation Loc) {
3122 if (CGM.getCodeGenOpts().getDebugInfo() <=
3123 llvm::codegenoptions::DebugLineTablesOnly)
3124 return;
3125 llvm::MDNode *node;
3126 if (AllocatedTy->isVoidType())
3127 node = llvm::MDNode::get(CGM.getLLVMContext(), {});
3128 else
3129 node = getOrCreateType(AllocatedTy, getOrCreateFile(Loc));
3130
3131 CI->setMetadata("heapallocsite", node);
3132}
3133
3135 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
3136 return;
3137 CanQualType Ty = CGM.getContext().getCanonicalTagType(ED);
3138 void *TyPtr = Ty.getAsOpaquePtr();
3139 auto I = TypeCache.find(TyPtr);
3140 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
3141 return;
3142 llvm::DIType *Res = CreateTypeDefinition(dyn_cast<EnumType>(Ty));
3143 assert(!Res->isForwardDecl());
3144 TypeCache[TyPtr].reset(Res);
3145}
3146
3148 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3149 !CGM.getLangOpts().CPlusPlus)
3151}
3152
3153/// Return true if the class or any of its methods are marked dllimport.
3155 if (RD->hasAttr<DLLImportAttr>())
3156 return true;
3157 for (const CXXMethodDecl *MD : RD->methods())
3158 if (MD->hasAttr<DLLImportAttr>())
3159 return true;
3160 return false;
3161}
3162
3163/// Does a type definition exist in an imported clang module?
3164static bool isDefinedInClangModule(const RecordDecl *RD) {
3165 // Only definitions that where imported from an AST file come from a module.
3166 if (!RD || !RD->isFromASTFile())
3167 return false;
3168 // Anonymous entities cannot be addressed. Treat them as not from module.
3169 if (!RD->isExternallyVisible() && RD->getName().empty())
3170 return false;
3171 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
3172 if (!CXXDecl->isCompleteDefinition())
3173 return false;
3174 // Check wether RD is a template.
3175 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
3176 if (TemplateKind != TSK_Undeclared) {
3177 // Unfortunately getOwningModule() isn't accurate enough to find the
3178 // owning module of a ClassTemplateSpecializationDecl that is inside a
3179 // namespace spanning multiple modules.
3180 bool Explicit = false;
3181 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
3182 Explicit = TD->isExplicitInstantiationOrSpecialization();
3183 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
3184 return false;
3185 // This is a template, check the origin of the first member.
3186 if (CXXDecl->fields().empty())
3187 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
3188 if (!CXXDecl->field_begin()->isFromASTFile())
3189 return false;
3190 }
3191 }
3192 return true;
3193}
3194
3196 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3197 if (CXXRD->isDynamicClass() &&
3198 CGM.getVTableLinkage(CXXRD) ==
3199 llvm::GlobalValue::AvailableExternallyLinkage &&
3201 return;
3202
3203 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3204 return;
3205
3206 completeClass(RD);
3207}
3208
3210 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
3211 return;
3212 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3213 void *TyPtr = Ty.getAsOpaquePtr();
3214 auto I = TypeCache.find(TyPtr);
3215 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
3216 return;
3217
3218 // We want the canonical definition of the structure to not
3219 // be the typedef. Since that would lead to circular typedef
3220 // metadata.
3221 auto [Res, PrefRes] = CreateTypeDefinition(dyn_cast<RecordType>(Ty));
3222 assert(!Res->isForwardDecl());
3223 TypeCache[TyPtr].reset(Res);
3224}
3225
3228 for (CXXMethodDecl *MD : llvm::make_range(I, End))
3230 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
3231 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
3232 return true;
3233 return false;
3234}
3235
3236static bool canUseCtorHoming(const CXXRecordDecl *RD) {
3237 // Constructor homing can be used for classes that cannnot be constructed
3238 // without emitting code for one of their constructors. This is classes that
3239 // don't have trivial or constexpr constructors, or can be created from
3240 // aggregate initialization. Also skip lambda objects because they don't call
3241 // constructors.
3242
3243 // Skip this optimization if the class or any of its methods are marked
3244 // dllimport.
3246 return false;
3247
3248 if (RD->isLambda() || RD->isAggregate() || RD->hasTrivialDefaultConstructor())
3249 return false;
3250
3251 // Skip this optimization if the class has an implicit constexpr default
3252 // constructor, since those constructors can be invoked without emitting type
3253 // information for the constructor.
3256 return false;
3257
3258 bool HasNonDeletedCtor = false;
3259 for (const CXXConstructorDecl *Ctor : RD->ctors()) {
3260 if (Ctor->isCopyOrMoveConstructor())
3261 continue;
3262 if (const FunctionDecl *Def = Ctor->getDefinition()) {
3263 const auto *CtorDef = cast<CXXConstructorDecl>(Def);
3264 // Ignore delegating constructors, the target constructor will either be
3265 // a non-deleted custom constructor that enables homing, or could be a
3266 // copy/move constructor, which does not enable homing.
3267 if (CtorDef->isDelegatingConstructor())
3268 continue;
3269 // Skip this optimization if we see a defined constexpr constructor, which
3270 // can be invoked without emitting type info.
3271 if (Ctor->isConstexpr() && !Ctor->isDeleted())
3272 return false;
3273 }
3274 if (!Ctor->isDeleted())
3275 HasNonDeletedCtor = true;
3276 }
3277 return HasNonDeletedCtor;
3278}
3279
3280static bool shouldOmitDefinition(llvm::codegenoptions::DebugInfoKind DebugKind,
3281 bool DebugTypeExtRefs, const RecordDecl *RD,
3282 const LangOptions &LangOpts) {
3283 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
3284 return true;
3285
3286 if (auto *ES = RD->getASTContext().getExternalSource())
3287 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
3288 return true;
3289
3290 // Only emit forward declarations in line tables only to keep debug info size
3291 // small. This only applies to CodeView, since we don't emit types in DWARF
3292 // line tables only.
3293 if (DebugKind == llvm::codegenoptions::DebugLineTablesOnly)
3294 return true;
3295
3296 if (DebugKind > llvm::codegenoptions::LimitedDebugInfo ||
3297 RD->hasAttr<StandaloneDebugAttr>())
3298 return false;
3299
3300 if (!LangOpts.CPlusPlus)
3301 return false;
3302
3304 return true;
3305
3306 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3307
3308 if (!CXXDecl)
3309 return false;
3310
3311 // Only emit complete debug info for a dynamic class when its vtable is
3312 // emitted. However, Microsoft debuggers don't resolve type information
3313 // across DLL boundaries, so skip this optimization if the class or any of its
3314 // methods are marked dllimport. This isn't a complete solution, since objects
3315 // without any dllimport methods can be used in one DLL and constructed in
3316 // another, but it is the current behavior of LimitedDebugInfo.
3317 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
3318 !isClassOrMethodDLLImport(CXXDecl) && !CXXDecl->hasAttr<MSNoVTableAttr>())
3319 return true;
3320
3322 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3323 Spec = SD->getSpecializationKind();
3324
3327 CXXDecl->method_end()))
3328 return true;
3329
3330 // In constructor homing mode, only emit complete debug info for a class
3331 // when its constructor is emitted.
3332 if ((DebugKind == llvm::codegenoptions::DebugInfoConstructor) &&
3333 canUseCtorHoming(CXXDecl))
3334 return true;
3335
3336 return false;
3337}
3338
3340 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
3341 return;
3342
3343 CanQualType Ty = CGM.getContext().getCanonicalTagType(RD);
3344 llvm::DIType *T = getTypeOrNull(Ty);
3345 if (T && T->isForwardDecl())
3347}
3348
3349llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
3350 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3351 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
3352 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
3353 CGM.getLangOpts())) {
3354 if (!T)
3355 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
3356 return T;
3357 }
3358
3359 auto [Def, Pref] = CreateTypeDefinition(Ty);
3360
3361 return Pref ? Pref : Def;
3362}
3363
3364llvm::DIType *CGDebugInfo::GetPreferredNameType(const CXXRecordDecl *RD,
3365 llvm::DIFile *Unit) {
3366 if (!RD)
3367 return nullptr;
3368
3369 auto const *PNA = RD->getAttr<PreferredNameAttr>();
3370 if (!PNA)
3371 return nullptr;
3372
3373 return getOrCreateType(PNA->getTypedefType(), Unit);
3374}
3375
3376static void completeStandardLayoutUnionType(CGDebugInfo &DebugInfo,
3377 QualType QT);
3378
3380 const CXXRecordDecl *RD) {
3381 for (const CXXBaseSpecifier &BS : RD->bases())
3382 completeStandardLayoutUnionType(DebugInfo, BS.getType());
3383
3384 for (const FieldDecl *FD : RD->fields()) {
3385 // Invalid declarations are skipped when determining the field layout of
3386 // unions. This will of course cause a compiler error, but skip these
3387 // fields anyway to avoid triggering the `isStandardLayout()` assertion in
3388 // `completeStandardLayoutUnionType`.
3389 if (FD->isInvalidDecl())
3390 continue;
3392 FD->getType()
3395 }
3396}
3397
3399 QualType QT) {
3400 const auto *RT = QT->getAs<RecordType>();
3401 if (!RT)
3402 return;
3403
3404 auto *CRD = dyn_cast<CXXRecordDecl>(RT->getDecl()->getDefinitionOrSelf());
3405 if (!CRD || !CRD->hasDefinition())
3406 return;
3407
3408 // We checked at the root that this is a standard-layout type, which
3409 // requires all its members / base types to be standard-layout.
3410 assert(CRD->isStandardLayout());
3411
3412 DebugInfo.completeClassData(CRD);
3413 completeStandardLayoutUnionMembers(DebugInfo, CRD);
3414}
3415
3416std::pair<llvm::DIType *, llvm::DIType *>
3417CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
3418 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
3419
3420 // Get overall information about the record type for the debug info.
3421 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3422
3423 // Records and classes and unions can all be recursive. To handle them, we
3424 // first generate a debug descriptor for the struct as a forward declaration.
3425 // Then (if it is a definition) we go through and get debug info for all of
3426 // its members. Finally, we create a descriptor for the complete type (which
3427 // may refer to the forward decl if the struct is recursive) and replace all
3428 // uses of the forward declaration with the final definition.
3429 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty);
3430
3431 const RecordDecl *D = RD->getDefinition();
3432 if (!D || !D->isCompleteDefinition())
3433 return {FwdDecl, nullptr};
3434
3435 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
3436 CollectContainingType(CXXDecl, FwdDecl);
3437
3438 // Push the struct on region stack.
3439 LexicalBlockStack.emplace_back(&*FwdDecl);
3440 RegionMap[RD].reset(FwdDecl);
3441
3442 // Convert all the elements.
3443 SmallVector<llvm::Metadata *, 16> EltTys;
3444 // what about nested types?
3445
3446 // Note: The split of CXXDecl information here is intentional, the
3447 // gdb tests will depend on a certain ordering at printout. The debug
3448 // information offsets are still correct if we merge them all together
3449 // though.
3450 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
3451 if (CXXDecl) {
3452 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
3453 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
3454 }
3455
3456 // Collect data fields (including static variables and any initializers).
3457 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
3458 if (CXXDecl && !CGM.getCodeGenOpts().DebugOmitUnreferencedMethods)
3459 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
3460
3461 LexicalBlockStack.pop_back();
3462 RegionMap.erase(RD);
3463
3464 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3465 DBuilder.replaceArrays(FwdDecl, Elements);
3466
3467 if (FwdDecl->isTemporary())
3468 FwdDecl =
3469 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
3470
3471 RegionMap[RD].reset(FwdDecl);
3472
3473 if (DebugKind == llvm::codegenoptions::DebugInfoConstructor) {
3474 // For standard-layout unions, recursively emit full debug info for all
3475 // user-defined types (and their bases/fields) in the union. Per the C++
3476 // spec, "it is permitted to inspect the common initial part of any of" the
3477 // "common initial sequence" of distinct types in a standard-layout union.
3478 // This exception to strict aliasing enables producing a reference to a
3479 // type without ever having constructed that type, breaking the assumption
3480 // made by constructor homing that all interesting types we'd want debug
3481 // info for must have been constructed.
3482 //
3483 // See: https://wg21.link/class.mem#general-30
3484 if (CXXDecl && CXXDecl->isUnion() && CXXDecl->isStandardLayout())
3485 completeStandardLayoutUnionMembers(*this, CXXDecl);
3486 }
3487
3488 if (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB)
3489 if (auto *PrefDI = GetPreferredNameType(CXXDecl, DefUnit))
3490 return {FwdDecl, PrefDI};
3491
3492 return {FwdDecl, nullptr};
3493}
3494
3495llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
3496 llvm::DIFile *Unit) {
3497 // Ignore protocols.
3498 return getOrCreateType(Ty->getBaseType(), Unit);
3499}
3500
3501llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
3502 llvm::DIFile *Unit) {
3503 // Ignore protocols.
3504 SourceLocation Loc = Ty->getDecl()->getLocation();
3505
3506 // Use Typedefs to represent ObjCTypeParamType.
3507 return DBuilder.createTypedef(
3508 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
3509 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
3510 getDeclContextDescriptor(Ty->getDecl()));
3511}
3512
3513/// \return true if Getter has the default name for the property PD.
3515 const ObjCMethodDecl *Getter) {
3516 assert(PD);
3517 if (!Getter)
3518 return true;
3519
3520 assert(Getter->getDeclName().isObjCZeroArgSelector());
3521 return PD->getName() ==
3523}
3524
3525/// \return true if Setter has the default name for the property PD.
3527 const ObjCMethodDecl *Setter) {
3528 assert(PD);
3529 if (!Setter)
3530 return true;
3531
3532 assert(Setter->getDeclName().isObjCOneArgSelector());
3535}
3536
3537llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
3538 llvm::DIFile *Unit) {
3539 ObjCInterfaceDecl *ID = Ty->getDecl();
3540 if (!ID)
3541 return nullptr;
3542
3543 auto RuntimeLang = static_cast<llvm::dwarf::SourceLanguage>(
3544 TheCU->getSourceLanguage().getUnversionedName());
3545
3546 // Return a forward declaration if this type was imported from a clang module,
3547 // and this is not the compile unit with the implementation of the type (which
3548 // may contain hidden ivars).
3549 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
3550 !ID->getImplementation())
3551 return DBuilder.createForwardDecl(
3552 llvm::dwarf::DW_TAG_structure_type, ID->getName(),
3553 getDeclContextDescriptor(ID), Unit, 0, RuntimeLang);
3554
3555 // Get overall information about the record type for the debug info.
3556 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3557 unsigned Line = getLineNumber(ID->getLocation());
3558
3559 // If this is just a forward declaration return a special forward-declaration
3560 // debug type since we won't be able to lay out the entire type.
3561 ObjCInterfaceDecl *Def = ID->getDefinition();
3562 if (!Def || !Def->getImplementation()) {
3563 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3564 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
3565 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
3566 DefUnit, Line, RuntimeLang);
3567 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
3568 return FwdDecl;
3569 }
3570
3571 return CreateTypeDefinition(Ty, Unit);
3572}
3573
3574llvm::DIModule *CGDebugInfo::getOrCreateModuleRef(ASTSourceDescriptor Mod,
3575 bool CreateSkeletonCU) {
3576 // Use the Module pointer as the key into the cache. This is a
3577 // nullptr if the "Module" is a PCH, which is safe because we don't
3578 // support chained PCH debug info, so there can only be a single PCH.
3579 const Module *M = Mod.getModuleOrNull();
3580 auto ModRef = ModuleCache.find(M);
3581 if (ModRef != ModuleCache.end())
3582 return cast<llvm::DIModule>(ModRef->second);
3583
3584 // Macro definitions that were defined with "-D" on the command line.
3585 SmallString<128> ConfigMacros;
3586 {
3587 llvm::raw_svector_ostream OS(ConfigMacros);
3588 const auto &PPOpts = CGM.getPreprocessorOpts();
3589 unsigned I = 0;
3590 // Translate the macro definitions back into a command line.
3591 for (auto &M : PPOpts.Macros) {
3592 if (++I > 1)
3593 OS << " ";
3594 const std::string &Macro = M.first;
3595 bool Undef = M.second;
3596 OS << "\"-" << (Undef ? 'U' : 'D');
3597 for (char c : Macro)
3598 switch (c) {
3599 case '\\':
3600 OS << "\\\\";
3601 break;
3602 case '"':
3603 OS << "\\\"";
3604 break;
3605 default:
3606 OS << c;
3607 }
3608 OS << '\"';
3609 }
3610 }
3611
3612 bool IsRootModule = M ? !M->Parent : true;
3613 // When a module name is specified as -fmodule-name, that module gets a
3614 // clang::Module object, but it won't actually be built or imported; it will
3615 // be textual.
3616 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
3617 assert(StringRef(M->Name).starts_with(CGM.getLangOpts().ModuleName) &&
3618 "clang module without ASTFile must be specified by -fmodule-name");
3619
3620 // Return a StringRef to the remapped Path.
3621 auto RemapPath = [this](StringRef Path) -> std::string {
3622 std::string Remapped = remapDIPath(Path);
3623 StringRef Relative(Remapped);
3624 StringRef CompDir = TheCU->getDirectory();
3625 if (CompDir.empty())
3626 return Remapped;
3627
3628 if (Relative.consume_front(CompDir))
3629 Relative.consume_front(llvm::sys::path::get_separator());
3630
3631 return Relative.str();
3632 };
3633
3634 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
3635 // PCH files don't have a signature field in the control block,
3636 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
3637 // We use the lower 64 bits for debug info.
3638
3639 uint64_t Signature = 0;
3640 if (const auto &ModSig = Mod.getSignature())
3641 Signature = ModSig.truncatedValue();
3642 else
3643 Signature = ~1ULL;
3644
3645 llvm::DIBuilder DIB(CGM.getModule());
3646 SmallString<0> PCM;
3647 if (!llvm::sys::path::is_absolute(Mod.getASTFile())) {
3648 if (CGM.getHeaderSearchOpts().ModuleFileHomeIsCwd)
3649 PCM = getCurrentDirname();
3650 else
3651 PCM = Mod.getPath();
3652 }
3653 llvm::sys::path::append(PCM, Mod.getASTFile());
3654 DIB.createCompileUnit(
3655 TheCU->getSourceLanguage(),
3656 // TODO: Support "Source" from external AST providers?
3657 DIB.createFile(Mod.getModuleName(), TheCU->getDirectory()),
3658 TheCU->getProducer(), false, StringRef(), 0, RemapPath(PCM),
3659 llvm::DICompileUnit::FullDebug, Signature);
3660 DIB.finalize();
3661 }
3662
3663 llvm::DIModule *Parent =
3664 IsRootModule ? nullptr
3665 : getOrCreateModuleRef(ASTSourceDescriptor(*M->Parent),
3666 CreateSkeletonCU);
3667 StringRef IncludePath = Mod.getPath();
3668 if (!CGM.getCodeGenOpts().DebugRecordSysroot) {
3669 StringRef Sysroot = CGM.getHeaderSearchOpts().Sysroot;
3670 if (!Sysroot.empty() && IncludePath.starts_with(Sysroot))
3671 IncludePath = "";
3672 }
3673 llvm::DIModule *DIMod =
3674 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
3675 RemapPath(IncludePath));
3676 ModuleCache[M].reset(DIMod);
3677 return DIMod;
3678}
3679
3680llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
3681 llvm::DIFile *Unit) {
3682 ObjCInterfaceDecl *ID = Ty->getDecl();
3683 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
3684 unsigned Line = getLineNumber(ID->getLocation());
3685
3686 unsigned RuntimeLang = TheCU->getSourceLanguage().getUnversionedName();
3687
3688 // Bit size, align and offset of the type.
3689 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3690 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3691
3692 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3693 if (ID->getImplementation())
3694 Flags |= llvm::DINode::FlagObjcClassComplete;
3695
3696 llvm::DIScope *Mod = getParentModuleOrNull(ID);
3697 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
3698 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
3699 nullptr, llvm::DINodeArray(), RuntimeLang);
3700
3701 QualType QTy(Ty, 0);
3702 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
3703
3704 // Push the struct on region stack.
3705 LexicalBlockStack.emplace_back(RealDecl);
3706 RegionMap[Ty->getDecl()].reset(RealDecl);
3707
3708 // Convert all the elements.
3709 SmallVector<llvm::Metadata *, 16> EltTys;
3710
3711 ObjCInterfaceDecl *SClass = ID->getSuperClass();
3712 if (SClass) {
3713 llvm::DIType *SClassTy =
3714 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
3715 if (!SClassTy)
3716 return nullptr;
3717
3718 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
3719 llvm::DINode::FlagZero);
3720 EltTys.push_back(InhTag);
3721 }
3722
3723 // Create entries for all of the properties.
3724 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
3725 SourceLocation Loc = PD->getLocation();
3726 llvm::DIFile *PUnit = getOrCreateFile(Loc);
3727 unsigned PLine = getLineNumber(Loc);
3728 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
3729 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
3730 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
3731 PD->getName(), PUnit, PLine,
3732 hasDefaultGetterName(PD, Getter) ? ""
3733 : getSelectorName(PD->getGetterName()),
3734 hasDefaultSetterName(PD, Setter) ? ""
3735 : getSelectorName(PD->getSetterName()),
3736 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
3737 EltTys.push_back(PropertyNode);
3738 };
3739 {
3740 // Use 'char' for the isClassProperty bit as DenseSet requires space for
3741 // the empty key in the data type (and bool is too small for that).
3742 typedef std::pair<char, const IdentifierInfo *> IsClassAndIdent;
3743 /// List of already emitted properties. Two distinct class and instance
3744 /// properties can share the same identifier (but not two instance
3745 /// properties or two class properties).
3746 llvm::DenseSet<IsClassAndIdent> PropertySet;
3747 /// Returns the IsClassAndIdent key for the given property.
3748 auto GetIsClassAndIdent = [](const ObjCPropertyDecl *PD) {
3749 return std::make_pair(PD->isClassProperty(), PD->getIdentifier());
3750 };
3751 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
3752 for (auto *PD : ClassExt->properties()) {
3753 PropertySet.insert(GetIsClassAndIdent(PD));
3754 AddProperty(PD);
3755 }
3756 for (const auto *PD : ID->properties()) {
3757 // Don't emit duplicate metadata for properties that were already in a
3758 // class extension.
3759 if (!PropertySet.insert(GetIsClassAndIdent(PD)).second)
3760 continue;
3761 AddProperty(PD);
3762 }
3763 }
3764
3765 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
3766 unsigned FieldNo = 0;
3767 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
3768 Field = Field->getNextIvar(), ++FieldNo) {
3769 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3770 if (!FieldTy)
3771 return nullptr;
3772
3773 StringRef FieldName = Field->getName();
3774
3775 // Ignore unnamed fields.
3776 if (FieldName.empty())
3777 continue;
3778
3779 // Get the location for the field.
3780 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
3781 unsigned FieldLine = getLineNumber(Field->getLocation());
3782 QualType FType = Field->getType();
3783 uint64_t FieldSize = 0;
3784 uint32_t FieldAlign = 0;
3785
3786 if (!FType->isIncompleteArrayType()) {
3787
3788 // Bit size, align and offset of the type.
3789 FieldSize = Field->isBitField() ? Field->getBitWidthValue()
3790 : CGM.getContext().getTypeSize(FType);
3791 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3792 }
3793
3794 uint64_t FieldOffset;
3795 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3796 // We don't know the runtime offset of an ivar if we're using the
3797 // non-fragile ABI. For bitfields, use the bit offset into the first
3798 // byte of storage of the bitfield. For other fields, use zero.
3799 if (Field->isBitField()) {
3800 FieldOffset =
3801 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
3802 FieldOffset %= CGM.getContext().getCharWidth();
3803 } else {
3804 FieldOffset = 0;
3805 }
3806 } else {
3807 FieldOffset = RL.getFieldOffset(FieldNo);
3808 }
3809
3810 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3811 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
3812 Flags = llvm::DINode::FlagProtected;
3813 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
3814 Flags = llvm::DINode::FlagPrivate;
3815 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
3816 Flags = llvm::DINode::FlagPublic;
3817
3818 if (Field->isBitField())
3819 Flags |= llvm::DINode::FlagBitField;
3820
3821 llvm::MDNode *PropertyNode = nullptr;
3822 ObjCPropertyDecl *SynthesizedProperty = nullptr;
3823 llvm::DIFile *PUnit = nullptr;
3824 unsigned PLine = 0;
3825 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
3826 if (ObjCPropertyImplDecl *PImpD =
3827 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
3828 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
3829 SynthesizedProperty = PD;
3830 SourceLocation Loc = PD->getLocation();
3831 PUnit = getOrCreateFile(Loc);
3832 PLine = getLineNumber(Loc);
3833 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
3834 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
3835 PropertyNode = DBuilder.createObjCProperty(
3836 PD->getName(), PUnit, PLine,
3837 hasDefaultGetterName(PD, Getter)
3838 ? ""
3839 : getSelectorName(PD->getGetterName()),
3840 hasDefaultSetterName(PD, Setter)
3841 ? ""
3842 : getSelectorName(PD->getSetterName()),
3843 PD->getPropertyAttributes(),
3844 getOrCreateType(PD->getType(), PUnit));
3845 }
3846 }
3847 }
3848 auto *IvarTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
3849 FieldSize, FieldAlign, FieldOffset,
3850 Flags, FieldTy, PropertyNode);
3851 EltTys.push_back(IvarTy);
3852
3853 if (SynthesizedProperty) {
3854 assert(PUnit && "SynthesizedProperty implies PUnit");
3855 EltTys.push_back(DBuilder.createProperty(
3856 SynthesizedProperty->getName(), PUnit, PLine,
3857 getOrCreateType(SynthesizedProperty->getType(), PUnit), IvarTy));
3858 }
3859 }
3860
3861 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3862 DBuilder.replaceArrays(RealDecl, Elements);
3863
3864 LexicalBlockStack.pop_back();
3865 return RealDecl;
3866}
3867
3868llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
3869 llvm::DIFile *Unit) {
3870 if (Ty->isPackedVectorBoolType(CGM.getContext())) {
3871 // Boolean ext_vector_type(N) are special because their real element type
3872 // (bits of bit size) is not their Clang element type (_Bool of size byte).
3873 // For now, we pretend the boolean vector were actually a vector of bytes
3874 // (where each byte represents 8 bits of the actual vector).
3875 // FIXME Debug info should actually represent this proper as a vector mask
3876 // type.
3877 auto &Ctx = CGM.getContext();
3878 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3879 uint64_t NumVectorBytes = Size / Ctx.getCharWidth();
3880
3881 // Construct the vector of 'char' type.
3882 QualType CharVecTy =
3883 Ctx.getVectorType(Ctx.CharTy, NumVectorBytes, VectorKind::Generic);
3884 return CreateType(CharVecTy->getAs<VectorType>(), Unit);
3885 }
3886
3887 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3888 int64_t Count = Ty->getNumElements();
3889
3890 llvm::Metadata *Subscript;
3891 QualType QTy(Ty, 0);
3892 auto SizeExpr = SizeExprCache.find(QTy);
3893 if (SizeExpr != SizeExprCache.end())
3894 Subscript = DBuilder.getOrCreateSubrange(
3895 SizeExpr->getSecond() /*count*/, nullptr /*lowerBound*/,
3896 nullptr /*upperBound*/, nullptr /*stride*/);
3897 else {
3898 auto *CountNode =
3899 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3900 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count ? Count : -1));
3901 Subscript = DBuilder.getOrCreateSubrange(
3902 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3903 nullptr /*stride*/);
3904 }
3905 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
3906
3907 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3908 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3909
3910 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
3911}
3912
3913llvm::DIType *CGDebugInfo::CreateType(const ConstantMatrixType *Ty,
3914 llvm::DIFile *Unit) {
3915 // FIXME: Create another debug type for matrices
3916 // For the time being, it treats it like a nested ArrayType.
3917
3918 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
3919 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3920 uint32_t Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3921
3922 // Create ranges for both dimensions.
3923 llvm::SmallVector<llvm::Metadata *, 2> Subscripts;
3924 auto *ColumnCountNode =
3925 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3926 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumColumns()));
3927 auto *RowCountNode =
3928 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3929 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Ty->getNumRows()));
3930 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3931 ColumnCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3932 nullptr /*stride*/));
3933 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3934 RowCountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3935 nullptr /*stride*/));
3936 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
3937 return DBuilder.createArrayType(Size, Align, ElementTy, SubscriptArray);
3938}
3939
3940llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
3941 uint64_t Size;
3942 uint32_t Align;
3943
3944 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
3945 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3946 Size = 0;
3947 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
3948 CGM.getContext());
3949 } else if (Ty->isIncompleteArrayType()) {
3950 Size = 0;
3951 if (Ty->getElementType()->isIncompleteType())
3952 Align = 0;
3953 else
3954 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
3955 } else if (Ty->isIncompleteType()) {
3956 Size = 0;
3957 Align = 0;
3958 } else {
3959 // Size and align of the whole array, not the element type.
3960 Size = CGM.getContext().getTypeSize(Ty);
3961 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
3962 }
3963
3964 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
3965 // interior arrays, do we care? Why aren't nested arrays represented the
3966 // obvious/recursive way?
3967 SmallVector<llvm::Metadata *, 8> Subscripts;
3968 QualType EltTy(Ty, 0);
3969 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
3970 // If the number of elements is known, then count is that number. Otherwise,
3971 // it's -1. This allows us to represent a subrange with an array of 0
3972 // elements, like this:
3973 //
3974 // struct foo {
3975 // int x[0];
3976 // };
3977 int64_t Count = -1; // Count == -1 is an unbounded array.
3978 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
3979 Count = CAT->getZExtSize();
3980 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
3981 if (Expr *Size = VAT->getSizeExpr()) {
3982 Expr::EvalResult Result;
3983 if (Size->EvaluateAsInt(Result, CGM.getContext()))
3984 Count = Result.Val.getInt().getExtValue();
3985 }
3986 }
3987
3988 auto SizeNode = SizeExprCache.find(EltTy);
3989 if (SizeNode != SizeExprCache.end())
3990 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3991 SizeNode->getSecond() /*count*/, nullptr /*lowerBound*/,
3992 nullptr /*upperBound*/, nullptr /*stride*/));
3993 else {
3994 auto *CountNode =
3995 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getSigned(
3996 llvm::Type::getInt64Ty(CGM.getLLVMContext()), Count));
3997 Subscripts.push_back(DBuilder.getOrCreateSubrange(
3998 CountNode /*count*/, nullptr /*lowerBound*/, nullptr /*upperBound*/,
3999 nullptr /*stride*/));
4000 }
4001 EltTy = Ty->getElementType();
4002 }
4003
4004 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
4005
4006 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
4007 SubscriptArray);
4008}
4009
4010llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
4011 llvm::DIFile *Unit) {
4012 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
4013 Ty->getPointeeType(), Unit);
4014}
4015
4016llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
4017 llvm::DIFile *Unit) {
4018 llvm::dwarf::Tag Tag = llvm::dwarf::DW_TAG_rvalue_reference_type;
4019 // DW_TAG_rvalue_reference_type was introduced in DWARF 4.
4020 if (CGM.getCodeGenOpts().DebugStrictDwarf &&
4021 CGM.getCodeGenOpts().DwarfVersion < 4)
4022 Tag = llvm::dwarf::DW_TAG_reference_type;
4023
4024 return CreatePointerLikeType(Tag, Ty, Ty->getPointeeType(), Unit);
4025}
4026
4027llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
4028 llvm::DIFile *U) {
4029 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4030 uint64_t Size = 0;
4031
4032 if (!Ty->isIncompleteType()) {
4033 Size = CGM.getContext().getTypeSize(Ty);
4034
4035 // Set the MS inheritance model. There is no flag for the unspecified model.
4036 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
4039 Flags |= llvm::DINode::FlagSingleInheritance;
4040 break;
4042 Flags |= llvm::DINode::FlagMultipleInheritance;
4043 break;
4045 Flags |= llvm::DINode::FlagVirtualInheritance;
4046 break;
4048 break;
4049 }
4050 }
4051 }
4052
4053 CanQualType T =
4054 CGM.getContext().getCanonicalTagType(Ty->getMostRecentCXXRecordDecl());
4055 llvm::DIType *ClassType = getOrCreateType(T, U);
4056 if (Ty->isMemberDataPointerType())
4057 return DBuilder.createMemberPointerType(
4058 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
4059 Flags);
4060
4061 const FunctionProtoType *FPT =
4062 Ty->getPointeeType()->castAs<FunctionProtoType>();
4063 return DBuilder.createMemberPointerType(
4064 getOrCreateInstanceMethodType(
4066 FPT, U),
4067 ClassType, Size, /*Align=*/0, Flags);
4068}
4069
4070llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
4071 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
4072 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
4073}
4074
4075llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
4076 return getOrCreateType(Ty->getElementType(), U);
4077}
4078
4079llvm::DIType *CGDebugInfo::CreateType(const HLSLAttributedResourceType *Ty,
4080 llvm::DIFile *U) {
4081 return getOrCreateType(Ty->getWrappedType(), U);
4082}
4083
4084llvm::DIType *CGDebugInfo::CreateType(const HLSLInlineSpirvType *Ty,
4085 llvm::DIFile *U) {
4086 // Debug information unneeded.
4087 return nullptr;
4088}
4089
4090static auto getEnumInfo(CodeGenModule &CGM, llvm::DICompileUnit *TheCU,
4091 const EnumType *Ty) {
4092 const EnumDecl *ED = Ty->getDecl()->getDefinitionOrSelf();
4093
4094 uint64_t Size = 0;
4095 uint32_t Align = 0;
4096 if (ED->isComplete()) {
4097 Size = CGM.getContext().getTypeSize(QualType(Ty, 0));
4098 Align = getDeclAlignIfRequired(ED, CGM.getContext());
4099 }
4100 return std::make_tuple(ED, Size, Align, getTypeIdentifier(Ty, CGM, TheCU));
4101}
4102
4103llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
4104 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
4105
4106 bool isImportedFromModule =
4107 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
4108
4109 // If this is just a forward declaration, construct an appropriately
4110 // marked node and just return it.
4111 if (isImportedFromModule || !ED->getDefinition()) {
4112 // Note that it is possible for enums to be created as part of
4113 // their own declcontext. In this case a FwdDecl will be created
4114 // twice. This doesn't cause a problem because both FwdDecls are
4115 // entered into the ReplaceMap: finalize() will replace the first
4116 // FwdDecl with the second and then replace the second with
4117 // complete type.
4118 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
4119 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
4120 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
4121 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
4122
4123 unsigned Line = getLineNumber(ED->getLocation());
4124 StringRef EDName = ED->getName();
4125 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
4126 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
4127 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
4128
4129 ReplaceMap.emplace_back(
4130 std::piecewise_construct, std::make_tuple(Ty),
4131 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
4132 return RetTy;
4133 }
4134
4135 return CreateTypeDefinition(Ty);
4136}
4137
4138llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
4139 auto [ED, Size, Align, Identifier] = getEnumInfo(CGM, TheCU, Ty);
4140
4141 SmallVector<llvm::Metadata *, 16> Enumerators;
4142 ED = ED->getDefinition();
4143 assert(ED && "An enumeration definition is required");
4144 for (const auto *Enum : ED->enumerators()) {
4145 Enumerators.push_back(
4146 DBuilder.createEnumerator(Enum->getName(), Enum->getInitVal()));
4147 }
4148
4149 std::optional<EnumExtensibilityAttr::Kind> EnumKind;
4150 if (auto *Attr = ED->getAttr<EnumExtensibilityAttr>())
4151 EnumKind = Attr->getExtensibility();
4152
4153 // Return a CompositeType for the enum itself.
4154 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
4155
4156 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
4157 unsigned Line = getLineNumber(ED->getLocation());
4158 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
4159 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
4160 return DBuilder.createEnumerationType(
4161 EnumContext, ED->getName(), DefUnit, Line, Size, Align, EltArray, ClassTy,
4162 /*RunTimeLang=*/0, Identifier, ED->isScoped(), EnumKind);
4163}
4164
4165llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
4166 unsigned MType, SourceLocation LineLoc,
4167 StringRef Name, StringRef Value) {
4168 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
4169 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
4170}
4171
4172llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
4173 SourceLocation LineLoc,
4174 SourceLocation FileLoc) {
4175 llvm::DIFile *FName = getOrCreateFile(FileLoc);
4176 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
4177 return DBuilder.createTempMacroFile(Parent, Line, FName);
4178}
4179
4180llvm::DILocation *
4181CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc ParentLocation,
4182 llvm::DISubprogram *SynthSubprogram) {
4183 return llvm::DILocation::get(CGM.getLLVMContext(), /*Line=*/0, /*Column=*/0,
4184 SynthSubprogram, ParentLocation);
4185}
4186
4187llvm::DILocation *
4188CGDebugInfo::CreateSyntheticInlineAt(llvm::DebugLoc ParentLocation,
4189 StringRef SynthFuncName,
4190 llvm::DIFile *SynthFile) {
4191 llvm::DISubprogram *SP = createInlinedSubprogram(SynthFuncName, SynthFile);
4192 return CreateSyntheticInlineAt(ParentLocation, SP);
4193}
4194
4196 llvm::DebugLoc TrapLocation, StringRef Category, StringRef FailureMsg) {
4197 // Create a debug location from `TrapLocation` that adds an artificial inline
4198 // frame.
4200
4201 FuncName += "$";
4202 FuncName += Category;
4203 FuncName += "$";
4204 FuncName += FailureMsg;
4205
4206 return CreateSyntheticInlineAt(TrapLocation, FuncName,
4207 TrapLocation->getFile());
4208}
4209
4211 Qualifiers Quals;
4212 do {
4213 Qualifiers InnerQuals = T.getLocalQualifiers();
4214 // Qualifiers::operator+() doesn't like it if you add a Qualifier
4215 // that is already there.
4216 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
4217 Quals += InnerQuals;
4218 QualType LastT = T;
4219 switch (T->getTypeClass()) {
4220 default:
4221 return C.getQualifiedType(T.getTypePtr(), Quals);
4222 case Type::Enum:
4223 case Type::Record:
4224 case Type::InjectedClassName:
4225 return C.getQualifiedType(T->getCanonicalTypeUnqualified().getTypePtr(),
4226 Quals);
4227 case Type::TemplateSpecialization: {
4228 const auto *Spec = cast<TemplateSpecializationType>(T);
4229 if (Spec->isTypeAlias())
4230 return C.getQualifiedType(T.getTypePtr(), Quals);
4231 T = Spec->desugar();
4232 break;
4233 }
4234 case Type::TypeOfExpr:
4235 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
4236 break;
4237 case Type::TypeOf:
4238 T = cast<TypeOfType>(T)->getUnmodifiedType();
4239 break;
4240 case Type::Decltype:
4241 T = cast<DecltypeType>(T)->getUnderlyingType();
4242 break;
4243 case Type::UnaryTransform:
4244 T = cast<UnaryTransformType>(T)->getUnderlyingType();
4245 break;
4246 case Type::Attributed:
4247 T = cast<AttributedType>(T)->getEquivalentType();
4248 break;
4249 case Type::BTFTagAttributed:
4250 T = cast<BTFTagAttributedType>(T)->getWrappedType();
4251 break;
4252 case Type::CountAttributed:
4253 T = cast<CountAttributedType>(T)->desugar();
4254 break;
4255 case Type::Using:
4256 T = cast<UsingType>(T)->desugar();
4257 break;
4258 case Type::Paren:
4259 T = cast<ParenType>(T)->getInnerType();
4260 break;
4261 case Type::MacroQualified:
4262 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
4263 break;
4264 case Type::SubstTemplateTypeParm:
4265 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
4266 break;
4267 case Type::Auto:
4268 case Type::DeducedTemplateSpecialization: {
4269 QualType DT = cast<DeducedType>(T)->getDeducedType();
4270 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
4271 T = DT;
4272 break;
4273 }
4274 case Type::PackIndexing: {
4275 T = cast<PackIndexingType>(T)->getSelectedType();
4276 break;
4277 }
4278 case Type::Adjusted:
4279 case Type::Decayed:
4280 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
4281 T = cast<AdjustedType>(T)->getAdjustedType();
4282 break;
4283 }
4284
4285 assert(T != LastT && "Type unwrapping failed to unwrap!");
4286 (void)LastT;
4287 } while (true);
4288}
4289
4290llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
4291 assert(Ty == UnwrapTypeForDebugInfo(Ty, CGM.getContext()));
4292 auto It = TypeCache.find(Ty.getAsOpaquePtr());
4293 if (It != TypeCache.end()) {
4294 // Verify that the debug info still exists.
4295 if (llvm::Metadata *V = It->second)
4296 return cast<llvm::DIType>(V);
4297 }
4298
4299 return nullptr;
4300}
4301
4306
4308 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly ||
4309 D.isDynamicClass())
4310 return;
4311
4313 // In case this type has no member function definitions being emitted, ensure
4314 // it is retained
4315 RetainedTypes.push_back(
4316 CGM.getContext().getCanonicalTagType(&D).getAsOpaquePtr());
4317}
4318
4319llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
4320 if (Ty.isNull())
4321 return nullptr;
4322
4323 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
4324 std::string Name;
4325 llvm::raw_string_ostream OS(Name);
4326 Ty.print(OS, getPrintingPolicy());
4327 return Name;
4328 });
4329
4330 // Unwrap the type as needed for debug information.
4331 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
4332
4333 if (auto *T = getTypeOrNull(Ty))
4334 return T;
4335
4336 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
4337 void *TyPtr = Ty.getAsOpaquePtr();
4338
4339 // And update the type cache.
4340 TypeCache[TyPtr].reset(Res);
4341
4342 return Res;
4343}
4344
4345llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
4346 // A forward declaration inside a module header does not belong to the module.
4348 return nullptr;
4349 if (DebugTypeExtRefs && D->isFromASTFile()) {
4350 // Record a reference to an imported clang module or precompiled header.
4351 auto *Reader = CGM.getContext().getExternalSource();
4352 auto Idx = D->getOwningModuleID();
4353 auto Info = Reader->getSourceDescriptor(Idx);
4354 if (Info)
4355 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
4356 } else if (ClangModuleMap) {
4357 // We are building a clang module or a precompiled header.
4358 //
4359 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
4360 // and it wouldn't be necessary to specify the parent scope
4361 // because the type is already unique by definition (it would look
4362 // like the output of -fno-standalone-debug). On the other hand,
4363 // the parent scope helps a consumer to quickly locate the object
4364 // file where the type's definition is located, so it might be
4365 // best to make this behavior a command line or debugger tuning
4366 // option.
4367 if (Module *M = D->getOwningModule()) {
4368 // This is a (sub-)module.
4369 auto Info = ASTSourceDescriptor(*M);
4370 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
4371 } else {
4372 // This the precompiled header being built.
4373 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
4374 }
4375 }
4376
4377 return nullptr;
4378}
4379
4380llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
4381 // Handle qualifiers, which recursively handles what they refer to.
4382 if (Ty.hasLocalQualifiers())
4383 return CreateQualifiedType(Ty, Unit);
4384
4385 // Work out details of type.
4386 switch (Ty->getTypeClass()) {
4387#define TYPE(Class, Base)
4388#define ABSTRACT_TYPE(Class, Base)
4389#define NON_CANONICAL_TYPE(Class, Base)
4390#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4391#include "clang/AST/TypeNodes.inc"
4392 llvm_unreachable("Dependent types cannot show up in debug information");
4393
4394 case Type::ExtVector:
4395 case Type::Vector:
4396 return CreateType(cast<VectorType>(Ty), Unit);
4397 case Type::ConstantMatrix:
4398 return CreateType(cast<ConstantMatrixType>(Ty), Unit);
4399 case Type::ObjCObjectPointer:
4400 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
4401 case Type::ObjCObject:
4402 return CreateType(cast<ObjCObjectType>(Ty), Unit);
4403 case Type::ObjCTypeParam:
4404 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
4405 case Type::ObjCInterface:
4406 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
4407 case Type::Builtin:
4408 return CreateType(cast<BuiltinType>(Ty));
4409 case Type::Complex:
4410 return CreateType(cast<ComplexType>(Ty));
4411 case Type::Pointer:
4412 return CreateType(cast<PointerType>(Ty), Unit);
4413 case Type::BlockPointer:
4414 return CreateType(cast<BlockPointerType>(Ty), Unit);
4415 case Type::Typedef:
4416 return CreateType(cast<TypedefType>(Ty), Unit);
4417 case Type::Record:
4418 return CreateType(cast<RecordType>(Ty));
4419 case Type::Enum:
4420 return CreateEnumType(cast<EnumType>(Ty));
4421 case Type::FunctionProto:
4422 case Type::FunctionNoProto:
4423 return CreateType(cast<FunctionType>(Ty), Unit);
4424 case Type::ConstantArray:
4425 case Type::VariableArray:
4426 case Type::IncompleteArray:
4427 case Type::ArrayParameter:
4428 return CreateType(cast<ArrayType>(Ty), Unit);
4429
4430 case Type::LValueReference:
4431 return CreateType(cast<LValueReferenceType>(Ty), Unit);
4432 case Type::RValueReference:
4433 return CreateType(cast<RValueReferenceType>(Ty), Unit);
4434
4435 case Type::MemberPointer:
4436 return CreateType(cast<MemberPointerType>(Ty), Unit);
4437
4438 case Type::Atomic:
4439 return CreateType(cast<AtomicType>(Ty), Unit);
4440
4441 case Type::BitInt:
4442 return CreateType(cast<BitIntType>(Ty));
4443 case Type::OverflowBehavior:
4444 return CreateType(cast<OverflowBehaviorType>(Ty), Unit);
4445 case Type::Pipe:
4446 return CreateType(cast<PipeType>(Ty), Unit);
4447
4448 case Type::TemplateSpecialization:
4449 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
4450 case Type::HLSLAttributedResource:
4451 return CreateType(cast<HLSLAttributedResourceType>(Ty), Unit);
4452 case Type::HLSLInlineSpirv:
4453 return CreateType(cast<HLSLInlineSpirvType>(Ty), Unit);
4454 case Type::PredefinedSugar:
4455 return getOrCreateType(cast<PredefinedSugarType>(Ty)->desugar(), Unit);
4456 case Type::CountAttributed:
4457 case Type::LateParsedAttr:
4458 case Type::Auto:
4459 case Type::Attributed:
4460 case Type::BTFTagAttributed:
4461 case Type::Adjusted:
4462 case Type::Decayed:
4463 case Type::DeducedTemplateSpecialization:
4464 case Type::Using:
4465 case Type::Paren:
4466 case Type::MacroQualified:
4467 case Type::SubstTemplateTypeParm:
4468 case Type::TypeOfExpr:
4469 case Type::TypeOf:
4470 case Type::Decltype:
4471 case Type::PackIndexing:
4472 case Type::UnaryTransform:
4473 break;
4474 }
4475
4476 llvm_unreachable("type should have been unwrapped!");
4477}
4478
4479llvm::DICompositeType *
4480CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty) {
4481 QualType QTy(Ty, 0);
4482
4483 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
4484
4485 // We may have cached a forward decl when we could have created
4486 // a non-forward decl. Go ahead and create a non-forward decl
4487 // now.
4488 if (T && !T->isForwardDecl())
4489 return T;
4490
4491 // Otherwise create the type.
4492 llvm::DICompositeType *Res = CreateLimitedType(Ty);
4493
4494 // Propagate members from the declaration to the definition
4495 // CreateType(const RecordType*) will overwrite this with the members in the
4496 // correct order if the full type is needed.
4497 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
4498
4499 // And update the type cache.
4500 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
4501 return Res;
4502}
4503
4504// TODO: Currently used for context chains when limiting debug info.
4505llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
4506 RecordDecl *RD = Ty->getDecl()->getDefinitionOrSelf();
4507 bool NameIsSimplified = false;
4508
4509 // Get overall information about the record type for the debug info.
4510 StringRef RDName = getClassName(RD, &NameIsSimplified);
4511 const SourceLocation Loc = RD->getLocation();
4512 llvm::DIFile *DefUnit = nullptr;
4513 unsigned Line = 0;
4514 if (Loc.isValid()) {
4515 DefUnit = getOrCreateFile(Loc);
4516 Line = getLineNumber(Loc);
4517 }
4518
4519 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
4520
4521 // If we ended up creating the type during the context chain construction,
4522 // just return that.
4523 auto *T = cast_or_null<llvm::DICompositeType>(
4524 getTypeOrNull(CGM.getContext().getCanonicalTagType(RD)));
4525 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
4526 return T;
4527
4528 // If this is just a forward or incomplete declaration, construct an
4529 // appropriately marked node and just return it.
4530 const RecordDecl *D = RD->getDefinition();
4531 if (!D || !D->isCompleteDefinition())
4532 return getOrCreateRecordFwdDecl(Ty, RDContext);
4533
4534 uint64_t Size = CGM.getContext().getTypeSize(Ty);
4535 // __attribute__((aligned)) can increase or decrease alignment *except* on a
4536 // struct or struct member, where it only increases alignment unless 'packed'
4537 // is also specified. To handle this case, the `getTypeAlignIfRequired` needs
4538 // to be used.
4539 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
4540
4541 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
4542
4543 // Explicitly record the calling convention and export symbols for C++
4544 // records.
4545 auto Flags = llvm::DINode::FlagZero;
4546 if (NameIsSimplified)
4547 Flags |= llvm::DINode::FlagNameIsSimplified;
4548 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4549 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
4550 Flags |= llvm::DINode::FlagTypePassByReference;
4551 else
4552 Flags |= llvm::DINode::FlagTypePassByValue;
4553
4554 // Record if a C++ record is non-trivial type.
4555 if (!CXXRD->isTrivial())
4556 Flags |= llvm::DINode::FlagNonTrivial;
4557
4558 // Record exports it symbols to the containing structure.
4559 if (CXXRD->isAnonymousStructOrUnion())
4560 Flags |= llvm::DINode::FlagExportSymbols;
4561
4562 Flags |= getAccessFlag(CXXRD->getAccess(),
4563 dyn_cast<CXXRecordDecl>(CXXRD->getDeclContext()));
4564 }
4565
4566 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
4567 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
4568 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
4569 Flags, Identifier, Annotations);
4570
4571 // Elements of composite types usually have back to the type, creating
4572 // uniquing cycles. Distinct nodes are more efficient.
4573 switch (RealDecl->getTag()) {
4574 default:
4575 llvm_unreachable("invalid composite type tag");
4576
4577 case llvm::dwarf::DW_TAG_array_type:
4578 case llvm::dwarf::DW_TAG_enumeration_type:
4579 // Array elements and most enumeration elements don't have back references,
4580 // so they don't tend to be involved in uniquing cycles and there is some
4581 // chance of merging them when linking together two modules. Only make
4582 // them distinct if they are ODR-uniqued.
4583 if (Identifier.empty())
4584 break;
4585 [[fallthrough]];
4586
4587 case llvm::dwarf::DW_TAG_structure_type:
4588 case llvm::dwarf::DW_TAG_union_type:
4589 case llvm::dwarf::DW_TAG_class_type:
4590 // Immediately resolve to a distinct node.
4591 RealDecl =
4592 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
4593 break;
4594 }
4595
4596 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Ty->getDecl())) {
4597 CXXRecordDecl *TemplateDecl =
4598 CTSD->getSpecializedTemplate()->getTemplatedDecl();
4599 RegionMap[TemplateDecl].reset(RealDecl);
4600 } else {
4601 RegionMap[RD].reset(RealDecl);
4602 }
4603 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
4604
4605 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
4606 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
4607 CollectCXXTemplateParams(TSpecial, DefUnit));
4608 return RealDecl;
4609}
4610
4611void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
4612 llvm::DICompositeType *RealDecl) {
4613 // A class's primary base or the class itself contains the vtable.
4614 llvm::DIType *ContainingType = nullptr;
4615 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
4616 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
4617 // Seek non-virtual primary base root.
4618 while (true) {
4619 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
4620 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
4621 if (PBT && !BRL.isPrimaryBaseVirtual())
4622 PBase = PBT;
4623 else
4624 break;
4625 }
4626 CanQualType T = CGM.getContext().getCanonicalTagType(PBase);
4627 ContainingType = getOrCreateType(T, getOrCreateFile(RD->getLocation()));
4628 } else if (RD->isDynamicClass())
4629 ContainingType = RealDecl;
4630
4631 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
4632}
4633
4634llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
4635 StringRef Name, uint64_t *Offset) {
4636 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
4637 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
4638 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
4639 llvm::DIType *Ty =
4640 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
4641 *Offset, llvm::DINode::FlagZero, FieldTy);
4642 *Offset += FieldSize;
4643 return Ty;
4644}
4645
4646void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
4647 StringRef &Name,
4648 StringRef &LinkageName,
4649 llvm::DIScope *&FDContext,
4650 llvm::DINodeArray &TParamsArray,
4651 llvm::DINode::DIFlags &Flags) {
4652 const auto *FD = cast<FunctionDecl>(GD.getCanonicalDecl().getDecl());
4653 bool NameIsSimplified = false;
4654 Name = getFunctionName(FD, &NameIsSimplified);
4655 if (NameIsSimplified)
4656 Flags |= llvm::DINode::FlagNameIsSimplified;
4657 Name = getFunctionName(FD);
4658 // Use mangled name as linkage name for C/C++ functions.
4659 if (FD->getType()->getAs<FunctionProtoType>())
4660 LinkageName = CGM.getMangledName(GD);
4661 if (FD->hasPrototype())
4662 Flags |= llvm::DINode::FlagPrototyped;
4663 // No need to replicate the linkage name if it isn't different from the
4664 // subprogram name, no need to have it at all unless coverage is enabled or
4665 // debug is set to more than just line tables or extra debug info is needed.
4666 if (LinkageName == Name ||
4667 (CGM.getCodeGenOpts().CoverageNotesFile.empty() &&
4668 CGM.getCodeGenOpts().CoverageDataFile.empty() &&
4669 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
4670 !CGM.getCodeGenOpts().PseudoProbeForProfiling &&
4671 DebugKind <= llvm::codegenoptions::DebugLineTablesOnly))
4672 LinkageName = StringRef();
4673
4674 // Emit the function scope in line tables only mode (if CodeView) to
4675 // differentiate between function names.
4676 if (CGM.getCodeGenOpts().hasReducedDebugInfo() ||
4677 (DebugKind == llvm::codegenoptions::DebugLineTablesOnly &&
4678 CGM.getCodeGenOpts().EmitCodeView)) {
4679 if (const NamespaceDecl *NSDecl =
4680 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
4681 FDContext = getOrCreateNamespace(NSDecl);
4682 else if (const RecordDecl *RDecl =
4683 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
4684 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
4685 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
4686 }
4687 }
4688 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
4689 // Check if it is a noreturn-marked function
4690 if (FD->isNoReturn())
4691 Flags |= llvm::DINode::FlagNoReturn;
4692 // Collect template parameters.
4693 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
4694 }
4695}
4696
4697void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
4698 unsigned &LineNo, QualType &T,
4699 StringRef &Name, StringRef &LinkageName,
4700 llvm::MDTuple *&TemplateParameters,
4701 llvm::DIScope *&VDContext) {
4702 Unit = getOrCreateFile(VD->getLocation());
4703 LineNo = getLineNumber(VD->getLocation());
4704
4705 setLocation(VD->getLocation());
4706
4707 T = VD->getType();
4708 if (T->isIncompleteArrayType()) {
4709 // CodeGen turns int[] into int[1] so we'll do the same here.
4710 llvm::APInt ConstVal(32, 1);
4711 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
4712
4713 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
4715 }
4716
4717 Name = VD->getName();
4718 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
4720 LinkageName = CGM.getMangledName(VD);
4721 if (LinkageName == Name)
4722 LinkageName = StringRef();
4723
4725 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
4726 TemplateParameters = parameterNodes.get();
4727 } else {
4728 TemplateParameters = nullptr;
4729 }
4730
4731 // Get context for static locals (that are technically globals) the same way
4732 // we do for "local" locals -- by using current lexical block.
4733 if (VD->isStaticLocal()) {
4734 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4735 VDContext = LexicalBlockStack.back();
4736 return;
4737 }
4738
4739 // Since we emit declarations (DW_AT_members) for static members, place the
4740 // definition of those static members in the namespace they were declared in
4741 // in the source code (the lexical decl context).
4742 // FIXME: Generalize this for even non-member global variables where the
4743 // declaration and definition may have different lexical decl contexts, once
4744 // we have support for emitting declarations of (non-member) global variables.
4745 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
4746 : VD->getDeclContext();
4747 // When a record type contains an in-line initialization of a static data
4748 // member, and the record type is marked as __declspec(dllexport), an implicit
4749 // definition of the member will be created in the record context. DWARF
4750 // doesn't seem to have a nice way to describe this in a form that consumers
4751 // are likely to understand, so fake the "normal" situation of a definition
4752 // outside the class by putting it in the global scope.
4753 if (DC->isRecord())
4754 DC = CGM.getContext().getTranslationUnitDecl();
4755
4756 llvm::DIScope *Mod = getParentModuleOrNull(VD);
4757 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
4758}
4759
4760llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
4761 bool Stub) {
4762 llvm::DINodeArray TParamsArray;
4763 StringRef Name, LinkageName;
4764 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4765 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
4766 SourceLocation Loc = GD.getDecl()->getLocation();
4767 llvm::DIFile *Unit = getOrCreateFile(Loc);
4768 llvm::DIScope *DContext = Unit;
4769 unsigned Line = getLineNumber(Loc);
4770 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
4771 Flags);
4772 auto *FD = cast<FunctionDecl>(GD.getDecl());
4773
4774 // Build function type.
4775 SmallVector<QualType, 16> ArgTypes;
4776 for (const ParmVarDecl *Parm : FD->parameters())
4777 ArgTypes.push_back(Parm->getType());
4778
4779 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
4780 QualType FnType = CGM.getContext().getFunctionType(
4781 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
4782 if (!FD->isExternallyVisible())
4783 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
4784 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
4785 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
4786
4787 if (Stub) {
4788 Flags |= getCallSiteRelatedAttrs();
4789 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
4790 return DBuilder.createFunction(
4791 DContext, Name, LinkageName, Unit, Line,
4792 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4793 TParamsArray.get(), getFunctionDeclaration(FD), /*ThrownTypes*/ nullptr,
4794 /*Annotations*/ nullptr, /*TargetFuncName*/ "",
4795 CGM.getCodeGenOpts().DebugKeyInstructions);
4796 }
4797
4798 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
4799 DContext, Name, LinkageName, Unit, Line,
4800 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
4801 TParamsArray.get(), getFunctionDeclaration(FD));
4802 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
4803 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
4804 std::make_tuple(CanonDecl),
4805 std::make_tuple(SP));
4806 return SP;
4807}
4808
4809llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
4810 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
4811}
4812
4813llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
4814 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
4815}
4816
4817llvm::DIGlobalVariable *
4818CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
4819 QualType T;
4820 StringRef Name, LinkageName;
4821 SourceLocation Loc = VD->getLocation();
4822 llvm::DIFile *Unit = getOrCreateFile(Loc);
4823 llvm::DIScope *DContext = Unit;
4824 unsigned Line = getLineNumber(Loc);
4825 llvm::MDTuple *TemplateParameters = nullptr;
4826
4827 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
4828 DContext);
4829 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4830 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
4831 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
4832 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
4833 FwdDeclReplaceMap.emplace_back(
4834 std::piecewise_construct,
4835 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
4836 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
4837 return GV;
4838}
4839
4840llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
4841 // We only need a declaration (not a definition) of the type - so use whatever
4842 // we would otherwise do to get a type for a pointee. (forward declarations in
4843 // limited debug info, full definitions (if the type definition is available)
4844 // in unlimited debug info)
4845 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
4846 QualType Ty = CGM.getContext().getTypeDeclType(TD);
4847 return getOrCreateType(Ty, getOrCreateFile(TD->getLocation()));
4848 }
4849 auto I = DeclCache.find(D->getCanonicalDecl());
4850
4851 if (I != DeclCache.end()) {
4852 auto N = I->second;
4853 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
4854 return GVE->getVariable();
4855 return cast<llvm::DINode>(N);
4856 }
4857
4858 // Search imported declaration cache if it is already defined
4859 // as imported declaration.
4860 auto IE = ImportedDeclCache.find(D->getCanonicalDecl());
4861
4862 if (IE != ImportedDeclCache.end()) {
4863 auto N = IE->second;
4864 if (auto *GVE = dyn_cast_or_null<llvm::DIImportedEntity>(N))
4865 return cast<llvm::DINode>(GVE);
4866 return dyn_cast_or_null<llvm::DINode>(N);
4867 }
4868
4869 // No definition for now. Emit a forward definition that might be
4870 // merged with a potential upcoming definition.
4871 if (const auto *FD = dyn_cast<FunctionDecl>(D))
4872 return getFunctionForwardDeclaration(FD);
4873 else if (const auto *VD = dyn_cast<VarDecl>(D))
4874 return getGlobalVariableForwardDeclaration(VD);
4875
4876 return nullptr;
4877}
4878
4879llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
4880 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4881 return nullptr;
4882
4883 const auto *FD = dyn_cast<FunctionDecl>(D);
4884 if (!FD)
4885 return nullptr;
4886
4887 // Setup context.
4888 auto *S = getDeclContextDescriptor(D);
4889
4890 auto MI = SPCache.find(FD->getCanonicalDecl());
4891 if (MI == SPCache.end()) {
4892 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
4893 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
4895 }
4896 }
4897 if (MI != SPCache.end()) {
4898 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4899 if (SP && !SP->isDefinition())
4900 return SP;
4901 }
4902
4903 for (auto *NextFD : FD->redecls()) {
4904 auto MI = SPCache.find(NextFD->getCanonicalDecl());
4905 if (MI != SPCache.end()) {
4906 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
4907 if (SP && !SP->isDefinition())
4908 return SP;
4909 }
4910 }
4911 return nullptr;
4912}
4913
4914llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
4915 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
4916 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
4917 if (!D || DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
4918 return nullptr;
4919
4920 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
4921 if (!OMD)
4922 return nullptr;
4923
4924 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
4925 return nullptr;
4926
4927 if (OMD->isDirectMethod())
4928 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
4929
4930 // Starting with DWARF V5 method declarations are emitted as children of
4931 // the interface type.
4932 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
4933 if (!ID)
4934 ID = OMD->getClassInterface();
4935 if (!ID)
4936 return nullptr;
4937 QualType QTy(ID->getTypeForDecl(), 0);
4938 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4939 if (It == TypeCache.end())
4940 return nullptr;
4941 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
4942 llvm::DISubprogram *FD = DBuilder.createFunction(
4943 InterfaceType, getObjCMethodName(OMD), StringRef(),
4944 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
4945 DBuilder.finalizeSubprogram(FD);
4946 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
4947 return FD;
4948}
4949
4950// getOrCreateFunctionType - Construct type. If it is a c++ method, include
4951// implicit parameter "this".
4952llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
4953 QualType FnType,
4954 llvm::DIFile *F) {
4955 // In CodeView, we emit the function types in line tables only because the
4956 // only way to distinguish between functions is by display name and type.
4957 if (!D || (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly &&
4958 !CGM.getCodeGenOpts().EmitCodeView))
4959 // Create fake but valid subroutine type. Otherwise -verify would fail, and
4960 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
4961 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray({}));
4962
4963 if (const auto *Method = dyn_cast<CXXDestructorDecl>(D)) {
4964 // Read method type from 'FnType' because 'D.getType()' does not cover
4965 // implicit arguments for destructors.
4966 return getOrCreateMethodTypeForDestructor(Method, F, FnType);
4967 }
4968
4969 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
4970 return getOrCreateMethodType(Method, F);
4971
4972 const auto *FTy = FnType->getAs<FunctionType>();
4973 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
4974
4975 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
4976 // Add "self" and "_cmd"
4977 SmallVector<llvm::Metadata *, 16> Elts;
4978
4979 // First element is always return type. For 'void' functions it is NULL.
4980 QualType ResultTy = OMethod->getReturnType();
4981
4982 // Replace the instancetype keyword with the actual type.
4983 if (ResultTy == CGM.getContext().getObjCInstanceType())
4984 ResultTy = CGM.getContext().getPointerType(
4985 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
4986
4987 Elts.push_back(getOrCreateType(ResultTy, F));
4988 // "self" pointer is always first argument.
4989 QualType SelfDeclTy;
4990 if (auto *SelfDecl = OMethod->getSelfDecl())
4991 SelfDeclTy = SelfDecl->getType();
4992 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
4993 if (FPT->getNumParams() > 1)
4994 SelfDeclTy = FPT->getParamType(0);
4995 if (!SelfDeclTy.isNull())
4996 Elts.push_back(
4997 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
4998 // "_cmd" pointer is always second argument.
4999 Elts.push_back(DBuilder.createArtificialType(
5000 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
5001 // Get rest of the arguments.
5002 for (const auto *PI : OMethod->parameters())
5003 Elts.push_back(getOrCreateType(PI->getType(), F));
5004 // Variadic methods need a special marker at the end of the type list.
5005 if (OMethod->isVariadic())
5006 Elts.push_back(DBuilder.createUnspecifiedParameter());
5007
5008 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
5009 return DBuilder.createSubroutineType(
5010 EltTypeArray, llvm::DINode::FlagZero,
5011 getDwarfCC(CC, CGM.getTarget().getTriple()));
5012 }
5013
5014 // Handle variadic function types; they need an additional
5015 // unspecified parameter.
5016 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5017 if (FD->isVariadic()) {
5018 SmallVector<llvm::Metadata *, 16> EltTys;
5019 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
5020 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
5021 for (QualType ParamType : FPT->param_types())
5022 EltTys.push_back(getOrCreateType(ParamType, F));
5023 EltTys.push_back(DBuilder.createUnspecifiedParameter());
5024 llvm::DITypeArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
5025 return DBuilder.createSubroutineType(
5026 EltTypeArray, llvm::DINode::FlagZero,
5027 getDwarfCC(CC, CGM.getTarget().getTriple()));
5028 }
5029
5030 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
5031}
5032
5033QualType
5037 if (FD)
5038 if (const auto *SrcFnTy = FD->getType()->getAs<FunctionType>())
5039 CC = SrcFnTy->getCallConv();
5041 for (const VarDecl *VD : Args)
5042 ArgTypes.push_back(VD->getType());
5043 return CGM.getContext().getFunctionType(RetTy, ArgTypes,
5045}
5046
5048 SourceLocation ScopeLoc, QualType FnType,
5049 llvm::Function *Fn, bool CurFuncIsThunk) {
5050 StringRef Name;
5051 StringRef LinkageName;
5052
5053 FnBeginRegionCount.push_back(LexicalBlockStack.size());
5054
5055 const Decl *D = GD.getDecl();
5056 bool HasDecl = (D != nullptr);
5057
5058 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5059 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
5060 llvm::DIFile *Unit = getOrCreateFile(Loc);
5061 llvm::DIScope *FDContext = Unit;
5062 llvm::DINodeArray TParamsArray;
5063 bool KeyInstructions = CGM.getCodeGenOpts().DebugKeyInstructions;
5064 if (!HasDecl) {
5065 // Use llvm function name.
5066 LinkageName = Fn->getName();
5067 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5068 // If there is a subprogram for this function available then use it.
5069 auto FI = SPCache.find(FD->getCanonicalDecl());
5070 if (FI != SPCache.end()) {
5071 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
5072 if (SP && SP->isDefinition()) {
5073 LexicalBlockStack.emplace_back(SP);
5074 RegionMap[D].reset(SP);
5075 return;
5076 }
5077 }
5078 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
5079 TParamsArray, Flags);
5080 // Disable KIs if this is a coroutine.
5081 KeyInstructions =
5082 KeyInstructions && !isa_and_present<CoroutineBodyStmt>(FD->getBody());
5083 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
5084 Name = getObjCMethodName(OMD);
5085 Flags |= llvm::DINode::FlagPrototyped;
5086 } else if (isa<VarDecl>(D) &&
5088 // This is a global initializer or atexit destructor for a global variable.
5089 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
5090 Fn);
5091 if (Name != Fn->getName())
5092 LinkageName = Fn->getName();
5093 } else {
5094 Name = Fn->getName();
5095
5096 if (isa<BlockDecl>(D))
5097 LinkageName = Name;
5098
5099 Flags |= llvm::DINode::FlagPrototyped;
5100 }
5101 Name.consume_front("\01");
5102
5103 assert((!D || !isa<VarDecl>(D) ||
5105 "Unexpected DynamicInitKind !");
5106
5107 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>() ||
5109 Flags |= llvm::DINode::FlagArtificial;
5110 // Artificial functions should not silently reuse CurLoc.
5111 clearCurLoc();
5112 }
5113
5114 if (CurFuncIsThunk)
5115 Flags |= llvm::DINode::FlagThunk;
5116
5117 if (Fn->hasLocalLinkage())
5118 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
5119 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
5120 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
5121
5122 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
5123 llvm::DISubprogram::DISPFlags SPFlagsForDef =
5124 SPFlags | llvm::DISubprogram::SPFlagDefinition;
5125
5126 const unsigned LineNo = getLineNumber(Loc.isValid() ? Loc : CurLoc);
5127 unsigned ScopeLine = getLineNumber(ScopeLoc);
5128 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
5129 llvm::DISubprogram *Decl = nullptr;
5130 llvm::DINodeArray Annotations = nullptr;
5131 if (D) {
5133 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
5134 : getFunctionDeclaration(D);
5135 Annotations = CollectBTFDeclTagAnnotations(D);
5136 }
5137
5138 // FIXME: The function declaration we're constructing here is mostly reusing
5139 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
5140 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
5141 // all subprograms instead of the actual context since subprogram definitions
5142 // are emitted as CU level entities by the backend.
5143 llvm::DISubprogram *SP = DBuilder.createFunction(
5144 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
5145 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl, nullptr,
5146 Annotations, "", KeyInstructions);
5147 Fn->setSubprogram(SP);
5148
5149 // We might get here with a VarDecl in the case we're generating
5150 // code for the initialization of globals. Do not record these decls
5151 // as they will overwrite the actual VarDecl Decl in the cache.
5152 if (HasDecl && isa<FunctionDecl>(D))
5153 DeclCache[D->getCanonicalDecl()].reset(SP);
5154
5155 // Push the function onto the lexical block stack.
5156 LexicalBlockStack.emplace_back(SP);
5157
5158 if (HasDecl)
5159 RegionMap[D].reset(SP);
5160}
5161
5163 QualType FnType, llvm::Function *Fn) {
5164 StringRef Name;
5165 StringRef LinkageName;
5166
5167 const Decl *D = GD.getDecl();
5168 if (!D)
5169 return;
5170
5171 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
5172 return GetName(D, true);
5173 });
5174
5175 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5176 llvm::DIFile *Unit = getOrCreateFile(Loc);
5177 bool IsDeclForCallSite = Fn ? true : false;
5178 llvm::DIScope *FDContext =
5179 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
5180 llvm::DINodeArray TParamsArray;
5181 if (isa<FunctionDecl>(D)) {
5182 // If there is a DISubprogram for this function available then use it.
5183 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
5184 TParamsArray, Flags);
5185 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
5186 Name = getObjCMethodName(OMD);
5187 Flags |= llvm::DINode::FlagPrototyped;
5188 } else {
5189 llvm_unreachable("not a function or ObjC method");
5190 }
5191 Name.consume_front("\01");
5192
5193 if (D->isImplicit()) {
5194 Flags |= llvm::DINode::FlagArtificial;
5195 // Artificial functions without a location should not silently reuse CurLoc.
5196 if (Loc.isInvalid())
5197 clearCurLoc();
5198 }
5199 unsigned LineNo = getLineNumber(Loc);
5200 unsigned ScopeLine = 0;
5201 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
5202 if (CGM.getCodeGenOpts().OptimizationLevel != 0)
5203 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
5204
5205 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
5206 llvm::DISubroutineType *STy = getOrCreateFunctionType(D, FnType, Unit);
5207 // Key Instructions: Don't set flag on declarations.
5208 assert(~SPFlags & llvm::DISubprogram::SPFlagDefinition);
5209 llvm::DISubprogram *SP = DBuilder.createFunction(
5210 FDContext, Name, LinkageName, Unit, LineNo, STy, ScopeLine, Flags,
5211 SPFlags, TParamsArray.get(), nullptr, nullptr, Annotations,
5212 /*TargetFunctionName*/ "", /*UseKeyInstructions*/ false);
5213
5214 // Preserve btf_decl_tag attributes for parameters of extern functions
5215 // for BPF target. The parameters created in this loop are attached as
5216 // DISubprogram's retainedNodes in the DIBuilder::finalize() call.
5217 if (IsDeclForCallSite && CGM.getTarget().getTriple().isBPF()) {
5218 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
5219 llvm::DITypeArray ParamTypes = STy->getTypeArray();
5220 unsigned ArgNo = 1;
5221 for (ParmVarDecl *PD : FD->parameters()) {
5222 llvm::DINodeArray ParamAnnotations = CollectBTFDeclTagAnnotations(PD);
5223 DBuilder.createParameterVariable(
5224 SP, PD->getName(), ArgNo, Unit, LineNo, ParamTypes[ArgNo], true,
5225 llvm::DINode::FlagZero, ParamAnnotations);
5226 ++ArgNo;
5227 }
5228 }
5229 }
5230
5231 if (IsDeclForCallSite)
5232 Fn->setSubprogram(SP);
5233}
5234
5236 llvm::CallBase *CI) {
5237 if (!shouldGenerateVirtualCallSite())
5238 return;
5239
5240 if (!FD)
5241 return;
5242
5243 assert(CI && "Invalid Call Instruction.");
5244 if (!CI->isIndirectCall())
5245 return;
5246
5247 // Always get the method declaration.
5248 if (llvm::DISubprogram *MD = getFunctionDeclaration(FD))
5249 CI->setMetadata(llvm::LLVMContext::MD_call_target, MD);
5250}
5251
5252void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
5253 QualType CalleeType,
5254 GlobalDecl CalleeGlobalDecl) {
5255 if (!CallOrInvoke)
5256 return;
5257 auto *Func = dyn_cast<llvm::Function>(CallOrInvoke->getCalledOperand());
5258 if (!Func)
5259 return;
5260 if (Func->getSubprogram())
5261 return;
5262 // If the function has a definition, it either already has a
5263 // subprogram or it is a nodebug function.
5264 if (!Func->isDeclaration())
5265 return;
5266
5267 const FunctionDecl *CalleeDecl =
5268 cast<FunctionDecl>(CalleeGlobalDecl.getDecl());
5269
5270 // Do not emit a declaration subprogram for a function with nodebug
5271 // attribute, or if call site info isn't required. The attribute
5272 // could be on a later redeclaration than the one the call resolves to.
5273 if (CalleeDecl->getMostRecentDecl()->hasAttr<NoDebugAttr>() ||
5274 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
5275 return;
5276
5277 // If there is no DISubprogram attached to the function being called,
5278 // create the one describing the function in order to have complete
5279 // call site debug info.
5280 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined()) {
5281 // If this is a CXX method, use getFunctionDeclaration which checks the
5282 // SPCache first otherwise calls CreateCXXMemberFunction. This ensures that
5283 // debug info generated for a declaration here is consistent with that
5284 // generated for methods via other means.
5285 if (isa<CXXMethodDecl>(CalleeDecl->getCanonicalDecl())) {
5286 if (auto *SP = getFunctionDeclaration(CalleeDecl))
5287 Func->setSubprogram(SP);
5288 } else {
5289 EmitFunctionDecl(CalleeGlobalDecl, CalleeDecl->getLocation(), CalleeType,
5290 Func);
5291 }
5292 }
5293}
5294
5296 const auto *FD = cast<FunctionDecl>(GD.getDecl());
5297 // If there is a subprogram for this function available then use it.
5298 auto FI = SPCache.find(FD->getCanonicalDecl());
5299 llvm::DISubprogram *SP = nullptr;
5300 if (FI != SPCache.end())
5301 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
5302 if (!SP || !SP->isDefinition())
5303 SP = getFunctionStub(GD);
5304 FnBeginRegionCount.push_back(LexicalBlockStack.size());
5305 LexicalBlockStack.emplace_back(SP);
5306 setInlinedAt(Builder.getCurrentDebugLocation());
5307 EmitLocation(Builder, FD->getLocation());
5308}
5309
5311 assert(CurInlinedAt && "unbalanced inline scope stack");
5312 EmitFunctionEnd(Builder, nullptr);
5313 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
5314}
5315
5317 // Update our current location
5318 setLocation(Loc);
5319
5320 if (CurLoc.isInvalid() ||
5321 (CGM.getCodeGenOpts().DebugInfoMacroExpansionLoc && CurLoc.isMacroID()) ||
5322 LexicalBlockStack.empty())
5323 return;
5324
5325 llvm::MDNode *Scope = LexicalBlockStack.back();
5326 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
5327 CGM.getLLVMContext(), CurLocLine, CurLocColumn, Scope, CurInlinedAt));
5328}
5329
5330void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
5331 llvm::MDNode *Back = nullptr;
5332 if (!LexicalBlockStack.empty())
5333 Back = LexicalBlockStack.back().get();
5334 // A #line 0 macro carried no line information but still take column
5335 // information. This will finally be rejected by the lexer but is legal.
5336 unsigned Line = getLineNumber(CurLoc);
5337 unsigned Column = Line ? getColumnNumber(CurLoc) : 0;
5338 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
5339 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), Line, Column));
5340}
5341
5342void CGDebugInfo::AppendAddressSpaceXDeref(
5343 unsigned AddressSpace, SmallVectorImpl<uint64_t> &Expr) const {
5344 std::optional<unsigned> DWARFAddressSpace =
5345 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
5346 if (!DWARFAddressSpace)
5347 return;
5348
5349 Expr.push_back(llvm::dwarf::DW_OP_constu);
5350 Expr.push_back(*DWARFAddressSpace);
5351 Expr.push_back(llvm::dwarf::DW_OP_swap);
5352 Expr.push_back(llvm::dwarf::DW_OP_xderef);
5353}
5354
5356 SourceLocation Loc) {
5357 // Set our current location.
5358 setLocation(Loc);
5359
5360 // Emit a line table change for the current location inside the new scope.
5361 Builder.SetCurrentDebugLocation(llvm::DILocation::get(
5362 CGM.getLLVMContext(), getLineNumber(Loc), getColumnNumber(Loc),
5363 LexicalBlockStack.back(), CurInlinedAt));
5364
5365 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5366 return;
5367
5368 // Create a new lexical block and push it on the stack.
5369 CreateLexicalBlock(Loc);
5370}
5371
5373 SourceLocation Loc) {
5374 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5375
5376 // Provide an entry in the line table for the end of the block.
5377 EmitLocation(Builder, Loc);
5378
5379 if (DebugKind <= llvm::codegenoptions::DebugLineTablesOnly)
5380 return;
5381
5382 LexicalBlockStack.pop_back();
5383}
5384
5385void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
5386 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5387 unsigned RCount = FnBeginRegionCount.back();
5388 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
5389
5390 // Pop all regions for this function.
5391 while (LexicalBlockStack.size() != RCount) {
5392 // Provide an entry in the line table for the end of the block.
5393 EmitLocation(Builder, CurLoc);
5394 LexicalBlockStack.pop_back();
5395 }
5396 FnBeginRegionCount.pop_back();
5397
5398 if (Fn && Fn->getSubprogram())
5399 DBuilder.finalizeSubprogram(Fn->getSubprogram());
5400}
5401
5402CGDebugInfo::BlockByRefType
5403CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
5404 uint64_t *XOffset) {
5406 QualType FType;
5407 uint64_t FieldSize, FieldOffset;
5408 uint32_t FieldAlign;
5409
5410 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5411 QualType Type = VD->getType();
5412
5413 FieldOffset = 0;
5414 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5415 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
5416 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
5417 FType = CGM.getContext().IntTy;
5418 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
5419 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
5420
5421 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
5422 if (HasCopyAndDispose) {
5423 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5424 EltTys.push_back(
5425 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
5426 EltTys.push_back(
5427 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
5428 }
5429 bool HasByrefExtendedLayout;
5430 Qualifiers::ObjCLifetime Lifetime;
5431 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
5432 HasByrefExtendedLayout) &&
5433 HasByrefExtendedLayout) {
5434 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
5435 EltTys.push_back(
5436 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
5437 }
5438
5439 CharUnits Align = CGM.getContext().getDeclAlign(VD);
5440 if (Align > CGM.getContext().toCharUnitsFromBits(
5442 CharUnits FieldOffsetInBytes =
5443 CGM.getContext().toCharUnitsFromBits(FieldOffset);
5444 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
5445 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
5446
5447 if (NumPaddingBytes.isPositive()) {
5448 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
5449 FType = CGM.getContext().getConstantArrayType(
5450 CGM.getContext().CharTy, pad, nullptr, ArraySizeModifier::Normal, 0);
5451 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
5452 }
5453 }
5454
5455 FType = Type;
5456 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
5457 FieldSize = CGM.getContext().getTypeSize(FType);
5458 FieldAlign = CGM.getContext().toBits(Align);
5459
5460 *XOffset = FieldOffset;
5461 llvm::DIType *FieldTy = DBuilder.createMemberType(
5462 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
5463 llvm::DINode::FlagZero, WrappedTy);
5464 EltTys.push_back(FieldTy);
5465 FieldOffset += FieldSize;
5466
5467 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
5468 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
5469 llvm::DINode::FlagZero, nullptr, Elements),
5470 WrappedTy};
5471}
5472
5473llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
5474 llvm::Value *Storage,
5475 std::optional<unsigned> ArgNo,
5476 CGBuilderTy &Builder,
5477 const bool UsePointerValue) {
5478 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5479 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5480 if (VD->hasAttr<NoDebugAttr>())
5481 return nullptr;
5482
5483 const bool VarIsArtificial = IsArtificial(VD);
5484
5485 llvm::DIFile *Unit = nullptr;
5486 if (!VarIsArtificial)
5487 Unit = getOrCreateFile(VD->getLocation());
5488 llvm::DIType *Ty;
5489 uint64_t XOffset = 0;
5490 if (VD->hasAttr<BlocksAttr>())
5491 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5492 else
5493 Ty = getOrCreateType(VD->getType(), Unit);
5494
5495 // If there is no debug info for this type then do not emit debug info
5496 // for this variable.
5497 if (!Ty)
5498 return nullptr;
5499
5500 // Get location information.
5501 unsigned Line = 0;
5502 unsigned Column = 0;
5503 if (!VarIsArtificial) {
5504 Line = getLineNumber(VD->getLocation());
5505 Column = getColumnNumber(VD->getLocation());
5506 }
5507 SmallVector<uint64_t, 13> Expr;
5508 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
5509
5510 // While synthesized Objective-C property setters are "artificial" (i.e., they
5511 // are not spelled out in source), we want to pretend they are just like a
5512 // regular non-compiler generated method. Hence, don't mark explicitly passed
5513 // parameters of such methods as artificial.
5514 if (VarIsArtificial && !IsObjCSynthesizedPropertyExplicitParameter(VD))
5515 Flags |= llvm::DINode::FlagArtificial;
5516
5517 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5518
5519 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(VD->getType());
5520 AppendAddressSpaceXDeref(AddressSpace, Expr);
5521
5522 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
5523 // object pointer flag.
5524 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
5525 if (IPD->getParameterKind() == ImplicitParamKind::CXXThis ||
5526 IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5527 Flags |= llvm::DINode::FlagObjectPointer;
5528 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
5529 if (PVD->isExplicitObjectParameter())
5530 Flags |= llvm::DINode::FlagObjectPointer;
5531 }
5532
5533 // Note: Older versions of clang used to emit byval references with an extra
5534 // DW_OP_deref, because they referenced the IR arg directly instead of
5535 // referencing an alloca. Newer versions of LLVM don't treat allocas
5536 // differently from other function arguments when used in a dbg.declare.
5537 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5538 StringRef Name = VD->getName();
5539 if (!Name.empty()) {
5540 // __block vars are stored on the heap if they are captured by a block that
5541 // can escape the local scope.
5542 if (VD->isEscapingByref()) {
5543 // Here, we need an offset *into* the alloca.
5544 CharUnits offset = CharUnits::fromQuantity(32);
5545 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5546 // offset of __forwarding field
5547 offset = CGM.getContext().toCharUnitsFromBits(
5548 CGM.getTarget().getPointerWidth(LangAS::Default));
5549 Expr.push_back(offset.getQuantity());
5550 Expr.push_back(llvm::dwarf::DW_OP_deref);
5551 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5552 // offset of x field
5553 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5554 Expr.push_back(offset.getQuantity());
5555 }
5556 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
5557 // If VD is an anonymous union then Storage represents value for
5558 // all union fields.
5559 const RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
5560 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
5561 // GDB has trouble finding local variables in anonymous unions, so we emit
5562 // artificial local variables for each of the members.
5563 //
5564 // FIXME: Remove this code as soon as GDB supports this.
5565 // The debug info verifier in LLVM operates based on the assumption that a
5566 // variable has the same size as its storage and we had to disable the
5567 // check for artificial variables.
5568 for (const auto *Field : RD->fields()) {
5569 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
5570 StringRef FieldName = Field->getName();
5571
5572 // Ignore unnamed fields. Do not ignore unnamed records.
5573 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
5574 continue;
5575
5576 // Use VarDecl's Tag, Scope and Line number.
5577 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
5578 auto *D = DBuilder.createAutoVariable(
5579 Scope, FieldName, Unit, Line, FieldTy,
5580 CGM.getCodeGenOpts().OptimizationLevel != 0,
5581 Flags | llvm::DINode::FlagArtificial, FieldAlign);
5582
5583 // Insert an llvm.dbg.declare into the current block.
5584 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5585 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5586 Column, Scope,
5587 CurInlinedAt),
5588 Builder.GetInsertBlock());
5589 }
5590 }
5591 }
5592
5593 // Clang stores the sret pointer provided by the caller in a static alloca.
5594 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5595 // the address of the variable.
5596 if (UsePointerValue) {
5597 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5598 "Debug info already contains DW_OP_deref.");
5599 Expr.push_back(llvm::dwarf::DW_OP_deref);
5600 }
5601
5602 // Create the descriptor for the variable.
5603 llvm::DILocalVariable *D = nullptr;
5604 if (ArgNo) {
5605 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(VD);
5606 D = DBuilder.createParameterVariable(
5607 Scope, Name, *ArgNo, Unit, Line, Ty,
5608 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Annotations);
5609 } else {
5610 // For normal local variable, we will try to find out whether 'VD' is the
5611 // copy parameter of coroutine.
5612 // If yes, we are going to use DIVariable of the origin parameter instead
5613 // of creating the new one.
5614 // If no, it might be a normal alloc, we just create a new one for it.
5615
5616 // Check whether the VD is move parameters.
5617 auto RemapCoroArgToLocalVar = [&]() -> llvm::DILocalVariable * {
5618 // The scope of parameter and move-parameter should be distinct
5619 // DISubprogram.
5620 if (!isa<llvm::DISubprogram>(Scope) || !Scope->isDistinct())
5621 return nullptr;
5622
5623 auto Iter = llvm::find_if(CoroutineParameterMappings, [&](auto &Pair) {
5624 Stmt *StmtPtr = const_cast<Stmt *>(Pair.second);
5625 if (DeclStmt *DeclStmtPtr = dyn_cast<DeclStmt>(StmtPtr)) {
5626 DeclGroupRef DeclGroup = DeclStmtPtr->getDeclGroup();
5627 Decl *Decl = DeclGroup.getSingleDecl();
5628 if (VD == dyn_cast_or_null<VarDecl>(Decl))
5629 return true;
5630 }
5631 return false;
5632 });
5633
5634 if (Iter != CoroutineParameterMappings.end()) {
5635 ParmVarDecl *PD = const_cast<ParmVarDecl *>(Iter->first);
5636 auto Iter2 = llvm::find_if(ParamDbgMappings, [&](auto &DbgPair) {
5637 return DbgPair.first == PD && DbgPair.second->getScope() == Scope;
5638 });
5639 if (Iter2 != ParamDbgMappings.end())
5640 return const_cast<llvm::DILocalVariable *>(Iter2->second);
5641 }
5642 return nullptr;
5643 };
5644
5645 // If we couldn't find a move param DIVariable, create a new one.
5646 D = RemapCoroArgToLocalVar();
5647 // Or we will create a new DIVariable for this Decl if D dose not exists.
5648 if (!D)
5649 D = DBuilder.createAutoVariable(
5650 Scope, Name, Unit, Line, Ty,
5651 CGM.getCodeGenOpts().OptimizationLevel != 0, Flags, Align);
5652 }
5653 // Insert an llvm.dbg.declare into the current block.
5654 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5655 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5656 Column, Scope, CurInlinedAt),
5657 Builder.GetInsertBlock());
5658
5659 return D;
5660}
5661
5662llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const BindingDecl *BD,
5663 llvm::Value *Storage,
5664 std::optional<unsigned> ArgNo,
5665 CGBuilderTy &Builder,
5666 const bool UsePointerValue) {
5667 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5668 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5669 if (BD->hasAttr<NoDebugAttr>())
5670 return nullptr;
5671
5672 // Skip the tuple like case, we don't handle that here
5673 if (isa<DeclRefExpr>(BD->getBinding()))
5674 return nullptr;
5675
5676 llvm::DIFile *Unit = getOrCreateFile(BD->getLocation());
5677 llvm::DIType *Ty = getOrCreateType(BD->getType(), Unit);
5678
5679 // If there is no debug info for this type then do not emit debug info
5680 // for this variable.
5681 if (!Ty)
5682 return nullptr;
5683
5684 auto Align = getDeclAlignIfRequired(BD, CGM.getContext());
5685 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(BD->getType());
5686
5687 SmallVector<uint64_t, 3> Expr;
5688 AppendAddressSpaceXDeref(AddressSpace, Expr);
5689
5690 // Clang stores the sret pointer provided by the caller in a static alloca.
5691 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
5692 // the address of the variable.
5693 if (UsePointerValue) {
5694 assert(!llvm::is_contained(Expr, llvm::dwarf::DW_OP_deref) &&
5695 "Debug info already contains DW_OP_deref.");
5696 Expr.push_back(llvm::dwarf::DW_OP_deref);
5697 }
5698
5699 unsigned Line = getLineNumber(BD->getLocation());
5700 unsigned Column = getColumnNumber(BD->getLocation());
5701 StringRef Name = BD->getName();
5702 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5703 // Create the descriptor for the variable.
5704 llvm::DILocalVariable *D = DBuilder.createAutoVariable(
5705 Scope, Name, Unit, Line, Ty, CGM.getCodeGenOpts().OptimizationLevel != 0,
5706 llvm::DINode::FlagZero, Align);
5707
5708 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BD->getBinding())) {
5709 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
5710 const unsigned fieldIndex = FD->getFieldIndex();
5711 const clang::CXXRecordDecl *parent =
5712 (const CXXRecordDecl *)FD->getParent();
5713 const ASTRecordLayout &layout =
5714 CGM.getContext().getASTRecordLayout(parent);
5715 const uint64_t fieldOffset = layout.getFieldOffset(fieldIndex);
5716 if (FD->isBitField()) {
5717 const CGRecordLayout &RL =
5718 CGM.getTypes().getCGRecordLayout(FD->getParent());
5719 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD);
5720 // Use DW_OP_plus_uconst to adjust to the start of the bitfield
5721 // storage.
5722 if (!Info.StorageOffset.isZero()) {
5723 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5724 Expr.push_back(Info.StorageOffset.getQuantity());
5725 }
5726 // Use LLVM_extract_bits to extract the appropriate bits from this
5727 // bitfield.
5728 Expr.push_back(Info.IsSigned
5729 ? llvm::dwarf::DW_OP_LLVM_extract_bits_sext
5730 : llvm::dwarf::DW_OP_LLVM_extract_bits_zext);
5731 Expr.push_back(Info.Offset);
5732 // If we have an oversized bitfield then the value won't be more than
5733 // the size of the type.
5734 const uint64_t TypeSize = CGM.getContext().getTypeSize(BD->getType());
5735 Expr.push_back(std::min((uint64_t)Info.Size, TypeSize));
5736 } else if (fieldOffset != 0) {
5737 assert(fieldOffset % CGM.getContext().getCharWidth() == 0 &&
5738 "Unexpected non-bitfield with non-byte-aligned offset");
5739 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5740 Expr.push_back(
5741 CGM.getContext().toCharUnitsFromBits(fieldOffset).getQuantity());
5742 }
5743 }
5744 } else if (const ArraySubscriptExpr *ASE =
5745 dyn_cast<ArraySubscriptExpr>(BD->getBinding())) {
5746 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ASE->getIdx())) {
5747 const uint64_t value = IL->getValue().getZExtValue();
5748 const uint64_t typeSize = CGM.getContext().getTypeSize(BD->getType());
5749
5750 if (value != 0) {
5751 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5752 Expr.push_back(CGM.getContext()
5753 .toCharUnitsFromBits(value * typeSize)
5754 .getQuantity());
5755 }
5756 }
5757 }
5758
5759 // Insert an llvm.dbg.declare into the current block.
5760 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
5761 llvm::DILocation::get(CGM.getLLVMContext(), Line,
5762 Column, Scope, CurInlinedAt),
5763 Builder.GetInsertBlock());
5764
5765 return D;
5766}
5767
5768llvm::DILocalVariable *
5769CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
5770 CGBuilderTy &Builder,
5771 const bool UsePointerValue) {
5772 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5773
5774 if (auto *DD = dyn_cast<DecompositionDecl>(VD)) {
5775 for (BindingDecl *B : DD->flat_bindings())
5776 EmitDeclare(B, Storage, std::nullopt, Builder,
5777 VD->getType()->isReferenceType());
5778 // Don't emit an llvm.dbg.declare for the composite storage as it doesn't
5779 // correspond to a user variable.
5780 return nullptr;
5781 }
5782
5783 return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
5784}
5785
5787 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5788 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5789
5790 if (D->hasAttr<NoDebugAttr>())
5791 return;
5792
5793 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
5794 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
5795
5796 // Get location information.
5797 unsigned Line = getLineNumber(D->getLocation());
5798 unsigned Column = getColumnNumber(D->getLocation());
5799
5800 StringRef Name = D->getName();
5801
5802 // Create the descriptor for the label.
5803 auto *L = DBuilder.createLabel(Scope, Name, Unit, Line, Column,
5804 /*IsArtificial=*/false,
5805 /*CoroSuspendIdx=*/std::nullopt,
5806 CGM.getCodeGenOpts().OptimizationLevel != 0);
5807
5808 // Insert an llvm.dbg.label into the current block.
5809 DBuilder.insertLabel(L,
5810 llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5811 Scope, CurInlinedAt),
5812 Builder.GetInsertBlock()->end());
5813}
5814
5815llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
5816 llvm::DIType *Ty) {
5817 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
5818 if (CachedTy)
5819 Ty = CachedTy;
5820 return DBuilder.createObjectPointerType(Ty, /*Implicit=*/true);
5821}
5822
5824 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
5825 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
5826 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5827 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
5828
5829 if (Builder.GetInsertBlock() == nullptr)
5830 return;
5831 if (VD->hasAttr<NoDebugAttr>())
5832 return;
5833
5834 bool isByRef = VD->hasAttr<BlocksAttr>();
5835
5836 uint64_t XOffset = 0;
5837 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
5838 llvm::DIType *Ty;
5839 if (isByRef)
5840 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
5841 else
5842 Ty = getOrCreateType(VD->getType(), Unit);
5843
5844 // Self is passed along as an implicit non-arg variable in a
5845 // block. Mark it as the object pointer.
5846 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
5847 if (IPD->getParameterKind() == ImplicitParamKind::ObjCSelf)
5848 Ty = CreateSelfType(VD->getType(), Ty);
5849
5850 // Get location information.
5851 const unsigned Line =
5852 getLineNumber(VD->getLocation().isValid() ? VD->getLocation() : CurLoc);
5853 unsigned Column = getColumnNumber(VD->getLocation());
5854
5855 const llvm::DataLayout &target = CGM.getDataLayout();
5856
5858 target.getStructLayout(blockInfo.StructureType)
5859 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
5860
5862 addr.push_back(llvm::dwarf::DW_OP_deref);
5863 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5864 addr.push_back(offset.getQuantity());
5865 if (isByRef) {
5866 addr.push_back(llvm::dwarf::DW_OP_deref);
5867 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5868 // offset of __forwarding field
5869 offset =
5870 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
5871 addr.push_back(offset.getQuantity());
5872 addr.push_back(llvm::dwarf::DW_OP_deref);
5873 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
5874 // offset of x field
5875 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
5876 addr.push_back(offset.getQuantity());
5877 }
5878
5879 // Create the descriptor for the variable.
5880 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
5881 auto *D = DBuilder.createAutoVariable(
5882 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
5883 Line, Ty, false, llvm::DINode::FlagZero, Align);
5884
5885 // Insert an llvm.dbg.declare into the current block.
5886 auto DL = llvm::DILocation::get(CGM.getLLVMContext(), Line, Column,
5887 LexicalBlockStack.back(), CurInlinedAt);
5888 auto *Expr = DBuilder.createExpression(addr);
5889 if (InsertPoint)
5890 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint->getIterator());
5891 else
5892 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
5893}
5894
5895llvm::DILocalVariable *
5897 unsigned ArgNo, CGBuilderTy &Builder,
5898 bool UsePointerValue) {
5899 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5900 return EmitDeclare(VD, AI, ArgNo, Builder, UsePointerValue);
5901}
5902
5903namespace {
5904struct BlockLayoutChunk {
5905 uint64_t OffsetInBits;
5907};
5908bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
5909 return l.OffsetInBits < r.OffsetInBits;
5910}
5911} // namespace
5912
5913void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
5914 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
5915 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
5916 SmallVectorImpl<llvm::Metadata *> &Fields) {
5917 // Blocks in OpenCL have unique constraints which make the standard fields
5918 // redundant while requiring size and align fields for enqueue_kernel. See
5919 // initializeForBlockHeader in CGBlocks.cpp
5920 if (CGM.getLangOpts().OpenCL) {
5921 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
5922 BlockLayout.getElementOffsetInBits(0),
5923 Unit, Unit));
5924 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
5925 BlockLayout.getElementOffsetInBits(1),
5926 Unit, Unit));
5927 } else {
5928 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
5929 BlockLayout.getElementOffsetInBits(0),
5930 Unit, Unit));
5931 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
5932 BlockLayout.getElementOffsetInBits(1),
5933 Unit, Unit));
5934 Fields.push_back(
5935 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
5936 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
5937 auto *FnTy = Block.getBlockExpr()->getFunctionType();
5938 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
5939 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
5940 BlockLayout.getElementOffsetInBits(3),
5941 Unit, Unit));
5942 Fields.push_back(createFieldType(
5943 "__descriptor",
5944 Context.getPointerType(Block.NeedsCopyDispose
5946 : Context.getBlockDescriptorType()),
5947 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
5948 }
5949}
5950
5952 StringRef Name,
5953 unsigned ArgNo,
5954 llvm::AllocaInst *Alloca,
5955 CGBuilderTy &Builder) {
5956 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
5957 ASTContext &C = CGM.getContext();
5958 const BlockDecl *blockDecl = block.getBlockDecl();
5959
5960 // Collect some general information about the block's location.
5961 SourceLocation loc = blockDecl->getCaretLocation();
5962 llvm::DIFile *tunit = getOrCreateFile(loc);
5963 unsigned line = getLineNumber(loc);
5964 unsigned column = getColumnNumber(loc);
5965
5966 // Build the debug-info type for the block literal.
5967 getDeclContextDescriptor(blockDecl);
5968
5969 const llvm::StructLayout *blockLayout =
5970 CGM.getDataLayout().getStructLayout(block.StructureType);
5971
5973 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
5974 fields);
5975
5976 // We want to sort the captures by offset, not because DWARF
5977 // requires this, but because we're paranoid about debuggers.
5979
5980 // 'this' capture.
5981 if (blockDecl->capturesCXXThis()) {
5982 BlockLayoutChunk chunk;
5983 chunk.OffsetInBits =
5984 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
5985 chunk.Capture = nullptr;
5986 chunks.push_back(chunk);
5987 }
5988
5989 // Variable captures.
5990 for (const auto &capture : blockDecl->captures()) {
5991 const VarDecl *variable = capture.getVariable();
5992 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
5993
5994 // Ignore constant captures.
5995 if (captureInfo.isConstant())
5996 continue;
5997
5998 BlockLayoutChunk chunk;
5999 chunk.OffsetInBits =
6000 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
6001 chunk.Capture = &capture;
6002 chunks.push_back(chunk);
6003 }
6004
6005 // Sort by offset.
6006 llvm::array_pod_sort(chunks.begin(), chunks.end());
6007
6008 for (const BlockLayoutChunk &Chunk : chunks) {
6009 uint64_t offsetInBits = Chunk.OffsetInBits;
6010 const BlockDecl::Capture *capture = Chunk.Capture;
6011
6012 // If we have a null capture, this must be the C++ 'this' capture.
6013 if (!capture) {
6014 QualType type;
6015 if (auto *Method =
6016 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
6017 type = Method->getThisType();
6018 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
6019 type = CGM.getContext().getCanonicalTagType(RDecl);
6020 else
6021 llvm_unreachable("unexpected block declcontext");
6022
6023 fields.push_back(createFieldType("this", type, loc, AS_public,
6024 offsetInBits, tunit, tunit));
6025 continue;
6026 }
6027
6028 const VarDecl *variable = capture->getVariable();
6029 StringRef name = variable->getName();
6030
6031 llvm::DIType *fieldType;
6032 if (capture->isByRef()) {
6033 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
6034 auto Align = PtrInfo.isAlignRequired() ? PtrInfo.Align : 0;
6035 // FIXME: This recomputes the layout of the BlockByRefWrapper.
6036 uint64_t xoffset;
6037 fieldType =
6038 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
6039 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
6040 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
6041 PtrInfo.Width, Align, offsetInBits,
6042 llvm::DINode::FlagZero, fieldType);
6043 } else {
6044 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
6045 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
6046 offsetInBits, Align, tunit, tunit);
6047 }
6048 fields.push_back(fieldType);
6049 }
6050
6051 SmallString<36> typeName;
6052 llvm::raw_svector_ostream(typeName)
6053 << "__block_literal_" << CGM.getUniqueBlockCount();
6054
6055 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
6056
6057 llvm::DIType *type =
6058 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
6059 CGM.getContext().toBits(block.BlockSize), 0,
6060 llvm::DINode::FlagZero, nullptr, fieldsArray);
6061 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
6062
6063 // Get overall information about the block.
6064 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
6065 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
6066
6067 // Create the descriptor for the parameter.
6068 auto *debugVar = DBuilder.createParameterVariable(
6069 scope, Name, ArgNo, tunit, line, type,
6070 CGM.getCodeGenOpts().OptimizationLevel != 0, flags);
6071
6072 // Insert an llvm.dbg.declare into the current block.
6073 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
6074 llvm::DILocation::get(CGM.getLLVMContext(), line,
6075 column, scope, CurInlinedAt),
6076 Builder.GetInsertBlock());
6077}
6078
6079llvm::DIDerivedType *
6080CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
6081 if (!D || !D->isStaticDataMember())
6082 return nullptr;
6083
6084 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
6085 if (MI != StaticDataMemberCache.end()) {
6086 assert(MI->second && "Static data member declaration should still exist");
6087 return MI->second;
6088 }
6089
6090 // If the member wasn't found in the cache, lazily construct and add it to the
6091 // type (used when a limited form of the type is emitted).
6092 auto DC = D->getDeclContext();
6093 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
6094 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
6095}
6096
6097llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
6098 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
6099 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
6100 llvm::DIGlobalVariableExpression *GVE = nullptr;
6101
6102 for (const auto *Field : RD->fields()) {
6103 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
6104 StringRef FieldName = Field->getName();
6105
6106 // Ignore unnamed fields, but recurse into anonymous records.
6107 if (FieldName.empty()) {
6108 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
6109 GVE = CollectAnonRecordDecls(RT->getDecl()->getDefinitionOrSelf(), Unit,
6110 LineNo, LinkageName, Var, DContext);
6111 continue;
6112 }
6113 // Use VarDecl's Tag, Scope and Line number.
6114 GVE = DBuilder.createGlobalVariableExpression(
6115 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
6116 Var->hasLocalLinkage());
6117 Var->addDebugInfo(GVE);
6118 }
6119 return GVE;
6120}
6121
6122static bool ReferencesAnonymousEntity(ArrayRef<TemplateArgument> Args);
6123static bool ReferencesAnonymousEntity(RecordType *RT) {
6124 // Unnamed classes/lambdas can't be reconstituted due to a lack of column
6125 // info we produce in the DWARF, so we can't get Clang's full name back.
6126 // But so long as it's not one of those, it doesn't matter if some sub-type
6127 // of the record (a template parameter) can't be reconstituted - because the
6128 // un-reconstitutable type itself will carry its own name.
6129 const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
6130 if (!RD)
6131 return false;
6132 if (!RD->getIdentifier())
6133 return true;
6134 auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD);
6135 if (!TSpecial)
6136 return false;
6137 return ReferencesAnonymousEntity(TSpecial->getTemplateArgs().asArray());
6138}
6140 return llvm::any_of(Args, [&](const TemplateArgument &TA) {
6141 switch (TA.getKind()) {
6145 struct ReferencesAnonymous
6146 : public RecursiveASTVisitor<ReferencesAnonymous> {
6147 bool RefAnon = false;
6148 bool VisitRecordType(RecordType *RT) {
6149 if (ReferencesAnonymousEntity(RT)) {
6150 RefAnon = true;
6151 return false;
6152 }
6153 return true;
6154 }
6155 };
6156 ReferencesAnonymous RT;
6157 RT.TraverseType(TA.getAsType());
6158 if (RT.RefAnon)
6159 return true;
6160 break;
6161 }
6162 default:
6163 break;
6164 }
6165 return false;
6166 });
6167}
6168namespace {
6169struct ReconstitutableType : public RecursiveASTVisitor<ReconstitutableType> {
6170 bool Reconstitutable = true;
6171 bool VisitVectorType(VectorType *FT) {
6172 Reconstitutable = false;
6173 return false;
6174 }
6175 bool VisitAtomicType(AtomicType *FT) {
6176 Reconstitutable = false;
6177 return false;
6178 }
6179 bool TraverseEnumType(EnumType *ET, bool = false) {
6180 // Unnamed enums can't be reconstituted due to a lack of column info we
6181 // produce in the DWARF, so we can't get Clang's full name back.
6182 const EnumDecl *ED = ET->getDecl();
6183 if (!ED->getIdentifier()) {
6184 Reconstitutable = false;
6185 return false;
6186 }
6188 Reconstitutable = false;
6189 return false;
6190 }
6191 return true;
6192 }
6193 bool VisitFunctionProtoType(FunctionProtoType *FT) {
6194 // noexcept is not encoded in DWARF, so the reversi
6195 Reconstitutable &= !isNoexceptExceptionSpec(FT->getExceptionSpecType());
6196 Reconstitutable &= !FT->getNoReturnAttr();
6197 return Reconstitutable;
6198 }
6199 bool VisitRecordType(RecordType *RT, bool = false) {
6200 if (ReferencesAnonymousEntity(RT)) {
6201 Reconstitutable = false;
6202 return false;
6203 }
6204 return true;
6205 }
6206};
6207} // anonymous namespace
6208
6209// Test whether a type name could be rebuilt from emitted debug info.
6211 ReconstitutableType T;
6212 T.TraverseType(QT);
6213 return T.Reconstitutable;
6214}
6215
6216bool CGDebugInfo::HasReconstitutableArgs(
6217 ArrayRef<TemplateArgument> Args) const {
6218 return llvm::all_of(Args, [&](const TemplateArgument &TA) {
6219 switch (TA.getKind()) {
6221 // Easy to reconstitute - the value of the parameter in the debug
6222 // info is the string name of the template. The template name
6223 // itself won't benefit from any name rebuilding, but that's a
6224 // representational limitation - maybe DWARF could be
6225 // changed/improved to use some more structural representation.
6226 return true;
6228 // Reference and pointer non-type template parameters point to
6229 // variables, functions, etc and their value is, at best (for
6230 // variables) represented as an address - not a reference to the
6231 // DWARF describing the variable/function/etc. This makes it hard,
6232 // possibly impossible to rebuild the original name - looking up
6233 // the address in the executable file's symbol table would be
6234 // needed.
6235 return false;
6237 // These could be rebuilt, but figured they're close enough to the
6238 // declaration case, and not worth rebuilding.
6239 return false;
6241 // A pack is invalid if any of the elements of the pack are
6242 // invalid.
6243 return HasReconstitutableArgs(TA.getPackAsArray());
6245 // Larger integers get encoded as DWARF blocks which are a bit
6246 // harder to parse back into a large integer, etc - so punting on
6247 // this for now. Re-parsing the integers back into APInt is
6248 // probably feasible some day.
6249 return TA.getAsIntegral().getBitWidth() <= 64 &&
6252 return false;
6254 return IsReconstitutableType(TA.getAsType());
6256 return IsReconstitutableType(TA.getAsExpr()->getType());
6257 default:
6258 llvm_unreachable("Other, unresolved, template arguments should "
6259 "not be seen here");
6260 }
6261 });
6262}
6263
6264std::string CGDebugInfo::GetName(const Decl *D, bool Qualified,
6265 bool *NameIsSimplified) const {
6266 std::string Name;
6267 llvm::raw_string_ostream OS(Name);
6268 const NamedDecl *ND = dyn_cast<NamedDecl>(D);
6269 if (!ND)
6270 return Name;
6271 llvm::codegenoptions::DebugTemplateNamesKind TemplateNamesKind =
6272 CGM.getCodeGenOpts().getDebugSimpleTemplateNames();
6273
6274 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6275 TemplateNamesKind = llvm::codegenoptions::DebugTemplateNamesKind::Full;
6276
6277 std::optional<TemplateArgs> Args;
6278
6279 bool IsOperatorOverload = false; // isa<CXXConversionDecl>(ND);
6280 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
6281 Args = GetTemplateArgs(RD);
6282 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
6283 Args = GetTemplateArgs(FD);
6284 auto NameKind = ND->getDeclName().getNameKind();
6285 IsOperatorOverload |=
6288 } else if (auto *VD = dyn_cast<VarDecl>(ND)) {
6289 Args = GetTemplateArgs(VD);
6290 }
6291
6292 // A conversion operator presents complications/ambiguity if there's a
6293 // conversion to class template that is itself a template, eg:
6294 // template<typename T>
6295 // operator ns::t1<T, int>();
6296 // This should be named, eg: "operator ns::t1<float, int><float>"
6297 // (ignoring clang bug that means this is currently "operator t1<float>")
6298 // but if the arguments were stripped, the consumer couldn't differentiate
6299 // whether the template argument list for the conversion type was the
6300 // function's argument list (& no reconstitution was needed) or not.
6301 // This could be handled if reconstitutable names had a separate attribute
6302 // annotating them as such - this would remove the ambiguity.
6303 //
6304 // Alternatively the template argument list could be parsed enough to check
6305 // whether there's one list or two, then compare that with the DWARF
6306 // description of the return type and the template argument lists to determine
6307 // how many lists there should be and if one is missing it could be assumed(?)
6308 // to be the function's template argument list & then be rebuilt.
6309 //
6310 // Other operator overloads that aren't conversion operators could be
6311 // reconstituted but would require a bit more nuance about detecting the
6312 // difference between these different operators during that rebuilding.
6313 bool Reconstitutable =
6314 Args && HasReconstitutableArgs(Args->Args) && !IsOperatorOverload;
6315
6316 PrintingPolicy PP = getPrintingPolicy();
6317
6318 if (TemplateNamesKind == llvm::codegenoptions::DebugTemplateNamesKind::Full ||
6319 !Reconstitutable) {
6320 ND->getNameForDiagnostic(OS, PP, Qualified);
6321 } else {
6322 // Treat both "simple" and "mangled" as simplified.
6323 if (NameIsSimplified)
6324 *NameIsSimplified = true;
6325 bool Mangled = TemplateNamesKind ==
6326 llvm::codegenoptions::DebugTemplateNamesKind::Mangled;
6327 // check if it's a template
6328 if (Mangled)
6329 OS << "_STN|";
6330
6331 OS << ND->getDeclName();
6332 std::string EncodedOriginalName;
6333 llvm::raw_string_ostream EncodedOriginalNameOS(EncodedOriginalName);
6334 EncodedOriginalNameOS << ND->getDeclName();
6335
6336 if (Mangled) {
6337 OS << "|";
6338 printTemplateArgumentList(OS, Args->Args, PP);
6339 printTemplateArgumentList(EncodedOriginalNameOS, Args->Args, PP);
6340#ifndef NDEBUG
6341 std::string CanonicalOriginalName;
6342 llvm::raw_string_ostream OriginalOS(CanonicalOriginalName);
6343 ND->getNameForDiagnostic(OriginalOS, PP, Qualified);
6344 assert(EncodedOriginalName == CanonicalOriginalName);
6345#endif
6346 }
6347 }
6348 return Name;
6349}
6350
6351void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
6352 const VarDecl *D) {
6353 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6354 if (D->hasAttr<NoDebugAttr>())
6355 return;
6356
6357 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
6358 return GetName(D, true);
6359 });
6360
6361 // If we already created a DIGlobalVariable for this declaration, just attach
6362 // it to the llvm::GlobalVariable.
6363 auto Cached = DeclCache.find(D->getCanonicalDecl());
6364 if (Cached != DeclCache.end())
6365 return Var->addDebugInfo(
6367
6368 // Create global variable debug descriptor.
6369 llvm::DIFile *Unit = nullptr;
6370 llvm::DIScope *DContext = nullptr;
6371 unsigned LineNo;
6372 StringRef DeclName, LinkageName;
6373 QualType T;
6374 llvm::MDTuple *TemplateParameters = nullptr;
6375 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
6376 TemplateParameters, DContext);
6377
6378 // Attempt to store one global variable for the declaration - even if we
6379 // emit a lot of fields.
6380 llvm::DIGlobalVariableExpression *GVE = nullptr;
6381
6382 // If this is an anonymous union then we'll want to emit a global
6383 // variable for each member of the anonymous union so that it's possible
6384 // to find the name of any field in the union.
6385 if (T->isUnionType() && DeclName.empty()) {
6386 const auto *RD = T->castAsRecordDecl();
6387 assert(RD->isAnonymousStructOrUnion() &&
6388 "unnamed non-anonymous struct or union?");
6389 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
6390 } else {
6391 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6392
6394 unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(D->getType());
6395 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
6396 if (D->hasAttr<CUDASharedAttr>())
6397 AddressSpace =
6398 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
6399 else if (D->hasAttr<CUDAConstantAttr>())
6400 AddressSpace =
6401 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
6402 }
6403 AppendAddressSpaceXDeref(AddressSpace, Expr);
6404
6405 llvm::DINodeArray Annotations = CollectBTFDeclTagAnnotations(D);
6406 GVE = DBuilder.createGlobalVariableExpression(
6407 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
6408 Var->hasLocalLinkage(), true,
6409 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
6410 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
6411 Align, Annotations);
6412 Var->addDebugInfo(GVE);
6413 }
6414 DeclCache[D->getCanonicalDecl()].reset(GVE);
6415}
6416
6418 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6419 if (VD->hasAttr<NoDebugAttr>())
6420 return;
6421 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
6422 return GetName(VD, true);
6423 });
6424
6425 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
6426 // Create the descriptor for the variable.
6427 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
6428 StringRef Name = VD->getName();
6429 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
6430
6431 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
6432 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
6433 if (CGM.getCodeGenOpts().EmitCodeView) {
6434 // If CodeView, emit enums as global variables, unless they are defined
6435 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
6436 // enums in classes, and because it is difficult to attach this scope
6437 // information to the global variable.
6439 return;
6440 } else {
6441 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
6442 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
6443 // first time `ZERO` is referenced in a function.
6444 CanQualType T = CGM.getContext().getCanonicalTagType(ED);
6445 [[maybe_unused]] llvm::DIType *EDTy = getOrCreateType(T, Unit);
6446 assert(EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
6447 return;
6448 }
6449 }
6450
6451 // Do not emit separate definitions for function local consts.
6453 return;
6454
6456 auto *VarD = dyn_cast<VarDecl>(VD);
6457 if (VarD && VarD->isStaticDataMember()) {
6458 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
6459 getDeclContextDescriptor(VarD);
6460 // Ensure that the type is retained even though it's otherwise unreferenced.
6461 //
6462 // FIXME: This is probably unnecessary, since Ty should reference RD
6463 // through its scope.
6464 RetainedTypes.push_back(
6465 CGM.getContext().getCanonicalTagType(RD).getAsOpaquePtr());
6466
6467 return;
6468 }
6469 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
6470
6471 auto &GV = DeclCache[VD];
6472 if (GV)
6473 return;
6474
6475 llvm::DIExpression *InitExpr = createConstantValueExpression(VD, Init);
6476 llvm::MDTuple *TemplateParameters = nullptr;
6477
6479 if (VarD) {
6480 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
6481 TemplateParameters = parameterNodes.get();
6482 }
6483
6484 GV.reset(DBuilder.createGlobalVariableExpression(
6485 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
6486 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
6487 TemplateParameters, Align));
6488}
6489
6490void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
6491 const VarDecl *D) {
6492 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
6493 if (D->hasAttr<NoDebugAttr>())
6494 return;
6495
6496 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
6497 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
6498 StringRef Name = D->getName();
6499 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
6500
6501 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6502 llvm::DIGlobalVariableExpression *GVE =
6503 DBuilder.createGlobalVariableExpression(
6504 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
6505 Ty, false, false, nullptr, nullptr, nullptr, Align);
6506 Var->addDebugInfo(GVE);
6507}
6508
6510 llvm::Instruction *Value, QualType Ty) {
6511 // Only when -g2 or above is specified, debug info for variables will be
6512 // generated.
6513 if (CGM.getCodeGenOpts().getDebugInfo() <=
6514 llvm::codegenoptions::DebugLineTablesOnly)
6515 return;
6516
6517 llvm::DILocation *DIL = Value->getDebugLoc().get();
6518 if (!DIL)
6519 return;
6520
6521 llvm::DIFile *Unit = DIL->getFile();
6522 llvm::DIType *Type = getOrCreateType(Ty, Unit);
6523
6524 // Check if Value is already a declared variable and has debug info, in this
6525 // case we have nothing to do. Clang emits a declared variable as alloca, and
6526 // it is loaded upon use, so we identify such pattern here.
6527 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Value)) {
6528 llvm::Value *Var = Load->getPointerOperand();
6529 // There can be implicit type cast applied on a variable if it is an opaque
6530 // ptr, in this case its debug info may not match the actual type of object
6531 // being used as in the next instruction, so we will need to emit a pseudo
6532 // variable for type-casted value.
6533 auto DeclareTypeMatches = [&](llvm::DbgVariableRecord *DbgDeclare) {
6534 return DbgDeclare->getVariable()->getType() == Type;
6535 };
6536 if (any_of(llvm::findDVRDeclares(Var), DeclareTypeMatches))
6537 return;
6538 }
6539
6540 llvm::DILocalVariable *D =
6541 DBuilder.createAutoVariable(LexicalBlockStack.back(), "", nullptr, 0,
6542 Type, false, llvm::DINode::FlagArtificial);
6543
6544 if (auto InsertPoint = Value->getInsertionPointAfterDef()) {
6545 DBuilder.insertDbgValue(Value, D, DBuilder.createExpression(), DIL,
6546 *InsertPoint);
6547 }
6548}
6549
6550void CGDebugInfo::EmitGlobalAlias(const llvm::GlobalValue *GV,
6551 const GlobalDecl GD) {
6552
6553 assert(GV);
6554
6555 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6556 return;
6557
6558 const auto *D = cast<ValueDecl>(GD.getDecl());
6559 if (D->hasAttr<NoDebugAttr>())
6560 return;
6561
6562 auto AliaseeDecl = CGM.getMangledNameDecl(GV->getName());
6563 llvm::DINode *DI;
6564
6565 if (!AliaseeDecl)
6566 // FIXME: Aliasee not declared yet - possibly declared later
6567 // For example,
6568 //
6569 // 1 extern int newname __attribute__((alias("oldname")));
6570 // 2 int oldname = 1;
6571 //
6572 // No debug info would be generated for 'newname' in this case.
6573 //
6574 // Fix compiler to generate "newname" as imported_declaration
6575 // pointing to the DIE of "oldname".
6576 return;
6577 if (!(DI = getDeclarationOrDefinition(
6578 AliaseeDecl.getCanonicalDecl().getDecl())))
6579 return;
6580
6581 llvm::DIScope *DContext = getDeclContextDescriptor(D);
6582 auto Loc = D->getLocation();
6583
6584 llvm::DIImportedEntity *ImportDI = DBuilder.createImportedDeclaration(
6585 DContext, DI, getOrCreateFile(Loc), getLineNumber(Loc), D->getName());
6586
6587 // Record this DIE in the cache for nested declaration reference.
6588 ImportedDeclCache[GD.getCanonicalDecl().getDecl()].reset(ImportDI);
6589}
6590
6591void CGDebugInfo::AddStringLiteralDebugInfo(llvm::GlobalVariable *GV,
6592 const StringLiteral *S) {
6593 SourceLocation Loc = S->getStrTokenLoc(0);
6594 SourceManager &SM = CGM.getContext().getSourceManager();
6595 PresumedLoc PLoc = SM.getPresumedLoc(getMacroDebugLoc(CGM, Loc));
6596 if (!PLoc.isValid())
6597 return;
6598
6599 llvm::DIFile *File = getOrCreateFile(Loc);
6600 llvm::DIGlobalVariableExpression *Debug =
6601 DBuilder.createGlobalVariableExpression(
6602 nullptr, StringRef(), StringRef(), getOrCreateFile(Loc),
6603 getLineNumber(Loc), getOrCreateType(S->getType(), File), true);
6604 GV->addDebugInfo(Debug);
6605}
6606
6607llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
6608 if (!LexicalBlockStack.empty())
6609 return LexicalBlockStack.back();
6610 llvm::DIScope *Mod = getParentModuleOrNull(D);
6611 return getContextDescriptor(D, Mod ? Mod : TheCU);
6612}
6613
6615 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6616 return;
6617 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
6618 if (!NSDecl->isAnonymousNamespace() ||
6619 CGM.getCodeGenOpts().DebugExplicitImport) {
6620 auto Loc = UD.getLocation();
6621 if (!Loc.isValid())
6622 Loc = CurLoc;
6623 DBuilder.createImportedModule(
6624 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
6625 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
6626 }
6627}
6628
6630 if (llvm::DINode *Target =
6631 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
6632 auto Loc = USD.getLocation();
6633 DBuilder.createImportedDeclaration(
6634 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
6635 getOrCreateFile(Loc), getLineNumber(Loc));
6636 }
6637}
6638
6640 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6641 return;
6642 assert(UD.shadow_size() &&
6643 "We shouldn't be codegening an invalid UsingDecl containing no decls");
6644
6645 for (const auto *USD : UD.shadows()) {
6646 // FIXME: Skip functions with undeduced auto return type for now since we
6647 // don't currently have the plumbing for separate declarations & definitions
6648 // of free functions and mismatched types (auto in the declaration, concrete
6649 // return type in the definition)
6650 if (const auto *FD = dyn_cast<FunctionDecl>(USD->getUnderlyingDecl()))
6651 if (const auto *AT = FD->getType()
6652 ->castAs<FunctionProtoType>()
6654 if (AT->getDeducedType().isNull())
6655 continue;
6656
6657 EmitUsingShadowDecl(*USD);
6658 // Emitting one decl is sufficient - debuggers can detect that this is an
6659 // overloaded name & provide lookup for all the overloads.
6660 break;
6661 }
6662}
6663
6665 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6666 return;
6667 assert(UD.shadow_size() &&
6668 "We shouldn't be codegening an invalid UsingEnumDecl"
6669 " containing no decls");
6670
6671 for (const auto *USD : UD.shadows())
6672 EmitUsingShadowDecl(*USD);
6673}
6674
6676 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
6677 return;
6678 if (Module *M = ID.getImportedModule()) {
6679 auto Info = ASTSourceDescriptor(*M);
6680 auto Loc = ID.getLocation();
6681 DBuilder.createImportedDeclaration(
6682 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
6683 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
6684 getLineNumber(Loc));
6685 }
6686}
6687
6688llvm::DIImportedEntity *
6690 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
6691 return nullptr;
6692 auto &VH = NamespaceAliasCache[&NA];
6693 if (VH)
6695 llvm::DIImportedEntity *R;
6696 auto Loc = NA.getLocation();
6697 if (const auto *Underlying =
6698 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
6699 // This could cache & dedup here rather than relying on metadata deduping.
6700 R = DBuilder.createImportedDeclaration(
6701 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6702 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
6703 getLineNumber(Loc), NA.getName());
6704 else
6705 R = DBuilder.createImportedDeclaration(
6706 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
6707 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
6708 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
6709 VH.reset(R);
6710 return R;
6711}
6712
6713llvm::DINamespace *
6714CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
6715 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
6716 // if necessary, and this way multiple declarations of the same namespace in
6717 // different parent modules stay distinct.
6718 auto I = NamespaceCache.find(NSDecl);
6719 if (I != NamespaceCache.end())
6720 return cast<llvm::DINamespace>(I->second);
6721
6722 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
6723 // Don't trust the context if it is a DIModule (see comment above).
6724 llvm::DINamespace *NS =
6725 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
6726 NamespaceCache[NSDecl].reset(NS);
6727 return NS;
6728}
6729
6730void CGDebugInfo::setDwoId(uint64_t Signature) {
6731 assert(TheCU && "no main compile unit");
6732 TheCU->setDWOId(Signature);
6733}
6734
6736 // Creating types might create further types - invalidating the current
6737 // element and the size(), so don't cache/reference them.
6738 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
6739 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
6740 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
6741 ? CreateTypeDefinition(E.Type, E.Unit)
6742 : E.Decl;
6743 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
6744 }
6745
6746 // Add methods to interface.
6747 for (const auto &P : ObjCMethodCache) {
6748 if (P.second.empty())
6749 continue;
6750
6751 QualType QTy(P.first->getTypeForDecl(), 0);
6752 auto It = TypeCache.find(QTy.getAsOpaquePtr());
6753 assert(It != TypeCache.end());
6754
6755 llvm::DICompositeType *InterfaceDecl =
6756 cast<llvm::DICompositeType>(It->second);
6757
6758 auto CurElts = InterfaceDecl->getElements();
6759 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
6760
6761 // For DWARF v4 or earlier, only add objc_direct methods.
6762 for (auto &SubprogramDirect : P.second)
6763 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
6764 EltTys.push_back(SubprogramDirect.getPointer());
6765
6766 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
6767 DBuilder.replaceArrays(InterfaceDecl, Elements);
6768 }
6769
6770 for (const auto &P : ReplaceMap) {
6771 assert(P.second);
6772 auto *Ty = cast<llvm::DIType>(P.second);
6773 assert(Ty->isForwardDecl());
6774
6775 auto It = TypeCache.find(P.first);
6776 assert(It != TypeCache.end());
6777 assert(It->second);
6778
6779 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
6780 cast<llvm::DIType>(It->second));
6781 }
6782
6783 for (const auto &P : FwdDeclReplaceMap) {
6784 assert(P.second);
6785 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
6786 llvm::Metadata *Repl;
6787
6788 auto It = DeclCache.find(P.first);
6789 // If there has been no definition for the declaration, call RAUW
6790 // with ourselves, that will destroy the temporary MDNode and
6791 // replace it with a standard one, avoiding leaking memory.
6792 if (It == DeclCache.end())
6793 Repl = P.second;
6794 else
6795 Repl = It->second;
6796
6797 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
6798 Repl = GVE->getVariable();
6799 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
6800 }
6801
6802 // We keep our own list of retained types, because we need to look
6803 // up the final type in the type cache.
6804 for (auto &RT : RetainedTypes)
6805 if (auto MD = TypeCache[RT])
6806 DBuilder.retainType(cast<llvm::DIType>(MD));
6807
6808 DBuilder.finalize();
6809}
6810
6811// Don't ignore in case of explicit cast where it is referenced indirectly.
6813 if (CGM.getCodeGenOpts().hasReducedDebugInfo())
6814 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6815 DBuilder.retainType(DieTy);
6816}
6817
6819 if (CGM.getCodeGenOpts().hasMaybeUnusedDebugInfo())
6820 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
6821 DBuilder.retainType(DieTy);
6822}
6823
6825 if (LexicalBlockStack.empty())
6826 return llvm::DebugLoc();
6827
6828 llvm::MDNode *Scope = LexicalBlockStack.back();
6829 return llvm::DILocation::get(CGM.getLLVMContext(), getLineNumber(Loc),
6830 getColumnNumber(Loc), Scope);
6831}
6832
6833llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
6834 // Call site-related attributes are only useful in optimized programs, and
6835 // when there's a possibility of debugging backtraces.
6836 if (CGM.getCodeGenOpts().OptimizationLevel == 0 ||
6837 DebugKind == llvm::codegenoptions::NoDebugInfo ||
6838 DebugKind == llvm::codegenoptions::LocTrackingOnly ||
6839 !CGM.getCodeGenOpts().DebugCallSiteInfo)
6840 return llvm::DINode::FlagZero;
6841
6842 // Call site-related attributes are available in DWARF v5. Some debuggers,
6843 // while not fully DWARF v5-compliant, may accept these attributes as if they
6844 // were part of DWARF v4.
6845 bool SupportsDWARFv4Ext =
6846 CGM.getCodeGenOpts().DwarfVersion == 4 &&
6847 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
6848 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
6849
6850 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5)
6851 return llvm::DINode::FlagZero;
6852
6853 return llvm::DINode::FlagAllCallsDescribed;
6854}
6855
6856llvm::DIExpression *
6857CGDebugInfo::createConstantValueExpression(const clang::ValueDecl *VD,
6858 const APValue &Val) {
6859 // FIXME: Add a representation for integer constants wider than 64 bits.
6860 if (CGM.getContext().getTypeSize(VD->getType()) > 64)
6861 return nullptr;
6862
6863 if (Val.isFloat())
6864 return DBuilder.createConstantValueExpression(
6865 Val.getFloat().bitcastToAPInt().getZExtValue());
6866
6867 if (!Val.isInt())
6868 return nullptr;
6869
6870 llvm::APSInt const &ValInt = Val.getInt();
6871 std::optional<uint64_t> ValIntOpt;
6872 if (ValInt.isUnsigned())
6873 ValIntOpt = ValInt.tryZExtValue();
6874 else if (auto tmp = ValInt.trySExtValue())
6875 // Transform a signed optional to unsigned optional. When cpp 23 comes,
6876 // use std::optional::transform
6877 ValIntOpt = static_cast<uint64_t>(*tmp);
6878
6879 if (ValIntOpt)
6880 return DBuilder.createConstantValueExpression(ValIntOpt.value());
6881
6882 return nullptr;
6883}
6884
6885CodeGenFunction::LexicalScope::LexicalScope(CodeGenFunction &CGF,
6886 SourceRange Range)
6887 : RunCleanupsScope(CGF), Range(Range), ParentScope(CGF.CurLexicalScope) {
6888 CGF.CurLexicalScope = this;
6889 if (CGDebugInfo *DI = CGF.getDebugInfo())
6890 DI->EmitLexicalBlockStart(CGF.Builder, Range.getBegin());
6891}
6892
6894 if (CGDebugInfo *DI = CGF.getDebugInfo())
6895 DI->EmitLexicalBlockEnd(CGF.Builder, Range.getEnd());
6896
6897 // If we should perform a cleanup, force them now. Note that
6898 // this ends the cleanup scope before rescoping any labels.
6899 if (PerformCleanup) {
6900 ApplyDebugLocation DL(CGF, Range.getEnd());
6901 ForceCleanup();
6902 }
6903}
6904
6906 std::string Label;
6907 switch (Handler) {
6908#define SANITIZER_CHECK(Enum, Name, Version, Msg) \
6909 case Enum: \
6910 Label = "__ubsan_check_" #Name; \
6911 break;
6912
6914#undef SANITIZER_CHECK
6915 };
6916
6917 // Label doesn't require sanitization
6918 return Label;
6919}
6920
6921static std::string
6923 std::string Label;
6924 switch (Ordinal) {
6925#define SANITIZER(NAME, ID) \
6926 case SanitizerKind::SO_##ID: \
6927 Label = "__ubsan_check_" NAME; \
6928 break;
6929#include "clang/Basic/Sanitizers.def"
6930 default:
6931 llvm_unreachable("unexpected sanitizer kind");
6932 }
6933
6934 // Sanitize label (convert hyphens to underscores; also futureproof against
6935 // non-alpha)
6936 for (unsigned int i = 0; i < Label.length(); i++)
6937 if (!std::isalpha(Label[i]))
6938 Label[i] = '_';
6939
6940 return Label;
6941}
6942
6945 SanitizerHandler Handler) {
6946 llvm::DILocation *CheckDebugLoc = Builder.getCurrentDebugLocation();
6947 auto *DI = getDebugInfo();
6948 if (!DI || !CheckDebugLoc)
6949 return CheckDebugLoc;
6950 const auto &AnnotateDebugInfo =
6951 CGM.getCodeGenOpts().SanitizeAnnotateDebugInfo;
6952 if (AnnotateDebugInfo.empty())
6953 return CheckDebugLoc;
6954
6955 std::string Label;
6956 if (Ordinals.size() == 1)
6957 Label = SanitizerOrdinalToCheckLabel(Ordinals[0]);
6958 else
6959 Label = SanitizerHandlerToCheckLabel(Handler);
6960
6961 if (any_of(Ordinals, [&](auto Ord) { return AnnotateDebugInfo.has(Ord); })) {
6962 // Use ubsan header file to have the same filename for all checks. There is
6963 // nothing special in that file, we just want to make tools to count all
6964 // syntetic functions of a check as the same.
6965 llvm::DIFile *File = llvm::DIFile::get(CGM.getLLVMContext(),
6966 /*Filename=*/"ubsan_interface.h",
6967 /*Directory=*/"sanitizer");
6968 return DI->CreateSyntheticInlineAt(CheckDebugLoc, Label, File);
6969 }
6970
6971 return CheckDebugLoc;
6972}
6973
6976 SanitizerHandler Handler)
6977 : CGF(CGF),
6978 Apply(*CGF, CGF->SanitizerAnnotateDebugInfo(Ordinals, Handler)) {
6979 assert(!CGF->IsSanitizerScope);
6980 CGF->IsSanitizerScope = true;
6981}
6982
6984 assert(CGF->IsSanitizerScope);
6985 CGF->IsSanitizerScope = false;
6986}
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 void completeStandardLayoutUnionType(CGDebugInfo &DebugInfo, QualType QT)
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 void completeStandardLayoutUnionMembers(CGDebugInfo &DebugInfo, const CXXRecordDecl *RD)
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:124
bool hasArrayFiller() const
Definition APValue.h:659
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:651
APSInt & getInt()
Definition APValue.h:533
unsigned getArrayInitializedElts() const
Definition APValue.h:670
bool isFloat() const
Definition APValue.h:510
APValue & getArrayFiller()
Definition APValue.h:662
bool isInt() const
Definition APValue.h:509
unsigned getArraySize() const
Definition APValue.h:674
APFloat & getFloat()
Definition APValue.h:547
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
bool getByrefLifetime(QualType Ty, Qualifiers::ObjCLifetime &Lifetime, bool &HasByrefExtendedLayout) const
Returns true, if given type has a known lifetime.
SourceManager & getSourceManager()
Definition ASTContext.h:911
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:3832
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8262
unsigned shadow_size() const
Return the number of shadowed declarations associated with this using declaration.
Definition DeclCXX.h:3604
shadow_range shadows() const
Definition DeclCXX.h:3592
A binding in a decomposition declaration.
Definition DeclCXX.h:4215
Expr * getBinding() const
Get the expression to which this declaration is bound.
Definition DeclCXX.h:4241
bool isUnsigned() const
Definition TypeBase.h:8314
unsigned getNumBits() const
Definition TypeBase.h:8316
A class which contains all the information about a particular captured value.
Definition Decl.h:4816
bool isByRef() const
Whether this is a "by ref" capture, i.e.
Definition Decl.h:4841
Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy)
Definition Decl.h:4831
VarDecl * getVariable() const
The variable being captured.
Definition Decl.h:4837
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4810
QualType getPointeeType() const
Definition TypeBase.h:3665
Kind getKind() const
Definition TypeBase.h:3299
StringRef getName(const PrintingPolicy &Policy) const
Definition Type.cpp:3624
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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:1153
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1235
llvm::iterator_range< base_class_const_iterator > base_class_const_range
Definition DeclCXX.h:606
base_class_range bases()
Definition DeclCXX.h:609
specific_decl_iterator< CXXMethodDecl > method_iterator
Iterator access to method members.
Definition DeclCXX.h:647
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1028
bool needsImplicitDefaultConstructor() const
Determine if we need to declare a default constructor for this class.
Definition DeclCXX.h:771
capture_const_iterator captures_end() const
Definition DeclCXX.h:1117
method_range methods() const
Definition DeclCXX.h:651
bool defaultedDefaultConstructorIsConstexpr() const
Determine whether a defaulted default constructor for this class would be constexpr.
Definition DeclCXX.h:1279
method_iterator method_begin() const
Method begin iterator.
Definition DeclCXX.h:657
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:626
ctor_range ctors() const
Definition DeclCXX.h:671
bool isDynamicClass() const
Definition DeclCXX.h:575
const LambdaCapture * capture_const_iterator
Definition DeclCXX.h:1104
MSInheritanceModel getMSInheritanceModel() const
Returns the inheritance model used for this record.
bool hasDefinition() const
Definition DeclCXX.h:562
method_iterator method_end() const
Method past-the-end iterator.
Definition DeclCXX.h:662
capture_const_iterator captures_begin() const
Definition DeclCXX.h:1111
CXXRecordDecl * getDefinitionOrSelf() const
Definition DeclCXX.h:556
void * getAsOpaquePtr() const
Retrieve the internal representation of this canonical type.
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isPositive() const
Test whether the quantity is greater than zero.
Definition CharUnits.h:107
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
CharUnits alignTo(CharUnits Align) const
Returns the next integer (mod 2**64) that is greater than or equal to this quantity and is a multiple...
Definition CharUnits.h:169
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:153
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
static CharUnits Zero()
Construct a CharUnits quantity of zero.
Definition CharUnits.h:52
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:4512
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4509
bool isRecord() const
Definition DeclBase.h:2226
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:2423
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
bool isInvalidDecl() const
Definition DeclBase.h:596
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:4146
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4378
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4262
This represents one expression.
Definition Expr.h:113
bool isGLValue() const
Definition Expr.h:288
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:145
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3380
static InputKind getInputKindForExtension(StringRef Extension)
getInputKindForExtension - Return the appropriate input kind for a file extension.
Represents a function declaration or definition.
Definition Decl.h:2059
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:3052
bool isNoReturn() const
Determines whether this function is known to be 'noreturn', through an attribute on its declaration o...
Definition Decl.cpp:3693
QualType getReturnType() const
Definition Decl.h:2976
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2570
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition Decl.cpp:4362
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3789
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4368
@ TK_FunctionTemplateSpecialization
Definition Decl.h:2075
bool isStatic() const
Definition Decl.h:3060
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4183
FunctionDecl * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition Decl.h:2396
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4204
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5723
unsigned getNumParams() const
Definition TypeBase.h:5694
QualType getParamType(unsigned i) const
Definition TypeBase.h:5696
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5705
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5701
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5856
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4612
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4960
CallingConv getCallConv() const
Definition TypeBase.h:4967
QualType getReturnType() const
Definition TypeBase.h:4952
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
GlobalDecl getCanonicalDecl() const
Definition GlobalDecl.h:106
DynamicInitKind getDynamicInitKind() const
Definition GlobalDecl.h:127
const Decl * getDecl() const
Definition GlobalDecl.h:115
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition Decl.h:5191
bool isPreprocessed() const
Represents the declaration of a label.
Definition Decl.h:525
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:4454
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5847
QualType getPointeeType() const
Definition TypeBase.h:3769
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:275
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:488
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:302
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
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:318
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:1848
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:1689
bool isExternallyVisible() const
Definition Decl.h:434
Represents a C++ namespace alias.
Definition DeclCXX.h:3231
NamespaceBaseDecl * getAliasedNamespace() const
Retrieve the namespace that this alias refers to, which may either be a NamespaceDecl or a NamespaceA...
Definition DeclCXX.h:3324
Represent a C++ namespace.
Definition Decl.h:593
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition Decl.h:644
bool isInline() const
Returns true if this is an inline namespace declaration.
Definition Decl.h:649
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:1084
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:8162
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8099
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
QualType getType() const
Definition DeclObjC.h:810
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:1820
QualType getElementType() const
Definition TypeBase.h:8286
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:3413
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:8446
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:8393
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4984
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:4460
field_range fields() const
Definition Decl.h:4663
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition Decl.h:4644
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4648
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition Decl.h:4512
field_iterator field_begin() const
Definition Decl.cpp:5346
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
QualType getPointeeType() const
Definition TypeBase.h:3700
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:1819
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition Expr.h:1990
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3852
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
bool isStruct() const
Definition Decl.h:4060
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition Decl.h:4089
bool isCompleteDefinitionRequired() const
Return true if this complete decl is required to be complete for some existing use.
Definition Decl.h:3962
bool isUnion() const
Definition Decl.h:4063
bool isInterface() const
Definition Decl.h:4061
bool isClass() const
Definition Decl.h:4062
TagDecl * getDefinitionOrSelf() const
Definition Decl.h:4035
virtual std::optional< unsigned > getDWARFAddressSpace(unsigned AddressSpace) const
uint64_t getPointerAlign(LangAS AddrSpace) const
Definition TargetInfo.h:499
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:9068
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
bool isIncompleteArrayType() const
Definition TypeBase.h:8790
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition TypeBase.h:2980
bool isMemberDataPointerType() const
Definition TypeBase.h:8775
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9252
bool isComplexIntegerType() const
Definition Type.cpp:863
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
TypeClass getTypeClass() const
Definition TypeBase.h:2449
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isRecordType() const
Definition TypeBase.h:8810
QualType getUnderlyingType() const
Definition Decl.h:3752
TypedefNameDecl * getDecl() const
Definition TypeBase.h:6260
Represents a C++ using-declaration.
Definition DeclCXX.h:3621
Represents C++ using-directive.
Definition DeclCXX.h:3126
NamespaceDecl * getNominatedNamespace()
Returns the namespace nominated by this using-directive.
Definition DeclCXX.cpp:3357
Represents a C++ using-enum-declaration.
Definition DeclCXX.h:3822
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3429
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:713
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2237
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1307
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1215
const Expr * getInit() const
Definition Decl.h:1392
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2555
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition Decl.cpp:2681
unsigned getNumElements() const
Definition TypeBase.h:4288
QualType getElementType() const
Definition TypeBase.h:4287
@ 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:127
@ AS_public
Definition Specifiers.h:128
@ AS_protected
Definition Specifiers.h:129
@ AS_none
Definition Specifiers.h:131
@ AS_private
Definition Specifiers.h:130
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:36
@ 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:192
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:206
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_X86Pascal
Definition Specifiers.h:288
@ CC_Swift
Definition Specifiers.h:296
@ CC_IntelOclBicc
Definition Specifiers.h:294
@ CC_PreserveMost
Definition Specifiers.h:298
@ CC_Win64
Definition Specifiers.h:289
@ CC_X86ThisCall
Definition Specifiers.h:286
@ CC_AArch64VectorCall
Definition Specifiers.h:300
@ CC_DeviceKernel
Definition Specifiers.h:295
@ CC_AAPCS
Definition Specifiers.h:292
@ CC_PreserveNone
Definition Specifiers.h:303
@ CC_M68kRTD
Definition Specifiers.h:302
@ CC_SwiftAsync
Definition Specifiers.h:297
@ CC_X86RegCall
Definition Specifiers.h:291
@ CC_RISCVVectorCall
Definition Specifiers.h:304
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_AArch64SVEPCS
Definition Specifiers.h:301
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86_64SysV
Definition Specifiers.h:290
@ CC_PreserveAll
Definition Specifiers.h:299
@ CC_X86FastCall
Definition Specifiers.h:285
@ CC_AAPCS_VFP
Definition Specifiers.h:293
@ Generic
not a target-specific vector type
Definition TypeBase.h:4234
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6028
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1763
@ ObjCSelf
Parameter for Objective-C 'self' argument.
Definition Decl.h:1757
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
int32_t 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:5501
uint64_t Index
Method's index in the vftable.
unsigned PrettyEnums
Whether to print enumerators with a matching enumerator name or via cast.
unsigned SplitTemplateClosers
Whether nested templates must be closed like 'a<b<c> >' rather than 'a<b<c>>'.
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.
bool isAlignRequired()
Definition ASTContext.h:197