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