Thanks to visit codestin.com
Credit goes to clang.llvm.org

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