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