1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This coordinates the debug information generation while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "ConstantEmitter.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Attr.h"
23 #include "clang/AST/DeclFriend.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/Basic/CodeGenOptions.h"
29 #include "clang/Basic/FileManager.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/Version.h"
32 #include "clang/Frontend/FrontendOptions.h"
33 #include "clang/Lex/HeaderSearchOptions.h"
34 #include "clang/Lex/ModuleMap.h"
35 #include "clang/Lex/PreprocessorOptions.h"
36 #include "llvm/ADT/DenseSet.h"
37 #include "llvm/ADT/SmallVector.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/IR/Constants.h"
40 #include "llvm/IR/DataLayout.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/IR/Metadata.h"
45 #include "llvm/IR/Module.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/MD5.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/TimeProfiler.h"
50 using namespace clang;
51 using namespace clang::CodeGen;
53 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
54 auto TI = Ctx.getTypeInfo(Ty);
55 return TI.AlignIsRequired ? TI.Align : 0;
58 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
59 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
62 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
63 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
66 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
67 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
68 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
69 DBuilder(CGM.getModule()) {
70 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
71 DebugPrefixMap[KV.first] = KV.second;
75 CGDebugInfo::~CGDebugInfo() {
76 assert(LexicalBlockStack.empty() &&
77 "Region stack mismatch, stack not empty!");
80 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
81 SourceLocation TemporaryLocation)
83 init(TemporaryLocation);
86 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
88 SourceLocation TemporaryLocation)
90 init(TemporaryLocation, DefaultToEmpty);
93 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
94 bool DefaultToEmpty) {
95 auto *DI = CGF->getDebugInfo();
101 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
103 if (OriginalLocation && !DI->CGM.getExpressionLocationsEnabled())
106 if (TemporaryLocation.isValid()) {
107 DI->EmitLocation(CGF->Builder, TemporaryLocation);
111 if (DefaultToEmpty) {
112 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
116 // Construct a location that has a valid scope, but no line info.
117 assert(!DI->LexicalBlockStack.empty());
118 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
119 0, 0, DI->LexicalBlockStack.back(), DI->getInlinedAt()));
122 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
124 init(E->getExprLoc());
127 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
129 if (!CGF.getDebugInfo()) {
133 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
135 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
138 ApplyDebugLocation::~ApplyDebugLocation() {
139 // Query CGF so the location isn't overwritten when location updates are
140 // temporarily disabled (for C++ default function arguments)
142 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
145 ApplyInlineDebugLocation::ApplyInlineDebugLocation(CodeGenFunction &CGF,
146 GlobalDecl InlinedFn)
148 if (!CGF.getDebugInfo()) {
152 auto &DI = *CGF.getDebugInfo();
153 SavedLocation = DI.getLocation();
154 assert((DI.getInlinedAt() ==
155 CGF.Builder.getCurrentDebugLocation()->getInlinedAt()) &&
156 "CGDebugInfo and IRBuilder are out of sync");
158 DI.EmitInlineFunctionStart(CGF.Builder, InlinedFn);
161 ApplyInlineDebugLocation::~ApplyInlineDebugLocation() {
164 auto &DI = *CGF->getDebugInfo();
165 DI.EmitInlineFunctionEnd(CGF->Builder);
166 DI.EmitLocation(CGF->Builder, SavedLocation);
169 void CGDebugInfo::setLocation(SourceLocation Loc) {
170 // If the new location isn't valid return.
174 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
176 // If we've changed files in the middle of a lexical scope go ahead
177 // and create a new lexical scope with file node if it's different
178 // from the one in the scope.
179 if (LexicalBlockStack.empty())
182 SourceManager &SM = CGM.getContext().getSourceManager();
183 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
184 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
185 if (PCLoc.isInvalid() || Scope->getFile() == getOrCreateFile(CurLoc))
188 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
189 LexicalBlockStack.pop_back();
190 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
191 LBF->getScope(), getOrCreateFile(CurLoc)));
192 } else if (isa<llvm::DILexicalBlock>(Scope) ||
193 isa<llvm::DISubprogram>(Scope)) {
194 LexicalBlockStack.pop_back();
195 LexicalBlockStack.emplace_back(
196 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
200 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
201 llvm::DIScope *Mod = getParentModuleOrNull(D);
202 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
206 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
207 llvm::DIScope *Default) {
211 auto I = RegionMap.find(Context);
212 if (I != RegionMap.end()) {
213 llvm::Metadata *V = I->second;
214 return dyn_cast_or_null<llvm::DIScope>(V);
218 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
219 return getOrCreateNamespace(NSDecl);
221 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
222 if (!RDecl->isDependentType())
223 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
228 PrintingPolicy CGDebugInfo::getPrintingPolicy() const {
229 PrintingPolicy PP = CGM.getContext().getPrintingPolicy();
231 // If we're emitting codeview, it's important to try to match MSVC's naming so
232 // that visualizers written for MSVC will trigger for our class names. In
233 // particular, we can't have spaces between arguments of standard templates
234 // like basic_string and vector.
235 if (CGM.getCodeGenOpts().EmitCodeView)
236 PP.MSVCFormatting = true;
238 // Apply -fdebug-prefix-map.
239 PP.Callbacks = &PrintCB;
243 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
244 assert(FD && "Invalid FunctionDecl!");
245 IdentifierInfo *FII = FD->getIdentifier();
246 FunctionTemplateSpecializationInfo *Info =
247 FD->getTemplateSpecializationInfo();
249 // Emit the unqualified name in normal operation. LLVM and the debugger can
250 // compute the fully qualified name from the scope chain. If we're only
251 // emitting line table info, there won't be any scope chains, so emit the
252 // fully qualified name here so that stack traces are more accurate.
253 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
254 // evaluating the size impact.
255 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
256 CGM.getCodeGenOpts().EmitCodeView;
258 if (!Info && FII && !UseQualifiedName)
259 return FII->getName();
262 llvm::raw_svector_ostream OS(NS);
263 if (!UseQualifiedName)
266 FD->printQualifiedName(OS, getPrintingPolicy());
268 // Add any template specialization args.
270 const TemplateArgumentList *TArgs = Info->TemplateArguments;
271 printTemplateArgumentList(OS, TArgs->asArray(), getPrintingPolicy());
274 // Copy this name on the side and use its reference.
275 return internString(OS.str());
278 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
279 SmallString<256> MethodName;
280 llvm::raw_svector_ostream OS(MethodName);
281 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
282 const DeclContext *DC = OMD->getDeclContext();
283 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
284 OS << OID->getName();
285 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
286 OS << OID->getName();
287 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
288 if (OC->IsClassExtension()) {
289 OS << OC->getClassInterface()->getName();
291 OS << OC->getIdentifier()->getNameStart() << '('
292 << OC->getIdentifier()->getNameStart() << ')';
294 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
295 OS << OCD->getClassInterface()->getName() << '(' << OCD->getName() << ')';
297 OS << ' ' << OMD->getSelector().getAsString() << ']';
299 return internString(OS.str());
302 StringRef CGDebugInfo::getSelectorName(Selector S) {
303 return internString(S.getAsString());
306 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
307 if (isa<ClassTemplateSpecializationDecl>(RD)) {
308 SmallString<128> Name;
309 llvm::raw_svector_ostream OS(Name);
310 PrintingPolicy PP = getPrintingPolicy();
311 PP.PrintCanonicalTypes = true;
312 RD->getNameForDiagnostic(OS, PP,
313 /*Qualified*/ false);
315 // Copy this name on the side and use its reference.
316 return internString(Name);
319 // quick optimization to avoid having to intern strings that are already
320 // stored reliably elsewhere
321 if (const IdentifierInfo *II = RD->getIdentifier())
322 return II->getName();
324 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
325 // used to reconstruct the fully qualified type names.
326 if (CGM.getCodeGenOpts().EmitCodeView) {
327 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
328 assert(RD->getDeclContext() == D->getDeclContext() &&
329 "Typedef should not be in another decl context!");
330 assert(D->getDeclName().getAsIdentifierInfo() &&
331 "Typedef was not named!");
332 return D->getDeclName().getAsIdentifierInfo()->getName();
335 if (CGM.getLangOpts().CPlusPlus) {
338 ASTContext &Context = CGM.getContext();
339 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
340 // Anonymous types without a name for linkage purposes have their
341 // declarator mangled in if they have one.
342 Name = DD->getName();
343 else if (const TypedefNameDecl *TND =
344 Context.getTypedefNameForUnnamedTagDecl(RD))
345 // Anonymous types without a name for linkage purposes have their
346 // associate typedef mangled in if they have one.
347 Name = TND->getName();
350 SmallString<256> UnnamedType("<unnamed-type-");
353 return internString(UnnamedType);
361 Optional<llvm::DIFile::ChecksumKind>
362 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
365 if (!CGM.getCodeGenOpts().EmitCodeView &&
366 CGM.getCodeGenOpts().DwarfVersion < 5)
369 SourceManager &SM = CGM.getContext().getSourceManager();
371 const llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
376 llvm::MD5::MD5Result Result;
378 Hash.update(MemBuffer->getBuffer());
381 Hash.stringifyResult(Result, Checksum);
382 return llvm::DIFile::CSK_MD5;
385 Optional<StringRef> CGDebugInfo::getSource(const SourceManager &SM,
387 if (!CGM.getCodeGenOpts().EmbedSource)
390 bool SourceInvalid = false;
391 StringRef Source = SM.getBufferData(FID, &SourceInvalid);
399 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
401 // If Location is not valid then use main input file.
402 return TheCU->getFile();
404 SourceManager &SM = CGM.getContext().getSourceManager();
405 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
407 StringRef FileName = PLoc.getFilename();
408 if (PLoc.isInvalid() || FileName.empty())
409 // If the location is not valid then use main input file.
410 return TheCU->getFile();
412 // Cache the results.
413 auto It = DIFileCache.find(FileName.data());
414 if (It != DIFileCache.end()) {
415 // Verify that the information still exists.
416 if (llvm::Metadata *V = It->second)
417 return cast<llvm::DIFile>(V);
420 SmallString<32> Checksum;
422 // Compute the checksum if possible. If the location is affected by a #line
423 // directive that refers to a file, PLoc will have an invalid FileID, and we
424 // will correctly get no checksum.
425 Optional<llvm::DIFile::ChecksumKind> CSKind =
426 computeChecksum(PLoc.getFileID(), Checksum);
427 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
429 CSInfo.emplace(*CSKind, Checksum);
430 return createFile(FileName, CSInfo, getSource(SM, SM.getFileID(Loc)));
434 CGDebugInfo::createFile(StringRef FileName,
435 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo,
436 Optional<StringRef> Source) {
439 std::string RemappedFile = remapDIPath(FileName);
440 std::string CurDir = remapDIPath(getCurrentDirname());
441 SmallString<128> DirBuf;
442 SmallString<128> FileBuf;
443 if (llvm::sys::path::is_absolute(RemappedFile)) {
444 // Strip the common prefix (if it is more than just "/") from current
445 // directory and FileName for a more space-efficient encoding.
446 auto FileIt = llvm::sys::path::begin(RemappedFile);
447 auto FileE = llvm::sys::path::end(RemappedFile);
448 auto CurDirIt = llvm::sys::path::begin(CurDir);
449 auto CurDirE = llvm::sys::path::end(CurDir);
450 for (; CurDirIt != CurDirE && *CurDirIt == *FileIt; ++CurDirIt, ++FileIt)
451 llvm::sys::path::append(DirBuf, *CurDirIt);
452 if (std::distance(llvm::sys::path::begin(CurDir), CurDirIt) == 1) {
453 // Don't strip the common prefix if it is only the root "/"
454 // since that would make LLVM diagnostic locations confusing.
458 for (; FileIt != FileE; ++FileIt)
459 llvm::sys::path::append(FileBuf, *FileIt);
467 llvm::DIFile *F = DBuilder.createFile(File, Dir, CSInfo, Source);
468 DIFileCache[FileName.data()].reset(F);
472 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
473 for (const auto &Entry : DebugPrefixMap)
474 if (Path.startswith(Entry.first))
475 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
479 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
480 if (Loc.isInvalid() && CurLoc.isInvalid())
482 SourceManager &SM = CGM.getContext().getSourceManager();
483 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
484 return PLoc.isValid() ? PLoc.getLine() : 0;
487 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
488 // We may not want column information at all.
489 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
492 // If the location is invalid then use the current column.
493 if (Loc.isInvalid() && CurLoc.isInvalid())
495 SourceManager &SM = CGM.getContext().getSourceManager();
496 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
497 return PLoc.isValid() ? PLoc.getColumn() : 0;
500 StringRef CGDebugInfo::getCurrentDirname() {
501 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
502 return CGM.getCodeGenOpts().DebugCompilationDir;
504 if (!CWDName.empty())
506 SmallString<256> CWD;
507 llvm::sys::fs::current_path(CWD);
508 return CWDName = internString(CWD);
511 void CGDebugInfo::CreateCompileUnit() {
512 SmallString<32> Checksum;
513 Optional<llvm::DIFile::ChecksumKind> CSKind;
514 Optional<llvm::DIFile::ChecksumInfo<StringRef>> CSInfo;
516 // Should we be asking the SourceManager for the main file name, instead of
517 // accepting it as an argument? This just causes the main file name to
518 // mismatch with source locations and create extra lexical scopes or
519 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
520 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
521 // because that's what the SourceManager says)
523 // Get absolute path name.
524 SourceManager &SM = CGM.getContext().getSourceManager();
525 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
526 if (MainFileName.empty())
527 MainFileName = "<stdin>";
529 // The main file name provided via the "-main-file-name" option contains just
530 // the file name itself with no path information. This file name may have had
531 // a relative path, so we look into the actual file entry for the main
532 // file to determine the real absolute path for the file.
533 std::string MainFileDir;
534 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
535 MainFileDir = MainFile->getDir()->getName();
536 if (!llvm::sys::path::is_absolute(MainFileName)) {
537 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
538 llvm::sys::path::append(MainFileDirSS, MainFileName);
539 MainFileName = llvm::sys::path::remove_leading_dotslash(MainFileDirSS);
541 // If the main file name provided is identical to the input file name, and
542 // if the input file is a preprocessed source, use the module name for
543 // debug info. The module name comes from the name specified in the first
544 // linemarker if the input is a preprocessed source.
545 if (MainFile->getName() == MainFileName &&
546 FrontendOptions::getInputKindForExtension(
547 MainFile->getName().rsplit('.').second)
549 MainFileName = CGM.getModule().getName().str();
551 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
554 llvm::dwarf::SourceLanguage LangTag;
555 const LangOptions &LO = CGM.getLangOpts();
558 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
559 else if (LO.CPlusPlus14)
560 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_14;
561 else if (LO.CPlusPlus11)
562 LangTag = llvm::dwarf::DW_LANG_C_plus_plus_11;
564 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
565 } else if (LO.ObjC) {
566 LangTag = llvm::dwarf::DW_LANG_ObjC;
567 } else if (LO.RenderScript) {
568 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
570 LangTag = llvm::dwarf::DW_LANG_C99;
572 LangTag = llvm::dwarf::DW_LANG_C89;
575 std::string Producer = getClangFullVersion();
577 // Figure out which version of the ObjC runtime we have.
578 unsigned RuntimeVers = 0;
580 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
582 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
584 case codegenoptions::NoDebugInfo:
585 case codegenoptions::LocTrackingOnly:
586 EmissionKind = llvm::DICompileUnit::NoDebug;
588 case codegenoptions::DebugLineTablesOnly:
589 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
591 case codegenoptions::DebugDirectivesOnly:
592 EmissionKind = llvm::DICompileUnit::DebugDirectivesOnly;
594 case codegenoptions::DebugInfoConstructor:
595 case codegenoptions::LimitedDebugInfo:
596 case codegenoptions::FullDebugInfo:
597 EmissionKind = llvm::DICompileUnit::FullDebug;
602 auto &CGOpts = CGM.getCodeGenOpts();
603 // The DIFile used by the CU is distinct from the main source
604 // file. Its directory part specifies what becomes the
605 // DW_AT_comp_dir (the compilation directory), even if the source
606 // file was specified with an absolute path.
608 CSInfo.emplace(*CSKind, Checksum);
609 llvm::DIFile *CUFile = DBuilder.createFile(
610 remapDIPath(MainFileName), remapDIPath(getCurrentDirname()), CSInfo,
611 getSource(SM, SM.getMainFileID()));
613 // Create new compile unit.
614 TheCU = DBuilder.createCompileUnit(
615 LangTag, CUFile, CGOpts.EmitVersionIdentMetadata ? Producer : "",
616 LO.Optimize || CGOpts.PrepareForLTO || CGOpts.PrepareForThinLTO,
617 CGOpts.DwarfDebugFlags, RuntimeVers, CGOpts.SplitDwarfFile, EmissionKind,
618 DwoId, CGOpts.SplitDwarfInlining, CGOpts.DebugInfoForProfiling,
619 CGM.getTarget().getTriple().isNVPTX()
620 ? llvm::DICompileUnit::DebugNameTableKind::None
621 : static_cast<llvm::DICompileUnit::DebugNameTableKind>(
622 CGOpts.DebugNameTable),
623 CGOpts.DebugRangesBaseAddress);
626 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
627 llvm::dwarf::TypeKind Encoding;
629 switch (BT->getKind()) {
630 #define BUILTIN_TYPE(Id, SingletonId)
631 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
632 #include "clang/AST/BuiltinTypes.def"
633 case BuiltinType::Dependent:
634 llvm_unreachable("Unexpected builtin type");
635 case BuiltinType::NullPtr:
636 return DBuilder.createNullPtrType();
637 case BuiltinType::Void:
639 case BuiltinType::ObjCClass:
642 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
643 "objc_class", TheCU, TheCU->getFile(), 0);
645 case BuiltinType::ObjCId: {
646 // typedef struct objc_class *Class;
647 // typedef struct objc_object {
656 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
657 "objc_class", TheCU, TheCU->getFile(), 0);
659 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
661 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
663 ObjTy = DBuilder.createStructType(TheCU, "objc_object", TheCU->getFile(), 0,
664 0, 0, llvm::DINode::FlagZero, nullptr,
665 llvm::DINodeArray());
667 DBuilder.replaceArrays(
668 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
669 ObjTy, "isa", TheCU->getFile(), 0, Size, 0, 0,
670 llvm::DINode::FlagZero, ISATy)));
673 case BuiltinType::ObjCSel: {
675 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
676 "objc_selector", TheCU,
677 TheCU->getFile(), 0);
681 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
682 case BuiltinType::Id: \
683 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
685 #include "clang/Basic/OpenCLImageTypes.def"
686 case BuiltinType::OCLSampler:
687 return getOrCreateStructPtrType("opencl_sampler_t", OCLSamplerDITy);
688 case BuiltinType::OCLEvent:
689 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
690 case BuiltinType::OCLClkEvent:
691 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
692 case BuiltinType::OCLQueue:
693 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
694 case BuiltinType::OCLReserveID:
695 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
696 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
697 case BuiltinType::Id: \
698 return getOrCreateStructPtrType("opencl_" #ExtType, Id##Ty);
699 #include "clang/Basic/OpenCLExtensionTypes.def"
700 // TODO: real support for SVE types requires more infrastructure
701 // to be added first. The types have a variable length and are
702 // represented in debug info as types whose length depends on a
703 // target-specific pseudo register.
704 #define SVE_TYPE(Name, Id, SingletonId) \
705 case BuiltinType::Id:
706 #include "clang/Basic/AArch64SVEACLETypes.def"
708 unsigned DiagID = CGM.getDiags().getCustomDiagID(
709 DiagnosticsEngine::Error,
710 "cannot yet generate debug info for SVE type '%0'");
711 auto Name = BT->getName(CGM.getContext().getPrintingPolicy());
712 CGM.getDiags().Report(DiagID) << Name;
713 // Return something safe.
714 return CreateType(cast<const BuiltinType>(CGM.getContext().IntTy));
717 case BuiltinType::UChar:
718 case BuiltinType::Char_U:
719 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
721 case BuiltinType::Char_S:
722 case BuiltinType::SChar:
723 Encoding = llvm::dwarf::DW_ATE_signed_char;
725 case BuiltinType::Char8:
726 case BuiltinType::Char16:
727 case BuiltinType::Char32:
728 Encoding = llvm::dwarf::DW_ATE_UTF;
730 case BuiltinType::UShort:
731 case BuiltinType::UInt:
732 case BuiltinType::UInt128:
733 case BuiltinType::ULong:
734 case BuiltinType::WChar_U:
735 case BuiltinType::ULongLong:
736 Encoding = llvm::dwarf::DW_ATE_unsigned;
738 case BuiltinType::Short:
739 case BuiltinType::Int:
740 case BuiltinType::Int128:
741 case BuiltinType::Long:
742 case BuiltinType::WChar_S:
743 case BuiltinType::LongLong:
744 Encoding = llvm::dwarf::DW_ATE_signed;
746 case BuiltinType::Bool:
747 Encoding = llvm::dwarf::DW_ATE_boolean;
749 case BuiltinType::Half:
750 case BuiltinType::Float:
751 case BuiltinType::LongDouble:
752 case BuiltinType::Float16:
753 case BuiltinType::Float128:
754 case BuiltinType::Double:
755 // FIXME: For targets where long double and __float128 have the same size,
756 // they are currently indistinguishable in the debugger without some
757 // special treatment. However, there is currently no consensus on encoding
758 // and this should be updated once a DWARF encoding exists for distinct
759 // floating point types of the same size.
760 Encoding = llvm::dwarf::DW_ATE_float;
762 case BuiltinType::ShortAccum:
763 case BuiltinType::Accum:
764 case BuiltinType::LongAccum:
765 case BuiltinType::ShortFract:
766 case BuiltinType::Fract:
767 case BuiltinType::LongFract:
768 case BuiltinType::SatShortFract:
769 case BuiltinType::SatFract:
770 case BuiltinType::SatLongFract:
771 case BuiltinType::SatShortAccum:
772 case BuiltinType::SatAccum:
773 case BuiltinType::SatLongAccum:
774 Encoding = llvm::dwarf::DW_ATE_signed_fixed;
776 case BuiltinType::UShortAccum:
777 case BuiltinType::UAccum:
778 case BuiltinType::ULongAccum:
779 case BuiltinType::UShortFract:
780 case BuiltinType::UFract:
781 case BuiltinType::ULongFract:
782 case BuiltinType::SatUShortAccum:
783 case BuiltinType::SatUAccum:
784 case BuiltinType::SatULongAccum:
785 case BuiltinType::SatUShortFract:
786 case BuiltinType::SatUFract:
787 case BuiltinType::SatULongFract:
788 Encoding = llvm::dwarf::DW_ATE_unsigned_fixed;
792 switch (BT->getKind()) {
793 case BuiltinType::Long:
796 case BuiltinType::LongLong:
797 BTName = "long long int";
799 case BuiltinType::ULong:
800 BTName = "long unsigned int";
802 case BuiltinType::ULongLong:
803 BTName = "long long unsigned int";
806 BTName = BT->getName(CGM.getLangOpts());
809 // Bit size and offset of the type.
810 uint64_t Size = CGM.getContext().getTypeSize(BT);
811 return DBuilder.createBasicType(BTName, Size, Encoding);
814 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
815 // Bit size and offset of the type.
816 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
817 if (Ty->isComplexIntegerType())
818 Encoding = llvm::dwarf::DW_ATE_lo_user;
820 uint64_t Size = CGM.getContext().getTypeSize(Ty);
821 return DBuilder.createBasicType("complex", Size, Encoding);
824 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
825 llvm::DIFile *Unit) {
826 QualifierCollector Qc;
827 const Type *T = Qc.strip(Ty);
829 // Ignore these qualifiers for now.
830 Qc.removeObjCGCAttr();
831 Qc.removeAddressSpace();
832 Qc.removeObjCLifetime();
834 // We will create one Derived type for one qualifier and recurse to handle any
836 llvm::dwarf::Tag Tag;
838 Tag = llvm::dwarf::DW_TAG_const_type;
840 } else if (Qc.hasVolatile()) {
841 Tag = llvm::dwarf::DW_TAG_volatile_type;
843 } else if (Qc.hasRestrict()) {
844 Tag = llvm::dwarf::DW_TAG_restrict_type;
847 assert(Qc.empty() && "Unknown type qualifier for debug info");
848 return getOrCreateType(QualType(T, 0), Unit);
851 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
853 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
854 // CVR derived types.
855 return DBuilder.createQualifiedType(Tag, FromTy);
858 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
859 llvm::DIFile *Unit) {
861 // The frontend treats 'id' as a typedef to an ObjCObjectType,
862 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
863 // debug info, we want to emit 'id' in both cases.
864 if (Ty->isObjCQualifiedIdType())
865 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
867 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
868 Ty->getPointeeType(), Unit);
871 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
872 llvm::DIFile *Unit) {
873 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
874 Ty->getPointeeType(), Unit);
877 /// \return whether a C++ mangling exists for the type defined by TD.
878 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
879 switch (TheCU->getSourceLanguage()) {
880 case llvm::dwarf::DW_LANG_C_plus_plus:
881 case llvm::dwarf::DW_LANG_C_plus_plus_11:
882 case llvm::dwarf::DW_LANG_C_plus_plus_14:
884 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
885 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
891 // Determines if the debug info for this tag declaration needs a type
892 // identifier. The purpose of the unique identifier is to deduplicate type
893 // information for identical types across TUs. Because of the C++ one definition
894 // rule (ODR), it is valid to assume that the type is defined the same way in
895 // every TU and its debug info is equivalent.
897 // C does not have the ODR, and it is common for codebases to contain multiple
898 // different definitions of a struct with the same name in different TUs.
899 // Therefore, if the type doesn't have a C++ mangling, don't give it an
900 // identifer. Type information in C is smaller and simpler than C++ type
901 // information, so the increase in debug info size is negligible.
903 // If the type is not externally visible, it should be unique to the current TU,
904 // and should not need an identifier to participate in type deduplication.
905 // However, when emitting CodeView, the format internally uses these
906 // unique type name identifers for references between debug info. For example,
907 // the method of a class in an anonymous namespace uses the identifer to refer
908 // to its parent class. The Microsoft C++ ABI attempts to provide unique names
909 // for such types, so when emitting CodeView, always use identifiers for C++
910 // types. This may create problems when attempting to emit CodeView when the MS
911 // C++ ABI is not in use.
912 static bool needsTypeIdentifier(const TagDecl *TD, CodeGenModule &CGM,
913 llvm::DICompileUnit *TheCU) {
914 // We only add a type identifier for types with C++ name mangling.
915 if (!hasCXXMangling(TD, TheCU))
918 // Externally visible types with C++ mangling need a type identifier.
919 if (TD->isExternallyVisible())
922 // CodeView types with C++ mangling need a type identifier.
923 if (CGM.getCodeGenOpts().EmitCodeView)
929 // Returns a unique type identifier string if one exists, or an empty string.
930 static SmallString<256> getTypeIdentifier(const TagType *Ty, CodeGenModule &CGM,
931 llvm::DICompileUnit *TheCU) {
932 SmallString<256> Identifier;
933 const TagDecl *TD = Ty->getDecl();
935 if (!needsTypeIdentifier(TD, CGM, TheCU))
937 if (const auto *RD = dyn_cast<CXXRecordDecl>(TD))
938 if (RD->getDefinition())
939 if (RD->isDynamicClass() &&
940 CGM.getVTableLinkage(RD) == llvm::GlobalValue::ExternalLinkage)
943 // TODO: This is using the RTTI name. Is there a better way to get
944 // a unique string for a type?
945 llvm::raw_svector_ostream Out(Identifier);
946 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
950 /// \return the appropriate DWARF tag for a composite type.
951 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
952 llvm::dwarf::Tag Tag;
953 if (RD->isStruct() || RD->isInterface())
954 Tag = llvm::dwarf::DW_TAG_structure_type;
955 else if (RD->isUnion())
956 Tag = llvm::dwarf::DW_TAG_union_type;
958 // FIXME: This could be a struct type giving a default visibility different
959 // than C++ class type, but needs llvm metadata changes first.
960 assert(RD->isClass());
961 Tag = llvm::dwarf::DW_TAG_class_type;
966 llvm::DICompositeType *
967 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
968 llvm::DIScope *Ctx) {
969 const RecordDecl *RD = Ty->getDecl();
970 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
971 return cast<llvm::DICompositeType>(T);
972 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
973 unsigned Line = getLineNumber(RD->getLocation());
974 StringRef RDName = getClassName(RD);
980 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
981 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
982 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
983 llvm::DINode::FlagFwdDecl, Identifier);
984 if (CGM.getCodeGenOpts().DebugFwdTemplateParams)
985 if (auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
986 DBuilder.replaceArrays(RetTy, llvm::DINodeArray(),
987 CollectCXXTemplateParams(TSpecial, DefUnit));
988 ReplaceMap.emplace_back(
989 std::piecewise_construct, std::make_tuple(Ty),
990 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
994 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
997 llvm::DIFile *Unit) {
998 // Bit size, align and offset of the type.
999 // Size is always the size of a pointer. We can't use getTypeSize here
1000 // because that does not return the correct value for references.
1001 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(PointeeTy);
1002 uint64_t Size = CGM.getTarget().getPointerWidth(AddressSpace);
1003 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
1004 Optional<unsigned> DWARFAddressSpace =
1005 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
1007 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
1008 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
1009 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
1010 Size, Align, DWARFAddressSpace);
1012 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
1013 Align, DWARFAddressSpace);
1016 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
1017 llvm::DIType *&Cache) {
1020 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
1021 TheCU, TheCU->getFile(), 0);
1022 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1023 Cache = DBuilder.createPointerType(Cache, Size);
1027 uint64_t CGDebugInfo::collectDefaultElementTypesForBlockPointer(
1028 const BlockPointerType *Ty, llvm::DIFile *Unit, llvm::DIDerivedType *DescTy,
1029 unsigned LineNo, SmallVectorImpl<llvm::Metadata *> &EltTys) {
1032 // Advanced by calls to CreateMemberType in increments of FType, then
1033 // returned as the overall size of the default elements.
1034 uint64_t FieldOffset = 0;
1036 // Blocks in OpenCL have unique constraints which make the standard fields
1037 // redundant while requiring size and align fields for enqueue_kernel. See
1038 // initializeForBlockHeader in CGBlocks.cpp
1039 if (CGM.getLangOpts().OpenCL) {
1040 FType = CGM.getContext().IntTy;
1041 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1042 EltTys.push_back(CreateMemberType(Unit, FType, "__align", &FieldOffset));
1044 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1045 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1046 FType = CGM.getContext().IntTy;
1047 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1048 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
1049 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
1050 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
1051 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1052 uint64_t FieldSize = CGM.getContext().getTypeSize(Ty);
1053 uint32_t FieldAlign = CGM.getContext().getTypeAlign(Ty);
1054 EltTys.push_back(DBuilder.createMemberType(
1055 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign,
1056 FieldOffset, llvm::DINode::FlagZero, DescTy));
1057 FieldOffset += FieldSize;
1063 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
1064 llvm::DIFile *Unit) {
1065 SmallVector<llvm::Metadata *, 8> EltTys;
1067 uint64_t FieldOffset;
1068 llvm::DINodeArray Elements;
1071 FType = CGM.getContext().UnsignedLongTy;
1072 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
1073 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
1075 Elements = DBuilder.getOrCreateArray(EltTys);
1078 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
1081 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, 0,
1082 FieldOffset, 0, Flags, nullptr, Elements);
1084 // Bit size, align and offset of the type.
1085 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1087 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
1089 FieldOffset = collectDefaultElementTypesForBlockPointer(Ty, Unit, DescTy,
1092 Elements = DBuilder.getOrCreateArray(EltTys);
1094 // The __block_literal_generic structs are marked with a special
1095 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
1096 // the debugger needs to know about. To allow type uniquing, emit
1097 // them without a name or a location.
1098 EltTy = DBuilder.createStructType(Unit, "", nullptr, 0, FieldOffset, 0,
1099 Flags, nullptr, Elements);
1101 return DBuilder.createPointerType(EltTy, Size);
1104 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
1105 llvm::DIFile *Unit) {
1106 assert(Ty->isTypeAlias());
1107 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
1110 cast<TypeAliasTemplateDecl>(Ty->getTemplateName().getAsTemplateDecl())
1111 ->getTemplatedDecl();
1113 if (AliasDecl->hasAttr<NoDebugAttr>())
1116 SmallString<128> NS;
1117 llvm::raw_svector_ostream OS(NS);
1118 Ty->getTemplateName().print(OS, getPrintingPolicy(), /*qualified*/ false);
1119 printTemplateArgumentList(OS, Ty->template_arguments(), getPrintingPolicy());
1121 SourceLocation Loc = AliasDecl->getLocation();
1122 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
1124 getDeclContextDescriptor(AliasDecl));
1127 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
1128 llvm::DIFile *Unit) {
1129 llvm::DIType *Underlying =
1130 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
1132 if (Ty->getDecl()->hasAttr<NoDebugAttr>())
1135 // We don't set size information, but do specify where the typedef was
1137 SourceLocation Loc = Ty->getDecl()->getLocation();
1139 uint32_t Align = getDeclAlignIfRequired(Ty->getDecl(), CGM.getContext());
1140 // Typedefs are derived from some other type.
1141 return DBuilder.createTypedef(Underlying, Ty->getDecl()->getName(),
1142 getOrCreateFile(Loc), getLineNumber(Loc),
1143 getDeclContextDescriptor(Ty->getDecl()), Align);
1146 static unsigned getDwarfCC(CallingConv CC) {
1149 // Avoid emitting DW_AT_calling_convention if the C convention was used.
1153 return llvm::dwarf::DW_CC_BORLAND_stdcall;
1154 case CC_X86FastCall:
1155 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
1156 case CC_X86ThisCall:
1157 return llvm::dwarf::DW_CC_BORLAND_thiscall;
1158 case CC_X86VectorCall:
1159 return llvm::dwarf::DW_CC_LLVM_vectorcall;
1161 return llvm::dwarf::DW_CC_BORLAND_pascal;
1163 return llvm::dwarf::DW_CC_LLVM_Win64;
1165 return llvm::dwarf::DW_CC_LLVM_X86_64SysV;
1167 case CC_AArch64VectorCall:
1168 return llvm::dwarf::DW_CC_LLVM_AAPCS;
1170 return llvm::dwarf::DW_CC_LLVM_AAPCS_VFP;
1171 case CC_IntelOclBicc:
1172 return llvm::dwarf::DW_CC_LLVM_IntelOclBicc;
1173 case CC_SpirFunction:
1174 return llvm::dwarf::DW_CC_LLVM_SpirFunction;
1175 case CC_OpenCLKernel:
1176 return llvm::dwarf::DW_CC_LLVM_OpenCLKernel;
1178 return llvm::dwarf::DW_CC_LLVM_Swift;
1179 case CC_PreserveMost:
1180 return llvm::dwarf::DW_CC_LLVM_PreserveMost;
1181 case CC_PreserveAll:
1182 return llvm::dwarf::DW_CC_LLVM_PreserveAll;
1184 return llvm::dwarf::DW_CC_LLVM_X86RegCall;
1189 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
1190 llvm::DIFile *Unit) {
1191 SmallVector<llvm::Metadata *, 16> EltTys;
1193 // Add the result type at least.
1194 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
1196 // Set up remainder of arguments if there is a prototype.
1197 // otherwise emit it as a variadic function.
1198 if (isa<FunctionNoProtoType>(Ty))
1199 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1200 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
1201 for (const QualType &ParamType : FPT->param_types())
1202 EltTys.push_back(getOrCreateType(ParamType, Unit));
1203 if (FPT->isVariadic())
1204 EltTys.push_back(DBuilder.createUnspecifiedParameter());
1207 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
1208 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
1209 getDwarfCC(Ty->getCallConv()));
1212 /// Convert an AccessSpecifier into the corresponding DINode flag.
1213 /// As an optimization, return 0 if the access specifier equals the
1214 /// default for the containing type.
1215 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
1216 const RecordDecl *RD) {
1217 AccessSpecifier Default = clang::AS_none;
1218 if (RD && RD->isClass())
1219 Default = clang::AS_private;
1220 else if (RD && (RD->isStruct() || RD->isUnion()))
1221 Default = clang::AS_public;
1223 if (Access == Default)
1224 return llvm::DINode::FlagZero;
1227 case clang::AS_private:
1228 return llvm::DINode::FlagPrivate;
1229 case clang::AS_protected:
1230 return llvm::DINode::FlagProtected;
1231 case clang::AS_public:
1232 return llvm::DINode::FlagPublic;
1233 case clang::AS_none:
1234 return llvm::DINode::FlagZero;
1236 llvm_unreachable("unexpected access enumerator");
1239 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
1240 llvm::DIScope *RecordTy,
1241 const RecordDecl *RD) {
1242 StringRef Name = BitFieldDecl->getName();
1243 QualType Ty = BitFieldDecl->getType();
1244 SourceLocation Loc = BitFieldDecl->getLocation();
1245 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1246 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1248 // Get the location for the field.
1249 llvm::DIFile *File = getOrCreateFile(Loc);
1250 unsigned Line = getLineNumber(Loc);
1252 const CGBitFieldInfo &BitFieldInfo =
1253 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1254 uint64_t SizeInBits = BitFieldInfo.Size;
1255 assert(SizeInBits > 0 && "found named 0-width bitfield");
1256 uint64_t StorageOffsetInBits =
1257 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1258 uint64_t Offset = BitFieldInfo.Offset;
1259 // The bit offsets for big endian machines are reversed for big
1260 // endian target, compensate for that as the DIDerivedType requires
1261 // un-reversed offsets.
1262 if (CGM.getDataLayout().isBigEndian())
1263 Offset = BitFieldInfo.StorageSize - BitFieldInfo.Size - Offset;
1264 uint64_t OffsetInBits = StorageOffsetInBits + Offset;
1265 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1266 return DBuilder.createBitFieldMemberType(
1267 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1272 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1273 AccessSpecifier AS, uint64_t offsetInBits,
1274 uint32_t AlignInBits, llvm::DIFile *tunit,
1275 llvm::DIScope *scope, const RecordDecl *RD) {
1276 llvm::DIType *debugType = getOrCreateType(type, tunit);
1278 // Get the location for the field.
1279 llvm::DIFile *file = getOrCreateFile(loc);
1280 unsigned line = getLineNumber(loc);
1282 uint64_t SizeInBits = 0;
1283 auto Align = AlignInBits;
1284 if (!type->isIncompleteArrayType()) {
1285 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1286 SizeInBits = TI.Width;
1288 Align = getTypeAlignIfRequired(type, CGM.getContext());
1291 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1292 return DBuilder.createMemberType(scope, name, file, line, SizeInBits, Align,
1293 offsetInBits, flags, debugType);
1296 void CGDebugInfo::CollectRecordLambdaFields(
1297 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1298 llvm::DIType *RecordTy) {
1299 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1300 // has the name and the location of the variable so we should iterate over
1301 // both concurrently.
1302 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1303 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1304 unsigned fieldno = 0;
1305 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1306 E = CXXDecl->captures_end();
1307 I != E; ++I, ++Field, ++fieldno) {
1308 const LambdaCapture &C = *I;
1309 if (C.capturesVariable()) {
1310 SourceLocation Loc = C.getLocation();
1311 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1312 VarDecl *V = C.getCapturedVar();
1313 StringRef VName = V->getName();
1314 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1315 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1316 llvm::DIType *FieldType = createFieldType(
1317 VName, Field->getType(), Loc, Field->getAccess(),
1318 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1319 elements.push_back(FieldType);
1320 } else if (C.capturesThis()) {
1321 // TODO: Need to handle 'this' in some way by probably renaming the
1322 // this of the lambda class and having a field member of 'this' or
1323 // by using AT_object_pointer for the function and having that be
1324 // used as 'this' for semantic references.
1325 FieldDecl *f = *Field;
1326 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1327 QualType type = f->getType();
1328 llvm::DIType *fieldType = createFieldType(
1329 "this", type, f->getLocation(), f->getAccess(),
1330 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1332 elements.push_back(fieldType);
1337 llvm::DIDerivedType *
1338 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1339 const RecordDecl *RD) {
1340 // Create the descriptor for the static variable, with or without
1341 // constant initializers.
1342 Var = Var->getCanonicalDecl();
1343 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1344 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1346 unsigned LineNumber = getLineNumber(Var->getLocation());
1347 StringRef VName = Var->getName();
1348 llvm::Constant *C = nullptr;
1349 if (Var->getInit()) {
1350 const APValue *Value = Var->evaluateValue();
1353 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1354 if (Value->isFloat())
1355 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1359 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1360 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1361 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1362 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1363 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1367 void CGDebugInfo::CollectRecordNormalField(
1368 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1369 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1370 const RecordDecl *RD) {
1371 StringRef name = field->getName();
1372 QualType type = field->getType();
1374 // Ignore unnamed fields unless they're anonymous structs/unions.
1375 if (name.empty() && !type->isRecordType())
1378 llvm::DIType *FieldType;
1379 if (field->isBitField()) {
1380 FieldType = createBitFieldType(field, RecordTy, RD);
1382 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1384 createFieldType(name, type, field->getLocation(), field->getAccess(),
1385 OffsetInBits, Align, tunit, RecordTy, RD);
1388 elements.push_back(FieldType);
1391 void CGDebugInfo::CollectRecordNestedType(
1392 const TypeDecl *TD, SmallVectorImpl<llvm::Metadata *> &elements) {
1393 QualType Ty = CGM.getContext().getTypeDeclType(TD);
1394 // Injected class names are not considered nested records.
1395 if (isa<InjectedClassNameType>(Ty))
1397 SourceLocation Loc = TD->getLocation();
1398 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1399 elements.push_back(nestedType);
1402 void CGDebugInfo::CollectRecordFields(
1403 const RecordDecl *record, llvm::DIFile *tunit,
1404 SmallVectorImpl<llvm::Metadata *> &elements,
1405 llvm::DICompositeType *RecordTy) {
1406 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1408 if (CXXDecl && CXXDecl->isLambda())
1409 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1411 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1413 // Field number for non-static fields.
1414 unsigned fieldNo = 0;
1416 // Static and non-static members should appear in the same order as
1417 // the corresponding declarations in the source program.
1418 for (const auto *I : record->decls())
1419 if (const auto *V = dyn_cast<VarDecl>(I)) {
1420 if (V->hasAttr<NoDebugAttr>())
1423 // Skip variable template specializations when emitting CodeView. MSVC
1424 // doesn't emit them.
1425 if (CGM.getCodeGenOpts().EmitCodeView &&
1426 isa<VarTemplateSpecializationDecl>(V))
1429 if (isa<VarTemplatePartialSpecializationDecl>(V))
1432 // Reuse the existing static member declaration if one exists
1433 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1434 if (MI != StaticDataMemberCache.end()) {
1435 assert(MI->second &&
1436 "Static data member declaration should still exist");
1437 elements.push_back(MI->second);
1439 auto Field = CreateRecordStaticField(V, RecordTy, record);
1440 elements.push_back(Field);
1442 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1443 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1444 elements, RecordTy, record);
1446 // Bump field number for next field.
1448 } else if (CGM.getCodeGenOpts().EmitCodeView) {
1449 // Debug info for nested types is included in the member list only for
1451 if (const auto *nestedType = dyn_cast<TypeDecl>(I))
1452 if (!nestedType->isImplicit() &&
1453 nestedType->getDeclContext() == record)
1454 CollectRecordNestedType(nestedType, elements);
1459 llvm::DISubroutineType *
1460 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1461 llvm::DIFile *Unit) {
1462 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1463 if (Method->isStatic())
1464 return cast_or_null<llvm::DISubroutineType>(
1465 getOrCreateType(QualType(Func, 0), Unit));
1466 return getOrCreateInstanceMethodType(Method->getThisType(), Func, Unit);
1469 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1470 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1471 // Add "this" pointer.
1472 llvm::DITypeRefArray Args(
1473 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1475 assert(Args.size() && "Invalid number of arguments!");
1477 SmallVector<llvm::Metadata *, 16> Elts;
1479 // First element is always return type. For 'void' functions it is NULL.
1480 Elts.push_back(Args[0]);
1482 // "this" pointer is always first argument.
1483 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1484 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1485 // Create pointer type directly in this case.
1486 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1487 QualType PointeeTy = ThisPtrTy->getPointeeType();
1488 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1489 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1490 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1491 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1492 llvm::DIType *ThisPtrType =
1493 DBuilder.createPointerType(PointeeType, Size, Align);
1494 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1495 // TODO: This and the artificial type below are misleading, the
1496 // types aren't artificial the argument is, but the current
1497 // metadata doesn't represent that.
1498 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1499 Elts.push_back(ThisPtrType);
1501 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1502 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1503 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1504 Elts.push_back(ThisPtrType);
1507 // Copy rest of the arguments.
1508 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1509 Elts.push_back(Args[i]);
1511 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1513 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1514 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1515 Flags |= llvm::DINode::FlagLValueReference;
1516 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1517 Flags |= llvm::DINode::FlagRValueReference;
1519 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1520 getDwarfCC(Func->getCallConv()));
1523 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1524 /// inside a function.
1525 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1526 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1527 return isFunctionLocalClass(NRD);
1528 if (isa<FunctionDecl>(RD->getDeclContext()))
1533 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1534 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1536 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1538 StringRef MethodName = getFunctionName(Method);
1539 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1541 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1542 // make sense to give a single ctor/dtor a linkage name.
1543 StringRef MethodLinkageName;
1544 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1545 // property to use here. It may've been intended to model "is non-external
1546 // type" but misses cases of non-function-local but non-external classes such
1547 // as those in anonymous namespaces as well as the reverse - external types
1548 // that are function local, such as those in (non-local) inline functions.
1549 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1550 MethodLinkageName = CGM.getMangledName(Method);
1552 // Get the location for the method.
1553 llvm::DIFile *MethodDefUnit = nullptr;
1554 unsigned MethodLine = 0;
1555 if (!Method->isImplicit()) {
1556 MethodDefUnit = getOrCreateFile(Method->getLocation());
1557 MethodLine = getLineNumber(Method->getLocation());
1560 // Collect virtual method info.
1561 llvm::DIType *ContainingType = nullptr;
1562 unsigned VIndex = 0;
1563 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1564 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
1565 int ThisAdjustment = 0;
1567 if (Method->isVirtual()) {
1568 if (Method->isPure())
1569 SPFlags |= llvm::DISubprogram::SPFlagPureVirtual;
1571 SPFlags |= llvm::DISubprogram::SPFlagVirtual;
1573 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1574 // It doesn't make sense to give a virtual destructor a vtable index,
1575 // since a single destructor has two entries in the vtable.
1576 if (!isa<CXXDestructorDecl>(Method))
1577 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1579 // Emit MS ABI vftable information. There is only one entry for the
1581 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1582 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1583 MethodVFTableLocation ML =
1584 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1587 // CodeView only records the vftable offset in the class that introduces
1588 // the virtual method. This is possible because, unlike Itanium, the MS
1589 // C++ ABI does not include all virtual methods from non-primary bases in
1590 // the vtable for the most derived class. For example, if C inherits from
1591 // A and B, C's primary vftable will not include B's virtual methods.
1592 if (Method->size_overridden_methods() == 0)
1593 Flags |= llvm::DINode::FlagIntroducedVirtual;
1595 // The 'this' adjustment accounts for both the virtual and non-virtual
1596 // portions of the adjustment. Presumably the debugger only uses it when
1597 // it knows the dynamic type of an object.
1598 ThisAdjustment = CGM.getCXXABI()
1599 .getVirtualFunctionPrologueThisAdjustment(GD)
1602 ContainingType = RecordTy;
1605 // We're checking for deleted C++ special member functions
1606 // [Ctors,Dtors, Copy/Move]
1607 auto checkAttrDeleted = [&](const auto *Method) {
1608 if (Method->getCanonicalDecl()->isDeleted())
1609 SPFlags |= llvm::DISubprogram::SPFlagDeleted;
1612 switch (Method->getKind()) {
1614 case Decl::CXXConstructor:
1615 case Decl::CXXDestructor:
1616 checkAttrDeleted(Method);
1618 case Decl::CXXMethod:
1619 if (Method->isCopyAssignmentOperator() ||
1620 Method->isMoveAssignmentOperator())
1621 checkAttrDeleted(Method);
1627 if (Method->isNoReturn())
1628 Flags |= llvm::DINode::FlagNoReturn;
1630 if (Method->isStatic())
1631 Flags |= llvm::DINode::FlagStaticMember;
1632 if (Method->isImplicit())
1633 Flags |= llvm::DINode::FlagArtificial;
1634 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1635 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1636 if (CXXC->isExplicit())
1637 Flags |= llvm::DINode::FlagExplicit;
1638 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1639 if (CXXC->isExplicit())
1640 Flags |= llvm::DINode::FlagExplicit;
1642 if (Method->hasPrototype())
1643 Flags |= llvm::DINode::FlagPrototyped;
1644 if (Method->getRefQualifier() == RQ_LValue)
1645 Flags |= llvm::DINode::FlagLValueReference;
1646 if (Method->getRefQualifier() == RQ_RValue)
1647 Flags |= llvm::DINode::FlagRValueReference;
1648 if (CGM.getLangOpts().Optimize)
1649 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
1651 // In this debug mode, emit type info for a class when its constructor type
1653 if (DebugKind == codegenoptions::DebugInfoConstructor)
1654 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1655 completeClass(CD->getParent());
1657 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1658 llvm::DISubprogram *SP = DBuilder.createMethod(
1659 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1660 MethodTy, VIndex, ThisAdjustment, ContainingType, Flags, SPFlags,
1661 TParamsArray.get());
1663 SPCache[Method->getCanonicalDecl()].reset(SP);
1668 void CGDebugInfo::CollectCXXMemberFunctions(
1669 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1670 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1672 // Since we want more than just the individual member decls if we
1673 // have templated functions iterate over every declaration to gather
1675 for (const auto *I : RD->decls()) {
1676 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1677 // If the member is implicit, don't add it to the member list. This avoids
1678 // the member being added to type units by LLVM, while still allowing it
1679 // to be emitted into the type declaration/reference inside the compile
1681 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1682 // FIXME: Handle Using(Shadow?)Decls here to create
1683 // DW_TAG_imported_declarations inside the class for base decls brought into
1684 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1685 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1687 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1690 if (Method->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
1693 // Reuse the existing member function declaration if it exists.
1694 // It may be associated with the declaration of the type & should be
1695 // reused as we're building the definition.
1697 // This situation can arise in the vtable-based debug info reduction where
1698 // implicit members are emitted in a non-vtable TU.
1699 auto MI = SPCache.find(Method->getCanonicalDecl());
1700 EltTys.push_back(MI == SPCache.end()
1701 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1702 : static_cast<llvm::Metadata *>(MI->second));
1706 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1707 SmallVectorImpl<llvm::Metadata *> &EltTys,
1708 llvm::DIType *RecordTy) {
1709 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1710 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1711 llvm::DINode::FlagZero);
1713 // If we are generating CodeView debug info, we also need to emit records for
1714 // indirect virtual base classes.
1715 if (CGM.getCodeGenOpts().EmitCodeView) {
1716 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1717 llvm::DINode::FlagIndirectVirtualBase);
1721 void CGDebugInfo::CollectCXXBasesAux(
1722 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1723 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1724 const CXXRecordDecl::base_class_const_range &Bases,
1725 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1726 llvm::DINode::DIFlags StartingFlags) {
1727 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1728 for (const auto &BI : Bases) {
1730 cast<CXXRecordDecl>(BI.getType()->castAs<RecordType>()->getDecl());
1731 if (!SeenTypes.insert(Base).second)
1733 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1734 llvm::DINode::DIFlags BFlags = StartingFlags;
1735 uint64_t BaseOffset;
1736 uint32_t VBPtrOffset = 0;
1738 if (BI.isVirtual()) {
1739 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1740 // virtual base offset offset is -ve. The code generator emits dwarf
1741 // expression where it expects +ve number.
1742 BaseOffset = 0 - CGM.getItaniumVTableContext()
1743 .getVirtualBaseOffsetOffset(RD, Base)
1746 // In the MS ABI, store the vbtable offset, which is analogous to the
1747 // vbase offset offset in Itanium.
1749 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1750 VBPtrOffset = CGM.getContext()
1751 .getASTRecordLayout(RD)
1755 BFlags |= llvm::DINode::FlagVirtual;
1757 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1758 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1759 // BI->isVirtual() and bits when not.
1761 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1762 llvm::DIType *DTy = DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset,
1763 VBPtrOffset, BFlags);
1764 EltTys.push_back(DTy);
1769 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1770 ArrayRef<TemplateArgument> TAList,
1771 llvm::DIFile *Unit) {
1772 SmallVector<llvm::Metadata *, 16> TemplateParams;
1773 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1774 const TemplateArgument &TA = TAList[i];
1777 Name = TPList->getParam(i)->getName();
1778 switch (TA.getKind()) {
1779 case TemplateArgument::Type: {
1780 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1781 TemplateParams.push_back(
1782 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1784 case TemplateArgument::Integral: {
1785 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1786 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1788 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1790 case TemplateArgument::Declaration: {
1791 const ValueDecl *D = TA.getAsDecl();
1792 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1793 llvm::DIType *TTy = getOrCreateType(T, Unit);
1794 llvm::Constant *V = nullptr;
1795 // Skip retrieve the value if that template parameter has cuda device
1796 // attribute, i.e. that value is not available at the host side.
1797 if (!CGM.getLangOpts().CUDA || CGM.getLangOpts().CUDAIsDevice ||
1798 !D->hasAttr<CUDADeviceAttr>()) {
1799 const CXXMethodDecl *MD;
1800 // Variable pointer template parameters have a value that is the address
1802 if (const auto *VD = dyn_cast<VarDecl>(D))
1803 V = CGM.GetAddrOfGlobalVar(VD);
1804 // Member function pointers have special support for building them,
1805 // though this is currently unsupported in LLVM CodeGen.
1806 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1807 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1808 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1809 V = CGM.GetAddrOfFunction(FD);
1810 // Member data pointers have special handling too to compute the fixed
1811 // offset within the object.
1812 else if (const auto *MPT =
1813 dyn_cast<MemberPointerType>(T.getTypePtr())) {
1814 // These five lines (& possibly the above member function pointer
1815 // handling) might be able to be refactored to use similar code in
1816 // CodeGenModule::getMemberPointerConstant
1817 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1819 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1820 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1822 assert(V && "Failed to find template parameter pointer");
1823 V = V->stripPointerCasts();
1825 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1826 TheCU, Name, TTy, cast_or_null<llvm::Constant>(V)));
1828 case TemplateArgument::NullPtr: {
1829 QualType T = TA.getNullPtrType();
1830 llvm::DIType *TTy = getOrCreateType(T, Unit);
1831 llvm::Constant *V = nullptr;
1832 // Special case member data pointer null values since they're actually -1
1834 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1835 // But treat member function pointers as simple zero integers because
1836 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1837 // CodeGen grows handling for values of non-null member function
1838 // pointers then perhaps we could remove this special case and rely on
1839 // EmitNullMemberPointer for member function pointers.
1840 if (MPT->isMemberDataPointer())
1841 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1843 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1844 TemplateParams.push_back(
1845 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V));
1847 case TemplateArgument::Template:
1848 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1849 TheCU, Name, nullptr,
1850 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1852 case TemplateArgument::Pack:
1853 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1854 TheCU, Name, nullptr,
1855 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1857 case TemplateArgument::Expression: {
1858 const Expr *E = TA.getAsExpr();
1859 QualType T = E->getType();
1861 T = CGM.getContext().getLValueReferenceType(T);
1862 llvm::Constant *V = ConstantEmitter(CGM).emitAbstract(E, T);
1863 assert(V && "Expression in template argument isn't constant");
1864 llvm::DIType *TTy = getOrCreateType(T, Unit);
1865 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1866 TheCU, Name, TTy, V->stripPointerCasts()));
1868 // And the following should never occur:
1869 case TemplateArgument::TemplateExpansion:
1870 case TemplateArgument::Null:
1872 "These argument types shouldn't exist in concrete types");
1875 return DBuilder.getOrCreateArray(TemplateParams);
1879 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1880 llvm::DIFile *Unit) {
1881 if (FD->getTemplatedKind() ==
1882 FunctionDecl::TK_FunctionTemplateSpecialization) {
1883 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1885 ->getTemplateParameters();
1886 return CollectTemplateParams(
1887 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1889 return llvm::DINodeArray();
1892 llvm::DINodeArray CGDebugInfo::CollectVarTemplateParams(const VarDecl *VL,
1893 llvm::DIFile *Unit) {
1894 // Always get the full list of parameters, not just the ones from the
1895 // specialization. A partial specialization may have fewer parameters than
1896 // there are arguments.
1897 auto *TS = dyn_cast<VarTemplateSpecializationDecl>(VL);
1899 return llvm::DINodeArray();
1900 VarTemplateDecl *T = TS->getSpecializedTemplate();
1901 const TemplateParameterList *TList = T->getTemplateParameters();
1902 auto TA = TS->getTemplateArgs().asArray();
1903 return CollectTemplateParams(TList, TA, Unit);
1906 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1907 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1908 // Always get the full list of parameters, not just the ones from the
1909 // specialization. A partial specialization may have fewer parameters than
1910 // there are arguments.
1911 TemplateParameterList *TPList =
1912 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1913 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1914 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1917 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1919 return VTablePtrType;
1921 ASTContext &Context = CGM.getContext();
1924 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1925 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1926 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1927 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1928 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
1929 Optional<unsigned> DWARFAddressSpace =
1930 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
1932 llvm::DIType *vtbl_ptr_type = DBuilder.createPointerType(
1933 SubTy, Size, 0, DWARFAddressSpace, "__vtbl_ptr_type");
1934 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1935 return VTablePtrType;
1938 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1939 // Copy the gdb compatible name on the side and use its reference.
1940 return internString("_vptr$", RD->getNameAsString());
1943 StringRef CGDebugInfo::getDynamicInitializerName(const VarDecl *VD,
1944 DynamicInitKind StubKind,
1945 llvm::Function *InitFn) {
1946 // If we're not emitting codeview, use the mangled name. For Itanium, this is
1948 if (!CGM.getCodeGenOpts().EmitCodeView)
1949 return InitFn->getName();
1951 // Print the normal qualified name for the variable, then break off the last
1952 // NNS, and add the appropriate other text. Clang always prints the global
1953 // variable name without template arguments, so we can use rsplit("::") and
1954 // then recombine the pieces.
1955 SmallString<128> QualifiedGV;
1959 llvm::raw_svector_ostream OS(QualifiedGV);
1960 VD->printQualifiedName(OS, getPrintingPolicy());
1961 std::tie(Quals, GVName) = OS.str().rsplit("::");
1963 std::swap(Quals, GVName);
1966 SmallString<128> InitName;
1967 llvm::raw_svector_ostream OS(InitName);
1969 OS << Quals << "::";
1972 case DynamicInitKind::NoStub:
1973 llvm_unreachable("not an initializer");
1974 case DynamicInitKind::Initializer:
1975 OS << "`dynamic initializer for '";
1977 case DynamicInitKind::AtExit:
1978 OS << "`dynamic atexit destructor for '";
1984 // Add any template specialization args.
1985 if (const auto *VTpl = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
1986 printTemplateArgumentList(OS, VTpl->getTemplateArgs().asArray(),
1987 getPrintingPolicy());
1992 return internString(OS.str());
1995 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1996 SmallVectorImpl<llvm::Metadata *> &EltTys,
1997 llvm::DICompositeType *RecordTy) {
1998 // If this class is not dynamic then there is not any vtable info to collect.
1999 if (!RD->isDynamicClass())
2002 // Don't emit any vtable shape or vptr info if this class doesn't have an
2003 // extendable vfptr. This can happen if the class doesn't have virtual
2004 // methods, or in the MS ABI if those virtual methods only come from virtually
2006 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2007 if (!RL.hasExtendableVFPtr())
2010 // CodeView needs to know how large the vtable of every dynamic class is, so
2011 // emit a special named pointer type into the element list. The vptr type
2012 // points to this type as well.
2013 llvm::DIType *VPtrTy = nullptr;
2014 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
2015 CGM.getTarget().getCXXABI().isMicrosoft();
2016 if (NeedVTableShape) {
2018 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2019 const VTableLayout &VFTLayout =
2020 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
2021 unsigned VSlotCount =
2022 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
2023 unsigned VTableWidth = PtrWidth * VSlotCount;
2024 unsigned VtblPtrAddressSpace = CGM.getTarget().getVtblPtrAddressSpace();
2025 Optional<unsigned> DWARFAddressSpace =
2026 CGM.getTarget().getDWARFAddressSpace(VtblPtrAddressSpace);
2028 // Create a very wide void* type and insert it directly in the element list.
2029 llvm::DIType *VTableType = DBuilder.createPointerType(
2030 nullptr, VTableWidth, 0, DWARFAddressSpace, "__vtbl_ptr_type");
2031 EltTys.push_back(VTableType);
2033 // The vptr is a pointer to this special vtable type.
2034 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
2037 // If there is a primary base then the artificial vptr member lives there.
2038 if (RL.getPrimaryBase())
2042 VPtrTy = getOrCreateVTablePtrType(Unit);
2044 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
2045 llvm::DIType *VPtrMember =
2046 DBuilder.createMemberType(Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
2047 llvm::DINode::FlagArtificial, VPtrTy);
2048 EltTys.push_back(VPtrMember);
2051 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
2052 SourceLocation Loc) {
2053 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2054 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
2058 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
2059 SourceLocation Loc) {
2060 return getOrCreateStandaloneType(D, Loc);
2063 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
2064 SourceLocation Loc) {
2065 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
2066 assert(!D.isNull() && "null type");
2067 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
2068 assert(T && "could not create debug info for type");
2070 RetainedTypes.push_back(D.getAsOpaquePtr());
2074 void CGDebugInfo::addHeapAllocSiteMetadata(llvm::Instruction *CI,
2076 SourceLocation Loc) {
2078 if (D.getTypePtr()->isVoidPointerType()) {
2079 node = llvm::MDNode::get(CGM.getLLVMContext(), None);
2081 QualType PointeeTy = D.getTypePtr()->getPointeeType();
2082 node = getOrCreateType(PointeeTy, getOrCreateFile(Loc));
2085 CI->setMetadata("heapallocsite", node);
2088 void CGDebugInfo::completeType(const EnumDecl *ED) {
2089 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2091 QualType Ty = CGM.getContext().getEnumType(ED);
2092 void *TyPtr = Ty.getAsOpaquePtr();
2093 auto I = TypeCache.find(TyPtr);
2094 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
2096 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
2097 assert(!Res->isForwardDecl());
2098 TypeCache[TyPtr].reset(Res);
2101 void CGDebugInfo::completeType(const RecordDecl *RD) {
2102 if (DebugKind > codegenoptions::LimitedDebugInfo ||
2103 !CGM.getLangOpts().CPlusPlus)
2104 completeRequiredType(RD);
2107 /// Return true if the class or any of its methods are marked dllimport.
2108 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
2109 if (RD->hasAttr<DLLImportAttr>())
2111 for (const CXXMethodDecl *MD : RD->methods())
2112 if (MD->hasAttr<DLLImportAttr>())
2117 /// Does a type definition exist in an imported clang module?
2118 static bool isDefinedInClangModule(const RecordDecl *RD) {
2119 // Only definitions that where imported from an AST file come from a module.
2120 if (!RD || !RD->isFromASTFile())
2122 // Anonymous entities cannot be addressed. Treat them as not from module.
2123 if (!RD->isExternallyVisible() && RD->getName().empty())
2125 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
2126 if (!CXXDecl->isCompleteDefinition())
2128 // Check wether RD is a template.
2129 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
2130 if (TemplateKind != TSK_Undeclared) {
2131 // Unfortunately getOwningModule() isn't accurate enough to find the
2132 // owning module of a ClassTemplateSpecializationDecl that is inside a
2133 // namespace spanning multiple modules.
2134 bool Explicit = false;
2135 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2136 Explicit = TD->isExplicitInstantiationOrSpecialization();
2137 if (!Explicit && CXXDecl->getEnclosingNamespaceContext())
2139 // This is a template, check the origin of the first member.
2140 if (CXXDecl->field_begin() == CXXDecl->field_end())
2141 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
2142 if (!CXXDecl->field_begin()->isFromASTFile())
2149 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
2150 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2151 if (CXXRD->isDynamicClass() &&
2152 CGM.getVTableLinkage(CXXRD) ==
2153 llvm::GlobalValue::AvailableExternallyLinkage &&
2154 !isClassOrMethodDLLImport(CXXRD))
2157 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2163 void CGDebugInfo::completeClass(const RecordDecl *RD) {
2164 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2166 QualType Ty = CGM.getContext().getRecordType(RD);
2167 void *TyPtr = Ty.getAsOpaquePtr();
2168 auto I = TypeCache.find(TyPtr);
2169 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
2171 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
2172 assert(!Res->isForwardDecl());
2173 TypeCache[TyPtr].reset(Res);
2176 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
2177 CXXRecordDecl::method_iterator End) {
2178 for (CXXMethodDecl *MD : llvm::make_range(I, End))
2179 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
2180 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
2181 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
2186 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
2187 bool DebugTypeExtRefs, const RecordDecl *RD,
2188 const LangOptions &LangOpts) {
2189 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
2192 if (auto *ES = RD->getASTContext().getExternalSource())
2193 if (ES->hasExternalDefinitions(RD) == ExternalASTSource::EK_Always)
2196 if (DebugKind > codegenoptions::LimitedDebugInfo)
2199 if (!LangOpts.CPlusPlus)
2202 if (!RD->isCompleteDefinitionRequired())
2205 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2210 // Only emit complete debug info for a dynamic class when its vtable is
2211 // emitted. However, Microsoft debuggers don't resolve type information
2212 // across DLL boundaries, so skip this optimization if the class or any of its
2213 // methods are marked dllimport. This isn't a complete solution, since objects
2214 // without any dllimport methods can be used in one DLL and constructed in
2215 // another, but it is the current behavior of LimitedDebugInfo.
2216 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
2217 !isClassOrMethodDLLImport(CXXDecl))
2220 // In constructor debug mode, only emit debug info for a class when its
2221 // constructor is emitted. Skip this optimization if the class or any of
2222 // its methods are marked dllimport.
2223 if (DebugKind == codegenoptions::DebugInfoConstructor &&
2224 !CXXDecl->isLambda() && !isClassOrMethodDLLImport(CXXDecl)) {
2225 for (const auto *Ctor : CXXDecl->ctors()) {
2226 if (Ctor->isUserProvided())
2231 TemplateSpecializationKind Spec = TSK_Undeclared;
2232 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2233 Spec = SD->getSpecializationKind();
2235 if (Spec == TSK_ExplicitInstantiationDeclaration &&
2236 hasExplicitMemberDefinition(CXXDecl->method_begin(),
2237 CXXDecl->method_end()))
2243 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
2244 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
2247 QualType Ty = CGM.getContext().getRecordType(RD);
2248 llvm::DIType *T = getTypeOrNull(Ty);
2249 if (T && T->isForwardDecl())
2250 completeClassData(RD);
2253 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
2254 RecordDecl *RD = Ty->getDecl();
2255 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
2256 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
2257 CGM.getLangOpts())) {
2259 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
2263 return CreateTypeDefinition(Ty);
2266 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
2267 RecordDecl *RD = Ty->getDecl();
2269 // Get overall information about the record type for the debug info.
2270 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2272 // Records and classes and unions can all be recursive. To handle them, we
2273 // first generate a debug descriptor for the struct as a forward declaration.
2274 // Then (if it is a definition) we go through and get debug info for all of
2275 // its members. Finally, we create a descriptor for the complete type (which
2276 // may refer to the forward decl if the struct is recursive) and replace all
2277 // uses of the forward declaration with the final definition.
2278 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
2280 const RecordDecl *D = RD->getDefinition();
2281 if (!D || !D->isCompleteDefinition())
2284 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
2285 CollectContainingType(CXXDecl, FwdDecl);
2287 // Push the struct on region stack.
2288 LexicalBlockStack.emplace_back(&*FwdDecl);
2289 RegionMap[Ty->getDecl()].reset(FwdDecl);
2291 // Convert all the elements.
2292 SmallVector<llvm::Metadata *, 16> EltTys;
2293 // what about nested types?
2295 // Note: The split of CXXDecl information here is intentional, the
2296 // gdb tests will depend on a certain ordering at printout. The debug
2297 // information offsets are still correct if we merge them all together
2299 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2301 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
2302 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
2305 // Collect data fields (including static variables and any initializers).
2306 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
2308 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
2310 LexicalBlockStack.pop_back();
2311 RegionMap.erase(Ty->getDecl());
2313 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2314 DBuilder.replaceArrays(FwdDecl, Elements);
2316 if (FwdDecl->isTemporary())
2318 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
2320 RegionMap[Ty->getDecl()].reset(FwdDecl);
2324 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
2325 llvm::DIFile *Unit) {
2326 // Ignore protocols.
2327 return getOrCreateType(Ty->getBaseType(), Unit);
2330 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
2331 llvm::DIFile *Unit) {
2332 // Ignore protocols.
2333 SourceLocation Loc = Ty->getDecl()->getLocation();
2335 // Use Typedefs to represent ObjCTypeParamType.
2336 return DBuilder.createTypedef(
2337 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
2338 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
2339 getDeclContextDescriptor(Ty->getDecl()));
2342 /// \return true if Getter has the default name for the property PD.
2343 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
2344 const ObjCMethodDecl *Getter) {
2349 assert(Getter->getDeclName().isObjCZeroArgSelector());
2350 return PD->getName() ==
2351 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
2354 /// \return true if Setter has the default name for the property PD.
2355 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
2356 const ObjCMethodDecl *Setter) {
2361 assert(Setter->getDeclName().isObjCOneArgSelector());
2362 return SelectorTable::constructSetterName(PD->getName()) ==
2363 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
2366 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
2367 llvm::DIFile *Unit) {
2368 ObjCInterfaceDecl *ID = Ty->getDecl();
2372 // Return a forward declaration if this type was imported from a clang module,
2373 // and this is not the compile unit with the implementation of the type (which
2374 // may contain hidden ivars).
2375 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
2376 !ID->getImplementation())
2377 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2379 getDeclContextDescriptor(ID), Unit, 0);
2381 // Get overall information about the record type for the debug info.
2382 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2383 unsigned Line = getLineNumber(ID->getLocation());
2385 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
2387 // If this is just a forward declaration return a special forward-declaration
2388 // debug type since we won't be able to lay out the entire type.
2389 ObjCInterfaceDecl *Def = ID->getDefinition();
2390 if (!Def || !Def->getImplementation()) {
2391 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2392 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
2393 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
2394 DefUnit, Line, RuntimeLang);
2395 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
2399 return CreateTypeDefinition(Ty, Unit);
2403 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
2404 bool CreateSkeletonCU) {
2405 // Use the Module pointer as the key into the cache. This is a
2406 // nullptr if the "Module" is a PCH, which is safe because we don't
2407 // support chained PCH debug info, so there can only be a single PCH.
2408 const Module *M = Mod.getModuleOrNull();
2409 auto ModRef = ModuleCache.find(M);
2410 if (ModRef != ModuleCache.end())
2411 return cast<llvm::DIModule>(ModRef->second);
2413 // Macro definitions that were defined with "-D" on the command line.
2414 SmallString<128> ConfigMacros;
2416 llvm::raw_svector_ostream OS(ConfigMacros);
2417 const auto &PPOpts = CGM.getPreprocessorOpts();
2419 // Translate the macro definitions back into a command line.
2420 for (auto &M : PPOpts.Macros) {
2423 const std::string &Macro = M.first;
2424 bool Undef = M.second;
2425 OS << "\"-" << (Undef ? 'U' : 'D');
2426 for (char c : Macro)
2441 bool IsRootModule = M ? !M->Parent : true;
2442 // When a module name is specified as -fmodule-name, that module gets a
2443 // clang::Module object, but it won't actually be built or imported; it will
2445 if (CreateSkeletonCU && IsRootModule && Mod.getASTFile().empty() && M)
2446 assert(StringRef(M->Name).startswith(CGM.getLangOpts().ModuleName) &&
2447 "clang module without ASTFile must be specified by -fmodule-name");
2449 if (CreateSkeletonCU && IsRootModule && !Mod.getASTFile().empty()) {
2450 // PCH files don't have a signature field in the control block,
2451 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2452 // We use the lower 64 bits for debug info.
2453 uint64_t Signature =
2455 ? (uint64_t)Mod.getSignature()[1] << 32 | Mod.getSignature()[0]
2457 llvm::DIBuilder DIB(CGM.getModule());
2458 DIB.createCompileUnit(TheCU->getSourceLanguage(),
2459 // TODO: Support "Source" from external AST providers?
2460 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2461 TheCU->getProducer(), true, StringRef(), 0,
2462 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2467 llvm::DIModule *Parent =
2468 IsRootModule ? nullptr
2469 : getOrCreateModuleRef(
2470 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2472 llvm::DIModule *DIMod =
2473 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2474 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2475 ModuleCache[M].reset(DIMod);
2479 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2480 llvm::DIFile *Unit) {
2481 ObjCInterfaceDecl *ID = Ty->getDecl();
2482 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2483 unsigned Line = getLineNumber(ID->getLocation());
2484 unsigned RuntimeLang = TheCU->getSourceLanguage();
2486 // Bit size, align and offset of the type.
2487 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2488 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2490 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2491 if (ID->getImplementation())
2492 Flags |= llvm::DINode::FlagObjcClassComplete;
2494 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2495 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2496 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2497 nullptr, llvm::DINodeArray(), RuntimeLang);
2499 QualType QTy(Ty, 0);
2500 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2502 // Push the struct on region stack.
2503 LexicalBlockStack.emplace_back(RealDecl);
2504 RegionMap[Ty->getDecl()].reset(RealDecl);
2506 // Convert all the elements.
2507 SmallVector<llvm::Metadata *, 16> EltTys;
2509 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2511 llvm::DIType *SClassTy =
2512 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2516 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0,
2517 llvm::DINode::FlagZero);
2518 EltTys.push_back(InhTag);
2521 // Create entries for all of the properties.
2522 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2523 SourceLocation Loc = PD->getLocation();
2524 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2525 unsigned PLine = getLineNumber(Loc);
2526 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2527 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2528 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2529 PD->getName(), PUnit, PLine,
2530 hasDefaultGetterName(PD, Getter) ? ""
2531 : getSelectorName(PD->getGetterName()),
2532 hasDefaultSetterName(PD, Setter) ? ""
2533 : getSelectorName(PD->getSetterName()),
2534 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2535 EltTys.push_back(PropertyNode);
2538 llvm::SmallPtrSet<const IdentifierInfo *, 16> PropertySet;
2539 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2540 for (auto *PD : ClassExt->properties()) {
2541 PropertySet.insert(PD->getIdentifier());
2544 for (const auto *PD : ID->properties()) {
2545 // Don't emit duplicate metadata for properties that were already in a
2547 if (!PropertySet.insert(PD->getIdentifier()).second)
2553 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2554 unsigned FieldNo = 0;
2555 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2556 Field = Field->getNextIvar(), ++FieldNo) {
2557 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2561 StringRef FieldName = Field->getName();
2563 // Ignore unnamed fields.
2564 if (FieldName.empty())
2567 // Get the location for the field.
2568 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2569 unsigned FieldLine = getLineNumber(Field->getLocation());
2570 QualType FType = Field->getType();
2571 uint64_t FieldSize = 0;
2572 uint32_t FieldAlign = 0;
2574 if (!FType->isIncompleteArrayType()) {
2576 // Bit size, align and offset of the type.
2577 FieldSize = Field->isBitField()
2578 ? Field->getBitWidthValue(CGM.getContext())
2579 : CGM.getContext().getTypeSize(FType);
2580 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2583 uint64_t FieldOffset;
2584 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2585 // We don't know the runtime offset of an ivar if we're using the
2586 // non-fragile ABI. For bitfields, use the bit offset into the first
2587 // byte of storage of the bitfield. For other fields, use zero.
2588 if (Field->isBitField()) {
2590 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2591 FieldOffset %= CGM.getContext().getCharWidth();
2596 FieldOffset = RL.getFieldOffset(FieldNo);
2599 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2600 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2601 Flags = llvm::DINode::FlagProtected;
2602 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2603 Flags = llvm::DINode::FlagPrivate;
2604 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2605 Flags = llvm::DINode::FlagPublic;
2607 llvm::MDNode *PropertyNode = nullptr;
2608 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2609 if (ObjCPropertyImplDecl *PImpD =
2610 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2611 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2612 SourceLocation Loc = PD->getLocation();
2613 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2614 unsigned PLine = getLineNumber(Loc);
2615 ObjCMethodDecl *Getter = PImpD->getGetterMethodDecl();
2616 ObjCMethodDecl *Setter = PImpD->getSetterMethodDecl();
2617 PropertyNode = DBuilder.createObjCProperty(
2618 PD->getName(), PUnit, PLine,
2619 hasDefaultGetterName(PD, Getter)
2621 : getSelectorName(PD->getGetterName()),
2622 hasDefaultSetterName(PD, Setter)
2624 : getSelectorName(PD->getSetterName()),
2625 PD->getPropertyAttributes(),
2626 getOrCreateType(PD->getType(), PUnit));
2630 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2631 FieldSize, FieldAlign, FieldOffset, Flags,
2632 FieldTy, PropertyNode);
2633 EltTys.push_back(FieldTy);
2636 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2637 DBuilder.replaceArrays(RealDecl, Elements);
2639 LexicalBlockStack.pop_back();
2643 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2644 llvm::DIFile *Unit) {
2645 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2646 int64_t Count = Ty->getNumElements();
2648 llvm::Metadata *Subscript;
2649 QualType QTy(Ty, 0);
2650 auto SizeExpr = SizeExprCache.find(QTy);
2651 if (SizeExpr != SizeExprCache.end())
2652 Subscript = DBuilder.getOrCreateSubrange(0, SizeExpr->getSecond());
2654 Subscript = DBuilder.getOrCreateSubrange(0, Count ? Count : -1);
2655 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2657 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2658 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2660 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2663 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2667 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2668 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2670 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2672 } else if (Ty->isIncompleteArrayType()) {
2674 if (Ty->getElementType()->isIncompleteType())
2677 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2678 } else if (Ty->isIncompleteType()) {
2682 // Size and align of the whole array, not the element type.
2683 Size = CGM.getContext().getTypeSize(Ty);
2684 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2687 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2688 // interior arrays, do we care? Why aren't nested arrays represented the
2689 // obvious/recursive way?
2690 SmallVector<llvm::Metadata *, 8> Subscripts;
2691 QualType EltTy(Ty, 0);
2692 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2693 // If the number of elements is known, then count is that number. Otherwise,
2694 // it's -1. This allows us to represent a subrange with an array of 0
2695 // elements, like this:
2700 int64_t Count = -1; // Count == -1 is an unbounded array.
2701 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2702 Count = CAT->getSize().getZExtValue();
2703 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2704 if (Expr *Size = VAT->getSizeExpr()) {
2705 Expr::EvalResult Result;
2706 if (Size->EvaluateAsInt(Result, CGM.getContext()))
2707 Count = Result.Val.getInt().getExtValue();
2711 auto SizeNode = SizeExprCache.find(EltTy);
2712 if (SizeNode != SizeExprCache.end())
2713 Subscripts.push_back(
2714 DBuilder.getOrCreateSubrange(0, SizeNode->getSecond()));
2716 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2717 EltTy = Ty->getElementType();
2720 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2722 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2726 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2727 llvm::DIFile *Unit) {
2728 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2729 Ty->getPointeeType(), Unit);
2732 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2733 llvm::DIFile *Unit) {
2734 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2735 Ty->getPointeeType(), Unit);
2738 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2740 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2743 if (!Ty->isIncompleteType()) {
2744 Size = CGM.getContext().getTypeSize(Ty);
2746 // Set the MS inheritance model. There is no flag for the unspecified model.
2747 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2748 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2749 case MSInheritanceModel::Single:
2750 Flags |= llvm::DINode::FlagSingleInheritance;
2752 case MSInheritanceModel::Multiple:
2753 Flags |= llvm::DINode::FlagMultipleInheritance;
2755 case MSInheritanceModel::Virtual:
2756 Flags |= llvm::DINode::FlagVirtualInheritance;
2758 case MSInheritanceModel::Unspecified:
2764 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2765 if (Ty->isMemberDataPointerType())
2766 return DBuilder.createMemberPointerType(
2767 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2770 const FunctionProtoType *FPT =
2771 Ty->getPointeeType()->getAs<FunctionProtoType>();
2772 return DBuilder.createMemberPointerType(
2773 getOrCreateInstanceMethodType(
2774 CXXMethodDecl::getThisType(FPT, Ty->getMostRecentCXXRecordDecl()),
2776 ClassType, Size, /*Align=*/0, Flags);
2779 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2780 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2781 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2784 llvm::DIType *CGDebugInfo::CreateType(const PipeType *Ty, llvm::DIFile *U) {
2785 return getOrCreateType(Ty->getElementType(), U);
2788 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2789 const EnumDecl *ED = Ty->getDecl();
2793 if (!ED->getTypeForDecl()->isIncompleteType()) {
2794 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2795 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2798 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2800 bool isImportedFromModule =
2801 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2803 // If this is just a forward declaration, construct an appropriately
2804 // marked node and just return it.
2805 if (isImportedFromModule || !ED->getDefinition()) {
2806 // Note that it is possible for enums to be created as part of
2807 // their own declcontext. In this case a FwdDecl will be created
2808 // twice. This doesn't cause a problem because both FwdDecls are
2809 // entered into the ReplaceMap: finalize() will replace the first
2810 // FwdDecl with the second and then replace the second with
2812 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2813 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2814 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2815 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2817 unsigned Line = getLineNumber(ED->getLocation());
2818 StringRef EDName = ED->getName();
2819 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2820 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2821 0, Size, Align, llvm::DINode::FlagFwdDecl, Identifier);
2823 ReplaceMap.emplace_back(
2824 std::piecewise_construct, std::make_tuple(Ty),
2825 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2829 return CreateTypeDefinition(Ty);
2832 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2833 const EnumDecl *ED = Ty->getDecl();
2836 if (!ED->getTypeForDecl()->isIncompleteType()) {
2837 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2838 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2841 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
2843 // Create elements for each enumerator.
2844 SmallVector<llvm::Metadata *, 16> Enumerators;
2845 ED = ED->getDefinition();
2846 bool IsSigned = ED->getIntegerType()->isSignedIntegerType();
2847 for (const auto *Enum : ED->enumerators()) {
2848 const auto &InitVal = Enum->getInitVal();
2849 auto Value = IsSigned ? InitVal.getSExtValue() : InitVal.getZExtValue();
2850 Enumerators.push_back(
2851 DBuilder.createEnumerator(Enum->getName(), Value, !IsSigned));
2854 // Return a CompositeType for the enum itself.
2855 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2857 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2858 unsigned Line = getLineNumber(ED->getLocation());
2859 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2860 llvm::DIType *ClassTy = getOrCreateType(ED->getIntegerType(), DefUnit);
2861 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2862 Line, Size, Align, EltArray, ClassTy,
2863 Identifier, ED->isScoped());
2866 llvm::DIMacro *CGDebugInfo::CreateMacro(llvm::DIMacroFile *Parent,
2867 unsigned MType, SourceLocation LineLoc,
2868 StringRef Name, StringRef Value) {
2869 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2870 return DBuilder.createMacro(Parent, Line, MType, Name, Value);
2873 llvm::DIMacroFile *CGDebugInfo::CreateTempMacroFile(llvm::DIMacroFile *Parent,
2874 SourceLocation LineLoc,
2875 SourceLocation FileLoc) {
2876 llvm::DIFile *FName = getOrCreateFile(FileLoc);
2877 unsigned Line = LineLoc.isInvalid() ? 0 : getLineNumber(LineLoc);
2878 return DBuilder.createTempMacroFile(Parent, Line, FName);
2881 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2884 Qualifiers InnerQuals = T.getLocalQualifiers();
2885 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2886 // that is already there.
2887 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2888 Quals += InnerQuals;
2890 switch (T->getTypeClass()) {
2892 return C.getQualifiedType(T.getTypePtr(), Quals);
2893 case Type::TemplateSpecialization: {
2894 const auto *Spec = cast<TemplateSpecializationType>(T);
2895 if (Spec->isTypeAlias())
2896 return C.getQualifiedType(T.getTypePtr(), Quals);
2897 T = Spec->desugar();
2900 case Type::TypeOfExpr:
2901 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2904 T = cast<TypeOfType>(T)->getUnderlyingType();
2906 case Type::Decltype:
2907 T = cast<DecltypeType>(T)->getUnderlyingType();
2909 case Type::UnaryTransform:
2910 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2912 case Type::Attributed:
2913 T = cast<AttributedType>(T)->getEquivalentType();
2915 case Type::Elaborated:
2916 T = cast<ElaboratedType>(T)->getNamedType();
2919 T = cast<ParenType>(T)->getInnerType();
2921 case Type::MacroQualified:
2922 T = cast<MacroQualifiedType>(T)->getUnderlyingType();
2924 case Type::SubstTemplateTypeParm:
2925 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2928 case Type::DeducedTemplateSpecialization: {
2929 QualType DT = cast<DeducedType>(T)->getDeducedType();
2930 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2934 case Type::Adjusted:
2936 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2937 T = cast<AdjustedType>(T)->getAdjustedType();
2941 assert(T != LastT && "Type unwrapping failed to unwrap!");
2946 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2948 // Unwrap the type as needed for debug information.
2949 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2951 auto It = TypeCache.find(Ty.getAsOpaquePtr());
2952 if (It != TypeCache.end()) {
2953 // Verify that the debug info still exists.
2954 if (llvm::Metadata *V = It->second)
2955 return cast<llvm::DIType>(V);
2961 void CGDebugInfo::completeTemplateDefinition(
2962 const ClassTemplateSpecializationDecl &SD) {
2963 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2965 completeUnusedClass(SD);
2968 void CGDebugInfo::completeUnusedClass(const CXXRecordDecl &D) {
2969 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2972 completeClassData(&D);
2973 // In case this type has no member function definitions being emitted, ensure
2975 RetainedTypes.push_back(CGM.getContext().getRecordType(&D).getAsOpaquePtr());
2978 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2982 llvm::TimeTraceScope TimeScope("DebugType", [&]() {
2984 llvm::raw_string_ostream OS(Name);
2985 Ty.print(OS, getPrintingPolicy());
2989 // Unwrap the type as needed for debug information.
2990 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2992 if (auto *T = getTypeOrNull(Ty))
2995 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2996 void *TyPtr = Ty.getAsOpaquePtr();
2998 // And update the type cache.
2999 TypeCache[TyPtr].reset(Res);
3004 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
3005 // A forward declaration inside a module header does not belong to the module.
3006 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
3008 if (DebugTypeExtRefs && D->isFromASTFile()) {
3009 // Record a reference to an imported clang module or precompiled header.
3010 auto *Reader = CGM.getContext().getExternalSource();
3011 auto Idx = D->getOwningModuleID();
3012 auto Info = Reader->getSourceDescriptor(Idx);
3014 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
3015 } else if (ClangModuleMap) {
3016 // We are building a clang module or a precompiled header.
3018 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
3019 // and it wouldn't be necessary to specify the parent scope
3020 // because the type is already unique by definition (it would look
3021 // like the output of -fno-standalone-debug). On the other hand,
3022 // the parent scope helps a consumer to quickly locate the object
3023 // file where the type's definition is located, so it might be
3024 // best to make this behavior a command line or debugger tuning
3026 if (Module *M = D->getOwningModule()) {
3027 // This is a (sub-)module.
3028 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
3029 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
3031 // This the precompiled header being built.
3032 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
3039 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
3040 // Handle qualifiers, which recursively handles what they refer to.
3041 if (Ty.hasLocalQualifiers())
3042 return CreateQualifiedType(Ty, Unit);
3044 // Work out details of type.
3045 switch (Ty->getTypeClass()) {
3046 #define TYPE(Class, Base)
3047 #define ABSTRACT_TYPE(Class, Base)
3048 #define NON_CANONICAL_TYPE(Class, Base)
3049 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3050 #include "clang/AST/TypeNodes.inc"
3051 llvm_unreachable("Dependent types cannot show up in debug information");
3053 case Type::ExtVector:
3055 return CreateType(cast<VectorType>(Ty), Unit);
3056 case Type::ObjCObjectPointer:
3057 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
3058 case Type::ObjCObject:
3059 return CreateType(cast<ObjCObjectType>(Ty), Unit);
3060 case Type::ObjCTypeParam:
3061 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
3062 case Type::ObjCInterface:
3063 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
3065 return CreateType(cast<BuiltinType>(Ty));
3067 return CreateType(cast<ComplexType>(Ty));
3069 return CreateType(cast<PointerType>(Ty), Unit);
3070 case Type::BlockPointer:
3071 return CreateType(cast<BlockPointerType>(Ty), Unit);
3073 return CreateType(cast<TypedefType>(Ty), Unit);
3075 return CreateType(cast<RecordType>(Ty));
3077 return CreateEnumType(cast<EnumType>(Ty));
3078 case Type::FunctionProto:
3079 case Type::FunctionNoProto:
3080 return CreateType(cast<FunctionType>(Ty), Unit);
3081 case Type::ConstantArray:
3082 case Type::VariableArray:
3083 case Type::IncompleteArray:
3084 return CreateType(cast<ArrayType>(Ty), Unit);
3086 case Type::LValueReference:
3087 return CreateType(cast<LValueReferenceType>(Ty), Unit);
3088 case Type::RValueReference:
3089 return CreateType(cast<RValueReferenceType>(Ty), Unit);
3091 case Type::MemberPointer:
3092 return CreateType(cast<MemberPointerType>(Ty), Unit);
3095 return CreateType(cast<AtomicType>(Ty), Unit);
3098 return CreateType(cast<PipeType>(Ty), Unit);
3100 case Type::TemplateSpecialization:
3101 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
3104 case Type::Attributed:
3105 case Type::Adjusted:
3107 case Type::DeducedTemplateSpecialization:
3108 case Type::Elaborated:
3110 case Type::MacroQualified:
3111 case Type::SubstTemplateTypeParm:
3112 case Type::TypeOfExpr:
3114 case Type::Decltype:
3115 case Type::UnaryTransform:
3116 case Type::PackExpansion:
3120 llvm_unreachable("type should have been unwrapped!");
3123 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
3124 llvm::DIFile *Unit) {
3125 QualType QTy(Ty, 0);
3127 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
3129 // We may have cached a forward decl when we could have created
3130 // a non-forward decl. Go ahead and create a non-forward decl
3132 if (T && !T->isForwardDecl())
3135 // Otherwise create the type.
3136 llvm::DICompositeType *Res = CreateLimitedType(Ty);
3138 // Propagate members from the declaration to the definition
3139 // CreateType(const RecordType*) will overwrite this with the members in the
3140 // correct order if the full type is needed.
3141 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
3143 // And update the type cache.
3144 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
3148 // TODO: Currently used for context chains when limiting debug info.
3149 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
3150 RecordDecl *RD = Ty->getDecl();
3152 // Get overall information about the record type for the debug info.
3153 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
3154 unsigned Line = getLineNumber(RD->getLocation());
3155 StringRef RDName = getClassName(RD);
3157 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
3159 // If we ended up creating the type during the context chain construction,
3160 // just return that.
3161 auto *T = cast_or_null<llvm::DICompositeType>(
3162 getTypeOrNull(CGM.getContext().getRecordType(RD)));
3163 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
3166 // If this is just a forward or incomplete declaration, construct an
3167 // appropriately marked node and just return it.
3168 const RecordDecl *D = RD->getDefinition();
3169 if (!D || !D->isCompleteDefinition())
3170 return getOrCreateRecordFwdDecl(Ty, RDContext);
3172 uint64_t Size = CGM.getContext().getTypeSize(Ty);
3173 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3175 SmallString<256> Identifier = getTypeIdentifier(Ty, CGM, TheCU);
3177 // Explicitly record the calling convention and export symbols for C++
3179 auto Flags = llvm::DINode::FlagZero;
3180 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3181 if (CGM.getCXXABI().getRecordArgABI(CXXRD) == CGCXXABI::RAA_Indirect)
3182 Flags |= llvm::DINode::FlagTypePassByReference;
3184 Flags |= llvm::DINode::FlagTypePassByValue;
3186 // Record if a C++ record is non-trivial type.
3187 if (!CXXRD->isTrivial())
3188 Flags |= llvm::DINode::FlagNonTrivial;
3190 // Record exports it symbols to the containing structure.
3191 if (CXXRD->isAnonymousStructOrUnion())
3192 Flags |= llvm::DINode::FlagExportSymbols;
3195 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
3196 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
3199 // Elements of composite types usually have back to the type, creating
3200 // uniquing cycles. Distinct nodes are more efficient.
3201 switch (RealDecl->getTag()) {
3203 llvm_unreachable("invalid composite type tag");
3205 case llvm::dwarf::DW_TAG_array_type:
3206 case llvm::dwarf::DW_TAG_enumeration_type:
3207 // Array elements and most enumeration elements don't have back references,
3208 // so they don't tend to be involved in uniquing cycles and there is some
3209 // chance of merging them when linking together two modules. Only make
3210 // them distinct if they are ODR-uniqued.
3211 if (Identifier.empty())
3215 case llvm::dwarf::DW_TAG_structure_type:
3216 case llvm::dwarf::DW_TAG_union_type:
3217 case llvm::dwarf::DW_TAG_class_type:
3218 // Immediately resolve to a distinct node.
3220 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
3224 RegionMap[Ty->getDecl()].reset(RealDecl);
3225 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
3227 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
3228 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
3229 CollectCXXTemplateParams(TSpecial, DefUnit));
3233 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
3234 llvm::DICompositeType *RealDecl) {
3235 // A class's primary base or the class itself contains the vtable.
3236 llvm::DICompositeType *ContainingType = nullptr;
3237 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
3238 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
3239 // Seek non-virtual primary base root.
3241 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
3242 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
3243 if (PBT && !BRL.isPrimaryBaseVirtual())
3248 ContainingType = cast<llvm::DICompositeType>(
3249 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
3250 getOrCreateFile(RD->getLocation())));
3251 } else if (RD->isDynamicClass())
3252 ContainingType = RealDecl;
3254 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
3257 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
3258 StringRef Name, uint64_t *Offset) {
3259 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
3260 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
3261 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
3263 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
3264 *Offset, llvm::DINode::FlagZero, FieldTy);
3265 *Offset += FieldSize;
3269 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
3271 StringRef &LinkageName,
3272 llvm::DIScope *&FDContext,
3273 llvm::DINodeArray &TParamsArray,
3274 llvm::DINode::DIFlags &Flags) {
3275 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3276 Name = getFunctionName(FD);
3277 // Use mangled name as linkage name for C/C++ functions.
3278 if (FD->hasPrototype()) {
3279 LinkageName = CGM.getMangledName(GD);
3280 Flags |= llvm::DINode::FlagPrototyped;
3282 // No need to replicate the linkage name if it isn't different from the
3283 // subprogram name, no need to have it at all unless coverage is enabled or
3284 // debug is set to more than just line tables or extra debug info is needed.
3285 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
3286 !CGM.getCodeGenOpts().EmitGcovNotes &&
3287 !CGM.getCodeGenOpts().DebugInfoForProfiling &&
3288 DebugKind <= codegenoptions::DebugLineTablesOnly))
3289 LinkageName = StringRef();
3291 if (CGM.getCodeGenOpts().hasReducedDebugInfo()) {
3292 if (const NamespaceDecl *NSDecl =
3293 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
3294 FDContext = getOrCreateNamespace(NSDecl);
3295 else if (const RecordDecl *RDecl =
3296 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
3297 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
3298 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
3300 // Check if it is a noreturn-marked function
3301 if (FD->isNoReturn())
3302 Flags |= llvm::DINode::FlagNoReturn;
3303 // Collect template parameters.
3304 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
3308 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
3309 unsigned &LineNo, QualType &T,
3310 StringRef &Name, StringRef &LinkageName,
3311 llvm::MDTuple *&TemplateParameters,
3312 llvm::DIScope *&VDContext) {
3313 Unit = getOrCreateFile(VD->getLocation());
3314 LineNo = getLineNumber(VD->getLocation());
3316 setLocation(VD->getLocation());
3319 if (T->isIncompleteArrayType()) {
3320 // CodeGen turns int[] into int[1] so we'll do the same here.
3321 llvm::APInt ConstVal(32, 1);
3322 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3324 T = CGM.getContext().getConstantArrayType(ET, ConstVal, nullptr,
3325 ArrayType::Normal, 0);
3328 Name = VD->getName();
3329 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
3330 !isa<ObjCMethodDecl>(VD->getDeclContext()))
3331 LinkageName = CGM.getMangledName(VD);
3332 if (LinkageName == Name)
3333 LinkageName = StringRef();
3335 if (isa<VarTemplateSpecializationDecl>(VD)) {
3336 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VD, &*Unit);
3337 TemplateParameters = parameterNodes.get();
3339 TemplateParameters = nullptr;
3342 // Since we emit declarations (DW_AT_members) for static members, place the
3343 // definition of those static members in the namespace they were declared in
3344 // in the source code (the lexical decl context).
3345 // FIXME: Generalize this for even non-member global variables where the
3346 // declaration and definition may have different lexical decl contexts, once
3347 // we have support for emitting declarations of (non-member) global variables.
3348 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
3349 : VD->getDeclContext();
3350 // When a record type contains an in-line initialization of a static data
3351 // member, and the record type is marked as __declspec(dllexport), an implicit
3352 // definition of the member will be created in the record context. DWARF
3353 // doesn't seem to have a nice way to describe this in a form that consumers
3354 // are likely to understand, so fake the "normal" situation of a definition
3355 // outside the class by putting it in the global scope.
3357 DC = CGM.getContext().getTranslationUnitDecl();
3359 llvm::DIScope *Mod = getParentModuleOrNull(VD);
3360 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
3363 llvm::DISubprogram *CGDebugInfo::getFunctionFwdDeclOrStub(GlobalDecl GD,
3365 llvm::DINodeArray TParamsArray;
3366 StringRef Name, LinkageName;
3367 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3368 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3369 SourceLocation Loc = GD.getDecl()->getLocation();
3370 llvm::DIFile *Unit = getOrCreateFile(Loc);
3371 llvm::DIScope *DContext = Unit;
3372 unsigned Line = getLineNumber(Loc);
3373 collectFunctionDeclProps(GD, Unit, Name, LinkageName, DContext, TParamsArray,
3375 auto *FD = cast<FunctionDecl>(GD.getDecl());
3377 // Build function type.
3378 SmallVector<QualType, 16> ArgTypes;
3379 for (const ParmVarDecl *Parm : FD->parameters())
3380 ArgTypes.push_back(Parm->getType());
3382 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
3383 QualType FnType = CGM.getContext().getFunctionType(
3384 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
3385 if (!FD->isExternallyVisible())
3386 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3387 if (CGM.getLangOpts().Optimize)
3388 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3391 Flags |= getCallSiteRelatedAttrs();
3392 SPFlags |= llvm::DISubprogram::SPFlagDefinition;
3393 return DBuilder.createFunction(
3394 DContext, Name, LinkageName, Unit, Line,
3395 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3396 TParamsArray.get(), getFunctionDeclaration(FD));
3399 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
3400 DContext, Name, LinkageName, Unit, Line,
3401 getOrCreateFunctionType(GD.getDecl(), FnType, Unit), 0, Flags, SPFlags,
3402 TParamsArray.get(), getFunctionDeclaration(FD));
3403 const FunctionDecl *CanonDecl = FD->getCanonicalDecl();
3404 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
3405 std::make_tuple(CanonDecl),
3406 std::make_tuple(SP));
3410 llvm::DISubprogram *CGDebugInfo::getFunctionForwardDeclaration(GlobalDecl GD) {
3411 return getFunctionFwdDeclOrStub(GD, /* Stub = */ false);
3414 llvm::DISubprogram *CGDebugInfo::getFunctionStub(GlobalDecl GD) {
3415 return getFunctionFwdDeclOrStub(GD, /* Stub = */ true);
3418 llvm::DIGlobalVariable *
3419 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
3421 StringRef Name, LinkageName;
3422 SourceLocation Loc = VD->getLocation();
3423 llvm::DIFile *Unit = getOrCreateFile(Loc);
3424 llvm::DIScope *DContext = Unit;
3425 unsigned Line = getLineNumber(Loc);
3426 llvm::MDTuple *TemplateParameters = nullptr;
3428 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, TemplateParameters,
3430 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3431 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
3432 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
3433 !VD->isExternallyVisible(), nullptr, TemplateParameters, Align);
3434 FwdDeclReplaceMap.emplace_back(
3435 std::piecewise_construct,
3436 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
3437 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
3441 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
3442 // We only need a declaration (not a definition) of the type - so use whatever
3443 // we would otherwise do to get a type for a pointee. (forward declarations in
3444 // limited debug info, full definitions (if the type definition is available)
3445 // in unlimited debug info)
3446 if (const auto *TD = dyn_cast<TypeDecl>(D))
3447 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
3448 getOrCreateFile(TD->getLocation()));
3449 auto I = DeclCache.find(D->getCanonicalDecl());
3451 if (I != DeclCache.end()) {
3453 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
3454 return GVE->getVariable();
3455 return dyn_cast_or_null<llvm::DINode>(N);
3458 // No definition for now. Emit a forward definition that might be
3459 // merged with a potential upcoming definition.
3460 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3461 return getFunctionForwardDeclaration(FD);
3462 else if (const auto *VD = dyn_cast<VarDecl>(D))
3463 return getGlobalVariableForwardDeclaration(VD);
3468 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
3469 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3472 const auto *FD = dyn_cast<FunctionDecl>(D);
3477 auto *S = getDeclContextDescriptor(D);
3479 auto MI = SPCache.find(FD->getCanonicalDecl());
3480 if (MI == SPCache.end()) {
3481 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
3482 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
3483 cast<llvm::DICompositeType>(S));
3486 if (MI != SPCache.end()) {
3487 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3488 if (SP && !SP->isDefinition())
3492 for (auto NextFD : FD->redecls()) {
3493 auto MI = SPCache.find(NextFD->getCanonicalDecl());
3494 if (MI != SPCache.end()) {
3495 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
3496 if (SP && !SP->isDefinition())
3503 llvm::DISubprogram *CGDebugInfo::getObjCMethodDeclaration(
3504 const Decl *D, llvm::DISubroutineType *FnType, unsigned LineNo,
3505 llvm::DINode::DIFlags Flags, llvm::DISubprogram::DISPFlags SPFlags) {
3506 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3509 const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
3513 if (CGM.getCodeGenOpts().DwarfVersion < 5 && !OMD->isDirectMethod())
3516 if (OMD->isDirectMethod())
3517 SPFlags |= llvm::DISubprogram::SPFlagObjCDirect;
3519 // Starting with DWARF V5 method declarations are emitted as children of
3520 // the interface type.
3521 auto *ID = dyn_cast_or_null<ObjCInterfaceDecl>(D->getDeclContext());
3523 ID = OMD->getClassInterface();
3526 QualType QTy(ID->getTypeForDecl(), 0);
3527 auto It = TypeCache.find(QTy.getAsOpaquePtr());
3528 if (It == TypeCache.end())
3530 auto *InterfaceType = cast<llvm::DICompositeType>(It->second);
3531 llvm::DISubprogram *FD = DBuilder.createFunction(
3532 InterfaceType, getObjCMethodName(OMD), StringRef(),
3533 InterfaceType->getFile(), LineNo, FnType, LineNo, Flags, SPFlags);
3534 DBuilder.finalizeSubprogram(FD);
3535 ObjCMethodCache[ID].push_back({FD, OMD->isDirectMethod()});
3539 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
3540 // implicit parameter "this".
3541 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
3544 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
3545 // Create fake but valid subroutine type. Otherwise -verify would fail, and
3546 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
3547 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
3549 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
3550 return getOrCreateMethodType(Method, F);
3552 const auto *FTy = FnType->getAs<FunctionType>();
3553 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
3555 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
3556 // Add "self" and "_cmd"
3557 SmallVector<llvm::Metadata *, 16> Elts;
3559 // First element is always return type. For 'void' functions it is NULL.
3560 QualType ResultTy = OMethod->getReturnType();
3562 // Replace the instancetype keyword with the actual type.
3563 if (ResultTy == CGM.getContext().getObjCInstanceType())
3564 ResultTy = CGM.getContext().getPointerType(
3565 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
3567 Elts.push_back(getOrCreateType(ResultTy, F));
3568 // "self" pointer is always first argument.
3569 QualType SelfDeclTy;
3570 if (auto *SelfDecl = OMethod->getSelfDecl())
3571 SelfDeclTy = SelfDecl->getType();
3572 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3573 if (FPT->getNumParams() > 1)
3574 SelfDeclTy = FPT->getParamType(0);
3575 if (!SelfDeclTy.isNull())
3577 CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
3578 // "_cmd" pointer is always second argument.
3579 Elts.push_back(DBuilder.createArtificialType(
3580 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3581 // Get rest of the arguments.
3582 for (const auto *PI : OMethod->parameters())
3583 Elts.push_back(getOrCreateType(PI->getType(), F));
3584 // Variadic methods need a special marker at the end of the type list.
3585 if (OMethod->isVariadic())
3586 Elts.push_back(DBuilder.createUnspecifiedParameter());
3588 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3589 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3593 // Handle variadic function types; they need an additional
3594 // unspecified parameter.
3595 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3596 if (FD->isVariadic()) {
3597 SmallVector<llvm::Metadata *, 16> EltTys;
3598 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3599 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3600 for (QualType ParamType : FPT->param_types())
3601 EltTys.push_back(getOrCreateType(ParamType, F));
3602 EltTys.push_back(DBuilder.createUnspecifiedParameter());
3603 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3604 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3608 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3611 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3612 SourceLocation ScopeLoc, QualType FnType,
3613 llvm::Function *Fn, bool CurFuncIsThunk,
3614 CGBuilderTy &Builder) {
3617 StringRef LinkageName;
3619 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3621 const Decl *D = GD.getDecl();
3622 bool HasDecl = (D != nullptr);
3624 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3625 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3626 llvm::DIFile *Unit = getOrCreateFile(Loc);
3627 llvm::DIScope *FDContext = Unit;
3628 llvm::DINodeArray TParamsArray;
3630 // Use llvm function name.
3631 LinkageName = Fn->getName();
3632 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3633 // If there is a subprogram for this function available then use it.
3634 auto FI = SPCache.find(FD->getCanonicalDecl());
3635 if (FI != SPCache.end()) {
3636 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3637 if (SP && SP->isDefinition()) {
3638 LexicalBlockStack.emplace_back(SP);
3639 RegionMap[D].reset(SP);
3643 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3644 TParamsArray, Flags);
3645 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3646 Name = getObjCMethodName(OMD);
3647 Flags |= llvm::DINode::FlagPrototyped;
3648 } else if (isa<VarDecl>(D) &&
3649 GD.getDynamicInitKind() != DynamicInitKind::NoStub) {
3650 // This is a global initializer or atexit destructor for a global variable.
3651 Name = getDynamicInitializerName(cast<VarDecl>(D), GD.getDynamicInitKind(),
3654 // Use llvm function name.
3655 Name = Fn->getName();
3656 Flags |= llvm::DINode::FlagPrototyped;
3658 if (Name.startswith("\01"))
3659 Name = Name.substr(1);
3661 if (!HasDecl || D->isImplicit() || D->hasAttr<ArtificialAttr>()) {
3662 Flags |= llvm::DINode::FlagArtificial;
3663 // Artificial functions should not silently reuse CurLoc.
3664 CurLoc = SourceLocation();
3668 Flags |= llvm::DINode::FlagThunk;
3670 if (Fn->hasLocalLinkage())
3671 SPFlags |= llvm::DISubprogram::SPFlagLocalToUnit;
3672 if (CGM.getLangOpts().Optimize)
3673 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3675 llvm::DINode::DIFlags FlagsForDef = Flags | getCallSiteRelatedAttrs();
3676 llvm::DISubprogram::DISPFlags SPFlagsForDef =
3677 SPFlags | llvm::DISubprogram::SPFlagDefinition;
3679 unsigned LineNo = getLineNumber(Loc);
3680 unsigned ScopeLine = getLineNumber(ScopeLoc);
3681 llvm::DISubroutineType *DIFnType = getOrCreateFunctionType(D, FnType, Unit);
3682 llvm::DISubprogram *Decl = nullptr;
3684 Decl = isa<ObjCMethodDecl>(D)
3685 ? getObjCMethodDeclaration(D, DIFnType, LineNo, Flags, SPFlags)
3686 : getFunctionDeclaration(D);
3688 // FIXME: The function declaration we're constructing here is mostly reusing
3689 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3690 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3691 // all subprograms instead of the actual context since subprogram definitions
3692 // are emitted as CU level entities by the backend.
3693 llvm::DISubprogram *SP = DBuilder.createFunction(
3694 FDContext, Name, LinkageName, Unit, LineNo, DIFnType, ScopeLine,
3695 FlagsForDef, SPFlagsForDef, TParamsArray.get(), Decl);
3696 Fn->setSubprogram(SP);
3697 // We might get here with a VarDecl in the case we're generating
3698 // code for the initialization of globals. Do not record these decls
3699 // as they will overwrite the actual VarDecl Decl in the cache.
3700 if (HasDecl && isa<FunctionDecl>(D))
3701 DeclCache[D->getCanonicalDecl()].reset(SP);
3703 // Push the function onto the lexical block stack.
3704 LexicalBlockStack.emplace_back(SP);
3707 RegionMap[D].reset(SP);
3710 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3711 QualType FnType, llvm::Function *Fn) {
3713 StringRef LinkageName;
3715 const Decl *D = GD.getDecl();
3719 llvm::TimeTraceScope TimeScope("DebugFunction", [&]() {
3721 llvm::raw_string_ostream OS(Name);
3722 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
3723 ND->getNameForDiagnostic(OS, getPrintingPolicy(),
3724 /*Qualified=*/true);
3728 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3729 llvm::DIFile *Unit = getOrCreateFile(Loc);
3730 bool IsDeclForCallSite = Fn ? true : false;
3731 llvm::DIScope *FDContext =
3732 IsDeclForCallSite ? Unit : getDeclContextDescriptor(D);
3733 llvm::DINodeArray TParamsArray;
3734 if (isa<FunctionDecl>(D)) {
3735 // If there is a DISubprogram for this function available then use it.
3736 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3737 TParamsArray, Flags);
3738 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3739 Name = getObjCMethodName(OMD);
3740 Flags |= llvm::DINode::FlagPrototyped;
3742 llvm_unreachable("not a function or ObjC method");
3744 if (!Name.empty() && Name[0] == '\01')
3745 Name = Name.substr(1);
3747 if (D->isImplicit()) {
3748 Flags |= llvm::DINode::FlagArtificial;
3749 // Artificial functions without a location should not silently reuse CurLoc.
3750 if (Loc.isInvalid())
3751 CurLoc = SourceLocation();
3753 unsigned LineNo = getLineNumber(Loc);
3754 unsigned ScopeLine = 0;
3755 llvm::DISubprogram::DISPFlags SPFlags = llvm::DISubprogram::SPFlagZero;
3756 if (CGM.getLangOpts().Optimize)
3757 SPFlags |= llvm::DISubprogram::SPFlagOptimized;
3759 llvm::DISubprogram *SP = DBuilder.createFunction(
3760 FDContext, Name, LinkageName, Unit, LineNo,
3761 getOrCreateFunctionType(D, FnType, Unit), ScopeLine, Flags, SPFlags,
3762 TParamsArray.get(), getFunctionDeclaration(D));
3764 if (IsDeclForCallSite)
3765 Fn->setSubprogram(SP);
3767 DBuilder.retainType(SP);
3770 void CGDebugInfo::EmitFuncDeclForCallSite(llvm::CallBase *CallOrInvoke,
3771 QualType CalleeType,
3772 const FunctionDecl *CalleeDecl) {
3775 auto *Func = CallOrInvoke->getCalledFunction();
3778 if (Func->getSubprogram())
3781 // Do not emit a declaration subprogram for a builtin or if call site info
3782 // isn't required. Also, elide declarations for functions with reserved names,
3783 // as call site-related features aren't interesting in this case (& also, the
3784 // compiler may emit calls to these functions without debug locations, which
3785 // makes the verifier complain).
3786 if (CalleeDecl->getBuiltinID() != 0 ||
3787 getCallSiteRelatedAttrs() == llvm::DINode::FlagZero)
3789 if (const auto *Id = CalleeDecl->getIdentifier())
3790 if (Id->isReservedName())
3793 // If there is no DISubprogram attached to the function being called,
3794 // create the one describing the function in order to have complete
3795 // call site debug info.
3796 if (!CalleeDecl->isStatic() && !CalleeDecl->isInlined())
3797 EmitFunctionDecl(CalleeDecl, CalleeDecl->getLocation(), CalleeType, Func);
3800 void CGDebugInfo::EmitInlineFunctionStart(CGBuilderTy &Builder, GlobalDecl GD) {
3801 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3802 // If there is a subprogram for this function available then use it.
3803 auto FI = SPCache.find(FD->getCanonicalDecl());
3804 llvm::DISubprogram *SP = nullptr;
3805 if (FI != SPCache.end())
3806 SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3807 if (!SP || !SP->isDefinition())
3808 SP = getFunctionStub(GD);
3809 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3810 LexicalBlockStack.emplace_back(SP);
3811 setInlinedAt(Builder.getCurrentDebugLocation());
3812 EmitLocation(Builder, FD->getLocation());
3815 void CGDebugInfo::EmitInlineFunctionEnd(CGBuilderTy &Builder) {
3816 assert(CurInlinedAt && "unbalanced inline scope stack");
3817 EmitFunctionEnd(Builder, nullptr);
3818 setInlinedAt(llvm::DebugLoc(CurInlinedAt).getInlinedAt());
3821 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3822 // Update our current location
3825 if (CurLoc.isInvalid() || CurLoc.isMacroID() || LexicalBlockStack.empty())
3828 llvm::MDNode *Scope = LexicalBlockStack.back();
3829 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3830 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope, CurInlinedAt));
3833 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3834 llvm::MDNode *Back = nullptr;
3835 if (!LexicalBlockStack.empty())
3836 Back = LexicalBlockStack.back().get();
3837 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3838 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3839 getColumnNumber(CurLoc)));
3842 void CGDebugInfo::AppendAddressSpaceXDeref(
3843 unsigned AddressSpace, SmallVectorImpl<int64_t> &Expr) const {
3844 Optional<unsigned> DWARFAddressSpace =
3845 CGM.getTarget().getDWARFAddressSpace(AddressSpace);
3846 if (!DWARFAddressSpace)
3849 Expr.push_back(llvm::dwarf::DW_OP_constu);
3850 Expr.push_back(DWARFAddressSpace.getValue());
3851 Expr.push_back(llvm::dwarf::DW_OP_swap);
3852 Expr.push_back(llvm::dwarf::DW_OP_xderef);
3855 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3856 SourceLocation Loc) {
3857 // Set our current location.
3860 // Emit a line table change for the current location inside the new scope.
3861 Builder.SetCurrentDebugLocation(
3862 llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc),
3863 LexicalBlockStack.back(), CurInlinedAt));
3865 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3868 // Create a new lexical block and push it on the stack.
3869 CreateLexicalBlock(Loc);
3872 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3873 SourceLocation Loc) {
3874 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3876 // Provide an entry in the line table for the end of the block.
3877 EmitLocation(Builder, Loc);
3879 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3882 LexicalBlockStack.pop_back();
3885 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder, llvm::Function *Fn) {
3886 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3887 unsigned RCount = FnBeginRegionCount.back();
3888 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3890 // Pop all regions for this function.
3891 while (LexicalBlockStack.size() != RCount) {
3892 // Provide an entry in the line table for the end of the block.
3893 EmitLocation(Builder, CurLoc);
3894 LexicalBlockStack.pop_back();
3896 FnBeginRegionCount.pop_back();
3898 if (Fn && Fn->getSubprogram())
3899 DBuilder.finalizeSubprogram(Fn->getSubprogram());
3902 CGDebugInfo::BlockByRefType
3903 CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3904 uint64_t *XOffset) {
3905 SmallVector<llvm::Metadata *, 5> EltTys;
3907 uint64_t FieldSize, FieldOffset;
3908 uint32_t FieldAlign;
3910 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3911 QualType Type = VD->getType();
3914 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3915 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3916 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3917 FType = CGM.getContext().IntTy;
3918 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3919 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3921 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3922 if (HasCopyAndDispose) {
3923 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3925 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3927 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3929 bool HasByrefExtendedLayout;
3930 Qualifiers::ObjCLifetime Lifetime;
3931 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3932 HasByrefExtendedLayout) &&
3933 HasByrefExtendedLayout) {
3934 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3936 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3939 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3940 if (Align > CGM.getContext().toCharUnitsFromBits(
3941 CGM.getTarget().getPointerAlign(0))) {
3942 CharUnits FieldOffsetInBytes =
3943 CGM.getContext().toCharUnitsFromBits(FieldOffset);
3944 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3945 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3947 if (NumPaddingBytes.isPositive()) {
3948 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3949 FType = CGM.getContext().getConstantArrayType(
3950 CGM.getContext().CharTy, pad, nullptr, ArrayType::Normal, 0);
3951 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3956 llvm::DIType *WrappedTy = getOrCreateType(FType, Unit);
3957 FieldSize = CGM.getContext().getTypeSize(FType);
3958 FieldAlign = CGM.getContext().toBits(Align);
3960 *XOffset = FieldOffset;
3961 llvm::DIType *FieldTy = DBuilder.createMemberType(
3962 Unit, VD->getName(), Unit, 0, FieldSize, FieldAlign, FieldOffset,
3963 llvm::DINode::FlagZero, WrappedTy);
3964 EltTys.push_back(FieldTy);
3965 FieldOffset += FieldSize;
3967 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3968 return {DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0,
3969 llvm::DINode::FlagZero, nullptr, Elements),
3973 llvm::DILocalVariable *CGDebugInfo::EmitDeclare(const VarDecl *VD,
3974 llvm::Value *Storage,
3975 llvm::Optional<unsigned> ArgNo,
3976 CGBuilderTy &Builder,
3977 const bool UsePointerValue) {
3978 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
3979 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3980 if (VD->hasAttr<NoDebugAttr>())
3984 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3985 cast<Decl>(VD->getDeclContext())->isImplicit());
3986 llvm::DIFile *Unit = nullptr;
3988 Unit = getOrCreateFile(VD->getLocation());
3990 uint64_t XOffset = 0;
3991 if (VD->hasAttr<BlocksAttr>())
3992 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
3994 Ty = getOrCreateType(VD->getType(), Unit);
3996 // If there is no debug info for this type then do not emit debug info
3997 // for this variable.
4001 // Get location information.
4003 unsigned Column = 0;
4005 Line = getLineNumber(VD->getLocation());
4006 Column = getColumnNumber(VD->getLocation());
4008 SmallVector<int64_t, 13> Expr;
4009 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
4010 if (VD->isImplicit())
4011 Flags |= llvm::DINode::FlagArtificial;
4013 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4015 unsigned AddressSpace = CGM.getContext().getTargetAddressSpace(VD->getType());
4016 AppendAddressSpaceXDeref(AddressSpace, Expr);
4018 // If this is implicit parameter of CXXThis or ObjCSelf kind, then give it an
4019 // object pointer flag.
4020 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD)) {
4021 if (IPD->getParameterKind() == ImplicitParamDecl::CXXThis ||
4022 IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4023 Flags |= llvm::DINode::FlagObjectPointer;
4026 // Note: Older versions of clang used to emit byval references with an extra
4027 // DW_OP_deref, because they referenced the IR arg directly instead of
4028 // referencing an alloca. Newer versions of LLVM don't treat allocas
4029 // differently from other function arguments when used in a dbg.declare.
4030 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4031 StringRef Name = VD->getName();
4032 if (!Name.empty()) {
4033 if (VD->hasAttr<BlocksAttr>()) {
4034 // Here, we need an offset *into* the alloca.
4035 CharUnits offset = CharUnits::fromQuantity(32);
4036 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4037 // offset of __forwarding field
4038 offset = CGM.getContext().toCharUnitsFromBits(
4039 CGM.getTarget().getPointerWidth(0));
4040 Expr.push_back(offset.getQuantity());
4041 Expr.push_back(llvm::dwarf::DW_OP_deref);
4042 Expr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4043 // offset of x field
4044 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4045 Expr.push_back(offset.getQuantity());
4047 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
4048 // If VD is an anonymous union then Storage represents value for
4049 // all union fields.
4050 const RecordDecl *RD = RT->getDecl();
4051 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
4052 // GDB has trouble finding local variables in anonymous unions, so we emit
4053 // artificial local variables for each of the members.
4055 // FIXME: Remove this code as soon as GDB supports this.
4056 // The debug info verifier in LLVM operates based on the assumption that a
4057 // variable has the same size as its storage and we had to disable the
4058 // check for artificial variables.
4059 for (const auto *Field : RD->fields()) {
4060 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4061 StringRef FieldName = Field->getName();
4063 // Ignore unnamed fields. Do not ignore unnamed records.
4064 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
4067 // Use VarDecl's Tag, Scope and Line number.
4068 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
4069 auto *D = DBuilder.createAutoVariable(
4070 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
4071 Flags | llvm::DINode::FlagArtificial, FieldAlign);
4073 // Insert an llvm.dbg.declare into the current block.
4074 DBuilder.insertDeclare(
4075 Storage, D, DBuilder.createExpression(Expr),
4076 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4077 Builder.GetInsertBlock());
4082 // Clang stores the sret pointer provided by the caller in a static alloca.
4083 // Use DW_OP_deref to tell the debugger to load the pointer and treat it as
4084 // the address of the variable.
4085 if (UsePointerValue) {
4086 assert(std::find(Expr.begin(), Expr.end(), llvm::dwarf::DW_OP_deref) ==
4088 "Debug info already contains DW_OP_deref.");
4089 Expr.push_back(llvm::dwarf::DW_OP_deref);
4092 // Create the descriptor for the variable.
4093 auto *D = ArgNo ? DBuilder.createParameterVariable(
4094 Scope, Name, *ArgNo, Unit, Line, Ty,
4095 CGM.getLangOpts().Optimize, Flags)
4096 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
4097 CGM.getLangOpts().Optimize,
4100 // Insert an llvm.dbg.declare into the current block.
4101 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
4102 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4103 Builder.GetInsertBlock());
4108 llvm::DILocalVariable *
4109 CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD, llvm::Value *Storage,
4110 CGBuilderTy &Builder,
4111 const bool UsePointerValue) {
4112 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4113 return EmitDeclare(VD, Storage, llvm::None, Builder, UsePointerValue);
4116 void CGDebugInfo::EmitLabel(const LabelDecl *D, CGBuilderTy &Builder) {
4117 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4118 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4120 if (D->hasAttr<NoDebugAttr>())
4123 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
4124 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4126 // Get location information.
4127 unsigned Line = getLineNumber(D->getLocation());
4128 unsigned Column = getColumnNumber(D->getLocation());
4130 StringRef Name = D->getName();
4132 // Create the descriptor for the label.
4134 DBuilder.createLabel(Scope, Name, Unit, Line, CGM.getLangOpts().Optimize);
4136 // Insert an llvm.dbg.label into the current block.
4137 DBuilder.insertLabel(L,
4138 llvm::DebugLoc::get(Line, Column, Scope, CurInlinedAt),
4139 Builder.GetInsertBlock());
4142 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
4144 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
4147 return DBuilder.createObjectPointerType(Ty);
4150 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
4151 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
4152 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
4153 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4154 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
4156 if (Builder.GetInsertBlock() == nullptr)
4158 if (VD->hasAttr<NoDebugAttr>())
4161 bool isByRef = VD->hasAttr<BlocksAttr>();
4163 uint64_t XOffset = 0;
4164 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4167 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset).WrappedType;
4169 Ty = getOrCreateType(VD->getType(), Unit);
4171 // Self is passed along as an implicit non-arg variable in a
4172 // block. Mark it as the object pointer.
4173 if (const auto *IPD = dyn_cast<ImplicitParamDecl>(VD))
4174 if (IPD->getParameterKind() == ImplicitParamDecl::ObjCSelf)
4175 Ty = CreateSelfType(VD->getType(), Ty);
4177 // Get location information.
4178 unsigned Line = getLineNumber(VD->getLocation());
4179 unsigned Column = getColumnNumber(VD->getLocation());
4181 const llvm::DataLayout &target = CGM.getDataLayout();
4183 CharUnits offset = CharUnits::fromQuantity(
4184 target.getStructLayout(blockInfo.StructureType)
4185 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
4187 SmallVector<int64_t, 9> addr;
4188 addr.push_back(llvm::dwarf::DW_OP_deref);
4189 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4190 addr.push_back(offset.getQuantity());
4192 addr.push_back(llvm::dwarf::DW_OP_deref);
4193 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4194 // offset of __forwarding field
4196 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
4197 addr.push_back(offset.getQuantity());
4198 addr.push_back(llvm::dwarf::DW_OP_deref);
4199 addr.push_back(llvm::dwarf::DW_OP_plus_uconst);
4200 // offset of x field
4201 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
4202 addr.push_back(offset.getQuantity());
4205 // Create the descriptor for the variable.
4206 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4207 auto *D = DBuilder.createAutoVariable(
4208 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
4209 Line, Ty, false, llvm::DINode::FlagZero, Align);
4211 // Insert an llvm.dbg.declare into the current block.
4213 llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back(), CurInlinedAt);
4214 auto *Expr = DBuilder.createExpression(addr);
4216 DBuilder.insertDeclare(Storage, D, Expr, DL, InsertPoint);
4218 DBuilder.insertDeclare(Storage, D, Expr, DL, Builder.GetInsertBlock());
4221 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
4223 CGBuilderTy &Builder) {
4224 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4225 EmitDeclare(VD, AI, ArgNo, Builder);
4229 struct BlockLayoutChunk {
4230 uint64_t OffsetInBits;
4231 const BlockDecl::Capture *Capture;
4233 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
4234 return l.OffsetInBits < r.OffsetInBits;
4238 void CGDebugInfo::collectDefaultFieldsForBlockLiteralDeclare(
4239 const CGBlockInfo &Block, const ASTContext &Context, SourceLocation Loc,
4240 const llvm::StructLayout &BlockLayout, llvm::DIFile *Unit,
4241 SmallVectorImpl<llvm::Metadata *> &Fields) {
4242 // Blocks in OpenCL have unique constraints which make the standard fields
4243 // redundant while requiring size and align fields for enqueue_kernel. See
4244 // initializeForBlockHeader in CGBlocks.cpp
4245 if (CGM.getLangOpts().OpenCL) {
4246 Fields.push_back(createFieldType("__size", Context.IntTy, Loc, AS_public,
4247 BlockLayout.getElementOffsetInBits(0),
4249 Fields.push_back(createFieldType("__align", Context.IntTy, Loc, AS_public,
4250 BlockLayout.getElementOffsetInBits(1),
4253 Fields.push_back(createFieldType("__isa", Context.VoidPtrTy, Loc, AS_public,
4254 BlockLayout.getElementOffsetInBits(0),
4256 Fields.push_back(createFieldType("__flags", Context.IntTy, Loc, AS_public,
4257 BlockLayout.getElementOffsetInBits(1),
4260 createFieldType("__reserved", Context.IntTy, Loc, AS_public,
4261 BlockLayout.getElementOffsetInBits(2), Unit, Unit));
4262 auto *FnTy = Block.getBlockExpr()->getFunctionType();
4263 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
4264 Fields.push_back(createFieldType("__FuncPtr", FnPtrType, Loc, AS_public,
4265 BlockLayout.getElementOffsetInBits(3),
4267 Fields.push_back(createFieldType(
4269 Context.getPointerType(Block.NeedsCopyDispose
4270 ? Context.getBlockDescriptorExtendedType()
4271 : Context.getBlockDescriptorType()),
4272 Loc, AS_public, BlockLayout.getElementOffsetInBits(4), Unit, Unit));
4276 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
4279 llvm::AllocaInst *Alloca,
4280 CGBuilderTy &Builder) {
4281 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4282 ASTContext &C = CGM.getContext();
4283 const BlockDecl *blockDecl = block.getBlockDecl();
4285 // Collect some general information about the block's location.
4286 SourceLocation loc = blockDecl->getCaretLocation();
4287 llvm::DIFile *tunit = getOrCreateFile(loc);
4288 unsigned line = getLineNumber(loc);
4289 unsigned column = getColumnNumber(loc);
4291 // Build the debug-info type for the block literal.
4292 getDeclContextDescriptor(blockDecl);
4294 const llvm::StructLayout *blockLayout =
4295 CGM.getDataLayout().getStructLayout(block.StructureType);
4297 SmallVector<llvm::Metadata *, 16> fields;
4298 collectDefaultFieldsForBlockLiteralDeclare(block, C, loc, *blockLayout, tunit,
4301 // We want to sort the captures by offset, not because DWARF
4302 // requires this, but because we're paranoid about debuggers.
4303 SmallVector<BlockLayoutChunk, 8> chunks;
4306 if (blockDecl->capturesCXXThis()) {
4307 BlockLayoutChunk chunk;
4308 chunk.OffsetInBits =
4309 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
4310 chunk.Capture = nullptr;
4311 chunks.push_back(chunk);
4314 // Variable captures.
4315 for (const auto &capture : blockDecl->captures()) {
4316 const VarDecl *variable = capture.getVariable();
4317 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
4319 // Ignore constant captures.
4320 if (captureInfo.isConstant())
4323 BlockLayoutChunk chunk;
4324 chunk.OffsetInBits =
4325 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
4326 chunk.Capture = &capture;
4327 chunks.push_back(chunk);
4331 llvm::array_pod_sort(chunks.begin(), chunks.end());
4333 for (const BlockLayoutChunk &Chunk : chunks) {
4334 uint64_t offsetInBits = Chunk.OffsetInBits;
4335 const BlockDecl::Capture *capture = Chunk.Capture;
4337 // If we have a null capture, this must be the C++ 'this' capture.
4341 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
4342 type = Method->getThisType();
4343 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
4344 type = QualType(RDecl->getTypeForDecl(), 0);
4346 llvm_unreachable("unexpected block declcontext");
4348 fields.push_back(createFieldType("this", type, loc, AS_public,
4349 offsetInBits, tunit, tunit));
4353 const VarDecl *variable = capture->getVariable();
4354 StringRef name = variable->getName();
4356 llvm::DIType *fieldType;
4357 if (capture->isByRef()) {
4358 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
4359 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
4360 // FIXME: This recomputes the layout of the BlockByRefWrapper.
4363 EmitTypeForVarWithBlocksAttr(variable, &xoffset).BlockByRefWrapper;
4364 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
4365 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
4366 PtrInfo.Width, Align, offsetInBits,
4367 llvm::DINode::FlagZero, fieldType);
4369 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
4370 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
4371 offsetInBits, Align, tunit, tunit);
4373 fields.push_back(fieldType);
4376 SmallString<36> typeName;
4377 llvm::raw_svector_ostream(typeName)
4378 << "__block_literal_" << CGM.getUniqueBlockCount();
4380 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
4382 llvm::DIType *type =
4383 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
4384 CGM.getContext().toBits(block.BlockSize), 0,
4385 llvm::DINode::FlagZero, nullptr, fieldsArray);
4386 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
4388 // Get overall information about the block.
4389 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
4390 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
4392 // Create the descriptor for the parameter.
4393 auto *debugVar = DBuilder.createParameterVariable(
4394 scope, Name, ArgNo, tunit, line, type, CGM.getLangOpts().Optimize, flags);
4396 // Insert an llvm.dbg.declare into the current block.
4397 DBuilder.insertDeclare(Alloca, debugVar, DBuilder.createExpression(),
4398 llvm::DebugLoc::get(line, column, scope, CurInlinedAt),
4399 Builder.GetInsertBlock());
4402 llvm::DIDerivedType *
4403 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
4404 if (!D || !D->isStaticDataMember())
4407 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
4408 if (MI != StaticDataMemberCache.end()) {
4409 assert(MI->second && "Static data member declaration should still exist");
4413 // If the member wasn't found in the cache, lazily construct and add it to the
4414 // type (used when a limited form of the type is emitted).
4415 auto DC = D->getDeclContext();
4416 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
4417 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
4420 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
4421 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
4422 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
4423 llvm::DIGlobalVariableExpression *GVE = nullptr;
4425 for (const auto *Field : RD->fields()) {
4426 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
4427 StringRef FieldName = Field->getName();
4429 // Ignore unnamed fields, but recurse into anonymous records.
4430 if (FieldName.empty()) {
4431 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
4432 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
4436 // Use VarDecl's Tag, Scope and Line number.
4437 GVE = DBuilder.createGlobalVariableExpression(
4438 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
4439 Var->hasLocalLinkage());
4440 Var->addDebugInfo(GVE);
4445 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
4447 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4448 if (D->hasAttr<NoDebugAttr>())
4451 llvm::TimeTraceScope TimeScope("DebugGlobalVariable", [&]() {
4453 llvm::raw_string_ostream OS(Name);
4454 D->getNameForDiagnostic(OS, getPrintingPolicy(),
4455 /*Qualified=*/true);
4459 // If we already created a DIGlobalVariable for this declaration, just attach
4460 // it to the llvm::GlobalVariable.
4461 auto Cached = DeclCache.find(D->getCanonicalDecl());
4462 if (Cached != DeclCache.end())
4463 return Var->addDebugInfo(
4464 cast<llvm::DIGlobalVariableExpression>(Cached->second));
4466 // Create global variable debug descriptor.
4467 llvm::DIFile *Unit = nullptr;
4468 llvm::DIScope *DContext = nullptr;
4470 StringRef DeclName, LinkageName;
4472 llvm::MDTuple *TemplateParameters = nullptr;
4473 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName,
4474 TemplateParameters, DContext);
4476 // Attempt to store one global variable for the declaration - even if we
4477 // emit a lot of fields.
4478 llvm::DIGlobalVariableExpression *GVE = nullptr;
4480 // If this is an anonymous union then we'll want to emit a global
4481 // variable for each member of the anonymous union so that it's possible
4482 // to find the name of any field in the union.
4483 if (T->isUnionType() && DeclName.empty()) {
4484 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
4485 assert(RD->isAnonymousStructOrUnion() &&
4486 "unnamed non-anonymous struct or union?");
4487 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
4489 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4491 SmallVector<int64_t, 4> Expr;
4492 unsigned AddressSpace =
4493 CGM.getContext().getTargetAddressSpace(D->getType());
4494 if (CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) {
4495 if (D->hasAttr<CUDASharedAttr>())
4497 CGM.getContext().getTargetAddressSpace(LangAS::cuda_shared);
4498 else if (D->hasAttr<CUDAConstantAttr>())
4500 CGM.getContext().getTargetAddressSpace(LangAS::cuda_constant);
4502 AppendAddressSpaceXDeref(AddressSpace, Expr);
4504 GVE = DBuilder.createGlobalVariableExpression(
4505 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
4506 Var->hasLocalLinkage(), true,
4507 Expr.empty() ? nullptr : DBuilder.createExpression(Expr),
4508 getOrCreateStaticDataMemberDeclarationOrNull(D), TemplateParameters,
4510 Var->addDebugInfo(GVE);
4512 DeclCache[D->getCanonicalDecl()].reset(GVE);
4515 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
4516 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4517 if (VD->hasAttr<NoDebugAttr>())
4519 llvm::TimeTraceScope TimeScope("DebugConstGlobalVariable", [&]() {
4521 llvm::raw_string_ostream OS(Name);
4522 VD->getNameForDiagnostic(OS, getPrintingPolicy(),
4523 /*Qualified=*/true);
4527 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
4528 // Create the descriptor for the variable.
4529 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
4530 StringRef Name = VD->getName();
4531 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
4533 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
4534 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
4535 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
4537 if (CGM.getCodeGenOpts().EmitCodeView) {
4538 // If CodeView, emit enums as global variables, unless they are defined
4539 // inside a class. We do this because MSVC doesn't emit S_CONSTANTs for
4540 // enums in classes, and because it is difficult to attach this scope
4541 // information to the global variable.
4542 if (isa<RecordDecl>(ED->getDeclContext()))
4545 // If not CodeView, emit DW_TAG_enumeration_type if necessary. For
4546 // example: for "enum { ZERO };", a DW_TAG_enumeration_type is created the
4547 // first time `ZERO` is referenced in a function.
4548 llvm::DIType *EDTy =
4549 getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
4550 assert (EDTy->getTag() == llvm::dwarf::DW_TAG_enumeration_type);
4556 llvm::DIScope *DContext = nullptr;
4558 // Do not emit separate definitions for function local consts.
4559 if (isa<FunctionDecl>(VD->getDeclContext()))
4562 // Emit definition for static members in CodeView.
4563 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4564 auto *VarD = dyn_cast<VarDecl>(VD);
4565 if (VarD && VarD->isStaticDataMember()) {
4566 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
4567 getDeclContextDescriptor(VarD);
4568 // Ensure that the type is retained even though it's otherwise unreferenced.
4570 // FIXME: This is probably unnecessary, since Ty should reference RD
4571 // through its scope.
4572 RetainedTypes.push_back(
4573 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
4575 if (!CGM.getCodeGenOpts().EmitCodeView)
4578 // Use the global scope for static members.
4579 DContext = getContextDescriptor(
4580 cast<Decl>(CGM.getContext().getTranslationUnitDecl()), TheCU);
4582 DContext = getDeclContextDescriptor(VD);
4585 auto &GV = DeclCache[VD];
4588 llvm::DIExpression *InitExpr = nullptr;
4589 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
4590 // FIXME: Add a representation for integer constants wider than 64 bits.
4593 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
4594 else if (Init.isFloat())
4595 InitExpr = DBuilder.createConstantValueExpression(
4596 Init.getFloat().bitcastToAPInt().getZExtValue());
4599 llvm::MDTuple *TemplateParameters = nullptr;
4601 if (isa<VarTemplateSpecializationDecl>(VD))
4603 llvm::DINodeArray parameterNodes = CollectVarTemplateParams(VarD, &*Unit);
4604 TemplateParameters = parameterNodes.get();
4607 GV.reset(DBuilder.createGlobalVariableExpression(
4608 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
4609 true, true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
4610 TemplateParameters, Align));
4613 void CGDebugInfo::EmitExternalVariable(llvm::GlobalVariable *Var,
4615 assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
4616 if (D->hasAttr<NoDebugAttr>())
4619 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
4620 llvm::DIFile *Unit = getOrCreateFile(D->getLocation());
4621 StringRef Name = D->getName();
4622 llvm::DIType *Ty = getOrCreateType(D->getType(), Unit);
4624 llvm::DIScope *DContext = getDeclContextDescriptor(D);
4625 llvm::DIGlobalVariableExpression *GVE =
4626 DBuilder.createGlobalVariableExpression(
4627 DContext, Name, StringRef(), Unit, getLineNumber(D->getLocation()),
4628 Ty, false, false, nullptr, nullptr, nullptr, Align);
4629 Var->addDebugInfo(GVE);
4632 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
4633 if (!LexicalBlockStack.empty())
4634 return LexicalBlockStack.back();
4635 llvm::DIScope *Mod = getParentModuleOrNull(D);
4636 return getContextDescriptor(D, Mod ? Mod : TheCU);
4639 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
4640 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4642 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
4643 if (!NSDecl->isAnonymousNamespace() ||
4644 CGM.getCodeGenOpts().DebugExplicitImport) {
4645 auto Loc = UD.getLocation();
4646 DBuilder.createImportedModule(
4647 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
4648 getOrCreateNamespace(NSDecl), getOrCreateFile(Loc), getLineNumber(Loc));
4652 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
4653 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4655 assert(UD.shadow_size() &&
4656 "We shouldn't be codegening an invalid UsingDecl containing no decls");
4657 // Emitting one decl is sufficient - debuggers can detect that this is an
4658 // overloaded name & provide lookup for all the overloads.
4659 const UsingShadowDecl &USD = **UD.shadow_begin();
4661 // FIXME: Skip functions with undeduced auto return type for now since we
4662 // don't currently have the plumbing for separate declarations & definitions
4663 // of free functions and mismatched types (auto in the declaration, concrete
4664 // return type in the definition)
4665 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
4666 if (const auto *AT =
4667 FD->getType()->castAs<FunctionProtoType>()->getContainedAutoType())
4668 if (AT->getDeducedType().isNull())
4670 if (llvm::DINode *Target =
4671 getDeclarationOrDefinition(USD.getUnderlyingDecl())) {
4672 auto Loc = USD.getLocation();
4673 DBuilder.createImportedDeclaration(
4674 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
4675 getOrCreateFile(Loc), getLineNumber(Loc));
4679 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
4680 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
4682 if (Module *M = ID.getImportedModule()) {
4683 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
4684 auto Loc = ID.getLocation();
4685 DBuilder.createImportedDeclaration(
4686 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
4687 getOrCreateModuleRef(Info, DebugTypeExtRefs), getOrCreateFile(Loc),
4688 getLineNumber(Loc));
4692 llvm::DIImportedEntity *
4693 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
4694 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4696 auto &VH = NamespaceAliasCache[&NA];
4698 return cast<llvm::DIImportedEntity>(VH);
4699 llvm::DIImportedEntity *R;
4700 auto Loc = NA.getLocation();
4701 if (const auto *Underlying =
4702 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
4703 // This could cache & dedup here rather than relying on metadata deduping.
4704 R = DBuilder.createImportedDeclaration(
4705 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4706 EmitNamespaceAlias(*Underlying), getOrCreateFile(Loc),
4707 getLineNumber(Loc), NA.getName());
4709 R = DBuilder.createImportedDeclaration(
4710 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
4711 getOrCreateNamespace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
4712 getOrCreateFile(Loc), getLineNumber(Loc), NA.getName());
4718 CGDebugInfo::getOrCreateNamespace(const NamespaceDecl *NSDecl) {
4719 // Don't canonicalize the NamespaceDecl here: The DINamespace will be uniqued
4720 // if necessary, and this way multiple declarations of the same namespace in
4721 // different parent modules stay distinct.
4722 auto I = NamespaceCache.find(NSDecl);
4723 if (I != NamespaceCache.end())
4724 return cast<llvm::DINamespace>(I->second);
4726 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
4727 // Don't trust the context if it is a DIModule (see comment above).
4728 llvm::DINamespace *NS =
4729 DBuilder.createNameSpace(Context, NSDecl->getName(), NSDecl->isInline());
4730 NamespaceCache[NSDecl].reset(NS);
4734 void CGDebugInfo::setDwoId(uint64_t Signature) {
4735 assert(TheCU && "no main compile unit");
4736 TheCU->setDWOId(Signature);
4739 void CGDebugInfo::finalize() {
4740 // Creating types might create further types - invalidating the current
4741 // element and the size(), so don't cache/reference them.
4742 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
4743 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
4744 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
4745 ? CreateTypeDefinition(E.Type, E.Unit)
4747 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
4750 // Add methods to interface.
4751 for (const auto &P : ObjCMethodCache) {
4752 if (P.second.empty())
4755 QualType QTy(P.first->getTypeForDecl(), 0);
4756 auto It = TypeCache.find(QTy.getAsOpaquePtr());
4757 assert(It != TypeCache.end());
4759 llvm::DICompositeType *InterfaceDecl =
4760 cast<llvm::DICompositeType>(It->second);
4762 auto CurElts = InterfaceDecl->getElements();
4763 SmallVector<llvm::Metadata *, 16> EltTys(CurElts.begin(), CurElts.end());
4765 // For DWARF v4 or earlier, only add objc_direct methods.
4766 for (auto &SubprogramDirect : P.second)
4767 if (CGM.getCodeGenOpts().DwarfVersion >= 5 || SubprogramDirect.getInt())
4768 EltTys.push_back(SubprogramDirect.getPointer());
4770 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
4771 DBuilder.replaceArrays(InterfaceDecl, Elements);
4774 for (const auto &P : ReplaceMap) {
4776 auto *Ty = cast<llvm::DIType>(P.second);
4777 assert(Ty->isForwardDecl());
4779 auto It = TypeCache.find(P.first);
4780 assert(It != TypeCache.end());
4783 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
4784 cast<llvm::DIType>(It->second));
4787 for (const auto &P : FwdDeclReplaceMap) {
4789 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(P.second));
4790 llvm::Metadata *Repl;
4792 auto It = DeclCache.find(P.first);
4793 // If there has been no definition for the declaration, call RAUW
4794 // with ourselves, that will destroy the temporary MDNode and
4795 // replace it with a standard one, avoiding leaking memory.
4796 if (It == DeclCache.end())
4801 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
4802 Repl = GVE->getVariable();
4803 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
4806 // We keep our own list of retained types, because we need to look
4807 // up the final type in the type cache.
4808 for (auto &RT : RetainedTypes)
4809 if (auto MD = TypeCache[RT])
4810 DBuilder.retainType(cast<llvm::DIType>(MD));
4812 DBuilder.finalize();
4815 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
4816 if (!CGM.getCodeGenOpts().hasReducedDebugInfo())
4819 if (auto *DieTy = getOrCreateType(Ty, TheCU->getFile()))
4820 // Don't ignore in case of explicit cast where it is referenced indirectly.
4821 DBuilder.retainType(DieTy);
4824 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
4825 if (LexicalBlockStack.empty())
4826 return llvm::DebugLoc();
4828 llvm::MDNode *Scope = LexicalBlockStack.back();
4829 return llvm::DebugLoc::get(getLineNumber(Loc), getColumnNumber(Loc), Scope);
4832 llvm::DINode::DIFlags CGDebugInfo::getCallSiteRelatedAttrs() const {
4833 // Call site-related attributes are only useful in optimized programs, and
4834 // when there's a possibility of debugging backtraces.
4835 if (!CGM.getLangOpts().Optimize || DebugKind == codegenoptions::NoDebugInfo ||
4836 DebugKind == codegenoptions::LocTrackingOnly)
4837 return llvm::DINode::FlagZero;
4839 // Call site-related attributes are available in DWARF v5. Some debuggers,
4840 // while not fully DWARF v5-compliant, may accept these attributes as if they
4841 // were part of DWARF v4.
4842 bool SupportsDWARFv4Ext =
4843 CGM.getCodeGenOpts().DwarfVersion == 4 &&
4844 (CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::LLDB ||
4845 CGM.getCodeGenOpts().getDebuggerTuning() == llvm::DebuggerKind::GDB);
4847 if (!SupportsDWARFv4Ext && CGM.getCodeGenOpts().DwarfVersion < 5 &&
4848 !CGM.getCodeGenOpts().EnableDebugEntryValues)
4849 return llvm::DINode::FlagZero;
4851 return llvm::DINode::FlagAllCallsDescribed;