1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CGRecordLayout.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/Basic/FileManager.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/Version.h"
30 #include "clang/Frontend/CodeGenOptions.h"
31 #include "clang/Lex/HeaderSearchOptions.h"
32 #include "clang/Lex/ModuleMap.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DataLayout.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Instructions.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/Module.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 using namespace clang;
47 using namespace clang::CodeGen;
49 static uint32_t getTypeAlignIfRequired(const Type *Ty, const ASTContext &Ctx) {
50 auto TI = Ctx.getTypeInfo(Ty);
51 return TI.AlignIsRequired ? TI.Align : 0;
54 static uint32_t getTypeAlignIfRequired(QualType Ty, const ASTContext &Ctx) {
55 return getTypeAlignIfRequired(Ty.getTypePtr(), Ctx);
58 static uint32_t getDeclAlignIfRequired(const Decl *D, const ASTContext &Ctx) {
59 return D->hasAttr<AlignedAttr>() ? D->getMaxAlignment() : 0;
62 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
63 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
64 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
65 DBuilder(CGM.getModule()) {
66 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
67 DebugPrefixMap[KV.first] = KV.second;
71 CGDebugInfo::~CGDebugInfo() {
72 assert(LexicalBlockStack.empty() &&
73 "Region stack mismatch, stack not empty!");
76 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
77 SourceLocation TemporaryLocation)
79 init(TemporaryLocation);
82 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
84 SourceLocation TemporaryLocation)
86 init(TemporaryLocation, DefaultToEmpty);
89 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
90 bool DefaultToEmpty) {
91 auto *DI = CGF->getDebugInfo();
97 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
98 if (TemporaryLocation.isValid()) {
99 DI->EmitLocation(CGF->Builder, TemporaryLocation);
103 if (DefaultToEmpty) {
104 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
108 // Construct a location that has a valid scope, but no line info.
109 assert(!DI->LexicalBlockStack.empty());
110 CGF->Builder.SetCurrentDebugLocation(
111 llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
114 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
116 init(E->getExprLoc());
119 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
121 if (!CGF.getDebugInfo()) {
125 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
127 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
130 ApplyDebugLocation::~ApplyDebugLocation() {
131 // Query CGF so the location isn't overwritten when location updates are
132 // temporarily disabled (for C++ default function arguments)
134 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
137 void CGDebugInfo::setLocation(SourceLocation Loc) {
138 // If the new location isn't valid return.
142 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
144 // If we've changed files in the middle of a lexical scope go ahead
145 // and create a new lexical scope with file node if it's different
146 // from the one in the scope.
147 if (LexicalBlockStack.empty())
150 SourceManager &SM = CGM.getContext().getSourceManager();
151 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
152 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
154 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
157 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
158 LexicalBlockStack.pop_back();
159 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
160 LBF->getScope(), getOrCreateFile(CurLoc)));
161 } else if (isa<llvm::DILexicalBlock>(Scope) ||
162 isa<llvm::DISubprogram>(Scope)) {
163 LexicalBlockStack.pop_back();
164 LexicalBlockStack.emplace_back(
165 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
169 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
170 llvm::DIScope *Mod = getParentModuleOrNull(D);
171 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
175 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
176 llvm::DIScope *Default) {
180 auto I = RegionMap.find(Context);
181 if (I != RegionMap.end()) {
182 llvm::Metadata *V = I->second;
183 return dyn_cast_or_null<llvm::DIScope>(V);
187 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
188 return getOrCreateNameSpace(NSDecl);
190 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
191 if (!RDecl->isDependentType())
192 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
193 getOrCreateMainFile());
197 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
198 assert(FD && "Invalid FunctionDecl!");
199 IdentifierInfo *FII = FD->getIdentifier();
200 FunctionTemplateSpecializationInfo *Info =
201 FD->getTemplateSpecializationInfo();
203 // Emit the unqualified name in normal operation. LLVM and the debugger can
204 // compute the fully qualified name from the scope chain. If we're only
205 // emitting line table info, there won't be any scope chains, so emit the
206 // fully qualified name here so that stack traces are more accurate.
207 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
208 // evaluating the size impact.
209 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
210 CGM.getCodeGenOpts().EmitCodeView;
212 if (!Info && FII && !UseQualifiedName)
213 return FII->getName();
216 llvm::raw_svector_ostream OS(NS);
217 PrintingPolicy Policy(CGM.getLangOpts());
218 Policy.MSVCFormatting = CGM.getCodeGenOpts().EmitCodeView;
219 if (!UseQualifiedName)
222 FD->printQualifiedName(OS, Policy);
224 // Add any template specialization args.
226 const TemplateArgumentList *TArgs = Info->TemplateArguments;
227 TemplateSpecializationType::PrintTemplateArgumentList(OS, TArgs->asArray(),
231 // Copy this name on the side and use its reference.
232 return internString(OS.str());
235 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
236 SmallString<256> MethodName;
237 llvm::raw_svector_ostream OS(MethodName);
238 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
239 const DeclContext *DC = OMD->getDeclContext();
240 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
241 OS << OID->getName();
242 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
243 OS << OID->getName();
244 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
245 if (OC->IsClassExtension()) {
246 OS << OC->getClassInterface()->getName();
248 OS << OC->getIdentifier()->getNameStart() << '('
249 << OC->getIdentifier()->getNameStart() << ')';
251 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
252 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
253 << OCD->getIdentifier()->getNameStart() << ')';
254 } else if (isa<ObjCProtocolDecl>(DC)) {
255 // We can extract the type of the class from the self pointer.
256 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
258 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
259 ClassTy.print(OS, PrintingPolicy(LangOptions()));
262 OS << ' ' << OMD->getSelector().getAsString() << ']';
264 return internString(OS.str());
267 StringRef CGDebugInfo::getSelectorName(Selector S) {
268 return internString(S.getAsString());
271 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
272 if (isa<ClassTemplateSpecializationDecl>(RD)) {
273 SmallString<128> Name;
274 llvm::raw_svector_ostream OS(Name);
275 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
276 /*Qualified*/ false);
278 // Copy this name on the side and use its reference.
279 return internString(Name);
282 // quick optimization to avoid having to intern strings that are already
283 // stored reliably elsewhere
284 if (const IdentifierInfo *II = RD->getIdentifier())
285 return II->getName();
287 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
288 // used to reconstruct the fully qualified type names.
289 if (CGM.getCodeGenOpts().EmitCodeView) {
290 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
291 assert(RD->getDeclContext() == D->getDeclContext() &&
292 "Typedef should not be in another decl context!");
293 assert(D->getDeclName().getAsIdentifierInfo() &&
294 "Typedef was not named!");
295 return D->getDeclName().getAsIdentifierInfo()->getName();
298 if (CGM.getLangOpts().CPlusPlus) {
301 ASTContext &Context = CGM.getContext();
302 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
303 // Anonymous types without a name for linkage purposes have their
304 // declarator mangled in if they have one.
305 Name = DD->getName();
306 else if (const TypedefNameDecl *TND =
307 Context.getTypedefNameForUnnamedTagDecl(RD))
308 // Anonymous types without a name for linkage purposes have their
309 // associate typedef mangled in if they have one.
310 Name = TND->getName();
313 SmallString<256> UnnamedType("<unnamed-type-");
316 return internString(UnnamedType);
324 llvm::DIFile::ChecksumKind
325 CGDebugInfo::computeChecksum(FileID FID, SmallString<32> &Checksum) const {
328 if (!CGM.getCodeGenOpts().EmitCodeView)
329 return llvm::DIFile::CSK_None;
331 SourceManager &SM = CGM.getContext().getSourceManager();
333 llvm::MemoryBuffer *MemBuffer = SM.getBuffer(FID, &Invalid);
335 return llvm::DIFile::CSK_None;
338 llvm::MD5::MD5Result Result;
340 Hash.update(MemBuffer->getBuffer());
343 Hash.stringifyResult(Result, Checksum);
344 return llvm::DIFile::CSK_MD5;
347 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
349 // If Location is not valid then use main input file.
350 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
351 remapDIPath(TheCU->getDirectory()),
352 TheCU->getFile()->getChecksumKind(),
353 TheCU->getFile()->getChecksum());
355 SourceManager &SM = CGM.getContext().getSourceManager();
356 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
358 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
359 // If the location is not valid then use main input file.
360 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
361 remapDIPath(TheCU->getDirectory()),
362 TheCU->getFile()->getChecksumKind(),
363 TheCU->getFile()->getChecksum());
365 // Cache the results.
366 const char *fname = PLoc.getFilename();
367 auto it = DIFileCache.find(fname);
369 if (it != DIFileCache.end()) {
370 // Verify that the information still exists.
371 if (llvm::Metadata *V = it->second)
372 return cast<llvm::DIFile>(V);
375 SmallString<32> Checksum;
376 llvm::DIFile::ChecksumKind CSKind =
377 computeChecksum(SM.getFileID(Loc), Checksum);
379 llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
380 remapDIPath(getCurrentDirname()),
383 DIFileCache[fname].reset(F);
387 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
388 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
389 remapDIPath(TheCU->getDirectory()),
390 TheCU->getFile()->getChecksumKind(),
391 TheCU->getFile()->getChecksum());
394 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
395 for (const auto &Entry : DebugPrefixMap)
396 if (Path.startswith(Entry.first))
397 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
401 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
402 if (Loc.isInvalid() && CurLoc.isInvalid())
404 SourceManager &SM = CGM.getContext().getSourceManager();
405 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
406 return PLoc.isValid() ? PLoc.getLine() : 0;
409 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
410 // We may not want column information at all.
411 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
414 // If the location is invalid then use the current column.
415 if (Loc.isInvalid() && CurLoc.isInvalid())
417 SourceManager &SM = CGM.getContext().getSourceManager();
418 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
419 return PLoc.isValid() ? PLoc.getColumn() : 0;
422 StringRef CGDebugInfo::getCurrentDirname() {
423 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
424 return CGM.getCodeGenOpts().DebugCompilationDir;
426 if (!CWDName.empty())
428 SmallString<256> CWD;
429 llvm::sys::fs::current_path(CWD);
430 return CWDName = internString(CWD);
433 void CGDebugInfo::CreateCompileUnit() {
434 SmallString<32> Checksum;
435 llvm::DIFile::ChecksumKind CSKind = llvm::DIFile::CSK_None;
437 // Should we be asking the SourceManager for the main file name, instead of
438 // accepting it as an argument? This just causes the main file name to
439 // mismatch with source locations and create extra lexical scopes or
440 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
441 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
442 // because that's what the SourceManager says)
444 // Get absolute path name.
445 SourceManager &SM = CGM.getContext().getSourceManager();
446 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
447 if (MainFileName.empty())
448 MainFileName = "<stdin>";
450 // The main file name provided via the "-main-file-name" option contains just
451 // the file name itself with no path information. This file name may have had
452 // a relative path, so we look into the actual file entry for the main
453 // file to determine the real absolute path for the file.
454 std::string MainFileDir;
455 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
456 MainFileDir = remapDIPath(MainFile->getDir()->getName());
457 if (MainFileDir != ".") {
458 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
459 llvm::sys::path::append(MainFileDirSS, MainFileName);
460 MainFileName = MainFileDirSS.str();
462 CSKind = computeChecksum(SM.getMainFileID(), Checksum);
465 llvm::dwarf::SourceLanguage LangTag;
466 const LangOptions &LO = CGM.getLangOpts();
469 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
471 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
472 } else if (LO.ObjC1) {
473 LangTag = llvm::dwarf::DW_LANG_ObjC;
474 } else if (LO.RenderScript) {
475 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
477 LangTag = llvm::dwarf::DW_LANG_C99;
479 LangTag = llvm::dwarf::DW_LANG_C89;
482 std::string Producer = getClangFullVersion();
484 // Figure out which version of the ObjC runtime we have.
485 unsigned RuntimeVers = 0;
487 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
489 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
491 case codegenoptions::NoDebugInfo:
492 case codegenoptions::LocTrackingOnly:
493 EmissionKind = llvm::DICompileUnit::NoDebug;
495 case codegenoptions::DebugLineTablesOnly:
496 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
498 case codegenoptions::LimitedDebugInfo:
499 case codegenoptions::FullDebugInfo:
500 EmissionKind = llvm::DICompileUnit::FullDebug;
504 // Create new compile unit.
505 // FIXME - Eliminate TheCU.
506 TheCU = DBuilder.createCompileUnit(
507 LangTag, DBuilder.createFile(remapDIPath(MainFileName),
508 remapDIPath(getCurrentDirname()), CSKind,
510 Producer, LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers,
511 CGM.getCodeGenOpts().SplitDwarfFile, EmissionKind, 0 /* DWOid */,
512 CGM.getCodeGenOpts().SplitDwarfInlining);
515 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
516 llvm::dwarf::TypeKind Encoding;
518 switch (BT->getKind()) {
519 #define BUILTIN_TYPE(Id, SingletonId)
520 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
521 #include "clang/AST/BuiltinTypes.def"
522 case BuiltinType::Dependent:
523 llvm_unreachable("Unexpected builtin type");
524 case BuiltinType::NullPtr:
525 return DBuilder.createNullPtrType();
526 case BuiltinType::Void:
528 case BuiltinType::ObjCClass:
530 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
532 getOrCreateMainFile(), 0);
534 case BuiltinType::ObjCId: {
535 // typedef struct objc_class *Class;
536 // typedef struct objc_object {
544 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
546 getOrCreateMainFile(), 0);
548 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
550 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
552 ObjTy = DBuilder.createStructType(
553 TheCU, "objc_object", getOrCreateMainFile(), 0, 0, 0,
554 llvm::DINode::FlagZero, nullptr, llvm::DINodeArray());
556 DBuilder.replaceArrays(
557 ObjTy, DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
558 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0,
559 llvm::DINode::FlagZero, ISATy)));
562 case BuiltinType::ObjCSel: {
564 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
565 "objc_selector", TheCU,
566 getOrCreateMainFile(), 0);
570 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
571 case BuiltinType::Id: \
572 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
574 #include "clang/Basic/OpenCLImageTypes.def"
575 case BuiltinType::OCLSampler:
576 return getOrCreateStructPtrType("opencl_sampler_t",
578 case BuiltinType::OCLEvent:
579 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
580 case BuiltinType::OCLClkEvent:
581 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
582 case BuiltinType::OCLQueue:
583 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
584 case BuiltinType::OCLNDRange:
585 return getOrCreateStructPtrType("opencl_ndrange_t", OCLNDRangeDITy);
586 case BuiltinType::OCLReserveID:
587 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
589 case BuiltinType::UChar:
590 case BuiltinType::Char_U:
591 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
593 case BuiltinType::Char_S:
594 case BuiltinType::SChar:
595 Encoding = llvm::dwarf::DW_ATE_signed_char;
597 case BuiltinType::Char16:
598 case BuiltinType::Char32:
599 Encoding = llvm::dwarf::DW_ATE_UTF;
601 case BuiltinType::UShort:
602 case BuiltinType::UInt:
603 case BuiltinType::UInt128:
604 case BuiltinType::ULong:
605 case BuiltinType::WChar_U:
606 case BuiltinType::ULongLong:
607 Encoding = llvm::dwarf::DW_ATE_unsigned;
609 case BuiltinType::Short:
610 case BuiltinType::Int:
611 case BuiltinType::Int128:
612 case BuiltinType::Long:
613 case BuiltinType::WChar_S:
614 case BuiltinType::LongLong:
615 Encoding = llvm::dwarf::DW_ATE_signed;
617 case BuiltinType::Bool:
618 Encoding = llvm::dwarf::DW_ATE_boolean;
620 case BuiltinType::Half:
621 case BuiltinType::Float:
622 case BuiltinType::LongDouble:
623 case BuiltinType::Float128:
624 case BuiltinType::Double:
625 // FIXME: For targets where long double and __float128 have the same size,
626 // they are currently indistinguishable in the debugger without some
627 // special treatment. However, there is currently no consensus on encoding
628 // and this should be updated once a DWARF encoding exists for distinct
629 // floating point types of the same size.
630 Encoding = llvm::dwarf::DW_ATE_float;
634 switch (BT->getKind()) {
635 case BuiltinType::Long:
638 case BuiltinType::LongLong:
639 BTName = "long long int";
641 case BuiltinType::ULong:
642 BTName = "long unsigned int";
644 case BuiltinType::ULongLong:
645 BTName = "long long unsigned int";
648 BTName = BT->getName(CGM.getLangOpts());
651 // Bit size and offset of the type.
652 uint64_t Size = CGM.getContext().getTypeSize(BT);
653 return DBuilder.createBasicType(BTName, Size, Encoding);
656 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
657 // Bit size and offset of the type.
658 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
659 if (Ty->isComplexIntegerType())
660 Encoding = llvm::dwarf::DW_ATE_lo_user;
662 uint64_t Size = CGM.getContext().getTypeSize(Ty);
663 return DBuilder.createBasicType("complex", Size, Encoding);
666 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
667 llvm::DIFile *Unit) {
668 QualifierCollector Qc;
669 const Type *T = Qc.strip(Ty);
671 // Ignore these qualifiers for now.
672 Qc.removeObjCGCAttr();
673 Qc.removeAddressSpace();
674 Qc.removeObjCLifetime();
676 // We will create one Derived type for one qualifier and recurse to handle any
678 llvm::dwarf::Tag Tag;
680 Tag = llvm::dwarf::DW_TAG_const_type;
682 } else if (Qc.hasVolatile()) {
683 Tag = llvm::dwarf::DW_TAG_volatile_type;
685 } else if (Qc.hasRestrict()) {
686 Tag = llvm::dwarf::DW_TAG_restrict_type;
689 assert(Qc.empty() && "Unknown type qualifier for debug info");
690 return getOrCreateType(QualType(T, 0), Unit);
693 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
695 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
696 // CVR derived types.
697 return DBuilder.createQualifiedType(Tag, FromTy);
700 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
701 llvm::DIFile *Unit) {
703 // The frontend treats 'id' as a typedef to an ObjCObjectType,
704 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
705 // debug info, we want to emit 'id' in both cases.
706 if (Ty->isObjCQualifiedIdType())
707 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
709 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
710 Ty->getPointeeType(), Unit);
713 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
714 llvm::DIFile *Unit) {
715 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
716 Ty->getPointeeType(), Unit);
719 /// \return whether a C++ mangling exists for the type defined by TD.
720 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
721 switch (TheCU->getSourceLanguage()) {
722 case llvm::dwarf::DW_LANG_C_plus_plus:
724 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
725 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
731 /// In C++ mode, types have linkage, so we can rely on the ODR and
732 /// on their mangled names, if they're external.
733 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
735 llvm::DICompileUnit *TheCU) {
736 SmallString<256> FullName;
737 const TagDecl *TD = Ty->getDecl();
739 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
742 // TODO: This is using the RTTI name. Is there a better way to get
743 // a unique string for a type?
744 llvm::raw_svector_ostream Out(FullName);
745 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
749 /// \return the approproate DWARF tag for a composite type.
750 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
751 llvm::dwarf::Tag Tag;
752 if (RD->isStruct() || RD->isInterface())
753 Tag = llvm::dwarf::DW_TAG_structure_type;
754 else if (RD->isUnion())
755 Tag = llvm::dwarf::DW_TAG_union_type;
757 // FIXME: This could be a struct type giving a default visibility different
758 // than C++ class type, but needs llvm metadata changes first.
759 assert(RD->isClass());
760 Tag = llvm::dwarf::DW_TAG_class_type;
765 llvm::DICompositeType *
766 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
767 llvm::DIScope *Ctx) {
768 const RecordDecl *RD = Ty->getDecl();
769 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
770 return cast<llvm::DICompositeType>(T);
771 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
772 unsigned Line = getLineNumber(RD->getLocation());
773 StringRef RDName = getClassName(RD);
779 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
780 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
781 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
782 llvm::DINode::FlagFwdDecl, FullName);
783 ReplaceMap.emplace_back(
784 std::piecewise_construct, std::make_tuple(Ty),
785 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
789 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
792 llvm::DIFile *Unit) {
793 // Bit size, align and offset of the type.
794 // Size is always the size of a pointer. We can't use getTypeSize here
795 // because that does not return the correct value for references.
796 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
797 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
798 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
800 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
801 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
802 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
805 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
809 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
810 llvm::DIType *&Cache) {
813 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
814 TheCU, getOrCreateMainFile(), 0);
815 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
816 Cache = DBuilder.createPointerType(Cache, Size);
820 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
821 llvm::DIFile *Unit) {
822 SmallVector<llvm::Metadata *, 8> EltTys;
824 uint64_t FieldSize, FieldOffset;
826 llvm::DINodeArray Elements;
829 FType = CGM.getContext().UnsignedLongTy;
830 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
831 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
833 Elements = DBuilder.getOrCreateArray(EltTys);
836 llvm::DINode::DIFlags Flags = llvm::DINode::FlagAppleBlock;
840 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
841 FieldOffset, 0, Flags, nullptr, Elements);
843 // Bit size, align and offset of the type.
844 uint64_t Size = CGM.getContext().getTypeSize(Ty);
846 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
849 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
850 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
851 FType = CGM.getContext().IntTy;
852 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
853 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
854 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
855 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
857 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
858 FieldSize = CGM.getContext().getTypeSize(Ty);
859 FieldAlign = CGM.getContext().getTypeAlign(Ty);
860 EltTys.push_back(DBuilder.createMemberType(
861 Unit, "__descriptor", nullptr, LineNo, FieldSize, FieldAlign, FieldOffset,
862 llvm::DINode::FlagZero, DescTy));
864 FieldOffset += FieldSize;
865 Elements = DBuilder.getOrCreateArray(EltTys);
867 // The __block_literal_generic structs are marked with a special
868 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
869 // the debugger needs to know about. To allow type uniquing, emit
870 // them without a name or a location.
872 DBuilder.createStructType(Unit, "", nullptr, LineNo,
873 FieldOffset, 0, Flags, nullptr, Elements);
875 return DBuilder.createPointerType(EltTy, Size);
878 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
879 llvm::DIFile *Unit) {
880 assert(Ty->isTypeAlias());
881 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
884 llvm::raw_svector_ostream OS(NS);
885 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
886 /*qualified*/ false);
888 TemplateSpecializationType::PrintTemplateArgumentList(
889 OS, Ty->template_arguments(),
890 CGM.getContext().getPrintingPolicy());
892 auto *AliasDecl = cast<TypeAliasTemplateDecl>(
893 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
895 SourceLocation Loc = AliasDecl->getLocation();
896 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
898 getDeclContextDescriptor(AliasDecl));
901 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
902 llvm::DIFile *Unit) {
903 // We don't set size information, but do specify where the typedef was
905 SourceLocation Loc = Ty->getDecl()->getLocation();
907 // Typedefs are derived from some other type.
908 return DBuilder.createTypedef(
909 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
910 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
911 getDeclContextDescriptor(Ty->getDecl()));
914 static unsigned getDwarfCC(CallingConv CC) {
917 // Avoid emitting DW_AT_calling_convention if the C convention was used.
921 return llvm::dwarf::DW_CC_BORLAND_stdcall;
923 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
925 return llvm::dwarf::DW_CC_BORLAND_thiscall;
926 case CC_X86VectorCall:
927 return llvm::dwarf::DW_CC_LLVM_vectorcall;
929 return llvm::dwarf::DW_CC_BORLAND_pascal;
931 // FIXME: Create new DW_CC_ codes for these calling conventions.
936 case CC_IntelOclBicc:
937 case CC_SpirFunction:
938 case CC_OpenCLKernel:
940 case CC_PreserveMost:
948 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
949 llvm::DIFile *Unit) {
950 SmallVector<llvm::Metadata *, 16> EltTys;
952 // Add the result type at least.
953 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
955 // Set up remainder of arguments if there is a prototype.
956 // otherwise emit it as a variadic function.
957 if (isa<FunctionNoProtoType>(Ty))
958 EltTys.push_back(DBuilder.createUnspecifiedParameter());
959 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
960 for (const QualType &ParamType : FPT->param_types())
961 EltTys.push_back(getOrCreateType(ParamType, Unit));
962 if (FPT->isVariadic())
963 EltTys.push_back(DBuilder.createUnspecifiedParameter());
966 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
967 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
968 getDwarfCC(Ty->getCallConv()));
971 /// Convert an AccessSpecifier into the corresponding DINode flag.
972 /// As an optimization, return 0 if the access specifier equals the
973 /// default for the containing type.
974 static llvm::DINode::DIFlags getAccessFlag(AccessSpecifier Access,
975 const RecordDecl *RD) {
976 AccessSpecifier Default = clang::AS_none;
977 if (RD && RD->isClass())
978 Default = clang::AS_private;
979 else if (RD && (RD->isStruct() || RD->isUnion()))
980 Default = clang::AS_public;
982 if (Access == Default)
983 return llvm::DINode::FlagZero;
986 case clang::AS_private:
987 return llvm::DINode::FlagPrivate;
988 case clang::AS_protected:
989 return llvm::DINode::FlagProtected;
990 case clang::AS_public:
991 return llvm::DINode::FlagPublic;
993 return llvm::DINode::FlagZero;
995 llvm_unreachable("unexpected access enumerator");
998 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
999 llvm::DIScope *RecordTy,
1000 const RecordDecl *RD) {
1001 StringRef Name = BitFieldDecl->getName();
1002 QualType Ty = BitFieldDecl->getType();
1003 SourceLocation Loc = BitFieldDecl->getLocation();
1004 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1005 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
1007 // Get the location for the field.
1008 llvm::DIFile *File = getOrCreateFile(Loc);
1009 unsigned Line = getLineNumber(Loc);
1011 const CGBitFieldInfo &BitFieldInfo =
1012 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
1013 uint64_t SizeInBits = BitFieldInfo.Size;
1014 assert(SizeInBits > 0 && "found named 0-width bitfield");
1015 uint64_t StorageOffsetInBits =
1016 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
1017 uint64_t OffsetInBits = StorageOffsetInBits + BitFieldInfo.Offset;
1018 llvm::DINode::DIFlags Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
1019 return DBuilder.createBitFieldMemberType(
1020 RecordTy, Name, File, Line, SizeInBits, OffsetInBits, StorageOffsetInBits,
1025 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
1026 AccessSpecifier AS, uint64_t offsetInBits,
1027 uint32_t AlignInBits, llvm::DIFile *tunit,
1028 llvm::DIScope *scope, const RecordDecl *RD) {
1029 llvm::DIType *debugType = getOrCreateType(type, tunit);
1031 // Get the location for the field.
1032 llvm::DIFile *file = getOrCreateFile(loc);
1033 unsigned line = getLineNumber(loc);
1035 uint64_t SizeInBits = 0;
1036 auto Align = AlignInBits;
1037 if (!type->isIncompleteArrayType()) {
1038 TypeInfo TI = CGM.getContext().getTypeInfo(type);
1039 SizeInBits = TI.Width;
1041 Align = getTypeAlignIfRequired(type, CGM.getContext());
1044 llvm::DINode::DIFlags flags = getAccessFlag(AS, RD);
1045 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
1046 Align, offsetInBits, flags, debugType);
1049 void CGDebugInfo::CollectRecordLambdaFields(
1050 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1051 llvm::DIType *RecordTy) {
1052 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1053 // has the name and the location of the variable so we should iterate over
1054 // both concurrently.
1055 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1056 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1057 unsigned fieldno = 0;
1058 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1059 E = CXXDecl->captures_end();
1060 I != E; ++I, ++Field, ++fieldno) {
1061 const LambdaCapture &C = *I;
1062 if (C.capturesVariable()) {
1063 SourceLocation Loc = C.getLocation();
1064 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1065 VarDecl *V = C.getCapturedVar();
1066 StringRef VName = V->getName();
1067 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1068 auto Align = getDeclAlignIfRequired(V, CGM.getContext());
1069 llvm::DIType *FieldType = createFieldType(
1070 VName, Field->getType(), Loc, Field->getAccess(),
1071 layout.getFieldOffset(fieldno), Align, VUnit, RecordTy, CXXDecl);
1072 elements.push_back(FieldType);
1073 } else if (C.capturesThis()) {
1074 // TODO: Need to handle 'this' in some way by probably renaming the
1075 // this of the lambda class and having a field member of 'this' or
1076 // by using AT_object_pointer for the function and having that be
1077 // used as 'this' for semantic references.
1078 FieldDecl *f = *Field;
1079 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1080 QualType type = f->getType();
1081 llvm::DIType *fieldType = createFieldType(
1082 "this", type, f->getLocation(), f->getAccess(),
1083 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1085 elements.push_back(fieldType);
1090 llvm::DIDerivedType *
1091 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1092 const RecordDecl *RD) {
1093 // Create the descriptor for the static variable, with or without
1094 // constant initializers.
1095 Var = Var->getCanonicalDecl();
1096 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1097 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1099 unsigned LineNumber = getLineNumber(Var->getLocation());
1100 StringRef VName = Var->getName();
1101 llvm::Constant *C = nullptr;
1102 if (Var->getInit()) {
1103 const APValue *Value = Var->evaluateValue();
1106 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1107 if (Value->isFloat())
1108 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1112 llvm::DINode::DIFlags Flags = getAccessFlag(Var->getAccess(), RD);
1113 auto Align = getDeclAlignIfRequired(Var, CGM.getContext());
1114 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1115 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C, Align);
1116 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1120 void CGDebugInfo::CollectRecordNormalField(
1121 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1122 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1123 const RecordDecl *RD) {
1124 StringRef name = field->getName();
1125 QualType type = field->getType();
1127 // Ignore unnamed fields unless they're anonymous structs/unions.
1128 if (name.empty() && !type->isRecordType())
1131 llvm::DIType *FieldType;
1132 if (field->isBitField()) {
1133 FieldType = createBitFieldType(field, RecordTy, RD);
1135 auto Align = getDeclAlignIfRequired(field, CGM.getContext());
1137 createFieldType(name, type, field->getLocation(), field->getAccess(),
1138 OffsetInBits, Align, tunit, RecordTy, RD);
1141 elements.push_back(FieldType);
1144 void CGDebugInfo::CollectRecordNestedRecord(
1145 const RecordDecl *RD, SmallVectorImpl<llvm::Metadata *> &elements) {
1146 QualType Ty = CGM.getContext().getTypeDeclType(RD);
1147 // Injected class names are not considered nested records.
1148 if (isa<InjectedClassNameType>(Ty))
1150 SourceLocation Loc = RD->getLocation();
1151 llvm::DIType *nestedType = getOrCreateType(Ty, getOrCreateFile(Loc));
1152 elements.push_back(nestedType);
1155 void CGDebugInfo::CollectRecordFields(
1156 const RecordDecl *record, llvm::DIFile *tunit,
1157 SmallVectorImpl<llvm::Metadata *> &elements,
1158 llvm::DICompositeType *RecordTy) {
1159 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1161 if (CXXDecl && CXXDecl->isLambda())
1162 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1164 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1166 // Debug info for nested records is included in the member list only for
1168 bool IncludeNestedRecords = CGM.getCodeGenOpts().EmitCodeView;
1170 // Field number for non-static fields.
1171 unsigned fieldNo = 0;
1173 // Static and non-static members should appear in the same order as
1174 // the corresponding declarations in the source program.
1175 for (const auto *I : record->decls())
1176 if (const auto *V = dyn_cast<VarDecl>(I)) {
1177 if (V->hasAttr<NoDebugAttr>())
1179 // Reuse the existing static member declaration if one exists
1180 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1181 if (MI != StaticDataMemberCache.end()) {
1182 assert(MI->second &&
1183 "Static data member declaration should still exist");
1184 elements.push_back(MI->second);
1186 auto Field = CreateRecordStaticField(V, RecordTy, record);
1187 elements.push_back(Field);
1189 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1190 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1191 elements, RecordTy, record);
1193 // Bump field number for next field.
1195 } else if (const auto *nestedRec = dyn_cast<CXXRecordDecl>(I))
1196 if (IncludeNestedRecords && !nestedRec->isImplicit() &&
1197 nestedRec->getDeclContext() == record)
1198 CollectRecordNestedRecord(nestedRec, elements);
1202 llvm::DISubroutineType *
1203 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1204 llvm::DIFile *Unit) {
1205 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1206 if (Method->isStatic())
1207 return cast_or_null<llvm::DISubroutineType>(
1208 getOrCreateType(QualType(Func, 0), Unit));
1209 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1213 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1214 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1215 // Add "this" pointer.
1216 llvm::DITypeRefArray Args(
1217 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1219 assert(Args.size() && "Invalid number of arguments!");
1221 SmallVector<llvm::Metadata *, 16> Elts;
1223 // First element is always return type. For 'void' functions it is NULL.
1224 Elts.push_back(Args[0]);
1226 // "this" pointer is always first argument.
1227 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1228 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1229 // Create pointer type directly in this case.
1230 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1231 QualType PointeeTy = ThisPtrTy->getPointeeType();
1232 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1233 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1234 auto Align = getTypeAlignIfRequired(ThisPtrTy, CGM.getContext());
1235 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1236 llvm::DIType *ThisPtrType =
1237 DBuilder.createPointerType(PointeeType, Size, Align);
1238 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1239 // TODO: This and the artificial type below are misleading, the
1240 // types aren't artificial the argument is, but the current
1241 // metadata doesn't represent that.
1242 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1243 Elts.push_back(ThisPtrType);
1245 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1246 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1247 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1248 Elts.push_back(ThisPtrType);
1251 // Copy rest of the arguments.
1252 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1253 Elts.push_back(Args[i]);
1255 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1257 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1258 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1259 Flags |= llvm::DINode::FlagLValueReference;
1260 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1261 Flags |= llvm::DINode::FlagRValueReference;
1263 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1264 getDwarfCC(Func->getCallConv()));
1267 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1268 /// inside a function.
1269 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1270 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1271 return isFunctionLocalClass(NRD);
1272 if (isa<FunctionDecl>(RD->getDeclContext()))
1277 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1278 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1280 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1282 StringRef MethodName = getFunctionName(Method);
1283 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1285 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1286 // make sense to give a single ctor/dtor a linkage name.
1287 StringRef MethodLinkageName;
1288 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1289 // property to use here. It may've been intended to model "is non-external
1290 // type" but misses cases of non-function-local but non-external classes such
1291 // as those in anonymous namespaces as well as the reverse - external types
1292 // that are function local, such as those in (non-local) inline functions.
1293 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1294 MethodLinkageName = CGM.getMangledName(Method);
1296 // Get the location for the method.
1297 llvm::DIFile *MethodDefUnit = nullptr;
1298 unsigned MethodLine = 0;
1299 if (!Method->isImplicit()) {
1300 MethodDefUnit = getOrCreateFile(Method->getLocation());
1301 MethodLine = getLineNumber(Method->getLocation());
1304 // Collect virtual method info.
1305 llvm::DIType *ContainingType = nullptr;
1306 unsigned Virtuality = 0;
1307 unsigned VIndex = 0;
1308 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
1309 int ThisAdjustment = 0;
1311 if (Method->isVirtual()) {
1312 if (Method->isPure())
1313 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1315 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1317 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1318 // It doesn't make sense to give a virtual destructor a vtable index,
1319 // since a single destructor has two entries in the vtable.
1320 if (!isa<CXXDestructorDecl>(Method))
1321 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1323 // Emit MS ABI vftable information. There is only one entry for the
1325 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1326 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1327 MicrosoftVTableContext::MethodVFTableLocation ML =
1328 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1331 // CodeView only records the vftable offset in the class that introduces
1332 // the virtual method. This is possible because, unlike Itanium, the MS
1333 // C++ ABI does not include all virtual methods from non-primary bases in
1334 // the vtable for the most derived class. For example, if C inherits from
1335 // A and B, C's primary vftable will not include B's virtual methods.
1336 if (Method->begin_overridden_methods() == Method->end_overridden_methods())
1337 Flags |= llvm::DINode::FlagIntroducedVirtual;
1339 // The 'this' adjustment accounts for both the virtual and non-virtual
1340 // portions of the adjustment. Presumably the debugger only uses it when
1341 // it knows the dynamic type of an object.
1342 ThisAdjustment = CGM.getCXXABI()
1343 .getVirtualFunctionPrologueThisAdjustment(GD)
1346 ContainingType = RecordTy;
1349 if (Method->isImplicit())
1350 Flags |= llvm::DINode::FlagArtificial;
1351 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1352 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1353 if (CXXC->isExplicit())
1354 Flags |= llvm::DINode::FlagExplicit;
1355 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1356 if (CXXC->isExplicit())
1357 Flags |= llvm::DINode::FlagExplicit;
1359 if (Method->hasPrototype())
1360 Flags |= llvm::DINode::FlagPrototyped;
1361 if (Method->getRefQualifier() == RQ_LValue)
1362 Flags |= llvm::DINode::FlagLValueReference;
1363 if (Method->getRefQualifier() == RQ_RValue)
1364 Flags |= llvm::DINode::FlagRValueReference;
1366 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1367 llvm::DISubprogram *SP = DBuilder.createMethod(
1368 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1369 MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
1370 VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
1371 TParamsArray.get());
1373 SPCache[Method->getCanonicalDecl()].reset(SP);
1378 void CGDebugInfo::CollectCXXMemberFunctions(
1379 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1380 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1382 // Since we want more than just the individual member decls if we
1383 // have templated functions iterate over every declaration to gather
1385 for (const auto *I : RD->decls()) {
1386 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1387 // If the member is implicit, don't add it to the member list. This avoids
1388 // the member being added to type units by LLVM, while still allowing it
1389 // to be emitted into the type declaration/reference inside the compile
1391 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1392 // FIXME: Handle Using(Shadow?)Decls here to create
1393 // DW_TAG_imported_declarations inside the class for base decls brought into
1394 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1395 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1397 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1400 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1403 // Reuse the existing member function declaration if it exists.
1404 // It may be associated with the declaration of the type & should be
1405 // reused as we're building the definition.
1407 // This situation can arise in the vtable-based debug info reduction where
1408 // implicit members are emitted in a non-vtable TU.
1409 auto MI = SPCache.find(Method->getCanonicalDecl());
1410 EltTys.push_back(MI == SPCache.end()
1411 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1412 : static_cast<llvm::Metadata *>(MI->second));
1416 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1417 SmallVectorImpl<llvm::Metadata *> &EltTys,
1418 llvm::DIType *RecordTy) {
1419 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> SeenTypes;
1420 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->bases(), SeenTypes,
1421 llvm::DINode::FlagZero);
1423 // If we are generating CodeView debug info, we also need to emit records for
1424 // indirect virtual base classes.
1425 if (CGM.getCodeGenOpts().EmitCodeView) {
1426 CollectCXXBasesAux(RD, Unit, EltTys, RecordTy, RD->vbases(), SeenTypes,
1427 llvm::DINode::FlagIndirectVirtualBase);
1431 void CGDebugInfo::CollectCXXBasesAux(
1432 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1433 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy,
1434 const CXXRecordDecl::base_class_const_range &Bases,
1435 llvm::DenseSet<CanonicalDeclPtr<const CXXRecordDecl>> &SeenTypes,
1436 llvm::DINode::DIFlags StartingFlags) {
1437 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1438 for (const auto &BI : Bases) {
1440 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1441 if (!SeenTypes.insert(Base).second)
1443 auto *BaseTy = getOrCreateType(BI.getType(), Unit);
1444 llvm::DINode::DIFlags BFlags = StartingFlags;
1445 uint64_t BaseOffset;
1447 if (BI.isVirtual()) {
1448 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1449 // virtual base offset offset is -ve. The code generator emits dwarf
1450 // expression where it expects +ve number.
1451 BaseOffset = 0 - CGM.getItaniumVTableContext()
1452 .getVirtualBaseOffsetOffset(RD, Base)
1455 // In the MS ABI, store the vbtable offset, which is analogous to the
1456 // vbase offset offset in Itanium.
1458 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1460 BFlags |= llvm::DINode::FlagVirtual;
1462 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1463 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1464 // BI->isVirtual() and bits when not.
1466 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1468 DBuilder.createInheritance(RecordTy, BaseTy, BaseOffset, BFlags);
1469 EltTys.push_back(DTy);
1474 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1475 ArrayRef<TemplateArgument> TAList,
1476 llvm::DIFile *Unit) {
1477 SmallVector<llvm::Metadata *, 16> TemplateParams;
1478 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1479 const TemplateArgument &TA = TAList[i];
1482 Name = TPList->getParam(i)->getName();
1483 switch (TA.getKind()) {
1484 case TemplateArgument::Type: {
1485 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1486 TemplateParams.push_back(
1487 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1489 case TemplateArgument::Integral: {
1490 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1491 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1493 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1495 case TemplateArgument::Declaration: {
1496 const ValueDecl *D = TA.getAsDecl();
1497 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1498 llvm::DIType *TTy = getOrCreateType(T, Unit);
1499 llvm::Constant *V = nullptr;
1500 const CXXMethodDecl *MD;
1501 // Variable pointer template parameters have a value that is the address
1503 if (const auto *VD = dyn_cast<VarDecl>(D))
1504 V = CGM.GetAddrOfGlobalVar(VD);
1505 // Member function pointers have special support for building them, though
1506 // this is currently unsupported in LLVM CodeGen.
1507 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1508 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1509 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1510 V = CGM.GetAddrOfFunction(FD);
1511 // Member data pointers have special handling too to compute the fixed
1512 // offset within the object.
1513 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1514 // These five lines (& possibly the above member function pointer
1515 // handling) might be able to be refactored to use similar code in
1516 // CodeGenModule::getMemberPointerConstant
1517 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1519 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1520 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1522 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1524 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1526 case TemplateArgument::NullPtr: {
1527 QualType T = TA.getNullPtrType();
1528 llvm::DIType *TTy = getOrCreateType(T, Unit);
1529 llvm::Constant *V = nullptr;
1530 // Special case member data pointer null values since they're actually -1
1532 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1533 // But treat member function pointers as simple zero integers because
1534 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1535 // CodeGen grows handling for values of non-null member function
1536 // pointers then perhaps we could remove this special case and rely on
1537 // EmitNullMemberPointer for member function pointers.
1538 if (MPT->isMemberDataPointer())
1539 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1541 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1542 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1543 TheCU, Name, TTy, V));
1545 case TemplateArgument::Template:
1546 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1547 TheCU, Name, nullptr,
1548 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1550 case TemplateArgument::Pack:
1551 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1552 TheCU, Name, nullptr,
1553 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1555 case TemplateArgument::Expression: {
1556 const Expr *E = TA.getAsExpr();
1557 QualType T = E->getType();
1559 T = CGM.getContext().getLValueReferenceType(T);
1560 llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1561 assert(V && "Expression in template argument isn't constant");
1562 llvm::DIType *TTy = getOrCreateType(T, Unit);
1563 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1564 TheCU, Name, TTy, V->stripPointerCasts()));
1566 // And the following should never occur:
1567 case TemplateArgument::TemplateExpansion:
1568 case TemplateArgument::Null:
1570 "These argument types shouldn't exist in concrete types");
1573 return DBuilder.getOrCreateArray(TemplateParams);
1577 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1578 llvm::DIFile *Unit) {
1579 if (FD->getTemplatedKind() ==
1580 FunctionDecl::TK_FunctionTemplateSpecialization) {
1581 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1583 ->getTemplateParameters();
1584 return CollectTemplateParams(
1585 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1587 return llvm::DINodeArray();
1590 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1591 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1592 // Always get the full list of parameters, not just the ones from
1593 // the specialization.
1594 TemplateParameterList *TPList =
1595 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1596 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1597 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1600 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1602 return VTablePtrType;
1604 ASTContext &Context = CGM.getContext();
1607 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1608 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1609 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1610 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1611 llvm::DIType *vtbl_ptr_type =
1612 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1613 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1614 return VTablePtrType;
1617 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1618 // Copy the gdb compatible name on the side and use its reference.
1619 return internString("_vptr$", RD->getNameAsString());
1622 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1623 SmallVectorImpl<llvm::Metadata *> &EltTys,
1624 llvm::DICompositeType *RecordTy) {
1625 // If this class is not dynamic then there is not any vtable info to collect.
1626 if (!RD->isDynamicClass())
1629 // Don't emit any vtable shape or vptr info if this class doesn't have an
1630 // extendable vfptr. This can happen if the class doesn't have virtual
1631 // methods, or in the MS ABI if those virtual methods only come from virtually
1633 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1634 if (!RL.hasExtendableVFPtr())
1637 // CodeView needs to know how large the vtable of every dynamic class is, so
1638 // emit a special named pointer type into the element list. The vptr type
1639 // points to this type as well.
1640 llvm::DIType *VPtrTy = nullptr;
1641 bool NeedVTableShape = CGM.getCodeGenOpts().EmitCodeView &&
1642 CGM.getTarget().getCXXABI().isMicrosoft();
1643 if (NeedVTableShape) {
1645 CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1646 const VTableLayout &VFTLayout =
1647 CGM.getMicrosoftVTableContext().getVFTableLayout(RD, CharUnits::Zero());
1648 unsigned VSlotCount =
1649 VFTLayout.vtable_components().size() - CGM.getLangOpts().RTTIData;
1650 unsigned VTableWidth = PtrWidth * VSlotCount;
1652 // Create a very wide void* type and insert it directly in the element list.
1653 llvm::DIType *VTableType =
1654 DBuilder.createPointerType(nullptr, VTableWidth, 0, "__vtbl_ptr_type");
1655 EltTys.push_back(VTableType);
1657 // The vptr is a pointer to this special vtable type.
1658 VPtrTy = DBuilder.createPointerType(VTableType, PtrWidth);
1661 // If there is a primary base then the artificial vptr member lives there.
1662 if (RL.getPrimaryBase())
1666 VPtrTy = getOrCreateVTablePtrType(Unit);
1668 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1669 llvm::DIType *VPtrMember = DBuilder.createMemberType(
1670 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1671 llvm::DINode::FlagArtificial, VPtrTy);
1672 EltTys.push_back(VPtrMember);
1675 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1676 SourceLocation Loc) {
1677 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1678 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1682 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1683 SourceLocation Loc) {
1684 return getOrCreateStandaloneType(D, Loc);
1687 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1688 SourceLocation Loc) {
1689 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1690 assert(!D.isNull() && "null type");
1691 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1692 assert(T && "could not create debug info for type");
1694 RetainedTypes.push_back(D.getAsOpaquePtr());
1698 void CGDebugInfo::completeType(const EnumDecl *ED) {
1699 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1701 QualType Ty = CGM.getContext().getEnumType(ED);
1702 void *TyPtr = Ty.getAsOpaquePtr();
1703 auto I = TypeCache.find(TyPtr);
1704 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1706 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1707 assert(!Res->isForwardDecl());
1708 TypeCache[TyPtr].reset(Res);
1711 void CGDebugInfo::completeType(const RecordDecl *RD) {
1712 if (DebugKind > codegenoptions::LimitedDebugInfo ||
1713 !CGM.getLangOpts().CPlusPlus)
1714 completeRequiredType(RD);
1717 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1718 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1720 QualType Ty = CGM.getContext().getRecordType(RD);
1721 void *TyPtr = Ty.getAsOpaquePtr();
1722 auto I = TypeCache.find(TyPtr);
1723 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1725 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1726 assert(!Res->isForwardDecl());
1727 TypeCache[TyPtr].reset(Res);
1730 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1731 CXXRecordDecl::method_iterator End) {
1732 for (CXXMethodDecl *MD : llvm::make_range(I, End))
1733 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
1734 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1735 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
1740 /// Does a type definition exist in an imported clang module?
1741 static bool isDefinedInClangModule(const RecordDecl *RD) {
1742 // Only definitions that where imported from an AST file come from a module.
1743 if (!RD || !RD->isFromASTFile())
1745 // Anonymous entities cannot be addressed. Treat them as not from module.
1746 if (!RD->isExternallyVisible() && RD->getName().empty())
1748 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1749 if (!CXXDecl->isCompleteDefinition())
1751 auto TemplateKind = CXXDecl->getTemplateSpecializationKind();
1752 if (TemplateKind != TSK_Undeclared) {
1753 // This is a template, check the origin of the first member.
1754 if (CXXDecl->field_begin() == CXXDecl->field_end())
1755 return TemplateKind == TSK_ExplicitInstantiationDeclaration;
1756 if (!CXXDecl->field_begin()->isFromASTFile())
1763 /// Return true if the class or any of its methods are marked dllimport.
1764 static bool isClassOrMethodDLLImport(const CXXRecordDecl *RD) {
1765 if (RD->hasAttr<DLLImportAttr>())
1767 for (const CXXMethodDecl *MD : RD->methods())
1768 if (MD->hasAttr<DLLImportAttr>())
1773 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
1774 bool DebugTypeExtRefs, const RecordDecl *RD,
1775 const LangOptions &LangOpts) {
1776 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1779 if (DebugKind > codegenoptions::LimitedDebugInfo)
1782 if (!LangOpts.CPlusPlus)
1785 if (!RD->isCompleteDefinitionRequired())
1788 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1793 // Only emit complete debug info for a dynamic class when its vtable is
1794 // emitted. However, Microsoft debuggers don't resolve type information
1795 // across DLL boundaries, so skip this optimization if the class or any of its
1796 // methods are marked dllimport. This isn't a complete solution, since objects
1797 // without any dllimport methods can be used in one DLL and constructed in
1798 // another, but it is the current behavior of LimitedDebugInfo.
1799 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass() &&
1800 !isClassOrMethodDLLImport(CXXDecl))
1803 TemplateSpecializationKind Spec = TSK_Undeclared;
1804 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1805 Spec = SD->getSpecializationKind();
1807 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1808 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1809 CXXDecl->method_end()))
1815 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1816 if (shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD, CGM.getLangOpts()))
1819 QualType Ty = CGM.getContext().getRecordType(RD);
1820 llvm::DIType *T = getTypeOrNull(Ty);
1821 if (T && T->isForwardDecl())
1822 completeClassData(RD);
1825 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1826 RecordDecl *RD = Ty->getDecl();
1827 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1828 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
1829 CGM.getLangOpts())) {
1831 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
1835 return CreateTypeDefinition(Ty);
1838 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1839 RecordDecl *RD = Ty->getDecl();
1841 // Get overall information about the record type for the debug info.
1842 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1844 // Records and classes and unions can all be recursive. To handle them, we
1845 // first generate a debug descriptor for the struct as a forward declaration.
1846 // Then (if it is a definition) we go through and get debug info for all of
1847 // its members. Finally, we create a descriptor for the complete type (which
1848 // may refer to the forward decl if the struct is recursive) and replace all
1849 // uses of the forward declaration with the final definition.
1850 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1852 const RecordDecl *D = RD->getDefinition();
1853 if (!D || !D->isCompleteDefinition())
1856 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1857 CollectContainingType(CXXDecl, FwdDecl);
1859 // Push the struct on region stack.
1860 LexicalBlockStack.emplace_back(&*FwdDecl);
1861 RegionMap[Ty->getDecl()].reset(FwdDecl);
1863 // Convert all the elements.
1864 SmallVector<llvm::Metadata *, 16> EltTys;
1865 // what about nested types?
1867 // Note: The split of CXXDecl information here is intentional, the
1868 // gdb tests will depend on a certain ordering at printout. The debug
1869 // information offsets are still correct if we merge them all together
1871 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1873 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1874 CollectVTableInfo(CXXDecl, DefUnit, EltTys, FwdDecl);
1877 // Collect data fields (including static variables and any initializers).
1878 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1880 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1882 LexicalBlockStack.pop_back();
1883 RegionMap.erase(Ty->getDecl());
1885 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1886 DBuilder.replaceArrays(FwdDecl, Elements);
1888 if (FwdDecl->isTemporary())
1890 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1892 RegionMap[Ty->getDecl()].reset(FwdDecl);
1896 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1897 llvm::DIFile *Unit) {
1898 // Ignore protocols.
1899 return getOrCreateType(Ty->getBaseType(), Unit);
1902 llvm::DIType *CGDebugInfo::CreateType(const ObjCTypeParamType *Ty,
1903 llvm::DIFile *Unit) {
1904 // Ignore protocols.
1905 SourceLocation Loc = Ty->getDecl()->getLocation();
1907 // Use Typedefs to represent ObjCTypeParamType.
1908 return DBuilder.createTypedef(
1909 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
1910 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
1911 getDeclContextDescriptor(Ty->getDecl()));
1914 /// \return true if Getter has the default name for the property PD.
1915 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1916 const ObjCMethodDecl *Getter) {
1921 assert(Getter->getDeclName().isObjCZeroArgSelector());
1922 return PD->getName() ==
1923 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1926 /// \return true if Setter has the default name for the property PD.
1927 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1928 const ObjCMethodDecl *Setter) {
1933 assert(Setter->getDeclName().isObjCOneArgSelector());
1934 return SelectorTable::constructSetterName(PD->getName()) ==
1935 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1938 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1939 llvm::DIFile *Unit) {
1940 ObjCInterfaceDecl *ID = Ty->getDecl();
1944 // Return a forward declaration if this type was imported from a clang module,
1945 // and this is not the compile unit with the implementation of the type (which
1946 // may contain hidden ivars).
1947 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
1948 !ID->getImplementation())
1949 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1951 getDeclContextDescriptor(ID), Unit, 0);
1953 // Get overall information about the record type for the debug info.
1954 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1955 unsigned Line = getLineNumber(ID->getLocation());
1957 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1959 // If this is just a forward declaration return a special forward-declaration
1960 // debug type since we won't be able to lay out the entire type.
1961 ObjCInterfaceDecl *Def = ID->getDefinition();
1962 if (!Def || !Def->getImplementation()) {
1963 llvm::DIScope *Mod = getParentModuleOrNull(ID);
1964 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1965 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
1966 DefUnit, Line, RuntimeLang);
1967 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1971 return CreateTypeDefinition(Ty, Unit);
1975 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
1976 bool CreateSkeletonCU) {
1977 // Use the Module pointer as the key into the cache. This is a
1978 // nullptr if the "Module" is a PCH, which is safe because we don't
1979 // support chained PCH debug info, so there can only be a single PCH.
1980 const Module *M = Mod.getModuleOrNull();
1981 auto ModRef = ModuleCache.find(M);
1982 if (ModRef != ModuleCache.end())
1983 return cast<llvm::DIModule>(ModRef->second);
1985 // Macro definitions that were defined with "-D" on the command line.
1986 SmallString<128> ConfigMacros;
1988 llvm::raw_svector_ostream OS(ConfigMacros);
1989 const auto &PPOpts = CGM.getPreprocessorOpts();
1991 // Translate the macro definitions back into a commmand line.
1992 for (auto &M : PPOpts.Macros) {
1995 const std::string &Macro = M.first;
1996 bool Undef = M.second;
1997 OS << "\"-" << (Undef ? 'U' : 'D');
1998 for (char c : Macro)
2000 case '\\' : OS << "\\\\"; break;
2001 case '"' : OS << "\\\""; break;
2008 bool IsRootModule = M ? !M->Parent : true;
2009 if (CreateSkeletonCU && IsRootModule) {
2010 // PCH files don't have a signature field in the control block,
2011 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
2012 uint64_t Signature = Mod.getSignature() ? Mod.getSignature() : ~1ULL;
2013 llvm::DIBuilder DIB(CGM.getModule());
2014 DIB.createCompileUnit(TheCU->getSourceLanguage(),
2015 DIB.createFile(Mod.getModuleName(), Mod.getPath()),
2016 TheCU->getProducer(), true, StringRef(), 0,
2017 Mod.getASTFile(), llvm::DICompileUnit::FullDebug,
2021 llvm::DIModule *Parent =
2022 IsRootModule ? nullptr
2023 : getOrCreateModuleRef(
2024 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
2026 llvm::DIModule *DIMod =
2027 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
2028 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
2029 ModuleCache[M].reset(DIMod);
2033 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
2034 llvm::DIFile *Unit) {
2035 ObjCInterfaceDecl *ID = Ty->getDecl();
2036 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
2037 unsigned Line = getLineNumber(ID->getLocation());
2038 unsigned RuntimeLang = TheCU->getSourceLanguage();
2040 // Bit size, align and offset of the type.
2041 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2042 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2044 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2045 if (ID->getImplementation())
2046 Flags |= llvm::DINode::FlagObjcClassComplete;
2048 llvm::DIScope *Mod = getParentModuleOrNull(ID);
2049 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
2050 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
2051 nullptr, llvm::DINodeArray(), RuntimeLang);
2053 QualType QTy(Ty, 0);
2054 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
2056 // Push the struct on region stack.
2057 LexicalBlockStack.emplace_back(RealDecl);
2058 RegionMap[Ty->getDecl()].reset(RealDecl);
2060 // Convert all the elements.
2061 SmallVector<llvm::Metadata *, 16> EltTys;
2063 ObjCInterfaceDecl *SClass = ID->getSuperClass();
2065 llvm::DIType *SClassTy =
2066 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
2070 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0,
2071 llvm::DINode::FlagZero);
2072 EltTys.push_back(InhTag);
2075 // Create entries for all of the properties.
2076 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
2077 SourceLocation Loc = PD->getLocation();
2078 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2079 unsigned PLine = getLineNumber(Loc);
2080 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2081 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2082 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
2083 PD->getName(), PUnit, PLine,
2084 hasDefaultGetterName(PD, Getter) ? ""
2085 : getSelectorName(PD->getGetterName()),
2086 hasDefaultSetterName(PD, Setter) ? ""
2087 : getSelectorName(PD->getSetterName()),
2088 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
2089 EltTys.push_back(PropertyNode);
2092 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
2093 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
2094 for (auto *PD : ClassExt->properties()) {
2095 PropertySet.insert(PD->getIdentifier());
2098 for (const auto *PD : ID->properties()) {
2099 // Don't emit duplicate metadata for properties that were already in a
2101 if (!PropertySet.insert(PD->getIdentifier()).second)
2107 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
2108 unsigned FieldNo = 0;
2109 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
2110 Field = Field->getNextIvar(), ++FieldNo) {
2111 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2115 StringRef FieldName = Field->getName();
2117 // Ignore unnamed fields.
2118 if (FieldName.empty())
2121 // Get the location for the field.
2122 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
2123 unsigned FieldLine = getLineNumber(Field->getLocation());
2124 QualType FType = Field->getType();
2125 uint64_t FieldSize = 0;
2126 uint32_t FieldAlign = 0;
2128 if (!FType->isIncompleteArrayType()) {
2130 // Bit size, align and offset of the type.
2131 FieldSize = Field->isBitField()
2132 ? Field->getBitWidthValue(CGM.getContext())
2133 : CGM.getContext().getTypeSize(FType);
2134 FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2137 uint64_t FieldOffset;
2138 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2139 // We don't know the runtime offset of an ivar if we're using the
2140 // non-fragile ABI. For bitfields, use the bit offset into the first
2141 // byte of storage of the bitfield. For other fields, use zero.
2142 if (Field->isBitField()) {
2144 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
2145 FieldOffset %= CGM.getContext().getCharWidth();
2150 FieldOffset = RL.getFieldOffset(FieldNo);
2153 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2154 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2155 Flags = llvm::DINode::FlagProtected;
2156 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2157 Flags = llvm::DINode::FlagPrivate;
2158 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2159 Flags = llvm::DINode::FlagPublic;
2161 llvm::MDNode *PropertyNode = nullptr;
2162 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2163 if (ObjCPropertyImplDecl *PImpD =
2164 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2165 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2166 SourceLocation Loc = PD->getLocation();
2167 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2168 unsigned PLine = getLineNumber(Loc);
2169 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2170 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2171 PropertyNode = DBuilder.createObjCProperty(
2172 PD->getName(), PUnit, PLine,
2173 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
2174 PD->getGetterName()),
2175 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
2176 PD->getSetterName()),
2177 PD->getPropertyAttributes(),
2178 getOrCreateType(PD->getType(), PUnit));
2182 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2183 FieldSize, FieldAlign, FieldOffset, Flags,
2184 FieldTy, PropertyNode);
2185 EltTys.push_back(FieldTy);
2188 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2189 DBuilder.replaceArrays(RealDecl, Elements);
2191 LexicalBlockStack.pop_back();
2195 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2196 llvm::DIFile *Unit) {
2197 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2198 int64_t Count = Ty->getNumElements();
2200 // If number of elements are not known then this is an unbounded array.
2201 // Use Count == -1 to express such arrays.
2204 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
2205 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2207 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2208 auto Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2210 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2213 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2217 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2218 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2220 Align = getTypeAlignIfRequired(CGM.getContext().getBaseElementType(VAT),
2222 } else if (Ty->isIncompleteArrayType()) {
2224 if (Ty->getElementType()->isIncompleteType())
2227 Align = getTypeAlignIfRequired(Ty->getElementType(), CGM.getContext());
2228 } else if (Ty->isIncompleteType()) {
2232 // Size and align of the whole array, not the element type.
2233 Size = CGM.getContext().getTypeSize(Ty);
2234 Align = getTypeAlignIfRequired(Ty, CGM.getContext());
2237 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2238 // interior arrays, do we care? Why aren't nested arrays represented the
2239 // obvious/recursive way?
2240 SmallVector<llvm::Metadata *, 8> Subscripts;
2241 QualType EltTy(Ty, 0);
2242 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2243 // If the number of elements is known, then count is that number. Otherwise,
2244 // it's -1. This allows us to represent a subrange with an array of 0
2245 // elements, like this:
2250 int64_t Count = -1; // Count == -1 is an unbounded array.
2251 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2252 Count = CAT->getSize().getZExtValue();
2253 else if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2254 if (Expr *Size = VAT->getSizeExpr()) {
2256 if (Size->EvaluateAsInt(V, CGM.getContext()))
2257 Count = V.getExtValue();
2261 // FIXME: Verify this is right for VLAs.
2262 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2263 EltTy = Ty->getElementType();
2266 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2268 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2272 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2273 llvm::DIFile *Unit) {
2274 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2275 Ty->getPointeeType(), Unit);
2278 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2279 llvm::DIFile *Unit) {
2280 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2281 Ty->getPointeeType(), Unit);
2284 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2286 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2289 if (!Ty->isIncompleteType()) {
2290 Size = CGM.getContext().getTypeSize(Ty);
2292 // Set the MS inheritance model. There is no flag for the unspecified model.
2293 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2294 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2295 case MSInheritanceAttr::Keyword_single_inheritance:
2296 Flags |= llvm::DINode::FlagSingleInheritance;
2298 case MSInheritanceAttr::Keyword_multiple_inheritance:
2299 Flags |= llvm::DINode::FlagMultipleInheritance;
2301 case MSInheritanceAttr::Keyword_virtual_inheritance:
2302 Flags |= llvm::DINode::FlagVirtualInheritance;
2304 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2310 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2311 if (Ty->isMemberDataPointerType())
2312 return DBuilder.createMemberPointerType(
2313 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2316 const FunctionProtoType *FPT =
2317 Ty->getPointeeType()->getAs<FunctionProtoType>();
2318 return DBuilder.createMemberPointerType(
2319 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2320 Ty->getClass(), FPT->getTypeQuals())),
2322 ClassType, Size, /*Align=*/0, Flags);
2325 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2326 auto *FromTy = getOrCreateType(Ty->getValueType(), U);
2327 return DBuilder.createQualifiedType(llvm::dwarf::DW_TAG_atomic_type, FromTy);
2330 llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
2332 return getOrCreateType(Ty->getElementType(), U);
2335 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2336 const EnumDecl *ED = Ty->getDecl();
2340 if (!ED->getTypeForDecl()->isIncompleteType()) {
2341 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2342 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2345 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2347 bool isImportedFromModule =
2348 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2350 // If this is just a forward declaration, construct an appropriately
2351 // marked node and just return it.
2352 if (isImportedFromModule || !ED->getDefinition()) {
2353 // Note that it is possible for enums to be created as part of
2354 // their own declcontext. In this case a FwdDecl will be created
2355 // twice. This doesn't cause a problem because both FwdDecls are
2356 // entered into the ReplaceMap: finalize() will replace the first
2357 // FwdDecl with the second and then replace the second with
2359 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2360 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2361 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2362 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2364 unsigned Line = getLineNumber(ED->getLocation());
2365 StringRef EDName = ED->getName();
2366 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2367 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2368 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
2370 ReplaceMap.emplace_back(
2371 std::piecewise_construct, std::make_tuple(Ty),
2372 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2376 return CreateTypeDefinition(Ty);
2379 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2380 const EnumDecl *ED = Ty->getDecl();
2383 if (!ED->getTypeForDecl()->isIncompleteType()) {
2384 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2385 Align = getDeclAlignIfRequired(ED, CGM.getContext());
2388 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2390 // Create elements for each enumerator.
2391 SmallVector<llvm::Metadata *, 16> Enumerators;
2392 ED = ED->getDefinition();
2393 for (const auto *Enum : ED->enumerators()) {
2394 Enumerators.push_back(DBuilder.createEnumerator(
2395 Enum->getName(), Enum->getInitVal().getSExtValue()));
2398 // Return a CompositeType for the enum itself.
2399 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2401 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2402 unsigned Line = getLineNumber(ED->getLocation());
2403 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2404 llvm::DIType *ClassTy =
2405 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
2406 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2407 Line, Size, Align, EltArray, ClassTy,
2411 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2414 Qualifiers InnerQuals = T.getLocalQualifiers();
2415 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2416 // that is already there.
2417 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2418 Quals += InnerQuals;
2420 switch (T->getTypeClass()) {
2422 return C.getQualifiedType(T.getTypePtr(), Quals);
2423 case Type::TemplateSpecialization: {
2424 const auto *Spec = cast<TemplateSpecializationType>(T);
2425 if (Spec->isTypeAlias())
2426 return C.getQualifiedType(T.getTypePtr(), Quals);
2427 T = Spec->desugar();
2430 case Type::TypeOfExpr:
2431 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2434 T = cast<TypeOfType>(T)->getUnderlyingType();
2436 case Type::Decltype:
2437 T = cast<DecltypeType>(T)->getUnderlyingType();
2439 case Type::UnaryTransform:
2440 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2442 case Type::Attributed:
2443 T = cast<AttributedType>(T)->getEquivalentType();
2445 case Type::Elaborated:
2446 T = cast<ElaboratedType>(T)->getNamedType();
2449 T = cast<ParenType>(T)->getInnerType();
2451 case Type::SubstTemplateTypeParm:
2452 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2455 QualType DT = cast<AutoType>(T)->getDeducedType();
2456 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2460 case Type::Adjusted:
2462 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2463 T = cast<AdjustedType>(T)->getAdjustedType();
2467 assert(T != LastT && "Type unwrapping failed to unwrap!");
2472 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2474 // Unwrap the type as needed for debug information.
2475 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2477 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2478 if (it != TypeCache.end()) {
2479 // Verify that the debug info still exists.
2480 if (llvm::Metadata *V = it->second)
2481 return cast<llvm::DIType>(V);
2487 void CGDebugInfo::completeTemplateDefinition(
2488 const ClassTemplateSpecializationDecl &SD) {
2489 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2492 completeClassData(&SD);
2493 // In case this type has no member function definitions being emitted, ensure
2495 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2498 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2502 // Unwrap the type as needed for debug information.
2503 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2505 if (auto *T = getTypeOrNull(Ty))
2508 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2509 void* TyPtr = Ty.getAsOpaquePtr();
2511 // And update the type cache.
2512 TypeCache[TyPtr].reset(Res);
2517 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2518 // A forward declaration inside a module header does not belong to the module.
2519 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2521 if (DebugTypeExtRefs && D->isFromASTFile()) {
2522 // Record a reference to an imported clang module or precompiled header.
2523 auto *Reader = CGM.getContext().getExternalSource();
2524 auto Idx = D->getOwningModuleID();
2525 auto Info = Reader->getSourceDescriptor(Idx);
2527 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2528 } else if (ClangModuleMap) {
2529 // We are building a clang module or a precompiled header.
2531 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2532 // and it wouldn't be necessary to specify the parent scope
2533 // because the type is already unique by definition (it would look
2534 // like the output of -fno-standalone-debug). On the other hand,
2535 // the parent scope helps a consumer to quickly locate the object
2536 // file where the type's definition is located, so it might be
2537 // best to make this behavior a command line or debugger tuning
2539 FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
2540 if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
2541 // This is a (sub-)module.
2542 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2543 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2545 // This the precompiled header being built.
2546 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2553 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2554 // Handle qualifiers, which recursively handles what they refer to.
2555 if (Ty.hasLocalQualifiers())
2556 return CreateQualifiedType(Ty, Unit);
2558 // Work out details of type.
2559 switch (Ty->getTypeClass()) {
2560 #define TYPE(Class, Base)
2561 #define ABSTRACT_TYPE(Class, Base)
2562 #define NON_CANONICAL_TYPE(Class, Base)
2563 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2564 #include "clang/AST/TypeNodes.def"
2565 llvm_unreachable("Dependent types cannot show up in debug information");
2567 case Type::ExtVector:
2569 return CreateType(cast<VectorType>(Ty), Unit);
2570 case Type::ObjCObjectPointer:
2571 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2572 case Type::ObjCObject:
2573 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2574 case Type::ObjCTypeParam:
2575 return CreateType(cast<ObjCTypeParamType>(Ty), Unit);
2576 case Type::ObjCInterface:
2577 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2579 return CreateType(cast<BuiltinType>(Ty));
2581 return CreateType(cast<ComplexType>(Ty));
2583 return CreateType(cast<PointerType>(Ty), Unit);
2584 case Type::BlockPointer:
2585 return CreateType(cast<BlockPointerType>(Ty), Unit);
2587 return CreateType(cast<TypedefType>(Ty), Unit);
2589 return CreateType(cast<RecordType>(Ty));
2591 return CreateEnumType(cast<EnumType>(Ty));
2592 case Type::FunctionProto:
2593 case Type::FunctionNoProto:
2594 return CreateType(cast<FunctionType>(Ty), Unit);
2595 case Type::ConstantArray:
2596 case Type::VariableArray:
2597 case Type::IncompleteArray:
2598 return CreateType(cast<ArrayType>(Ty), Unit);
2600 case Type::LValueReference:
2601 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2602 case Type::RValueReference:
2603 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2605 case Type::MemberPointer:
2606 return CreateType(cast<MemberPointerType>(Ty), Unit);
2609 return CreateType(cast<AtomicType>(Ty), Unit);
2612 return CreateType(cast<PipeType>(Ty), Unit);
2614 case Type::TemplateSpecialization:
2615 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2618 case Type::Attributed:
2619 case Type::Adjusted:
2621 case Type::Elaborated:
2623 case Type::SubstTemplateTypeParm:
2624 case Type::TypeOfExpr:
2626 case Type::Decltype:
2627 case Type::UnaryTransform:
2628 case Type::PackExpansion:
2632 llvm_unreachable("type should have been unwrapped!");
2635 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2636 llvm::DIFile *Unit) {
2637 QualType QTy(Ty, 0);
2639 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2641 // We may have cached a forward decl when we could have created
2642 // a non-forward decl. Go ahead and create a non-forward decl
2644 if (T && !T->isForwardDecl())
2647 // Otherwise create the type.
2648 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2650 // Propagate members from the declaration to the definition
2651 // CreateType(const RecordType*) will overwrite this with the members in the
2652 // correct order if the full type is needed.
2653 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2655 // And update the type cache.
2656 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2660 // TODO: Currently used for context chains when limiting debug info.
2661 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2662 RecordDecl *RD = Ty->getDecl();
2664 // Get overall information about the record type for the debug info.
2665 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2666 unsigned Line = getLineNumber(RD->getLocation());
2667 StringRef RDName = getClassName(RD);
2669 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2671 // If we ended up creating the type during the context chain construction,
2672 // just return that.
2673 auto *T = cast_or_null<llvm::DICompositeType>(
2674 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2675 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2678 // If this is just a forward or incomplete declaration, construct an
2679 // appropriately marked node and just return it.
2680 const RecordDecl *D = RD->getDefinition();
2681 if (!D || !D->isCompleteDefinition())
2682 return getOrCreateRecordFwdDecl(Ty, RDContext);
2684 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2685 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
2687 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2689 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2690 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align,
2691 llvm::DINode::FlagZero, FullName);
2693 // Elements of composite types usually have back to the type, creating
2694 // uniquing cycles. Distinct nodes are more efficient.
2695 switch (RealDecl->getTag()) {
2697 llvm_unreachable("invalid composite type tag");
2699 case llvm::dwarf::DW_TAG_array_type:
2700 case llvm::dwarf::DW_TAG_enumeration_type:
2701 // Array elements and most enumeration elements don't have back references,
2702 // so they don't tend to be involved in uniquing cycles and there is some
2703 // chance of merging them when linking together two modules. Only make
2704 // them distinct if they are ODR-uniqued.
2705 if (FullName.empty())
2708 case llvm::dwarf::DW_TAG_structure_type:
2709 case llvm::dwarf::DW_TAG_union_type:
2710 case llvm::dwarf::DW_TAG_class_type:
2711 // Immediatley resolve to a distinct node.
2713 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
2717 RegionMap[Ty->getDecl()].reset(RealDecl);
2718 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2720 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2721 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2722 CollectCXXTemplateParams(TSpecial, DefUnit));
2726 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2727 llvm::DICompositeType *RealDecl) {
2728 // A class's primary base or the class itself contains the vtable.
2729 llvm::DICompositeType *ContainingType = nullptr;
2730 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2731 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2732 // Seek non-virtual primary base root.
2734 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2735 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2736 if (PBT && !BRL.isPrimaryBaseVirtual())
2741 ContainingType = cast<llvm::DICompositeType>(
2742 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2743 getOrCreateFile(RD->getLocation())));
2744 } else if (RD->isDynamicClass())
2745 ContainingType = RealDecl;
2747 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2750 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2751 StringRef Name, uint64_t *Offset) {
2752 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2753 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2754 auto FieldAlign = getTypeAlignIfRequired(FType, CGM.getContext());
2756 DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize, FieldAlign,
2757 *Offset, llvm::DINode::FlagZero, FieldTy);
2758 *Offset += FieldSize;
2762 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2764 StringRef &LinkageName,
2765 llvm::DIScope *&FDContext,
2766 llvm::DINodeArray &TParamsArray,
2767 llvm::DINode::DIFlags &Flags) {
2768 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2769 Name = getFunctionName(FD);
2770 // Use mangled name as linkage name for C/C++ functions.
2771 if (FD->hasPrototype()) {
2772 LinkageName = CGM.getMangledName(GD);
2773 Flags |= llvm::DINode::FlagPrototyped;
2775 // No need to replicate the linkage name if it isn't different from the
2776 // subprogram name, no need to have it at all unless coverage is enabled or
2777 // debug is set to more than just line tables.
2778 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
2779 !CGM.getCodeGenOpts().EmitGcovNotes &&
2780 DebugKind <= codegenoptions::DebugLineTablesOnly))
2781 LinkageName = StringRef();
2783 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
2784 if (const NamespaceDecl *NSDecl =
2785 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2786 FDContext = getOrCreateNameSpace(NSDecl);
2787 else if (const RecordDecl *RDecl =
2788 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
2789 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
2790 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
2792 // Check if it is a noreturn-marked function
2793 if (FD->isNoReturn())
2794 Flags |= llvm::DINode::FlagNoReturn;
2795 // Collect template parameters.
2796 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2800 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2801 unsigned &LineNo, QualType &T,
2802 StringRef &Name, StringRef &LinkageName,
2803 llvm::DIScope *&VDContext) {
2804 Unit = getOrCreateFile(VD->getLocation());
2805 LineNo = getLineNumber(VD->getLocation());
2807 setLocation(VD->getLocation());
2810 if (T->isIncompleteArrayType()) {
2811 // CodeGen turns int[] into int[1] so we'll do the same here.
2812 llvm::APInt ConstVal(32, 1);
2813 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2815 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2816 ArrayType::Normal, 0);
2819 Name = VD->getName();
2820 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2821 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2822 LinkageName = CGM.getMangledName(VD);
2823 if (LinkageName == Name)
2824 LinkageName = StringRef();
2826 // Since we emit declarations (DW_AT_members) for static members, place the
2827 // definition of those static members in the namespace they were declared in
2828 // in the source code (the lexical decl context).
2829 // FIXME: Generalize this for even non-member global variables where the
2830 // declaration and definition may have different lexical decl contexts, once
2831 // we have support for emitting declarations of (non-member) global variables.
2832 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2833 : VD->getDeclContext();
2834 // When a record type contains an in-line initialization of a static data
2835 // member, and the record type is marked as __declspec(dllexport), an implicit
2836 // definition of the member will be created in the record context. DWARF
2837 // doesn't seem to have a nice way to describe this in a form that consumers
2838 // are likely to understand, so fake the "normal" situation of a definition
2839 // outside the class by putting it in the global scope.
2841 DC = CGM.getContext().getTranslationUnitDecl();
2843 llvm::DIScope *Mod = getParentModuleOrNull(VD);
2844 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
2847 llvm::DISubprogram *
2848 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2849 llvm::DINodeArray TParamsArray;
2850 StringRef Name, LinkageName;
2851 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
2852 SourceLocation Loc = FD->getLocation();
2853 llvm::DIFile *Unit = getOrCreateFile(Loc);
2854 llvm::DIScope *DContext = Unit;
2855 unsigned Line = getLineNumber(Loc);
2857 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2858 TParamsArray, Flags);
2859 // Build function type.
2860 SmallVector<QualType, 16> ArgTypes;
2861 for (const ParmVarDecl *Parm: FD->parameters())
2862 ArgTypes.push_back(Parm->getType());
2863 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
2864 QualType FnType = CGM.getContext().getFunctionType(
2865 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
2866 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2867 DContext, Name, LinkageName, Unit, Line,
2868 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2869 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
2870 TParamsArray.get(), getFunctionDeclaration(FD));
2871 const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2872 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2873 std::make_tuple(CanonDecl),
2874 std::make_tuple(SP));
2878 llvm::DIGlobalVariable *
2879 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2881 StringRef Name, LinkageName;
2882 SourceLocation Loc = VD->getLocation();
2883 llvm::DIFile *Unit = getOrCreateFile(Loc);
2884 llvm::DIScope *DContext = Unit;
2885 unsigned Line = getLineNumber(Loc);
2887 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2888 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
2889 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2890 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2891 !VD->isExternallyVisible(), nullptr, Align);
2892 FwdDeclReplaceMap.emplace_back(
2893 std::piecewise_construct,
2894 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2895 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2899 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2900 // We only need a declaration (not a definition) of the type - so use whatever
2901 // we would otherwise do to get a type for a pointee. (forward declarations in
2902 // limited debug info, full definitions (if the type definition is available)
2903 // in unlimited debug info)
2904 if (const auto *TD = dyn_cast<TypeDecl>(D))
2905 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2906 getOrCreateFile(TD->getLocation()));
2907 auto I = DeclCache.find(D->getCanonicalDecl());
2909 if (I != DeclCache.end()) {
2911 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(N))
2912 return GVE->getVariable();
2913 return dyn_cast_or_null<llvm::DINode>(N);
2916 // No definition for now. Emit a forward definition that might be
2917 // merged with a potential upcoming definition.
2918 if (const auto *FD = dyn_cast<FunctionDecl>(D))
2919 return getFunctionForwardDeclaration(FD);
2920 else if (const auto *VD = dyn_cast<VarDecl>(D))
2921 return getGlobalVariableForwardDeclaration(VD);
2926 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2927 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
2930 const auto *FD = dyn_cast<FunctionDecl>(D);
2935 auto *S = getDeclContextDescriptor(D);
2937 auto MI = SPCache.find(FD->getCanonicalDecl());
2938 if (MI == SPCache.end()) {
2939 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2940 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2941 cast<llvm::DICompositeType>(S));
2944 if (MI != SPCache.end()) {
2945 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2946 if (SP && !SP->isDefinition())
2950 for (auto NextFD : FD->redecls()) {
2951 auto MI = SPCache.find(NextFD->getCanonicalDecl());
2952 if (MI != SPCache.end()) {
2953 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2954 if (SP && !SP->isDefinition())
2961 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2962 // implicit parameter "this".
2963 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2966 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
2967 // Create fake but valid subroutine type. Otherwise -verify would fail, and
2968 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2969 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
2971 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
2972 return getOrCreateMethodType(Method, F);
2974 const auto *FTy = FnType->getAs<FunctionType>();
2975 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
2977 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2978 // Add "self" and "_cmd"
2979 SmallVector<llvm::Metadata *, 16> Elts;
2981 // First element is always return type. For 'void' functions it is NULL.
2982 QualType ResultTy = OMethod->getReturnType();
2984 // Replace the instancetype keyword with the actual type.
2985 if (ResultTy == CGM.getContext().getObjCInstanceType())
2986 ResultTy = CGM.getContext().getPointerType(
2987 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2989 Elts.push_back(getOrCreateType(ResultTy, F));
2990 // "self" pointer is always first argument.
2991 QualType SelfDeclTy;
2992 if (auto *SelfDecl = OMethod->getSelfDecl())
2993 SelfDeclTy = SelfDecl->getType();
2994 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
2995 if (FPT->getNumParams() > 1)
2996 SelfDeclTy = FPT->getParamType(0);
2997 if (!SelfDeclTy.isNull())
2998 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2999 // "_cmd" pointer is always second argument.
3000 Elts.push_back(DBuilder.createArtificialType(
3001 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
3002 // Get rest of the arguments.
3003 for (const auto *PI : OMethod->parameters())
3004 Elts.push_back(getOrCreateType(PI->getType(), F));
3005 // Variadic methods need a special marker at the end of the type list.
3006 if (OMethod->isVariadic())
3007 Elts.push_back(DBuilder.createUnspecifiedParameter());
3009 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
3010 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3014 // Handle variadic function types; they need an additional
3015 // unspecified parameter.
3016 if (const auto *FD = dyn_cast<FunctionDecl>(D))
3017 if (FD->isVariadic()) {
3018 SmallVector<llvm::Metadata *, 16> EltTys;
3019 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
3020 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
3021 for (QualType ParamType : FPT->param_types())
3022 EltTys.push_back(getOrCreateType(ParamType, F));
3023 EltTys.push_back(DBuilder.createUnspecifiedParameter());
3024 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
3025 return DBuilder.createSubroutineType(EltTypeArray, llvm::DINode::FlagZero,
3029 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
3032 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
3033 SourceLocation ScopeLoc, QualType FnType,
3034 llvm::Function *Fn, CGBuilderTy &Builder) {
3037 StringRef LinkageName;
3039 FnBeginRegionCount.push_back(LexicalBlockStack.size());
3041 const Decl *D = GD.getDecl();
3042 bool HasDecl = (D != nullptr);
3044 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3045 llvm::DIFile *Unit = getOrCreateFile(Loc);
3046 llvm::DIScope *FDContext = Unit;
3047 llvm::DINodeArray TParamsArray;
3049 // Use llvm function name.
3050 LinkageName = Fn->getName();
3051 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3052 // If there is a subprogram for this function available then use it.
3053 auto FI = SPCache.find(FD->getCanonicalDecl());
3054 if (FI != SPCache.end()) {
3055 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
3056 if (SP && SP->isDefinition()) {
3057 LexicalBlockStack.emplace_back(SP);
3058 RegionMap[D].reset(SP);
3062 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3063 TParamsArray, Flags);
3064 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3065 Name = getObjCMethodName(OMD);
3066 Flags |= llvm::DINode::FlagPrototyped;
3068 // Use llvm function name.
3069 Name = Fn->getName();
3070 Flags |= llvm::DINode::FlagPrototyped;
3072 if (Name.startswith("\01"))
3073 Name = Name.substr(1);
3075 if (!HasDecl || D->isImplicit()) {
3076 Flags |= llvm::DINode::FlagArtificial;
3077 // Artificial functions should not silently reuse CurLoc.
3078 CurLoc = SourceLocation();
3080 unsigned LineNo = getLineNumber(Loc);
3081 unsigned ScopeLine = getLineNumber(ScopeLoc);
3083 // FIXME: The function declaration we're constructing here is mostly reusing
3084 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
3085 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
3086 // all subprograms instead of the actual context since subprogram definitions
3087 // are emitted as CU level entities by the backend.
3088 llvm::DISubprogram *SP = DBuilder.createFunction(
3089 FDContext, Name, LinkageName, Unit, LineNo,
3090 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
3091 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3092 TParamsArray.get(), getFunctionDeclaration(D));
3093 Fn->setSubprogram(SP);
3094 // We might get here with a VarDecl in the case we're generating
3095 // code for the initialization of globals. Do not record these decls
3096 // as they will overwrite the actual VarDecl Decl in the cache.
3097 if (HasDecl && isa<FunctionDecl>(D))
3098 DeclCache[D->getCanonicalDecl()].reset(SP);
3100 // Push the function onto the lexical block stack.
3101 LexicalBlockStack.emplace_back(SP);
3104 RegionMap[D].reset(SP);
3107 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
3110 StringRef LinkageName;
3112 const Decl *D = GD.getDecl();
3116 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3117 llvm::DIFile *Unit = getOrCreateFile(Loc);
3118 llvm::DIScope *FDContext = getDeclContextDescriptor(D);
3119 llvm::DINodeArray TParamsArray;
3120 if (isa<FunctionDecl>(D)) {
3121 // If there is a DISubprogram for this function available then use it.
3122 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
3123 TParamsArray, Flags);
3124 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
3125 Name = getObjCMethodName(OMD);
3126 Flags |= llvm::DINode::FlagPrototyped;
3128 llvm_unreachable("not a function or ObjC method");
3130 if (!Name.empty() && Name[0] == '\01')
3131 Name = Name.substr(1);
3133 if (D->isImplicit()) {
3134 Flags |= llvm::DINode::FlagArtificial;
3135 // Artificial functions without a location should not silently reuse CurLoc.
3136 if (Loc.isInvalid())
3137 CurLoc = SourceLocation();
3139 unsigned LineNo = getLineNumber(Loc);
3140 unsigned ScopeLine = 0;
3142 DBuilder.retainType(DBuilder.createFunction(
3143 FDContext, Name, LinkageName, Unit, LineNo,
3144 getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
3145 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
3146 TParamsArray.get(), getFunctionDeclaration(D)));
3149 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
3150 // Update our current location
3153 if (CurLoc.isInvalid() || CurLoc.isMacroID())
3156 llvm::MDNode *Scope = LexicalBlockStack.back();
3157 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3158 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
3161 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
3162 llvm::MDNode *Back = nullptr;
3163 if (!LexicalBlockStack.empty())
3164 Back = LexicalBlockStack.back().get();
3165 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
3166 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
3167 getColumnNumber(CurLoc)));
3170 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
3171 SourceLocation Loc) {
3172 // Set our current location.
3175 // Emit a line table change for the current location inside the new scope.
3176 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3177 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
3179 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3182 // Create a new lexical block and push it on the stack.
3183 CreateLexicalBlock(Loc);
3186 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3187 SourceLocation Loc) {
3188 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3190 // Provide an entry in the line table for the end of the block.
3191 EmitLocation(Builder, Loc);
3193 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3196 LexicalBlockStack.pop_back();
3199 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
3200 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3201 unsigned RCount = FnBeginRegionCount.back();
3202 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3204 // Pop all regions for this function.
3205 while (LexicalBlockStack.size() != RCount) {
3206 // Provide an entry in the line table for the end of the block.
3207 EmitLocation(Builder, CurLoc);
3208 LexicalBlockStack.pop_back();
3210 FnBeginRegionCount.pop_back();
3213 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3214 uint64_t *XOffset) {
3216 SmallVector<llvm::Metadata *, 5> EltTys;
3218 uint64_t FieldSize, FieldOffset;
3219 uint32_t FieldAlign;
3221 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3222 QualType Type = VD->getType();
3225 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3226 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3227 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3228 FType = CGM.getContext().IntTy;
3229 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3230 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3232 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3233 if (HasCopyAndDispose) {
3234 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3236 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3238 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3240 bool HasByrefExtendedLayout;
3241 Qualifiers::ObjCLifetime Lifetime;
3242 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3243 HasByrefExtendedLayout) &&
3244 HasByrefExtendedLayout) {
3245 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3247 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3250 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3251 if (Align > CGM.getContext().toCharUnitsFromBits(
3252 CGM.getTarget().getPointerAlign(0))) {
3253 CharUnits FieldOffsetInBytes =
3254 CGM.getContext().toCharUnitsFromBits(FieldOffset);
3255 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3256 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3258 if (NumPaddingBytes.isPositive()) {
3259 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3260 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3261 pad, ArrayType::Normal, 0);
3262 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3267 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
3268 FieldSize = CGM.getContext().getTypeSize(FType);
3269 FieldAlign = CGM.getContext().toBits(Align);
3271 *XOffset = FieldOffset;
3272 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
3273 FieldAlign, FieldOffset,
3274 llvm::DINode::FlagZero, FieldTy);
3275 EltTys.push_back(FieldTy);
3276 FieldOffset += FieldSize;
3278 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3280 llvm::DINode::DIFlags Flags = llvm::DINode::FlagBlockByrefStruct;
3282 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
3286 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
3287 llvm::Optional<unsigned> ArgNo,
3288 CGBuilderTy &Builder) {
3289 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3290 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3291 if (VD->hasAttr<NoDebugAttr>())
3295 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3296 cast<Decl>(VD->getDeclContext())->isImplicit());
3297 llvm::DIFile *Unit = nullptr;
3299 Unit = getOrCreateFile(VD->getLocation());
3301 uint64_t XOffset = 0;
3302 if (VD->hasAttr<BlocksAttr>())
3303 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3305 Ty = getOrCreateType(VD->getType(), Unit);
3307 // If there is no debug info for this type then do not emit debug info
3308 // for this variable.
3312 // Get location information.
3314 unsigned Column = 0;
3316 Line = getLineNumber(VD->getLocation());
3317 Column = getColumnNumber(VD->getLocation());
3319 SmallVector<int64_t, 9> Expr;
3320 llvm::DINode::DIFlags Flags = llvm::DINode::FlagZero;
3321 if (VD->isImplicit())
3322 Flags |= llvm::DINode::FlagArtificial;
3324 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3326 // If this is the first argument and it is implicit then
3327 // give it an object pointer flag.
3328 // FIXME: There has to be a better way to do this, but for static
3329 // functions there won't be an implicit param at arg1 and
3330 // otherwise it is 'self' or 'this'.
3331 if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
3332 Flags |= llvm::DINode::FlagObjectPointer;
3333 if (auto *Arg = dyn_cast<llvm::Argument>(Storage))
3334 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
3335 !VD->getType()->isPointerType())
3336 Expr.push_back(llvm::dwarf::DW_OP_deref);
3338 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3340 StringRef Name = VD->getName();
3341 if (!Name.empty()) {
3342 if (VD->hasAttr<BlocksAttr>()) {
3343 CharUnits offset = CharUnits::fromQuantity(32);
3344 Expr.push_back(llvm::dwarf::DW_OP_plus);
3345 // offset of __forwarding field
3346 offset = CGM.getContext().toCharUnitsFromBits(
3347 CGM.getTarget().getPointerWidth(0));
3348 Expr.push_back(offset.getQuantity());
3349 Expr.push_back(llvm::dwarf::DW_OP_deref);
3350 Expr.push_back(llvm::dwarf::DW_OP_plus);
3351 // offset of x field
3352 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3353 Expr.push_back(offset.getQuantity());
3355 // Create the descriptor for the variable.
3357 ? DBuilder.createParameterVariable(Scope, VD->getName(),
3358 *ArgNo, Unit, Line, Ty)
3359 : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
3362 // Insert an llvm.dbg.declare into the current block.
3363 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3364 llvm::DebugLoc::get(Line, Column, Scope),
3365 Builder.GetInsertBlock());
3367 } else if (isa<VariableArrayType>(VD->getType()))
3368 Expr.push_back(llvm::dwarf::DW_OP_deref);
3369 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
3370 // If VD is an anonymous union then Storage represents value for
3371 // all union fields.
3372 const auto *RD = cast<RecordDecl>(RT->getDecl());
3373 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3374 // GDB has trouble finding local variables in anonymous unions, so we emit
3375 // artifical local variables for each of the members.
3377 // FIXME: Remove this code as soon as GDB supports this.
3378 // The debug info verifier in LLVM operates based on the assumption that a
3379 // variable has the same size as its storage and we had to disable the check
3380 // for artificial variables.
3381 for (const auto *Field : RD->fields()) {
3382 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3383 StringRef FieldName = Field->getName();
3385 // Ignore unnamed fields. Do not ignore unnamed records.
3386 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3389 // Use VarDecl's Tag, Scope and Line number.
3390 auto FieldAlign = getDeclAlignIfRequired(Field, CGM.getContext());
3391 auto *D = DBuilder.createAutoVariable(
3392 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3393 Flags | llvm::DINode::FlagArtificial, FieldAlign);
3395 // Insert an llvm.dbg.declare into the current block.
3396 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3397 llvm::DebugLoc::get(Line, Column, Scope),
3398 Builder.GetInsertBlock());
3403 // Create the descriptor for the variable.
3405 ? DBuilder.createParameterVariable(
3406 Scope, Name, *ArgNo, Unit, Line, Ty,
3407 CGM.getLangOpts().Optimize, Flags)
3408 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3409 CGM.getLangOpts().Optimize, Flags,
3412 // Insert an llvm.dbg.declare into the current block.
3413 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3414 llvm::DebugLoc::get(Line, Column, Scope),
3415 Builder.GetInsertBlock());
3418 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
3419 llvm::Value *Storage,
3420 CGBuilderTy &Builder) {
3421 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3422 EmitDeclare(VD, Storage, llvm::None, Builder);
3425 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3427 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3430 return DBuilder.createObjectPointerType(Ty);
3433 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3434 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3435 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3436 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3437 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3439 if (Builder.GetInsertBlock() == nullptr)
3441 if (VD->hasAttr<NoDebugAttr>())
3444 bool isByRef = VD->hasAttr<BlocksAttr>();
3446 uint64_t XOffset = 0;
3447 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3450 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3452 Ty = getOrCreateType(VD->getType(), Unit);
3454 // Self is passed along as an implicit non-arg variable in a
3455 // block. Mark it as the object pointer.
3456 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
3457 Ty = CreateSelfType(VD->getType(), Ty);
3459 // Get location information.
3460 unsigned Line = getLineNumber(VD->getLocation());
3461 unsigned Column = getColumnNumber(VD->getLocation());
3463 const llvm::DataLayout &target = CGM.getDataLayout();
3465 CharUnits offset = CharUnits::fromQuantity(
3466 target.getStructLayout(blockInfo.StructureType)
3467 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3469 SmallVector<int64_t, 9> addr;
3470 if (isa<llvm::AllocaInst>(Storage))
3471 addr.push_back(llvm::dwarf::DW_OP_deref);
3472 addr.push_back(llvm::dwarf::DW_OP_plus);
3473 addr.push_back(offset.getQuantity());
3475 addr.push_back(llvm::dwarf::DW_OP_deref);
3476 addr.push_back(llvm::dwarf::DW_OP_plus);
3477 // offset of __forwarding field
3479 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3480 addr.push_back(offset.getQuantity());
3481 addr.push_back(llvm::dwarf::DW_OP_deref);
3482 addr.push_back(llvm::dwarf::DW_OP_plus);
3483 // offset of x field
3484 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3485 addr.push_back(offset.getQuantity());
3488 // Create the descriptor for the variable.
3489 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3490 auto *D = DBuilder.createAutoVariable(
3491 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3492 Line, Ty, false, llvm::DINode::FlagZero, Align);
3494 // Insert an llvm.dbg.declare into the current block.
3495 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
3497 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3500 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3501 Builder.GetInsertBlock());
3504 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3506 CGBuilderTy &Builder) {
3507 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3508 EmitDeclare(VD, AI, ArgNo, Builder);
3512 struct BlockLayoutChunk {
3513 uint64_t OffsetInBits;
3514 const BlockDecl::Capture *Capture;
3516 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3517 return l.OffsetInBits < r.OffsetInBits;
3521 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3524 llvm::Value *LocalAddr,
3525 CGBuilderTy &Builder) {
3526 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3527 ASTContext &C = CGM.getContext();
3528 const BlockDecl *blockDecl = block.getBlockDecl();
3530 // Collect some general information about the block's location.
3531 SourceLocation loc = blockDecl->getCaretLocation();
3532 llvm::DIFile *tunit = getOrCreateFile(loc);
3533 unsigned line = getLineNumber(loc);
3534 unsigned column = getColumnNumber(loc);
3536 // Build the debug-info type for the block literal.
3537 getDeclContextDescriptor(blockDecl);
3539 const llvm::StructLayout *blockLayout =
3540 CGM.getDataLayout().getStructLayout(block.StructureType);
3542 SmallVector<llvm::Metadata *, 16> fields;
3543 fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
3544 blockLayout->getElementOffsetInBits(0),
3546 fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
3547 blockLayout->getElementOffsetInBits(1),
3549 fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
3550 blockLayout->getElementOffsetInBits(2),
3552 auto *FnTy = block.getBlockExpr()->getFunctionType();
3553 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3554 fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
3555 blockLayout->getElementOffsetInBits(3),
3557 fields.push_back(createFieldType(
3558 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3559 ? C.getBlockDescriptorExtendedType()
3560 : C.getBlockDescriptorType()),
3561 loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3563 // We want to sort the captures by offset, not because DWARF
3564 // requires this, but because we're paranoid about debuggers.
3565 SmallVector<BlockLayoutChunk, 8> chunks;
3568 if (blockDecl->capturesCXXThis()) {
3569 BlockLayoutChunk chunk;
3570 chunk.OffsetInBits =
3571 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3572 chunk.Capture = nullptr;
3573 chunks.push_back(chunk);
3576 // Variable captures.
3577 for (const auto &capture : blockDecl->captures()) {
3578 const VarDecl *variable = capture.getVariable();
3579 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3581 // Ignore constant captures.
3582 if (captureInfo.isConstant())
3585 BlockLayoutChunk chunk;
3586 chunk.OffsetInBits =
3587 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3588 chunk.Capture = &capture;
3589 chunks.push_back(chunk);
3593 llvm::array_pod_sort(chunks.begin(), chunks.end());
3595 for (const BlockLayoutChunk &Chunk : chunks) {
3596 uint64_t offsetInBits = Chunk.OffsetInBits;
3597 const BlockDecl::Capture *capture = Chunk.Capture;
3599 // If we have a null capture, this must be the C++ 'this' capture.
3603 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
3604 type = Method->getThisType(C);
3605 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
3606 type = QualType(RDecl->getTypeForDecl(), 0);
3608 llvm_unreachable("unexpected block declcontext");
3610 fields.push_back(createFieldType("this", type, loc, AS_public,
3611 offsetInBits, tunit, tunit));
3615 const VarDecl *variable = capture->getVariable();
3616 StringRef name = variable->getName();
3618 llvm::DIType *fieldType;
3619 if (capture->isByRef()) {
3620 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3621 auto Align = PtrInfo.AlignIsRequired ? PtrInfo.Align : 0;
3623 // FIXME: this creates a second copy of this type!
3625 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3626 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3627 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3628 PtrInfo.Width, Align, offsetInBits,
3629 llvm::DINode::FlagZero, fieldType);
3631 auto Align = getDeclAlignIfRequired(variable, CGM.getContext());
3632 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
3633 offsetInBits, Align, tunit, tunit);
3635 fields.push_back(fieldType);
3638 SmallString<36> typeName;
3639 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3640 << CGM.getUniqueBlockCount();
3642 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3644 llvm::DIType *type =
3645 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3646 CGM.getContext().toBits(block.BlockSize), 0,
3647 llvm::DINode::FlagZero, nullptr, fieldsArray);
3648 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3650 // Get overall information about the block.
3651 llvm::DINode::DIFlags flags = llvm::DINode::FlagArtificial;
3652 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3654 // Create the descriptor for the parameter.
3655 auto *debugVar = DBuilder.createParameterVariable(
3656 scope, Arg->getName(), ArgNo, tunit, line, type,
3657 CGM.getLangOpts().Optimize, flags);
3660 // Insert an llvm.dbg.value into the current block.
3661 DBuilder.insertDbgValueIntrinsic(
3662 LocalAddr, 0, debugVar, DBuilder.createExpression(),
3663 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3666 // Insert an llvm.dbg.declare into the current block.
3667 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3668 llvm::DebugLoc::get(line, column, scope),
3669 Builder.GetInsertBlock());
3672 llvm::DIDerivedType *
3673 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3674 if (!D->isStaticDataMember())
3677 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3678 if (MI != StaticDataMemberCache.end()) {
3679 assert(MI->second && "Static data member declaration should still exist");
3683 // If the member wasn't found in the cache, lazily construct and add it to the
3684 // type (used when a limited form of the type is emitted).
3685 auto DC = D->getDeclContext();
3686 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
3687 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3690 llvm::DIGlobalVariableExpression *CGDebugInfo::CollectAnonRecordDecls(
3691 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3692 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3693 llvm::DIGlobalVariableExpression *GVE = nullptr;
3695 for (const auto *Field : RD->fields()) {
3696 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3697 StringRef FieldName = Field->getName();
3699 // Ignore unnamed fields, but recurse into anonymous records.
3700 if (FieldName.empty()) {
3701 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
3702 GVE = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3706 // Use VarDecl's Tag, Scope and Line number.
3707 GVE = DBuilder.createGlobalVariableExpression(
3708 DContext, FieldName, LinkageName, Unit, LineNo, FieldTy,
3709 Var->hasLocalLinkage());
3710 Var->addDebugInfo(GVE);
3715 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3717 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3718 if (D->hasAttr<NoDebugAttr>())
3721 // If we already created a DIGlobalVariable for this declaration, just attach
3722 // it to the llvm::GlobalVariable.
3723 auto Cached = DeclCache.find(D->getCanonicalDecl());
3724 if (Cached != DeclCache.end())
3725 return Var->addDebugInfo(
3726 cast<llvm::DIGlobalVariableExpression>(Cached->second));
3728 // Create global variable debug descriptor.
3729 llvm::DIFile *Unit = nullptr;
3730 llvm::DIScope *DContext = nullptr;
3732 StringRef DeclName, LinkageName;
3734 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3736 // Attempt to store one global variable for the declaration - even if we
3737 // emit a lot of fields.
3738 llvm::DIGlobalVariableExpression *GVE = nullptr;
3740 // If this is an anonymous union then we'll want to emit a global
3741 // variable for each member of the anonymous union so that it's possible
3742 // to find the name of any field in the union.
3743 if (T->isUnionType() && DeclName.empty()) {
3744 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3745 assert(RD->isAnonymousStructOrUnion() &&
3746 "unnamed non-anonymous struct or union?");
3747 GVE = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3749 auto Align = getDeclAlignIfRequired(D, CGM.getContext());
3750 GVE = DBuilder.createGlobalVariableExpression(
3751 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3752 Var->hasLocalLinkage(), /*Expr=*/nullptr,
3753 getOrCreateStaticDataMemberDeclarationOrNull(D), Align);
3754 Var->addDebugInfo(GVE);
3756 DeclCache[D->getCanonicalDecl()].reset(GVE);
3759 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD, const APValue &Init) {
3760 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3761 if (VD->hasAttr<NoDebugAttr>())
3763 auto Align = getDeclAlignIfRequired(VD, CGM.getContext());
3764 // Create the descriptor for the variable.
3765 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3766 StringRef Name = VD->getName();
3767 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3768 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3769 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
3770 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3771 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3773 // Do not use global variables for enums.
3776 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3778 // Do not emit separate definitions for function local const/statics.
3779 if (isa<FunctionDecl>(VD->getDeclContext()))
3781 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3782 auto *VarD = cast<VarDecl>(VD);
3783 if (VarD->isStaticDataMember()) {
3784 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3785 getDeclContextDescriptor(VarD);
3786 // Ensure that the type is retained even though it's otherwise unreferenced.
3788 // FIXME: This is probably unnecessary, since Ty should reference RD
3789 // through its scope.
3790 RetainedTypes.push_back(
3791 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3795 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
3797 auto &GV = DeclCache[VD];
3800 llvm::DIExpression *InitExpr = nullptr;
3801 if (CGM.getContext().getTypeSize(VD->getType()) <= 64) {
3802 // FIXME: Add a representation for integer constants wider than 64 bits.
3805 DBuilder.createConstantValueExpression(Init.getInt().getExtValue());
3806 else if (Init.isFloat())
3807 InitExpr = DBuilder.createConstantValueExpression(
3808 Init.getFloat().bitcastToAPInt().getZExtValue());
3810 GV.reset(DBuilder.createGlobalVariableExpression(
3811 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3812 true, InitExpr, getOrCreateStaticDataMemberDeclarationOrNull(VarD),
3816 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3817 if (!LexicalBlockStack.empty())
3818 return LexicalBlockStack.back();
3819 llvm::DIScope *Mod = getParentModuleOrNull(D);
3820 return getContextDescriptor(D, Mod ? Mod : TheCU);
3823 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3824 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3826 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
3827 if (!NSDecl->isAnonymousNamespace() ||
3828 CGM.getCodeGenOpts().DebugExplicitImport) {
3829 DBuilder.createImportedModule(
3830 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3831 getOrCreateNameSpace(NSDecl),
3832 getLineNumber(UD.getLocation()));
3836 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3837 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3839 assert(UD.shadow_size() &&
3840 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3841 // Emitting one decl is sufficient - debuggers can detect that this is an
3842 // overloaded name & provide lookup for all the overloads.
3843 const UsingShadowDecl &USD = **UD.shadow_begin();
3845 // FIXME: Skip functions with undeduced auto return type for now since we
3846 // don't currently have the plumbing for separate declarations & definitions
3847 // of free functions and mismatched types (auto in the declaration, concrete
3848 // return type in the definition)
3849 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
3850 if (const auto *AT =
3851 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
3852 if (AT->getDeducedType().isNull())
3854 if (llvm::DINode *Target =
3855 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3856 DBuilder.createImportedDeclaration(
3857 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3858 getLineNumber(USD.getLocation()));
3861 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
3862 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
3864 if (Module *M = ID.getImportedModule()) {
3865 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
3866 DBuilder.createImportedDeclaration(
3867 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
3868 getOrCreateModuleRef(Info, DebugTypeExtRefs),
3869 getLineNumber(ID.getLocation()));
3873 llvm::DIImportedEntity *
3874 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3875 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3877 auto &VH = NamespaceAliasCache[&NA];
3879 return cast<llvm::DIImportedEntity>(VH);
3880 llvm::DIImportedEntity *R;
3881 if (const auto *Underlying =
3882 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3883 // This could cache & dedup here rather than relying on metadata deduping.
3884 R = DBuilder.createImportedDeclaration(
3885 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3886 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3889 R = DBuilder.createImportedDeclaration(
3890 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3891 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3892 getLineNumber(NA.getLocation()), NA.getName());
3898 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3899 NSDecl = NSDecl->getCanonicalDecl();
3900 auto I = NameSpaceCache.find(NSDecl);
3901 if (I != NameSpaceCache.end())
3902 return cast<llvm::DINamespace>(I->second);
3904 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3905 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3906 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
3907 llvm::DINamespace *NS = DBuilder.createNameSpace(
3908 Context, NSDecl->getName(), FileD, LineNo, NSDecl->isInline());
3909 NameSpaceCache[NSDecl].reset(NS);
3913 void CGDebugInfo::setDwoId(uint64_t Signature) {
3914 assert(TheCU && "no main compile unit");
3915 TheCU->setDWOId(Signature);
3919 void CGDebugInfo::finalize() {
3920 // Creating types might create further types - invalidating the current
3921 // element and the size(), so don't cache/reference them.
3922 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3923 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3924 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3925 ? CreateTypeDefinition(E.Type, E.Unit)
3927 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3930 for (auto p : ReplaceMap) {
3932 auto *Ty = cast<llvm::DIType>(p.second);
3933 assert(Ty->isForwardDecl());
3935 auto it = TypeCache.find(p.first);
3936 assert(it != TypeCache.end());
3939 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3940 cast<llvm::DIType>(it->second));
3943 for (const auto &p : FwdDeclReplaceMap) {
3945 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3946 llvm::Metadata *Repl;
3948 auto it = DeclCache.find(p.first);
3949 // If there has been no definition for the declaration, call RAUW
3950 // with ourselves, that will destroy the temporary MDNode and
3951 // replace it with a standard one, avoiding leaking memory.
3952 if (it == DeclCache.end())
3957 if (auto *GVE = dyn_cast_or_null<llvm::DIGlobalVariableExpression>(Repl))
3958 Repl = GVE->getVariable();
3959 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3962 // We keep our own list of retained types, because we need to look
3963 // up the final type in the type cache.
3964 for (auto &RT : RetainedTypes)
3965 if (auto MD = TypeCache[RT])
3966 DBuilder.retainType(cast<llvm::DIType>(MD));
3968 DBuilder.finalize();
3971 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3972 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3975 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3976 // Don't ignore in case of explicit cast where it is referenced indirectly.
3977 DBuilder.retainType(DieTy);
3980 llvm::DebugLoc CGDebugInfo::SourceLocToDebugLoc(SourceLocation Loc) {
3981 if (LexicalBlockStack.empty())
3982 return llvm::DebugLoc();
3984 llvm::MDNode *Scope = LexicalBlockStack.back();
3985 return llvm::DebugLoc::get(
3986 getLineNumber(Loc), getColumnNumber(Loc), Scope);