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"
16 #include "CGRecordLayout.h"
18 #include "CGObjCRuntime.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/SmallVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DataLayout.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/Support/FileSystem.h"
43 #include "llvm/Support/Path.h"
44 using namespace clang;
45 using namespace clang::CodeGen;
47 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
48 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
49 DebugTypeExtRefs(CGM.getCodeGenOpts().DebugTypeExtRefs),
50 DBuilder(CGM.getModule()) {
51 for (const auto &KV : CGM.getCodeGenOpts().DebugPrefixMap)
52 DebugPrefixMap[KV.first] = KV.second;
56 CGDebugInfo::~CGDebugInfo() {
57 assert(LexicalBlockStack.empty() &&
58 "Region stack mismatch, stack not empty!");
61 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
62 SourceLocation TemporaryLocation)
64 init(TemporaryLocation);
67 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
69 SourceLocation TemporaryLocation)
71 init(TemporaryLocation, DefaultToEmpty);
74 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
75 bool DefaultToEmpty) {
76 auto *DI = CGF->getDebugInfo();
82 OriginalLocation = CGF->Builder.getCurrentDebugLocation();
83 if (TemporaryLocation.isValid()) {
84 DI->EmitLocation(CGF->Builder, TemporaryLocation);
89 CGF->Builder.SetCurrentDebugLocation(llvm::DebugLoc());
93 // Construct a location that has a valid scope, but no line info.
94 assert(!DI->LexicalBlockStack.empty());
95 CGF->Builder.SetCurrentDebugLocation(
96 llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
99 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
101 init(E->getExprLoc());
104 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
106 if (!CGF.getDebugInfo()) {
110 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
112 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
115 ApplyDebugLocation::~ApplyDebugLocation() {
116 // Query CGF so the location isn't overwritten when location updates are
117 // temporarily disabled (for C++ default function arguments)
119 CGF->Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
122 void CGDebugInfo::setLocation(SourceLocation Loc) {
123 // If the new location isn't valid return.
127 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
129 // If we've changed files in the middle of a lexical scope go ahead
130 // and create a new lexical scope with file node if it's different
131 // from the one in the scope.
132 if (LexicalBlockStack.empty())
135 SourceManager &SM = CGM.getContext().getSourceManager();
136 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
137 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
139 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
142 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
143 LexicalBlockStack.pop_back();
144 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
145 LBF->getScope(), getOrCreateFile(CurLoc)));
146 } else if (isa<llvm::DILexicalBlock>(Scope) ||
147 isa<llvm::DISubprogram>(Scope)) {
148 LexicalBlockStack.pop_back();
149 LexicalBlockStack.emplace_back(
150 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
154 llvm::DIScope *CGDebugInfo::getDeclContextDescriptor(const Decl *D) {
155 llvm::DIScope *Mod = getParentModuleOrNull(D);
156 return getContextDescriptor(cast<Decl>(D->getDeclContext()),
160 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context,
161 llvm::DIScope *Default) {
165 auto I = RegionMap.find(Context);
166 if (I != RegionMap.end()) {
167 llvm::Metadata *V = I->second;
168 return dyn_cast_or_null<llvm::DIScope>(V);
172 if (const auto *NSDecl = dyn_cast<NamespaceDecl>(Context))
173 return getOrCreateNameSpace(NSDecl);
175 if (const auto *RDecl = dyn_cast<RecordDecl>(Context))
176 if (!RDecl->isDependentType())
177 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
178 getOrCreateMainFile());
182 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
183 assert(FD && "Invalid FunctionDecl!");
184 IdentifierInfo *FII = FD->getIdentifier();
185 FunctionTemplateSpecializationInfo *Info =
186 FD->getTemplateSpecializationInfo();
188 // Emit the unqualified name in normal operation. LLVM and the debugger can
189 // compute the fully qualified name from the scope chain. If we're only
190 // emitting line table info, there won't be any scope chains, so emit the
191 // fully qualified name here so that stack traces are more accurate.
192 // FIXME: Do this when emitting DWARF as well as when emitting CodeView after
193 // evaluating the size impact.
194 bool UseQualifiedName = DebugKind == codegenoptions::DebugLineTablesOnly &&
195 CGM.getCodeGenOpts().EmitCodeView;
197 if (!Info && FII && !UseQualifiedName)
198 return FII->getName();
201 llvm::raw_svector_ostream OS(NS);
202 PrintingPolicy Policy(CGM.getLangOpts());
203 Policy.MSVCFormatting = CGM.getCodeGenOpts().EmitCodeView;
204 if (!UseQualifiedName)
207 FD->printQualifiedName(OS, Policy);
209 // Add any template specialization args.
211 const TemplateArgumentList *TArgs = Info->TemplateArguments;
212 TemplateSpecializationType::PrintTemplateArgumentList(OS, TArgs->asArray(),
216 // Copy this name on the side and use its reference.
217 return internString(OS.str());
220 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
221 SmallString<256> MethodName;
222 llvm::raw_svector_ostream OS(MethodName);
223 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
224 const DeclContext *DC = OMD->getDeclContext();
225 if (const auto *OID = dyn_cast<ObjCImplementationDecl>(DC)) {
226 OS << OID->getName();
227 } else if (const auto *OID = dyn_cast<ObjCInterfaceDecl>(DC)) {
228 OS << OID->getName();
229 } else if (const auto *OC = dyn_cast<ObjCCategoryDecl>(DC)) {
230 if (OC->IsClassExtension()) {
231 OS << OC->getClassInterface()->getName();
233 OS << OC->getIdentifier()->getNameStart() << '('
234 << OC->getIdentifier()->getNameStart() << ')';
236 } else if (const auto *OCD = dyn_cast<ObjCCategoryImplDecl>(DC)) {
237 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
238 << OCD->getIdentifier()->getNameStart() << ')';
239 } else if (isa<ObjCProtocolDecl>(DC)) {
240 // We can extract the type of the class from the self pointer.
241 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
243 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
244 ClassTy.print(OS, PrintingPolicy(LangOptions()));
247 OS << ' ' << OMD->getSelector().getAsString() << ']';
249 return internString(OS.str());
252 StringRef CGDebugInfo::getSelectorName(Selector S) {
253 return internString(S.getAsString());
256 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
257 if (isa<ClassTemplateSpecializationDecl>(RD)) {
258 SmallString<128> Name;
259 llvm::raw_svector_ostream OS(Name);
260 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
261 /*Qualified*/ false);
263 // Copy this name on the side and use its reference.
264 return internString(Name);
267 // quick optimization to avoid having to intern strings that are already
268 // stored reliably elsewhere
269 if (const IdentifierInfo *II = RD->getIdentifier())
270 return II->getName();
272 // The CodeView printer in LLVM wants to see the names of unnamed types: it is
273 // used to reconstruct the fully qualified type names.
274 if (CGM.getCodeGenOpts().EmitCodeView) {
275 if (const TypedefNameDecl *D = RD->getTypedefNameForAnonDecl()) {
276 assert(RD->getDeclContext() == D->getDeclContext() &&
277 "Typedef should not be in another decl context!");
278 assert(D->getDeclName().getAsIdentifierInfo() &&
279 "Typedef was not named!");
280 return D->getDeclName().getAsIdentifierInfo()->getName();
283 if (CGM.getLangOpts().CPlusPlus) {
286 ASTContext &Context = CGM.getContext();
287 if (const DeclaratorDecl *DD = Context.getDeclaratorForUnnamedTagDecl(RD))
288 // Anonymous types without a name for linkage purposes have their
289 // declarator mangled in if they have one.
290 Name = DD->getName();
291 else if (const TypedefNameDecl *TND =
292 Context.getTypedefNameForUnnamedTagDecl(RD))
293 // Anonymous types without a name for linkage purposes have their
294 // associate typedef mangled in if they have one.
295 Name = TND->getName();
298 SmallString<256> UnnamedType("<unnamed-type-");
301 return internString(UnnamedType);
309 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
311 // If Location is not valid then use main input file.
312 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
313 remapDIPath(TheCU->getDirectory()));
315 SourceManager &SM = CGM.getContext().getSourceManager();
316 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
318 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
319 // If the location is not valid then use main input file.
320 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
321 remapDIPath(TheCU->getDirectory()));
323 // Cache the results.
324 const char *fname = PLoc.getFilename();
325 auto it = DIFileCache.find(fname);
327 if (it != DIFileCache.end()) {
328 // Verify that the information still exists.
329 if (llvm::Metadata *V = it->second)
330 return cast<llvm::DIFile>(V);
333 llvm::DIFile *F = DBuilder.createFile(remapDIPath(PLoc.getFilename()),
334 remapDIPath(getCurrentDirname()));
336 DIFileCache[fname].reset(F);
340 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
341 return DBuilder.createFile(remapDIPath(TheCU->getFilename()),
342 remapDIPath(TheCU->getDirectory()));
345 std::string CGDebugInfo::remapDIPath(StringRef Path) const {
346 for (const auto &Entry : DebugPrefixMap)
347 if (Path.startswith(Entry.first))
348 return (Twine(Entry.second) + Path.substr(Entry.first.size())).str();
352 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
353 if (Loc.isInvalid() && CurLoc.isInvalid())
355 SourceManager &SM = CGM.getContext().getSourceManager();
356 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
357 return PLoc.isValid() ? PLoc.getLine() : 0;
360 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
361 // We may not want column information at all.
362 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
365 // If the location is invalid then use the current column.
366 if (Loc.isInvalid() && CurLoc.isInvalid())
368 SourceManager &SM = CGM.getContext().getSourceManager();
369 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
370 return PLoc.isValid() ? PLoc.getColumn() : 0;
373 StringRef CGDebugInfo::getCurrentDirname() {
374 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
375 return CGM.getCodeGenOpts().DebugCompilationDir;
377 if (!CWDName.empty())
379 SmallString<256> CWD;
380 llvm::sys::fs::current_path(CWD);
381 return CWDName = internString(CWD);
384 void CGDebugInfo::CreateCompileUnit() {
386 // Should we be asking the SourceManager for the main file name, instead of
387 // accepting it as an argument? This just causes the main file name to
388 // mismatch with source locations and create extra lexical scopes or
389 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
390 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
391 // because that's what the SourceManager says)
393 // Get absolute path name.
394 SourceManager &SM = CGM.getContext().getSourceManager();
395 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
396 if (MainFileName.empty())
397 MainFileName = "<stdin>";
399 // The main file name provided via the "-main-file-name" option contains just
400 // the file name itself with no path information. This file name may have had
401 // a relative path, so we look into the actual file entry for the main
402 // file to determine the real absolute path for the file.
403 std::string MainFileDir;
404 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
405 MainFileDir = remapDIPath(MainFile->getDir()->getName());
406 if (MainFileDir != ".") {
407 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
408 llvm::sys::path::append(MainFileDirSS, MainFileName);
409 MainFileName = MainFileDirSS.str();
413 llvm::dwarf::SourceLanguage LangTag;
414 const LangOptions &LO = CGM.getLangOpts();
417 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
419 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
420 } else if (LO.ObjC1) {
421 LangTag = llvm::dwarf::DW_LANG_ObjC;
422 } else if (LO.RenderScript) {
423 LangTag = llvm::dwarf::DW_LANG_GOOGLE_RenderScript;
425 LangTag = llvm::dwarf::DW_LANG_C99;
427 LangTag = llvm::dwarf::DW_LANG_C89;
430 std::string Producer = getClangFullVersion();
432 // Figure out which version of the ObjC runtime we have.
433 unsigned RuntimeVers = 0;
435 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
437 llvm::DICompileUnit::DebugEmissionKind EmissionKind;
439 case codegenoptions::NoDebugInfo:
440 case codegenoptions::LocTrackingOnly:
441 EmissionKind = llvm::DICompileUnit::NoDebug;
443 case codegenoptions::DebugLineTablesOnly:
444 EmissionKind = llvm::DICompileUnit::LineTablesOnly;
446 case codegenoptions::LimitedDebugInfo:
447 case codegenoptions::FullDebugInfo:
448 EmissionKind = llvm::DICompileUnit::FullDebug;
452 // Create new compile unit.
453 // FIXME - Eliminate TheCU.
454 TheCU = DBuilder.createCompileUnit(
455 LangTag, remapDIPath(MainFileName), remapDIPath(getCurrentDirname()),
456 Producer, LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers,
457 CGM.getCodeGenOpts().SplitDwarfFile, EmissionKind, 0 /* DWOid */);
460 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
461 llvm::dwarf::TypeKind Encoding;
463 switch (BT->getKind()) {
464 #define BUILTIN_TYPE(Id, SingletonId)
465 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
466 #include "clang/AST/BuiltinTypes.def"
467 case BuiltinType::Dependent:
468 llvm_unreachable("Unexpected builtin type");
469 case BuiltinType::NullPtr:
470 return DBuilder.createNullPtrType();
471 case BuiltinType::Void:
473 case BuiltinType::ObjCClass:
475 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
477 getOrCreateMainFile(), 0);
479 case BuiltinType::ObjCId: {
480 // typedef struct objc_class *Class;
481 // typedef struct objc_object {
489 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
491 getOrCreateMainFile(), 0);
493 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
495 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
498 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
499 0, 0, 0, 0, nullptr, llvm::DINodeArray());
501 DBuilder.replaceArrays(
503 DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
504 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
507 case BuiltinType::ObjCSel: {
509 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
510 "objc_selector", TheCU,
511 getOrCreateMainFile(), 0);
515 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
516 case BuiltinType::Id: \
517 return getOrCreateStructPtrType("opencl_" #ImgType "_" #Suffix "_t", \
519 #include "clang/Basic/OpenCLImageTypes.def"
520 case BuiltinType::OCLSampler:
521 return DBuilder.createBasicType(
522 "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
523 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
524 case BuiltinType::OCLEvent:
525 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
526 case BuiltinType::OCLClkEvent:
527 return getOrCreateStructPtrType("opencl_clk_event_t", OCLClkEventDITy);
528 case BuiltinType::OCLQueue:
529 return getOrCreateStructPtrType("opencl_queue_t", OCLQueueDITy);
530 case BuiltinType::OCLNDRange:
531 return getOrCreateStructPtrType("opencl_ndrange_t", OCLNDRangeDITy);
532 case BuiltinType::OCLReserveID:
533 return getOrCreateStructPtrType("opencl_reserve_id_t", OCLReserveIDDITy);
535 case BuiltinType::UChar:
536 case BuiltinType::Char_U:
537 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
539 case BuiltinType::Char_S:
540 case BuiltinType::SChar:
541 Encoding = llvm::dwarf::DW_ATE_signed_char;
543 case BuiltinType::Char16:
544 case BuiltinType::Char32:
545 Encoding = llvm::dwarf::DW_ATE_UTF;
547 case BuiltinType::UShort:
548 case BuiltinType::UInt:
549 case BuiltinType::UInt128:
550 case BuiltinType::ULong:
551 case BuiltinType::WChar_U:
552 case BuiltinType::ULongLong:
553 Encoding = llvm::dwarf::DW_ATE_unsigned;
555 case BuiltinType::Short:
556 case BuiltinType::Int:
557 case BuiltinType::Int128:
558 case BuiltinType::Long:
559 case BuiltinType::WChar_S:
560 case BuiltinType::LongLong:
561 Encoding = llvm::dwarf::DW_ATE_signed;
563 case BuiltinType::Bool:
564 Encoding = llvm::dwarf::DW_ATE_boolean;
566 case BuiltinType::Half:
567 case BuiltinType::Float:
568 case BuiltinType::LongDouble:
569 case BuiltinType::Float128:
570 case BuiltinType::Double:
571 // FIXME: For targets where long double and __float128 have the same size,
572 // they are currently indistinguishable in the debugger without some
573 // special treatment. However, there is currently no consensus on encoding
574 // and this should be updated once a DWARF encoding exists for distinct
575 // floating point types of the same size.
576 Encoding = llvm::dwarf::DW_ATE_float;
580 switch (BT->getKind()) {
581 case BuiltinType::Long:
584 case BuiltinType::LongLong:
585 BTName = "long long int";
587 case BuiltinType::ULong:
588 BTName = "long unsigned int";
590 case BuiltinType::ULongLong:
591 BTName = "long long unsigned int";
594 BTName = BT->getName(CGM.getLangOpts());
597 // Bit size, align and offset of the type.
598 uint64_t Size = CGM.getContext().getTypeSize(BT);
599 uint64_t Align = CGM.getContext().getTypeAlign(BT);
600 return DBuilder.createBasicType(BTName, Size, Align, Encoding);
603 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
604 // Bit size, align and offset of the type.
605 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
606 if (Ty->isComplexIntegerType())
607 Encoding = llvm::dwarf::DW_ATE_lo_user;
609 uint64_t Size = CGM.getContext().getTypeSize(Ty);
610 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
611 return DBuilder.createBasicType("complex", Size, Align, Encoding);
614 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
615 llvm::DIFile *Unit) {
616 QualifierCollector Qc;
617 const Type *T = Qc.strip(Ty);
619 // Ignore these qualifiers for now.
620 Qc.removeObjCGCAttr();
621 Qc.removeAddressSpace();
622 Qc.removeObjCLifetime();
624 // We will create one Derived type for one qualifier and recurse to handle any
626 llvm::dwarf::Tag Tag;
628 Tag = llvm::dwarf::DW_TAG_const_type;
630 } else if (Qc.hasVolatile()) {
631 Tag = llvm::dwarf::DW_TAG_volatile_type;
633 } else if (Qc.hasRestrict()) {
634 Tag = llvm::dwarf::DW_TAG_restrict_type;
637 assert(Qc.empty() && "Unknown type qualifier for debug info");
638 return getOrCreateType(QualType(T, 0), Unit);
641 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
643 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
644 // CVR derived types.
645 return DBuilder.createQualifiedType(Tag, FromTy);
648 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
649 llvm::DIFile *Unit) {
651 // The frontend treats 'id' as a typedef to an ObjCObjectType,
652 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
653 // debug info, we want to emit 'id' in both cases.
654 if (Ty->isObjCQualifiedIdType())
655 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
657 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
658 Ty->getPointeeType(), Unit);
661 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
662 llvm::DIFile *Unit) {
663 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
664 Ty->getPointeeType(), Unit);
667 /// \return whether a C++ mangling exists for the type defined by TD.
668 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
669 switch (TheCU->getSourceLanguage()) {
670 case llvm::dwarf::DW_LANG_C_plus_plus:
672 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
673 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
679 /// In C++ mode, types have linkage, so we can rely on the ODR and
680 /// on their mangled names, if they're external.
681 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
683 llvm::DICompileUnit *TheCU) {
684 SmallString<256> FullName;
685 const TagDecl *TD = Ty->getDecl();
687 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
690 // TODO: This is using the RTTI name. Is there a better way to get
691 // a unique string for a type?
692 llvm::raw_svector_ostream Out(FullName);
693 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
697 /// \return the approproate DWARF tag for a composite type.
698 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
699 llvm::dwarf::Tag Tag;
700 if (RD->isStruct() || RD->isInterface())
701 Tag = llvm::dwarf::DW_TAG_structure_type;
702 else if (RD->isUnion())
703 Tag = llvm::dwarf::DW_TAG_union_type;
705 // FIXME: This could be a struct type giving a default visibility different
706 // than C++ class type, but needs llvm metadata changes first.
707 assert(RD->isClass());
708 Tag = llvm::dwarf::DW_TAG_class_type;
713 llvm::DICompositeType *
714 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
715 llvm::DIScope *Ctx) {
716 const RecordDecl *RD = Ty->getDecl();
717 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
718 return cast<llvm::DICompositeType>(T);
719 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
720 unsigned Line = getLineNumber(RD->getLocation());
721 StringRef RDName = getClassName(RD);
726 const RecordDecl *D = RD->getDefinition();
727 if (D && D->isCompleteDefinition()) {
728 Size = CGM.getContext().getTypeSize(Ty);
729 Align = CGM.getContext().getTypeAlign(Ty);
733 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
734 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
735 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
736 llvm::DINode::FlagFwdDecl, FullName);
737 ReplaceMap.emplace_back(
738 std::piecewise_construct, std::make_tuple(Ty),
739 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
743 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
746 llvm::DIFile *Unit) {
747 // Bit size, align and offset of the type.
748 // Size is always the size of a pointer. We can't use getTypeSize here
749 // because that does not return the correct value for references.
750 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
751 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
752 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
754 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
755 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
756 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit),
759 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
763 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
764 llvm::DIType *&Cache) {
767 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
768 TheCU, getOrCreateMainFile(), 0);
769 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
770 Cache = DBuilder.createPointerType(Cache, Size);
774 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
775 llvm::DIFile *Unit) {
776 SmallVector<llvm::Metadata *, 8> EltTys;
778 uint64_t FieldSize, FieldOffset;
780 llvm::DINodeArray Elements;
783 FType = CGM.getContext().UnsignedLongTy;
784 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
785 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
787 Elements = DBuilder.getOrCreateArray(EltTys);
790 unsigned Flags = llvm::DINode::FlagAppleBlock;
794 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
795 FieldOffset, 0, Flags, nullptr, Elements);
797 // Bit size, align and offset of the type.
798 uint64_t Size = CGM.getContext().getTypeSize(Ty);
800 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
803 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
804 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
805 FType = CGM.getContext().IntTy;
806 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
807 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
808 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
809 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
811 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
812 FieldSize = CGM.getContext().getTypeSize(Ty);
813 FieldAlign = CGM.getContext().getTypeAlign(Ty);
814 EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
815 FieldSize, FieldAlign, FieldOffset,
818 FieldOffset += FieldSize;
819 Elements = DBuilder.getOrCreateArray(EltTys);
821 // The __block_literal_generic structs are marked with a special
822 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
823 // the debugger needs to know about. To allow type uniquing, emit
824 // them without a name or a location.
826 DBuilder.createStructType(Unit, "", nullptr, LineNo,
827 FieldOffset, 0, Flags, nullptr, Elements);
829 return DBuilder.createPointerType(EltTy, Size);
832 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
833 llvm::DIFile *Unit) {
834 assert(Ty->isTypeAlias());
835 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
838 llvm::raw_svector_ostream OS(NS);
839 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
840 /*qualified*/ false);
842 TemplateSpecializationType::PrintTemplateArgumentList(
843 OS, Ty->template_arguments(),
844 CGM.getContext().getPrintingPolicy());
846 auto *AliasDecl = cast<TypeAliasTemplateDecl>(
847 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
849 SourceLocation Loc = AliasDecl->getLocation();
850 return DBuilder.createTypedef(Src, OS.str(), getOrCreateFile(Loc),
852 getDeclContextDescriptor(AliasDecl));
855 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
856 llvm::DIFile *Unit) {
857 // We don't set size information, but do specify where the typedef was
859 SourceLocation Loc = Ty->getDecl()->getLocation();
861 // Typedefs are derived from some other type.
862 return DBuilder.createTypedef(
863 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
864 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
865 getDeclContextDescriptor(Ty->getDecl()));
868 static unsigned getDwarfCC(CallingConv CC) {
871 // Avoid emitting DW_AT_calling_convention if the C convention was used.
875 return llvm::dwarf::DW_CC_BORLAND_stdcall;
877 return llvm::dwarf::DW_CC_BORLAND_msfastcall;
879 return llvm::dwarf::DW_CC_BORLAND_thiscall;
880 case CC_X86VectorCall:
881 return llvm::dwarf::DW_CC_LLVM_vectorcall;
883 return llvm::dwarf::DW_CC_BORLAND_pascal;
885 // FIXME: Create new DW_CC_ codes for these calling conventions.
890 case CC_IntelOclBicc:
891 case CC_SpirFunction:
892 case CC_OpenCLKernel:
894 case CC_PreserveMost:
901 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
902 llvm::DIFile *Unit) {
903 SmallVector<llvm::Metadata *, 16> EltTys;
905 // Add the result type at least.
906 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
908 // Set up remainder of arguments if there is a prototype.
909 // otherwise emit it as a variadic function.
910 if (isa<FunctionNoProtoType>(Ty))
911 EltTys.push_back(DBuilder.createUnspecifiedParameter());
912 else if (const auto *FPT = dyn_cast<FunctionProtoType>(Ty)) {
913 for (const QualType &ParamType : FPT->param_types())
914 EltTys.push_back(getOrCreateType(ParamType, Unit));
915 if (FPT->isVariadic())
916 EltTys.push_back(DBuilder.createUnspecifiedParameter());
919 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
920 return DBuilder.createSubroutineType(EltTypeArray, 0,
921 getDwarfCC(Ty->getCallConv()));
924 /// Convert an AccessSpecifier into the corresponding DINode flag.
925 /// As an optimization, return 0 if the access specifier equals the
926 /// default for the containing type.
927 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
928 AccessSpecifier Default = clang::AS_none;
929 if (RD && RD->isClass())
930 Default = clang::AS_private;
931 else if (RD && (RD->isStruct() || RD->isUnion()))
932 Default = clang::AS_public;
934 if (Access == Default)
938 case clang::AS_private:
939 return llvm::DINode::FlagPrivate;
940 case clang::AS_protected:
941 return llvm::DINode::FlagProtected;
942 case clang::AS_public:
943 return llvm::DINode::FlagPublic;
947 llvm_unreachable("unexpected access enumerator");
950 llvm::DIType *CGDebugInfo::createBitFieldType(const FieldDecl *BitFieldDecl,
951 llvm::DIScope *RecordTy,
952 const RecordDecl *RD) {
953 StringRef Name = BitFieldDecl->getName();
954 QualType Ty = BitFieldDecl->getType();
955 SourceLocation Loc = BitFieldDecl->getLocation();
956 llvm::DIFile *VUnit = getOrCreateFile(Loc);
957 llvm::DIType *DebugType = getOrCreateType(Ty, VUnit);
959 // Get the location for the field.
960 llvm::DIFile *File = getOrCreateFile(Loc);
961 unsigned Line = getLineNumber(Loc);
963 const CGBitFieldInfo &BitFieldInfo =
964 CGM.getTypes().getCGRecordLayout(RD).getBitFieldInfo(BitFieldDecl);
965 uint64_t SizeInBits = BitFieldInfo.Size;
966 assert(SizeInBits > 0 && "found named 0-width bitfield");
967 unsigned AlignInBits = CGM.getContext().getTypeAlign(Ty);
968 uint64_t StorageOffsetInBits =
969 CGM.getContext().toBits(BitFieldInfo.StorageOffset);
970 uint64_t OffsetInBits = StorageOffsetInBits + BitFieldInfo.Offset;
971 unsigned Flags = getAccessFlag(BitFieldDecl->getAccess(), RD);
972 return DBuilder.createBitFieldMemberType(
973 RecordTy, Name, File, Line, SizeInBits, AlignInBits, OffsetInBits,
974 StorageOffsetInBits, Flags, DebugType);
978 CGDebugInfo::createFieldType(StringRef name, QualType type, SourceLocation loc,
979 AccessSpecifier AS, uint64_t offsetInBits,
980 llvm::DIFile *tunit, llvm::DIScope *scope,
981 const RecordDecl *RD) {
982 llvm::DIType *debugType = getOrCreateType(type, tunit);
984 // Get the location for the field.
985 llvm::DIFile *file = getOrCreateFile(loc);
986 unsigned line = getLineNumber(loc);
988 uint64_t SizeInBits = 0;
989 unsigned AlignInBits = 0;
990 if (!type->isIncompleteArrayType()) {
991 TypeInfo TI = CGM.getContext().getTypeInfo(type);
992 SizeInBits = TI.Width;
993 AlignInBits = TI.Align;
996 unsigned flags = getAccessFlag(AS, RD);
997 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
998 AlignInBits, offsetInBits, flags, debugType);
1001 void CGDebugInfo::CollectRecordLambdaFields(
1002 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
1003 llvm::DIType *RecordTy) {
1004 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
1005 // has the name and the location of the variable so we should iterate over
1006 // both concurrently.
1007 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
1008 RecordDecl::field_iterator Field = CXXDecl->field_begin();
1009 unsigned fieldno = 0;
1010 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
1011 E = CXXDecl->captures_end();
1012 I != E; ++I, ++Field, ++fieldno) {
1013 const LambdaCapture &C = *I;
1014 if (C.capturesVariable()) {
1015 SourceLocation Loc = C.getLocation();
1016 assert(!Field->isBitField() && "lambdas don't have bitfield members!");
1017 VarDecl *V = C.getCapturedVar();
1018 StringRef VName = V->getName();
1019 llvm::DIFile *VUnit = getOrCreateFile(Loc);
1020 llvm::DIType *FieldType = createFieldType(
1021 VName, Field->getType(), Loc, Field->getAccess(),
1022 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1023 elements.push_back(FieldType);
1024 } else if (C.capturesThis()) {
1025 // TODO: Need to handle 'this' in some way by probably renaming the
1026 // this of the lambda class and having a field member of 'this' or
1027 // by using AT_object_pointer for the function and having that be
1028 // used as 'this' for semantic references.
1029 FieldDecl *f = *Field;
1030 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
1031 QualType type = f->getType();
1032 llvm::DIType *fieldType = createFieldType(
1033 "this", type, f->getLocation(), f->getAccess(),
1034 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
1036 elements.push_back(fieldType);
1041 llvm::DIDerivedType *
1042 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
1043 const RecordDecl *RD) {
1044 // Create the descriptor for the static variable, with or without
1045 // constant initializers.
1046 Var = Var->getCanonicalDecl();
1047 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
1048 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
1050 unsigned LineNumber = getLineNumber(Var->getLocation());
1051 StringRef VName = Var->getName();
1052 llvm::Constant *C = nullptr;
1053 if (Var->getInit()) {
1054 const APValue *Value = Var->evaluateValue();
1057 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
1058 if (Value->isFloat())
1059 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
1063 unsigned Flags = getAccessFlag(Var->getAccess(), RD);
1064 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
1065 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
1066 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
1070 void CGDebugInfo::CollectRecordNormalField(
1071 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
1072 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
1073 const RecordDecl *RD) {
1074 StringRef name = field->getName();
1075 QualType type = field->getType();
1077 // Ignore unnamed fields unless they're anonymous structs/unions.
1078 if (name.empty() && !type->isRecordType())
1081 llvm::DIType *FieldType;
1082 if (field->isBitField()) {
1083 FieldType = createBitFieldType(field, RecordTy, RD);
1086 createFieldType(name, type, field->getLocation(), field->getAccess(),
1087 OffsetInBits, tunit, RecordTy, RD);
1090 elements.push_back(FieldType);
1093 void CGDebugInfo::CollectRecordFields(
1094 const RecordDecl *record, llvm::DIFile *tunit,
1095 SmallVectorImpl<llvm::Metadata *> &elements,
1096 llvm::DICompositeType *RecordTy) {
1097 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(record);
1099 if (CXXDecl && CXXDecl->isLambda())
1100 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
1102 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
1104 // Field number for non-static fields.
1105 unsigned fieldNo = 0;
1107 // Static and non-static members should appear in the same order as
1108 // the corresponding declarations in the source program.
1109 for (const auto *I : record->decls())
1110 if (const auto *V = dyn_cast<VarDecl>(I)) {
1111 if (V->hasAttr<NoDebugAttr>())
1113 // Reuse the existing static member declaration if one exists
1114 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
1115 if (MI != StaticDataMemberCache.end()) {
1116 assert(MI->second &&
1117 "Static data member declaration should still exist");
1118 elements.push_back(MI->second);
1120 auto Field = CreateRecordStaticField(V, RecordTy, record);
1121 elements.push_back(Field);
1123 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1124 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1125 elements, RecordTy, record);
1127 // Bump field number for next field.
1133 llvm::DISubroutineType *
1134 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1135 llvm::DIFile *Unit) {
1136 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1137 if (Method->isStatic())
1138 return cast_or_null<llvm::DISubroutineType>(
1139 getOrCreateType(QualType(Func, 0), Unit));
1140 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1144 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1145 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1146 // Add "this" pointer.
1147 llvm::DITypeRefArray Args(
1148 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1150 assert(Args.size() && "Invalid number of arguments!");
1152 SmallVector<llvm::Metadata *, 16> Elts;
1154 // First element is always return type. For 'void' functions it is NULL.
1155 Elts.push_back(Args[0]);
1157 // "this" pointer is always first argument.
1158 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1159 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1160 // Create pointer type directly in this case.
1161 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1162 QualType PointeeTy = ThisPtrTy->getPointeeType();
1163 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1164 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1165 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1166 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1167 llvm::DIType *ThisPtrType =
1168 DBuilder.createPointerType(PointeeType, Size, Align);
1169 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1170 // TODO: This and the artificial type below are misleading, the
1171 // types aren't artificial the argument is, but the current
1172 // metadata doesn't represent that.
1173 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1174 Elts.push_back(ThisPtrType);
1176 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1177 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1178 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1179 Elts.push_back(ThisPtrType);
1182 // Copy rest of the arguments.
1183 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1184 Elts.push_back(Args[i]);
1186 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1189 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1190 Flags |= llvm::DINode::FlagLValueReference;
1191 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1192 Flags |= llvm::DINode::FlagRValueReference;
1194 return DBuilder.createSubroutineType(EltTypeArray, Flags,
1195 getDwarfCC(Func->getCallConv()));
1198 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1199 /// inside a function.
1200 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1201 if (const auto *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1202 return isFunctionLocalClass(NRD);
1203 if (isa<FunctionDecl>(RD->getDeclContext()))
1208 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1209 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1211 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1213 StringRef MethodName = getFunctionName(Method);
1214 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1216 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1217 // make sense to give a single ctor/dtor a linkage name.
1218 StringRef MethodLinkageName;
1219 // FIXME: 'isFunctionLocalClass' seems like an arbitrary/unintentional
1220 // property to use here. It may've been intended to model "is non-external
1221 // type" but misses cases of non-function-local but non-external classes such
1222 // as those in anonymous namespaces as well as the reverse - external types
1223 // that are function local, such as those in (non-local) inline functions.
1224 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1225 MethodLinkageName = CGM.getMangledName(Method);
1227 // Get the location for the method.
1228 llvm::DIFile *MethodDefUnit = nullptr;
1229 unsigned MethodLine = 0;
1230 if (!Method->isImplicit()) {
1231 MethodDefUnit = getOrCreateFile(Method->getLocation());
1232 MethodLine = getLineNumber(Method->getLocation());
1235 // Collect virtual method info.
1236 llvm::DIType *ContainingType = nullptr;
1237 unsigned Virtuality = 0;
1238 unsigned VIndex = 0;
1240 int ThisAdjustment = 0;
1242 if (Method->isVirtual()) {
1243 if (Method->isPure())
1244 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1246 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1248 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1249 // It doesn't make sense to give a virtual destructor a vtable index,
1250 // since a single destructor has two entries in the vtable.
1251 if (!isa<CXXDestructorDecl>(Method))
1252 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1254 // Emit MS ABI vftable information. There is only one entry for the
1256 const auto *DD = dyn_cast<CXXDestructorDecl>(Method);
1257 GlobalDecl GD = DD ? GlobalDecl(DD, Dtor_Deleting) : GlobalDecl(Method);
1258 MicrosoftVTableContext::MethodVFTableLocation ML =
1259 CGM.getMicrosoftVTableContext().getMethodVFTableLocation(GD);
1262 // CodeView only records the vftable offset in the class that introduces
1263 // the virtual method. This is possible because, unlike Itanium, the MS
1264 // C++ ABI does not include all virtual methods from non-primary bases in
1265 // the vtable for the most derived class. For example, if C inherits from
1266 // A and B, C's primary vftable will not include B's virtual methods.
1267 if (Method->begin_overridden_methods() == Method->end_overridden_methods())
1268 Flags |= llvm::DINode::FlagIntroducedVirtual;
1270 // The 'this' adjustment accounts for both the virtual and non-virtual
1271 // portions of the adjustment. Presumably the debugger only uses it when
1272 // it knows the dynamic type of an object.
1273 ThisAdjustment = CGM.getCXXABI()
1274 .getVirtualFunctionPrologueThisAdjustment(GD)
1277 ContainingType = RecordTy;
1280 if (Method->isImplicit())
1281 Flags |= llvm::DINode::FlagArtificial;
1282 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1283 if (const auto *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1284 if (CXXC->isExplicit())
1285 Flags |= llvm::DINode::FlagExplicit;
1286 } else if (const auto *CXXC = dyn_cast<CXXConversionDecl>(Method)) {
1287 if (CXXC->isExplicit())
1288 Flags |= llvm::DINode::FlagExplicit;
1290 if (Method->hasPrototype())
1291 Flags |= llvm::DINode::FlagPrototyped;
1292 if (Method->getRefQualifier() == RQ_LValue)
1293 Flags |= llvm::DINode::FlagLValueReference;
1294 if (Method->getRefQualifier() == RQ_RValue)
1295 Flags |= llvm::DINode::FlagRValueReference;
1297 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1298 llvm::DISubprogram *SP = DBuilder.createMethod(
1299 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1300 MethodTy, /*isLocalToUnit=*/false, /*isDefinition=*/false, Virtuality,
1301 VIndex, ThisAdjustment, ContainingType, Flags, CGM.getLangOpts().Optimize,
1302 TParamsArray.get());
1304 SPCache[Method->getCanonicalDecl()].reset(SP);
1309 void CGDebugInfo::CollectCXXMemberFunctions(
1310 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1311 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1313 // Since we want more than just the individual member decls if we
1314 // have templated functions iterate over every declaration to gather
1316 for (const auto *I : RD->decls()) {
1317 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1318 // If the member is implicit, don't add it to the member list. This avoids
1319 // the member being added to type units by LLVM, while still allowing it
1320 // to be emitted into the type declaration/reference inside the compile
1322 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1323 // FIXME: Handle Using(Shadow?)Decls here to create
1324 // DW_TAG_imported_declarations inside the class for base decls brought into
1325 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1326 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1328 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1331 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1334 // Reuse the existing member function declaration if it exists.
1335 // It may be associated with the declaration of the type & should be
1336 // reused as we're building the definition.
1338 // This situation can arise in the vtable-based debug info reduction where
1339 // implicit members are emitted in a non-vtable TU.
1340 auto MI = SPCache.find(Method->getCanonicalDecl());
1341 EltTys.push_back(MI == SPCache.end()
1342 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1343 : static_cast<llvm::Metadata *>(MI->second));
1347 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1348 SmallVectorImpl<llvm::Metadata *> &EltTys,
1349 llvm::DIType *RecordTy) {
1350 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1351 for (const auto &BI : RD->bases()) {
1352 unsigned BFlags = 0;
1353 uint64_t BaseOffset;
1356 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1358 if (BI.isVirtual()) {
1359 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1360 // virtual base offset offset is -ve. The code generator emits dwarf
1361 // expression where it expects +ve number.
1362 BaseOffset = 0 - CGM.getItaniumVTableContext()
1363 .getVirtualBaseOffsetOffset(RD, Base)
1366 // In the MS ABI, store the vbtable offset, which is analogous to the
1367 // vbase offset offset in Itanium.
1369 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1371 BFlags = llvm::DINode::FlagVirtual;
1373 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1374 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1375 // BI->isVirtual() and bits when not.
1377 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1378 llvm::DIType *DTy = DBuilder.createInheritance(
1379 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1380 EltTys.push_back(DTy);
1385 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1386 ArrayRef<TemplateArgument> TAList,
1387 llvm::DIFile *Unit) {
1388 SmallVector<llvm::Metadata *, 16> TemplateParams;
1389 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1390 const TemplateArgument &TA = TAList[i];
1393 Name = TPList->getParam(i)->getName();
1394 switch (TA.getKind()) {
1395 case TemplateArgument::Type: {
1396 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1397 TemplateParams.push_back(
1398 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1400 case TemplateArgument::Integral: {
1401 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1402 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1404 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1406 case TemplateArgument::Declaration: {
1407 const ValueDecl *D = TA.getAsDecl();
1408 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1409 llvm::DIType *TTy = getOrCreateType(T, Unit);
1410 llvm::Constant *V = nullptr;
1411 const CXXMethodDecl *MD;
1412 // Variable pointer template parameters have a value that is the address
1414 if (const auto *VD = dyn_cast<VarDecl>(D))
1415 V = CGM.GetAddrOfGlobalVar(VD);
1416 // Member function pointers have special support for building them, though
1417 // this is currently unsupported in LLVM CodeGen.
1418 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1419 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1420 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1421 V = CGM.GetAddrOfFunction(FD);
1422 // Member data pointers have special handling too to compute the fixed
1423 // offset within the object.
1424 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1425 // These five lines (& possibly the above member function pointer
1426 // handling) might be able to be refactored to use similar code in
1427 // CodeGenModule::getMemberPointerConstant
1428 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1430 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1431 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1433 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1435 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1437 case TemplateArgument::NullPtr: {
1438 QualType T = TA.getNullPtrType();
1439 llvm::DIType *TTy = getOrCreateType(T, Unit);
1440 llvm::Constant *V = nullptr;
1441 // Special case member data pointer null values since they're actually -1
1443 if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr()))
1444 // But treat member function pointers as simple zero integers because
1445 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1446 // CodeGen grows handling for values of non-null member function
1447 // pointers then perhaps we could remove this special case and rely on
1448 // EmitNullMemberPointer for member function pointers.
1449 if (MPT->isMemberDataPointer())
1450 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1452 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1453 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1454 TheCU, Name, TTy, V));
1456 case TemplateArgument::Template:
1457 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1458 TheCU, Name, nullptr,
1459 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1461 case TemplateArgument::Pack:
1462 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1463 TheCU, Name, nullptr,
1464 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1466 case TemplateArgument::Expression: {
1467 const Expr *E = TA.getAsExpr();
1468 QualType T = E->getType();
1470 T = CGM.getContext().getLValueReferenceType(T);
1471 llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1472 assert(V && "Expression in template argument isn't constant");
1473 llvm::DIType *TTy = getOrCreateType(T, Unit);
1474 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1475 TheCU, Name, TTy, V->stripPointerCasts()));
1477 // And the following should never occur:
1478 case TemplateArgument::TemplateExpansion:
1479 case TemplateArgument::Null:
1481 "These argument types shouldn't exist in concrete types");
1484 return DBuilder.getOrCreateArray(TemplateParams);
1488 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1489 llvm::DIFile *Unit) {
1490 if (FD->getTemplatedKind() ==
1491 FunctionDecl::TK_FunctionTemplateSpecialization) {
1492 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1494 ->getTemplateParameters();
1495 return CollectTemplateParams(
1496 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1498 return llvm::DINodeArray();
1501 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1502 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1503 // Always get the full list of parameters, not just the ones from
1504 // the specialization.
1505 TemplateParameterList *TPList =
1506 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1507 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1508 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1511 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1513 return VTablePtrType;
1515 ASTContext &Context = CGM.getContext();
1518 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1519 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1520 llvm::DIType *SubTy = DBuilder.createSubroutineType(SElements);
1521 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1522 llvm::DIType *vtbl_ptr_type =
1523 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1524 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1525 return VTablePtrType;
1528 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1529 // Copy the gdb compatible name on the side and use its reference.
1530 return internString("_vptr$", RD->getNameAsString());
1533 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1534 SmallVectorImpl<llvm::Metadata *> &EltTys) {
1535 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1537 // If there is a primary base then it will hold vtable info.
1538 if (RL.getPrimaryBase())
1541 // If this class is not dynamic then there is not any vtable info to collect.
1542 if (!RD->isDynamicClass())
1545 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1546 llvm::DIType *VPTR = DBuilder.createMemberType(
1547 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1548 llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1549 EltTys.push_back(VPTR);
1552 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1553 SourceLocation Loc) {
1554 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1555 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1559 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1560 SourceLocation Loc) {
1561 return getOrCreateStandaloneType(D, Loc);
1564 llvm::DIType *CGDebugInfo::getOrCreateStandaloneType(QualType D,
1565 SourceLocation Loc) {
1566 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
1567 assert(!D.isNull() && "null type");
1568 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1569 assert(T && "could not create debug info for type");
1571 RetainedTypes.push_back(D.getAsOpaquePtr());
1575 void CGDebugInfo::completeType(const EnumDecl *ED) {
1576 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1578 QualType Ty = CGM.getContext().getEnumType(ED);
1579 void *TyPtr = Ty.getAsOpaquePtr();
1580 auto I = TypeCache.find(TyPtr);
1581 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1583 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1584 assert(!Res->isForwardDecl());
1585 TypeCache[TyPtr].reset(Res);
1588 void CGDebugInfo::completeType(const RecordDecl *RD) {
1589 if (DebugKind > codegenoptions::LimitedDebugInfo ||
1590 !CGM.getLangOpts().CPlusPlus)
1591 completeRequiredType(RD);
1594 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1595 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1598 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1599 if (CXXDecl->isDynamicClass())
1602 if (DebugTypeExtRefs && RD->isFromASTFile())
1605 QualType Ty = CGM.getContext().getRecordType(RD);
1606 llvm::DIType *T = getTypeOrNull(Ty);
1607 if (T && T->isForwardDecl())
1608 completeClassData(RD);
1611 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1612 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
1614 QualType Ty = CGM.getContext().getRecordType(RD);
1615 void *TyPtr = Ty.getAsOpaquePtr();
1616 auto I = TypeCache.find(TyPtr);
1617 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1619 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1620 assert(!Res->isForwardDecl());
1621 TypeCache[TyPtr].reset(Res);
1624 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1625 CXXRecordDecl::method_iterator End) {
1626 for (CXXMethodDecl *MD : llvm::make_range(I, End))
1627 if (FunctionDecl *Tmpl = MD->getInstantiatedFromMemberFunction())
1628 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1629 !MD->getMemberSpecializationInfo()->isExplicitSpecialization())
1634 /// Does a type definition exist in an imported clang module?
1635 static bool isDefinedInClangModule(const RecordDecl *RD) {
1636 if (!RD || !RD->isFromASTFile())
1638 if (!RD->isExternallyVisible() && RD->getName().empty())
1640 if (auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
1641 assert(CXXDecl->isCompleteDefinition() && "incomplete record definition");
1642 if (CXXDecl->getTemplateSpecializationKind() != TSK_Undeclared)
1643 // Make sure the instantiation is actually in a module.
1644 if (CXXDecl->field_begin() != CXXDecl->field_end())
1645 return CXXDecl->field_begin()->isFromASTFile();
1651 static bool shouldOmitDefinition(codegenoptions::DebugInfoKind DebugKind,
1652 bool DebugTypeExtRefs, const RecordDecl *RD,
1653 const LangOptions &LangOpts) {
1654 if (DebugTypeExtRefs && isDefinedInClangModule(RD->getDefinition()))
1657 if (DebugKind > codegenoptions::LimitedDebugInfo)
1660 if (!LangOpts.CPlusPlus)
1663 if (!RD->isCompleteDefinitionRequired())
1666 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1671 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1674 TemplateSpecializationKind Spec = TSK_Undeclared;
1675 if (const auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1676 Spec = SD->getSpecializationKind();
1678 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1679 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1680 CXXDecl->method_end()))
1686 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1687 RecordDecl *RD = Ty->getDecl();
1688 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1689 if (T || shouldOmitDefinition(DebugKind, DebugTypeExtRefs, RD,
1690 CGM.getLangOpts())) {
1692 T = getOrCreateRecordFwdDecl(Ty, getDeclContextDescriptor(RD));
1696 return CreateTypeDefinition(Ty);
1699 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1700 RecordDecl *RD = Ty->getDecl();
1702 // Get overall information about the record type for the debug info.
1703 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1705 // Records and classes and unions can all be recursive. To handle them, we
1706 // first generate a debug descriptor for the struct as a forward declaration.
1707 // Then (if it is a definition) we go through and get debug info for all of
1708 // its members. Finally, we create a descriptor for the complete type (which
1709 // may refer to the forward decl if the struct is recursive) and replace all
1710 // uses of the forward declaration with the final definition.
1711 llvm::DICompositeType *FwdDecl = getOrCreateLimitedType(Ty, DefUnit);
1713 const RecordDecl *D = RD->getDefinition();
1714 if (!D || !D->isCompleteDefinition())
1717 if (const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1718 CollectContainingType(CXXDecl, FwdDecl);
1720 // Push the struct on region stack.
1721 LexicalBlockStack.emplace_back(&*FwdDecl);
1722 RegionMap[Ty->getDecl()].reset(FwdDecl);
1724 // Convert all the elements.
1725 SmallVector<llvm::Metadata *, 16> EltTys;
1726 // what about nested types?
1728 // Note: The split of CXXDecl information here is intentional, the
1729 // gdb tests will depend on a certain ordering at printout. The debug
1730 // information offsets are still correct if we merge them all together
1732 const auto *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1734 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1735 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1738 // Collect data fields (including static variables and any initializers).
1739 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1741 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1743 LexicalBlockStack.pop_back();
1744 RegionMap.erase(Ty->getDecl());
1746 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1747 DBuilder.replaceArrays(FwdDecl, Elements);
1749 if (FwdDecl->isTemporary())
1751 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1753 RegionMap[Ty->getDecl()].reset(FwdDecl);
1757 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1758 llvm::DIFile *Unit) {
1759 // Ignore protocols.
1760 return getOrCreateType(Ty->getBaseType(), Unit);
1763 /// \return true if Getter has the default name for the property PD.
1764 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1765 const ObjCMethodDecl *Getter) {
1770 assert(Getter->getDeclName().isObjCZeroArgSelector());
1771 return PD->getName() ==
1772 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1775 /// \return true if Setter has the default name for the property PD.
1776 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1777 const ObjCMethodDecl *Setter) {
1782 assert(Setter->getDeclName().isObjCOneArgSelector());
1783 return SelectorTable::constructSetterName(PD->getName()) ==
1784 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1787 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1788 llvm::DIFile *Unit) {
1789 ObjCInterfaceDecl *ID = Ty->getDecl();
1793 // Return a forward declaration if this type was imported from a clang module,
1794 // and this is not the compile unit with the implementation of the type (which
1795 // may contain hidden ivars).
1796 if (DebugTypeExtRefs && ID->isFromASTFile() && ID->getDefinition() &&
1797 !ID->getImplementation())
1798 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1800 getDeclContextDescriptor(ID), Unit, 0);
1802 // Get overall information about the record type for the debug info.
1803 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1804 unsigned Line = getLineNumber(ID->getLocation());
1806 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1808 // If this is just a forward declaration return a special forward-declaration
1809 // debug type since we won't be able to lay out the entire type.
1810 ObjCInterfaceDecl *Def = ID->getDefinition();
1811 if (!Def || !Def->getImplementation()) {
1812 llvm::DIScope *Mod = getParentModuleOrNull(ID);
1813 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1814 llvm::dwarf::DW_TAG_structure_type, ID->getName(), Mod ? Mod : TheCU,
1815 DefUnit, Line, RuntimeLang);
1816 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1820 return CreateTypeDefinition(Ty, Unit);
1824 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod,
1825 bool CreateSkeletonCU) {
1826 // Use the Module pointer as the key into the cache. This is a
1827 // nullptr if the "Module" is a PCH, which is safe because we don't
1828 // support chained PCH debug info, so there can only be a single PCH.
1829 const Module *M = Mod.getModuleOrNull();
1830 auto ModRef = ModuleCache.find(M);
1831 if (ModRef != ModuleCache.end())
1832 return cast<llvm::DIModule>(ModRef->second);
1834 // Macro definitions that were defined with "-D" on the command line.
1835 SmallString<128> ConfigMacros;
1837 llvm::raw_svector_ostream OS(ConfigMacros);
1838 const auto &PPOpts = CGM.getPreprocessorOpts();
1840 // Translate the macro definitions back into a commmand line.
1841 for (auto &M : PPOpts.Macros) {
1844 const std::string &Macro = M.first;
1845 bool Undef = M.second;
1846 OS << "\"-" << (Undef ? 'U' : 'D');
1847 for (char c : Macro)
1849 case '\\' : OS << "\\\\"; break;
1850 case '"' : OS << "\\\""; break;
1857 bool IsRootModule = M ? !M->Parent : true;
1858 if (CreateSkeletonCU && IsRootModule) {
1859 // PCH files don't have a signature field in the control block,
1860 // but LLVM detects skeleton CUs by looking for a non-zero DWO id.
1861 uint64_t Signature = Mod.getSignature() ? Mod.getSignature() : ~1ULL;
1862 llvm::DIBuilder DIB(CGM.getModule());
1863 DIB.createCompileUnit(TheCU->getSourceLanguage(), Mod.getModuleName(),
1864 Mod.getPath(), TheCU->getProducer(), true,
1865 StringRef(), 0, Mod.getASTFile(),
1866 llvm::DICompileUnit::FullDebug, Signature);
1869 llvm::DIModule *Parent =
1870 IsRootModule ? nullptr
1871 : getOrCreateModuleRef(
1872 ExternalASTSource::ASTSourceDescriptor(*M->Parent),
1874 llvm::DIModule *DIMod =
1875 DBuilder.createModule(Parent, Mod.getModuleName(), ConfigMacros,
1876 Mod.getPath(), CGM.getHeaderSearchOpts().Sysroot);
1877 ModuleCache[M].reset(DIMod);
1881 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1882 llvm::DIFile *Unit) {
1883 ObjCInterfaceDecl *ID = Ty->getDecl();
1884 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1885 unsigned Line = getLineNumber(ID->getLocation());
1886 unsigned RuntimeLang = TheCU->getSourceLanguage();
1888 // Bit size, align and offset of the type.
1889 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1890 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1893 if (ID->getImplementation())
1894 Flags |= llvm::DINode::FlagObjcClassComplete;
1896 llvm::DIScope *Mod = getParentModuleOrNull(ID);
1897 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
1898 Mod ? Mod : Unit, ID->getName(), DefUnit, Line, Size, Align, Flags,
1899 nullptr, llvm::DINodeArray(), RuntimeLang);
1901 QualType QTy(Ty, 0);
1902 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1904 // Push the struct on region stack.
1905 LexicalBlockStack.emplace_back(RealDecl);
1906 RegionMap[Ty->getDecl()].reset(RealDecl);
1908 // Convert all the elements.
1909 SmallVector<llvm::Metadata *, 16> EltTys;
1911 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1913 llvm::DIType *SClassTy =
1914 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1918 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1919 EltTys.push_back(InhTag);
1922 // Create entries for all of the properties.
1923 auto AddProperty = [&](const ObjCPropertyDecl *PD) {
1924 SourceLocation Loc = PD->getLocation();
1925 llvm::DIFile *PUnit = getOrCreateFile(Loc);
1926 unsigned PLine = getLineNumber(Loc);
1927 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1928 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1929 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1930 PD->getName(), PUnit, PLine,
1931 hasDefaultGetterName(PD, Getter) ? ""
1932 : getSelectorName(PD->getGetterName()),
1933 hasDefaultSetterName(PD, Setter) ? ""
1934 : getSelectorName(PD->getSetterName()),
1935 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1936 EltTys.push_back(PropertyNode);
1939 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
1940 for (const ObjCCategoryDecl *ClassExt : ID->known_extensions())
1941 for (auto *PD : ClassExt->properties()) {
1942 PropertySet.insert(PD->getIdentifier());
1945 for (const auto *PD : ID->properties()) {
1946 // Don't emit duplicate metadata for properties that were already in a
1948 if (!PropertySet.insert(PD->getIdentifier()).second)
1954 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1955 unsigned FieldNo = 0;
1956 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1957 Field = Field->getNextIvar(), ++FieldNo) {
1958 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
1962 StringRef FieldName = Field->getName();
1964 // Ignore unnamed fields.
1965 if (FieldName.empty())
1968 // Get the location for the field.
1969 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
1970 unsigned FieldLine = getLineNumber(Field->getLocation());
1971 QualType FType = Field->getType();
1972 uint64_t FieldSize = 0;
1973 unsigned FieldAlign = 0;
1975 if (!FType->isIncompleteArrayType()) {
1977 // Bit size, align and offset of the type.
1978 FieldSize = Field->isBitField()
1979 ? Field->getBitWidthValue(CGM.getContext())
1980 : CGM.getContext().getTypeSize(FType);
1981 FieldAlign = CGM.getContext().getTypeAlign(FType);
1984 uint64_t FieldOffset;
1985 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1986 // We don't know the runtime offset of an ivar if we're using the
1987 // non-fragile ABI. For bitfields, use the bit offset into the first
1988 // byte of storage of the bitfield. For other fields, use zero.
1989 if (Field->isBitField()) {
1991 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1992 FieldOffset %= CGM.getContext().getCharWidth();
1997 FieldOffset = RL.getFieldOffset(FieldNo);
2001 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
2002 Flags = llvm::DINode::FlagProtected;
2003 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
2004 Flags = llvm::DINode::FlagPrivate;
2005 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
2006 Flags = llvm::DINode::FlagPublic;
2008 llvm::MDNode *PropertyNode = nullptr;
2009 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
2010 if (ObjCPropertyImplDecl *PImpD =
2011 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
2012 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
2013 SourceLocation Loc = PD->getLocation();
2014 llvm::DIFile *PUnit = getOrCreateFile(Loc);
2015 unsigned PLine = getLineNumber(Loc);
2016 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
2017 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
2018 PropertyNode = DBuilder.createObjCProperty(
2019 PD->getName(), PUnit, PLine,
2020 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
2021 PD->getGetterName()),
2022 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
2023 PD->getSetterName()),
2024 PD->getPropertyAttributes(),
2025 getOrCreateType(PD->getType(), PUnit));
2029 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
2030 FieldSize, FieldAlign, FieldOffset, Flags,
2031 FieldTy, PropertyNode);
2032 EltTys.push_back(FieldTy);
2035 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2036 DBuilder.replaceArrays(RealDecl, Elements);
2038 LexicalBlockStack.pop_back();
2042 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
2043 llvm::DIFile *Unit) {
2044 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
2045 int64_t Count = Ty->getNumElements();
2047 // If number of elements are not known then this is an unbounded array.
2048 // Use Count == -1 to express such arrays.
2051 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
2052 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
2054 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2055 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2057 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
2060 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
2064 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
2065 if (const auto *VAT = dyn_cast<VariableArrayType>(Ty)) {
2068 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
2069 } else if (Ty->isIncompleteArrayType()) {
2071 if (Ty->getElementType()->isIncompleteType())
2074 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
2075 } else if (Ty->isIncompleteType()) {
2079 // Size and align of the whole array, not the element type.
2080 Size = CGM.getContext().getTypeSize(Ty);
2081 Align = CGM.getContext().getTypeAlign(Ty);
2084 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
2085 // interior arrays, do we care? Why aren't nested arrays represented the
2086 // obvious/recursive way?
2087 SmallVector<llvm::Metadata *, 8> Subscripts;
2088 QualType EltTy(Ty, 0);
2089 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
2090 // If the number of elements is known, then count is that number. Otherwise,
2091 // it's -1. This allows us to represent a subrange with an array of 0
2092 // elements, like this:
2097 int64_t Count = -1; // Count == -1 is an unbounded array.
2098 if (const auto *CAT = dyn_cast<ConstantArrayType>(Ty))
2099 Count = CAT->getSize().getZExtValue();
2101 // FIXME: Verify this is right for VLAs.
2102 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
2103 EltTy = Ty->getElementType();
2106 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
2108 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
2112 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
2113 llvm::DIFile *Unit) {
2114 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
2115 Ty->getPointeeType(), Unit);
2118 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
2119 llvm::DIFile *Unit) {
2120 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
2121 Ty->getPointeeType(), Unit);
2124 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
2129 if (!Ty->isIncompleteType()) {
2130 Size = CGM.getContext().getTypeSize(Ty);
2132 // Set the MS inheritance model. There is no flag for the unspecified model.
2133 if (CGM.getTarget().getCXXABI().isMicrosoft()) {
2134 switch (Ty->getMostRecentCXXRecordDecl()->getMSInheritanceModel()) {
2135 case MSInheritanceAttr::Keyword_single_inheritance:
2136 Flags |= llvm::DINode::FlagSingleInheritance;
2138 case MSInheritanceAttr::Keyword_multiple_inheritance:
2139 Flags |= llvm::DINode::FlagMultipleInheritance;
2141 case MSInheritanceAttr::Keyword_virtual_inheritance:
2142 Flags |= llvm::DINode::FlagVirtualInheritance;
2144 case MSInheritanceAttr::Keyword_unspecified_inheritance:
2150 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
2151 if (Ty->isMemberDataPointerType())
2152 return DBuilder.createMemberPointerType(
2153 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size, /*Align=*/0,
2156 const FunctionProtoType *FPT =
2157 Ty->getPointeeType()->getAs<FunctionProtoType>();
2158 return DBuilder.createMemberPointerType(
2159 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
2160 Ty->getClass(), FPT->getTypeQuals())),
2162 ClassType, Size, /*Align=*/0, Flags);
2165 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
2166 // Ignore the atomic wrapping
2167 // FIXME: What is the correct representation?
2168 return getOrCreateType(Ty->getValueType(), U);
2171 llvm::DIType* CGDebugInfo::CreateType(const PipeType *Ty,
2173 return getOrCreateType(Ty->getElementType(), U);
2176 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
2177 const EnumDecl *ED = Ty->getDecl();
2181 if (!ED->getTypeForDecl()->isIncompleteType()) {
2182 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2183 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
2186 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2188 bool isImportedFromModule =
2189 DebugTypeExtRefs && ED->isFromASTFile() && ED->getDefinition();
2191 // If this is just a forward declaration, construct an appropriately
2192 // marked node and just return it.
2193 if (isImportedFromModule || !ED->getDefinition()) {
2194 // Note that it is possible for enums to be created as part of
2195 // their own declcontext. In this case a FwdDecl will be created
2196 // twice. This doesn't cause a problem because both FwdDecls are
2197 // entered into the ReplaceMap: finalize() will replace the first
2198 // FwdDecl with the second and then replace the second with
2200 llvm::DIScope *EDContext = getDeclContextDescriptor(ED);
2201 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2202 llvm::TempDIScope TmpContext(DBuilder.createReplaceableCompositeType(
2203 llvm::dwarf::DW_TAG_enumeration_type, "", TheCU, DefUnit, 0));
2205 unsigned Line = getLineNumber(ED->getLocation());
2206 StringRef EDName = ED->getName();
2207 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
2208 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
2209 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
2211 ReplaceMap.emplace_back(
2212 std::piecewise_construct, std::make_tuple(Ty),
2213 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
2217 return CreateTypeDefinition(Ty);
2220 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
2221 const EnumDecl *ED = Ty->getDecl();
2224 if (!ED->getTypeForDecl()->isIncompleteType()) {
2225 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
2226 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
2229 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2231 // Create elements for each enumerator.
2232 SmallVector<llvm::Metadata *, 16> Enumerators;
2233 ED = ED->getDefinition();
2234 for (const auto *Enum : ED->enumerators()) {
2235 Enumerators.push_back(DBuilder.createEnumerator(
2236 Enum->getName(), Enum->getInitVal().getSExtValue()));
2239 // Return a CompositeType for the enum itself.
2240 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
2242 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
2243 unsigned Line = getLineNumber(ED->getLocation());
2244 llvm::DIScope *EnumContext = getDeclContextDescriptor(ED);
2245 llvm::DIType *ClassTy =
2246 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
2247 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
2248 Line, Size, Align, EltArray, ClassTy,
2252 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
2255 Qualifiers InnerQuals = T.getLocalQualifiers();
2256 // Qualifiers::operator+() doesn't like it if you add a Qualifier
2257 // that is already there.
2258 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
2259 Quals += InnerQuals;
2261 switch (T->getTypeClass()) {
2263 return C.getQualifiedType(T.getTypePtr(), Quals);
2264 case Type::TemplateSpecialization: {
2265 const auto *Spec = cast<TemplateSpecializationType>(T);
2266 if (Spec->isTypeAlias())
2267 return C.getQualifiedType(T.getTypePtr(), Quals);
2268 T = Spec->desugar();
2271 case Type::TypeOfExpr:
2272 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2275 T = cast<TypeOfType>(T)->getUnderlyingType();
2277 case Type::Decltype:
2278 T = cast<DecltypeType>(T)->getUnderlyingType();
2280 case Type::UnaryTransform:
2281 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2283 case Type::Attributed:
2284 T = cast<AttributedType>(T)->getEquivalentType();
2286 case Type::Elaborated:
2287 T = cast<ElaboratedType>(T)->getNamedType();
2290 T = cast<ParenType>(T)->getInnerType();
2292 case Type::SubstTemplateTypeParm:
2293 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2296 QualType DT = cast<AutoType>(T)->getDeducedType();
2297 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2302 assert(T != LastT && "Type unwrapping failed to unwrap!");
2307 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2309 // Unwrap the type as needed for debug information.
2310 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2312 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2313 if (it != TypeCache.end()) {
2314 // Verify that the debug info still exists.
2315 if (llvm::Metadata *V = it->second)
2316 return cast<llvm::DIType>(V);
2322 void CGDebugInfo::completeTemplateDefinition(
2323 const ClassTemplateSpecializationDecl &SD) {
2324 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
2327 completeClassData(&SD);
2328 // In case this type has no member function definitions being emitted, ensure
2330 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2333 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2337 // Unwrap the type as needed for debug information.
2338 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2340 if (auto *T = getTypeOrNull(Ty))
2343 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2344 void* TyPtr = Ty.getAsOpaquePtr();
2346 // And update the type cache.
2347 TypeCache[TyPtr].reset(Res);
2352 llvm::DIModule *CGDebugInfo::getParentModuleOrNull(const Decl *D) {
2353 // A forward declaration inside a module header does not belong to the module.
2354 if (isa<RecordDecl>(D) && !cast<RecordDecl>(D)->getDefinition())
2356 if (DebugTypeExtRefs && D->isFromASTFile()) {
2357 // Record a reference to an imported clang module or precompiled header.
2358 auto *Reader = CGM.getContext().getExternalSource();
2359 auto Idx = D->getOwningModuleID();
2360 auto Info = Reader->getSourceDescriptor(Idx);
2362 return getOrCreateModuleRef(*Info, /*SkeletonCU=*/true);
2363 } else if (ClangModuleMap) {
2364 // We are building a clang module or a precompiled header.
2366 // TODO: When D is a CXXRecordDecl or a C++ Enum, the ODR applies
2367 // and it wouldn't be necessary to specify the parent scope
2368 // because the type is already unique by definition (it would look
2369 // like the output of -fno-standalone-debug). On the other hand,
2370 // the parent scope helps a consumer to quickly locate the object
2371 // file where the type's definition is located, so it might be
2372 // best to make this behavior a command line or debugger tuning
2374 FullSourceLoc Loc(D->getLocation(), CGM.getContext().getSourceManager());
2375 if (Module *M = ClangModuleMap->inferModuleFromLocation(Loc)) {
2376 // This is a (sub-)module.
2377 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
2378 return getOrCreateModuleRef(Info, /*SkeletonCU=*/false);
2380 // This the precompiled header being built.
2381 return getOrCreateModuleRef(PCHDescriptor, /*SkeletonCU=*/false);
2388 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2389 // Handle qualifiers, which recursively handles what they refer to.
2390 if (Ty.hasLocalQualifiers())
2391 return CreateQualifiedType(Ty, Unit);
2393 // Work out details of type.
2394 switch (Ty->getTypeClass()) {
2395 #define TYPE(Class, Base)
2396 #define ABSTRACT_TYPE(Class, Base)
2397 #define NON_CANONICAL_TYPE(Class, Base)
2398 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2399 #include "clang/AST/TypeNodes.def"
2400 llvm_unreachable("Dependent types cannot show up in debug information");
2402 case Type::ExtVector:
2404 return CreateType(cast<VectorType>(Ty), Unit);
2405 case Type::ObjCObjectPointer:
2406 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2407 case Type::ObjCObject:
2408 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2409 case Type::ObjCInterface:
2410 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2412 return CreateType(cast<BuiltinType>(Ty));
2414 return CreateType(cast<ComplexType>(Ty));
2416 return CreateType(cast<PointerType>(Ty), Unit);
2417 case Type::Adjusted:
2419 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2421 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2422 case Type::BlockPointer:
2423 return CreateType(cast<BlockPointerType>(Ty), Unit);
2425 return CreateType(cast<TypedefType>(Ty), Unit);
2427 return CreateType(cast<RecordType>(Ty));
2429 return CreateEnumType(cast<EnumType>(Ty));
2430 case Type::FunctionProto:
2431 case Type::FunctionNoProto:
2432 return CreateType(cast<FunctionType>(Ty), Unit);
2433 case Type::ConstantArray:
2434 case Type::VariableArray:
2435 case Type::IncompleteArray:
2436 return CreateType(cast<ArrayType>(Ty), Unit);
2438 case Type::LValueReference:
2439 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2440 case Type::RValueReference:
2441 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2443 case Type::MemberPointer:
2444 return CreateType(cast<MemberPointerType>(Ty), Unit);
2447 return CreateType(cast<AtomicType>(Ty), Unit);
2450 return CreateType(cast<PipeType>(Ty), Unit);
2452 case Type::TemplateSpecialization:
2453 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2456 case Type::Attributed:
2457 case Type::Elaborated:
2459 case Type::SubstTemplateTypeParm:
2460 case Type::TypeOfExpr:
2462 case Type::Decltype:
2463 case Type::UnaryTransform:
2464 case Type::PackExpansion:
2468 llvm_unreachable("type should have been unwrapped!");
2471 llvm::DICompositeType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2472 llvm::DIFile *Unit) {
2473 QualType QTy(Ty, 0);
2475 auto *T = cast_or_null<llvm::DICompositeType>(getTypeOrNull(QTy));
2477 // We may have cached a forward decl when we could have created
2478 // a non-forward decl. Go ahead and create a non-forward decl
2480 if (T && !T->isForwardDecl())
2483 // Otherwise create the type.
2484 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2486 // Propagate members from the declaration to the definition
2487 // CreateType(const RecordType*) will overwrite this with the members in the
2488 // correct order if the full type is needed.
2489 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2491 // And update the type cache.
2492 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2496 // TODO: Currently used for context chains when limiting debug info.
2497 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2498 RecordDecl *RD = Ty->getDecl();
2500 // Get overall information about the record type for the debug info.
2501 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2502 unsigned Line = getLineNumber(RD->getLocation());
2503 StringRef RDName = getClassName(RD);
2505 llvm::DIScope *RDContext = getDeclContextDescriptor(RD);
2507 // If we ended up creating the type during the context chain construction,
2508 // just return that.
2509 auto *T = cast_or_null<llvm::DICompositeType>(
2510 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2511 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2514 // If this is just a forward or incomplete declaration, construct an
2515 // appropriately marked node and just return it.
2516 const RecordDecl *D = RD->getDefinition();
2517 if (!D || !D->isCompleteDefinition())
2518 return getOrCreateRecordFwdDecl(Ty, RDContext);
2520 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2521 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2523 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2525 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2526 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2529 // Elements of composite types usually have back to the type, creating
2530 // uniquing cycles. Distinct nodes are more efficient.
2531 switch (RealDecl->getTag()) {
2533 llvm_unreachable("invalid composite type tag");
2535 case llvm::dwarf::DW_TAG_array_type:
2536 case llvm::dwarf::DW_TAG_enumeration_type:
2537 // Array elements and most enumeration elements don't have back references,
2538 // so they don't tend to be involved in uniquing cycles and there is some
2539 // chance of merging them when linking together two modules. Only make
2540 // them distinct if they are ODR-uniqued.
2541 if (FullName.empty())
2544 case llvm::dwarf::DW_TAG_structure_type:
2545 case llvm::dwarf::DW_TAG_union_type:
2546 case llvm::dwarf::DW_TAG_class_type:
2547 // Immediatley resolve to a distinct node.
2549 llvm::MDNode::replaceWithDistinct(llvm::TempDICompositeType(RealDecl));
2553 RegionMap[Ty->getDecl()].reset(RealDecl);
2554 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2556 if (const auto *TSpecial = dyn_cast<ClassTemplateSpecializationDecl>(RD))
2557 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2558 CollectCXXTemplateParams(TSpecial, DefUnit));
2562 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2563 llvm::DICompositeType *RealDecl) {
2564 // A class's primary base or the class itself contains the vtable.
2565 llvm::DICompositeType *ContainingType = nullptr;
2566 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2567 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2568 // Seek non-virtual primary base root.
2570 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2571 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2572 if (PBT && !BRL.isPrimaryBaseVirtual())
2577 ContainingType = cast<llvm::DICompositeType>(
2578 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2579 getOrCreateFile(RD->getLocation())));
2580 } else if (RD->isDynamicClass())
2581 ContainingType = RealDecl;
2583 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2586 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2587 StringRef Name, uint64_t *Offset) {
2588 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2589 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2590 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2591 llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2592 FieldAlign, *Offset, 0, FieldTy);
2593 *Offset += FieldSize;
2597 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2599 StringRef &LinkageName,
2600 llvm::DIScope *&FDContext,
2601 llvm::DINodeArray &TParamsArray,
2603 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2604 Name = getFunctionName(FD);
2605 // Use mangled name as linkage name for C/C++ functions.
2606 if (FD->hasPrototype()) {
2607 LinkageName = CGM.getMangledName(GD);
2608 Flags |= llvm::DINode::FlagPrototyped;
2610 // No need to replicate the linkage name if it isn't different from the
2611 // subprogram name, no need to have it at all unless coverage is enabled or
2612 // debug is set to more than just line tables.
2613 if (LinkageName == Name || (!CGM.getCodeGenOpts().EmitGcovArcs &&
2614 !CGM.getCodeGenOpts().EmitGcovNotes &&
2615 DebugKind <= codegenoptions::DebugLineTablesOnly))
2616 LinkageName = StringRef();
2618 if (DebugKind >= codegenoptions::LimitedDebugInfo) {
2619 if (const NamespaceDecl *NSDecl =
2620 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2621 FDContext = getOrCreateNameSpace(NSDecl);
2622 else if (const RecordDecl *RDecl =
2623 dyn_cast_or_null<RecordDecl>(FD->getDeclContext())) {
2624 llvm::DIScope *Mod = getParentModuleOrNull(RDecl);
2625 FDContext = getContextDescriptor(RDecl, Mod ? Mod : TheCU);
2627 // Collect template parameters.
2628 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2632 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2633 unsigned &LineNo, QualType &T,
2634 StringRef &Name, StringRef &LinkageName,
2635 llvm::DIScope *&VDContext) {
2636 Unit = getOrCreateFile(VD->getLocation());
2637 LineNo = getLineNumber(VD->getLocation());
2639 setLocation(VD->getLocation());
2642 if (T->isIncompleteArrayType()) {
2643 // CodeGen turns int[] into int[1] so we'll do the same here.
2644 llvm::APInt ConstVal(32, 1);
2645 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2647 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2648 ArrayType::Normal, 0);
2651 Name = VD->getName();
2652 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2653 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2654 LinkageName = CGM.getMangledName(VD);
2655 if (LinkageName == Name)
2656 LinkageName = StringRef();
2658 // Since we emit declarations (DW_AT_members) for static members, place the
2659 // definition of those static members in the namespace they were declared in
2660 // in the source code (the lexical decl context).
2661 // FIXME: Generalize this for even non-member global variables where the
2662 // declaration and definition may have different lexical decl contexts, once
2663 // we have support for emitting declarations of (non-member) global variables.
2664 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2665 : VD->getDeclContext();
2666 // When a record type contains an in-line initialization of a static data
2667 // member, and the record type is marked as __declspec(dllexport), an implicit
2668 // definition of the member will be created in the record context. DWARF
2669 // doesn't seem to have a nice way to describe this in a form that consumers
2670 // are likely to understand, so fake the "normal" situation of a definition
2671 // outside the class by putting it in the global scope.
2673 DC = CGM.getContext().getTranslationUnitDecl();
2675 llvm::DIScope *Mod = getParentModuleOrNull(VD);
2676 VDContext = getContextDescriptor(cast<Decl>(DC), Mod ? Mod : TheCU);
2679 llvm::DISubprogram *
2680 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2681 llvm::DINodeArray TParamsArray;
2682 StringRef Name, LinkageName;
2684 SourceLocation Loc = FD->getLocation();
2685 llvm::DIFile *Unit = getOrCreateFile(Loc);
2686 llvm::DIScope *DContext = Unit;
2687 unsigned Line = getLineNumber(Loc);
2689 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2690 TParamsArray, Flags);
2691 // Build function type.
2692 SmallVector<QualType, 16> ArgTypes;
2693 for (const ParmVarDecl *Parm: FD->parameters())
2694 ArgTypes.push_back(Parm->getType());
2695 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
2696 QualType FnType = CGM.getContext().getFunctionType(
2697 FD->getReturnType(), ArgTypes, FunctionProtoType::ExtProtoInfo(CC));
2698 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2699 DContext, Name, LinkageName, Unit, Line,
2700 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2701 /* isDefinition = */ false, 0, Flags, CGM.getLangOpts().Optimize,
2702 TParamsArray.get(), getFunctionDeclaration(FD));
2703 const auto *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2704 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2705 std::make_tuple(CanonDecl),
2706 std::make_tuple(SP));
2710 llvm::DIGlobalVariable *
2711 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2713 StringRef Name, LinkageName;
2714 SourceLocation Loc = VD->getLocation();
2715 llvm::DIFile *Unit = getOrCreateFile(Loc);
2716 llvm::DIScope *DContext = Unit;
2717 unsigned Line = getLineNumber(Loc);
2719 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2720 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2721 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2722 !VD->isExternallyVisible(), nullptr, nullptr);
2723 FwdDeclReplaceMap.emplace_back(
2724 std::piecewise_construct,
2725 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2726 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2730 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2731 // We only need a declaration (not a definition) of the type - so use whatever
2732 // we would otherwise do to get a type for a pointee. (forward declarations in
2733 // limited debug info, full definitions (if the type definition is available)
2734 // in unlimited debug info)
2735 if (const auto *TD = dyn_cast<TypeDecl>(D))
2736 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2737 getOrCreateFile(TD->getLocation()));
2738 auto I = DeclCache.find(D->getCanonicalDecl());
2740 if (I != DeclCache.end())
2741 return dyn_cast_or_null<llvm::DINode>(I->second);
2743 // No definition for now. Emit a forward definition that might be
2744 // merged with a potential upcoming definition.
2745 if (const auto *FD = dyn_cast<FunctionDecl>(D))
2746 return getFunctionForwardDeclaration(FD);
2747 else if (const auto *VD = dyn_cast<VarDecl>(D))
2748 return getGlobalVariableForwardDeclaration(VD);
2753 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2754 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
2757 const auto *FD = dyn_cast<FunctionDecl>(D);
2762 auto *S = getDeclContextDescriptor(D);
2764 auto MI = SPCache.find(FD->getCanonicalDecl());
2765 if (MI == SPCache.end()) {
2766 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2767 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2768 cast<llvm::DICompositeType>(S));
2771 if (MI != SPCache.end()) {
2772 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2773 if (SP && !SP->isDefinition())
2777 for (auto NextFD : FD->redecls()) {
2778 auto MI = SPCache.find(NextFD->getCanonicalDecl());
2779 if (MI != SPCache.end()) {
2780 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2781 if (SP && !SP->isDefinition())
2788 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2789 // implicit parameter "this".
2790 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2793 if (!D || DebugKind <= codegenoptions::DebugLineTablesOnly)
2794 // Create fake but valid subroutine type. Otherwise -verify would fail, and
2795 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2796 return DBuilder.createSubroutineType(DBuilder.getOrCreateTypeArray(None));
2798 if (const auto *Method = dyn_cast<CXXMethodDecl>(D))
2799 return getOrCreateMethodType(Method, F);
2801 const auto *FTy = FnType->getAs<FunctionType>();
2802 CallingConv CC = FTy ? FTy->getCallConv() : CallingConv::CC_C;
2804 if (const auto *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2805 // Add "self" and "_cmd"
2806 SmallVector<llvm::Metadata *, 16> Elts;
2808 // First element is always return type. For 'void' functions it is NULL.
2809 QualType ResultTy = OMethod->getReturnType();
2811 // Replace the instancetype keyword with the actual type.
2812 if (ResultTy == CGM.getContext().getObjCInstanceType())
2813 ResultTy = CGM.getContext().getPointerType(
2814 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2816 Elts.push_back(getOrCreateType(ResultTy, F));
2817 // "self" pointer is always first argument.
2818 QualType SelfDeclTy;
2819 if (auto *SelfDecl = OMethod->getSelfDecl())
2820 SelfDeclTy = SelfDecl->getType();
2821 else if (auto *FPT = dyn_cast<FunctionProtoType>(FnType))
2822 if (FPT->getNumParams() > 1)
2823 SelfDeclTy = FPT->getParamType(0);
2824 if (!SelfDeclTy.isNull())
2825 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2826 // "_cmd" pointer is always second argument.
2827 Elts.push_back(DBuilder.createArtificialType(
2828 getOrCreateType(CGM.getContext().getObjCSelType(), F)));
2829 // Get rest of the arguments.
2830 for (const auto *PI : OMethod->parameters())
2831 Elts.push_back(getOrCreateType(PI->getType(), F));
2832 // Variadic methods need a special marker at the end of the type list.
2833 if (OMethod->isVariadic())
2834 Elts.push_back(DBuilder.createUnspecifiedParameter());
2836 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2837 return DBuilder.createSubroutineType(EltTypeArray, 0, getDwarfCC(CC));
2840 // Handle variadic function types; they need an additional
2841 // unspecified parameter.
2842 if (const auto *FD = dyn_cast<FunctionDecl>(D))
2843 if (FD->isVariadic()) {
2844 SmallVector<llvm::Metadata *, 16> EltTys;
2845 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2846 if (const auto *FPT = dyn_cast<FunctionProtoType>(FnType))
2847 for (QualType ParamType : FPT->param_types())
2848 EltTys.push_back(getOrCreateType(ParamType, F));
2849 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2850 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2851 return DBuilder.createSubroutineType(EltTypeArray, 0, getDwarfCC(CC));
2854 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
2857 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
2858 SourceLocation ScopeLoc, QualType FnType,
2859 llvm::Function *Fn, CGBuilderTy &Builder) {
2862 StringRef LinkageName;
2864 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2866 const Decl *D = GD.getDecl();
2867 bool HasDecl = (D != nullptr);
2870 llvm::DIFile *Unit = getOrCreateFile(Loc);
2871 llvm::DIScope *FDContext = Unit;
2872 llvm::DINodeArray TParamsArray;
2874 // Use llvm function name.
2875 LinkageName = Fn->getName();
2876 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2877 // If there is a subprogram for this function available then use it.
2878 auto FI = SPCache.find(FD->getCanonicalDecl());
2879 if (FI != SPCache.end()) {
2880 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
2881 if (SP && SP->isDefinition()) {
2882 LexicalBlockStack.emplace_back(SP);
2883 RegionMap[D].reset(SP);
2887 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2888 TParamsArray, Flags);
2889 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2890 Name = getObjCMethodName(OMD);
2891 Flags |= llvm::DINode::FlagPrototyped;
2893 // Use llvm function name.
2894 Name = Fn->getName();
2895 Flags |= llvm::DINode::FlagPrototyped;
2897 if (Name.startswith("\01"))
2898 Name = Name.substr(1);
2900 if (!HasDecl || D->isImplicit()) {
2901 Flags |= llvm::DINode::FlagArtificial;
2902 // Artificial functions without a location should not silently reuse CurLoc.
2903 if (Loc.isInvalid())
2904 CurLoc = SourceLocation();
2906 unsigned LineNo = getLineNumber(Loc);
2907 unsigned ScopeLine = getLineNumber(ScopeLoc);
2909 // FIXME: The function declaration we're constructing here is mostly reusing
2910 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2911 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2912 // all subprograms instead of the actual context since subprogram definitions
2913 // are emitted as CU level entities by the backend.
2914 llvm::DISubprogram *SP = DBuilder.createFunction(
2915 FDContext, Name, LinkageName, Unit, LineNo,
2916 getOrCreateFunctionType(D, FnType, Unit), Fn->hasLocalLinkage(),
2917 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
2918 TParamsArray.get(), getFunctionDeclaration(D));
2919 Fn->setSubprogram(SP);
2920 // We might get here with a VarDecl in the case we're generating
2921 // code for the initialization of globals. Do not record these decls
2922 // as they will overwrite the actual VarDecl Decl in the cache.
2923 if (HasDecl && isa<FunctionDecl>(D))
2924 DeclCache[D->getCanonicalDecl()].reset(SP);
2926 // Push the function onto the lexical block stack.
2927 LexicalBlockStack.emplace_back(SP);
2930 RegionMap[D].reset(SP);
2933 void CGDebugInfo::EmitFunctionDecl(GlobalDecl GD, SourceLocation Loc,
2936 StringRef LinkageName;
2938 const Decl *D = GD.getDecl();
2943 llvm::DIFile *Unit = getOrCreateFile(Loc);
2944 llvm::DIScope *FDContext = getDeclContextDescriptor(D);
2945 llvm::DINodeArray TParamsArray;
2946 if (isa<FunctionDecl>(D)) {
2947 // If there is a DISubprogram for this function available then use it.
2948 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2949 TParamsArray, Flags);
2950 } else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2951 Name = getObjCMethodName(OMD);
2952 Flags |= llvm::DINode::FlagPrototyped;
2954 llvm_unreachable("not a function or ObjC method");
2956 if (!Name.empty() && Name[0] == '\01')
2957 Name = Name.substr(1);
2959 if (D->isImplicit()) {
2960 Flags |= llvm::DINode::FlagArtificial;
2961 // Artificial functions without a location should not silently reuse CurLoc.
2962 if (Loc.isInvalid())
2963 CurLoc = SourceLocation();
2965 unsigned LineNo = getLineNumber(Loc);
2966 unsigned ScopeLine = 0;
2968 DBuilder.retainType(DBuilder.createFunction(
2969 FDContext, Name, LinkageName, Unit, LineNo,
2970 getOrCreateFunctionType(D, FnType, Unit), false /*internalLinkage*/,
2971 false /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize,
2972 TParamsArray.get(), getFunctionDeclaration(D)));
2975 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2976 // Update our current location
2979 if (CurLoc.isInvalid() || CurLoc.isMacroID())
2982 llvm::MDNode *Scope = LexicalBlockStack.back();
2983 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2984 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2987 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2988 llvm::MDNode *Back = nullptr;
2989 if (!LexicalBlockStack.empty())
2990 Back = LexicalBlockStack.back().get();
2991 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
2992 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2993 getColumnNumber(CurLoc)));
2996 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2997 SourceLocation Loc) {
2998 // Set our current location.
3001 // Emit a line table change for the current location inside the new scope.
3002 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
3003 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
3005 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3008 // Create a new lexical block and push it on the stack.
3009 CreateLexicalBlock(Loc);
3012 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
3013 SourceLocation Loc) {
3014 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3016 // Provide an entry in the line table for the end of the block.
3017 EmitLocation(Builder, Loc);
3019 if (DebugKind <= codegenoptions::DebugLineTablesOnly)
3022 LexicalBlockStack.pop_back();
3025 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
3026 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3027 unsigned RCount = FnBeginRegionCount.back();
3028 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
3030 // Pop all regions for this function.
3031 while (LexicalBlockStack.size() != RCount) {
3032 // Provide an entry in the line table for the end of the block.
3033 EmitLocation(Builder, CurLoc);
3034 LexicalBlockStack.pop_back();
3036 FnBeginRegionCount.pop_back();
3039 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
3040 uint64_t *XOffset) {
3042 SmallVector<llvm::Metadata *, 5> EltTys;
3044 uint64_t FieldSize, FieldOffset;
3045 unsigned FieldAlign;
3047 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3048 QualType Type = VD->getType();
3051 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3052 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
3053 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
3054 FType = CGM.getContext().IntTy;
3055 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
3056 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
3058 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
3059 if (HasCopyAndDispose) {
3060 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3062 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
3064 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
3066 bool HasByrefExtendedLayout;
3067 Qualifiers::ObjCLifetime Lifetime;
3068 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
3069 HasByrefExtendedLayout) &&
3070 HasByrefExtendedLayout) {
3071 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
3073 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
3076 CharUnits Align = CGM.getContext().getDeclAlign(VD);
3077 if (Align > CGM.getContext().toCharUnitsFromBits(
3078 CGM.getTarget().getPointerAlign(0))) {
3079 CharUnits FieldOffsetInBytes =
3080 CGM.getContext().toCharUnitsFromBits(FieldOffset);
3081 CharUnits AlignedOffsetInBytes = FieldOffsetInBytes.alignTo(Align);
3082 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
3084 if (NumPaddingBytes.isPositive()) {
3085 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
3086 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
3087 pad, ArrayType::Normal, 0);
3088 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
3093 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
3094 FieldSize = CGM.getContext().getTypeSize(FType);
3095 FieldAlign = CGM.getContext().toBits(Align);
3097 *XOffset = FieldOffset;
3098 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
3099 FieldAlign, FieldOffset, 0, FieldTy);
3100 EltTys.push_back(FieldTy);
3101 FieldOffset += FieldSize;
3103 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
3105 unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
3107 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
3111 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::Value *Storage,
3112 llvm::Optional<unsigned> ArgNo,
3113 CGBuilderTy &Builder) {
3114 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3115 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3116 if (VD->hasAttr<NoDebugAttr>())
3120 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
3121 cast<Decl>(VD->getDeclContext())->isImplicit());
3122 llvm::DIFile *Unit = nullptr;
3124 Unit = getOrCreateFile(VD->getLocation());
3126 uint64_t XOffset = 0;
3127 if (VD->hasAttr<BlocksAttr>())
3128 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3130 Ty = getOrCreateType(VD->getType(), Unit);
3132 // If there is no debug info for this type then do not emit debug info
3133 // for this variable.
3137 // Get location information.
3139 unsigned Column = 0;
3141 Line = getLineNumber(VD->getLocation());
3142 Column = getColumnNumber(VD->getLocation());
3144 SmallVector<int64_t, 9> Expr;
3146 if (VD->isImplicit())
3147 Flags |= llvm::DINode::FlagArtificial;
3148 // If this is the first argument and it is implicit then
3149 // give it an object pointer flag.
3150 // FIXME: There has to be a better way to do this, but for static
3151 // functions there won't be an implicit param at arg1 and
3152 // otherwise it is 'self' or 'this'.
3153 if (isa<ImplicitParamDecl>(VD) && ArgNo && *ArgNo == 1)
3154 Flags |= llvm::DINode::FlagObjectPointer;
3155 if (auto *Arg = dyn_cast<llvm::Argument>(Storage))
3156 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
3157 !VD->getType()->isPointerType())
3158 Expr.push_back(llvm::dwarf::DW_OP_deref);
3160 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
3162 StringRef Name = VD->getName();
3163 if (!Name.empty()) {
3164 if (VD->hasAttr<BlocksAttr>()) {
3165 CharUnits offset = CharUnits::fromQuantity(32);
3166 Expr.push_back(llvm::dwarf::DW_OP_plus);
3167 // offset of __forwarding field
3168 offset = CGM.getContext().toCharUnitsFromBits(
3169 CGM.getTarget().getPointerWidth(0));
3170 Expr.push_back(offset.getQuantity());
3171 Expr.push_back(llvm::dwarf::DW_OP_deref);
3172 Expr.push_back(llvm::dwarf::DW_OP_plus);
3173 // offset of x field
3174 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3175 Expr.push_back(offset.getQuantity());
3177 // Create the descriptor for the variable.
3179 ? DBuilder.createParameterVariable(Scope, VD->getName(),
3180 *ArgNo, Unit, Line, Ty)
3181 : DBuilder.createAutoVariable(Scope, VD->getName(), Unit,
3184 // Insert an llvm.dbg.declare into the current block.
3185 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3186 llvm::DebugLoc::get(Line, Column, Scope),
3187 Builder.GetInsertBlock());
3189 } else if (isa<VariableArrayType>(VD->getType()))
3190 Expr.push_back(llvm::dwarf::DW_OP_deref);
3191 } else if (const auto *RT = dyn_cast<RecordType>(VD->getType())) {
3192 // If VD is an anonymous union then Storage represents value for
3193 // all union fields.
3194 const auto *RD = cast<RecordDecl>(RT->getDecl());
3195 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
3196 // GDB has trouble finding local variables in anonymous unions, so we emit
3197 // artifical local variables for each of the members.
3199 // FIXME: Remove this code as soon as GDB supports this.
3200 // The debug info verifier in LLVM operates based on the assumption that a
3201 // variable has the same size as its storage and we had to disable the check
3202 // for artificial variables.
3203 for (const auto *Field : RD->fields()) {
3204 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3205 StringRef FieldName = Field->getName();
3207 // Ignore unnamed fields. Do not ignore unnamed records.
3208 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
3211 // Use VarDecl's Tag, Scope and Line number.
3212 auto *D = DBuilder.createAutoVariable(
3213 Scope, FieldName, Unit, Line, FieldTy, CGM.getLangOpts().Optimize,
3214 Flags | llvm::DINode::FlagArtificial);
3216 // Insert an llvm.dbg.declare into the current block.
3217 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3218 llvm::DebugLoc::get(Line, Column, Scope),
3219 Builder.GetInsertBlock());
3224 // Create the descriptor for the variable.
3227 ? DBuilder.createParameterVariable(Scope, Name, *ArgNo, Unit, Line,
3228 Ty, CGM.getLangOpts().Optimize,
3230 : DBuilder.createAutoVariable(Scope, Name, Unit, Line, Ty,
3231 CGM.getLangOpts().Optimize, Flags);
3233 // Insert an llvm.dbg.declare into the current block.
3234 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
3235 llvm::DebugLoc::get(Line, Column, Scope),
3236 Builder.GetInsertBlock());
3239 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
3240 llvm::Value *Storage,
3241 CGBuilderTy &Builder) {
3242 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3243 EmitDeclare(VD, Storage, llvm::None, Builder);
3246 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
3248 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
3251 return DBuilder.createObjectPointerType(Ty);
3254 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
3255 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
3256 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
3257 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3258 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
3260 if (Builder.GetInsertBlock() == nullptr)
3262 if (VD->hasAttr<NoDebugAttr>())
3265 bool isByRef = VD->hasAttr<BlocksAttr>();
3267 uint64_t XOffset = 0;
3268 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3271 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
3273 Ty = getOrCreateType(VD->getType(), Unit);
3275 // Self is passed along as an implicit non-arg variable in a
3276 // block. Mark it as the object pointer.
3277 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
3278 Ty = CreateSelfType(VD->getType(), Ty);
3280 // Get location information.
3281 unsigned Line = getLineNumber(VD->getLocation());
3282 unsigned Column = getColumnNumber(VD->getLocation());
3284 const llvm::DataLayout &target = CGM.getDataLayout();
3286 CharUnits offset = CharUnits::fromQuantity(
3287 target.getStructLayout(blockInfo.StructureType)
3288 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
3290 SmallVector<int64_t, 9> addr;
3291 if (isa<llvm::AllocaInst>(Storage))
3292 addr.push_back(llvm::dwarf::DW_OP_deref);
3293 addr.push_back(llvm::dwarf::DW_OP_plus);
3294 addr.push_back(offset.getQuantity());
3296 addr.push_back(llvm::dwarf::DW_OP_deref);
3297 addr.push_back(llvm::dwarf::DW_OP_plus);
3298 // offset of __forwarding field
3300 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
3301 addr.push_back(offset.getQuantity());
3302 addr.push_back(llvm::dwarf::DW_OP_deref);
3303 addr.push_back(llvm::dwarf::DW_OP_plus);
3304 // offset of x field
3305 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
3306 addr.push_back(offset.getQuantity());
3309 // Create the descriptor for the variable.
3310 auto *D = DBuilder.createAutoVariable(
3311 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
3314 // Insert an llvm.dbg.declare into the current block.
3315 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
3317 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3320 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
3321 Builder.GetInsertBlock());
3324 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
3326 CGBuilderTy &Builder) {
3327 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3328 EmitDeclare(VD, AI, ArgNo, Builder);
3332 struct BlockLayoutChunk {
3333 uint64_t OffsetInBits;
3334 const BlockDecl::Capture *Capture;
3336 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3337 return l.OffsetInBits < r.OffsetInBits;
3341 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3344 llvm::Value *LocalAddr,
3345 CGBuilderTy &Builder) {
3346 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3347 ASTContext &C = CGM.getContext();
3348 const BlockDecl *blockDecl = block.getBlockDecl();
3350 // Collect some general information about the block's location.
3351 SourceLocation loc = blockDecl->getCaretLocation();
3352 llvm::DIFile *tunit = getOrCreateFile(loc);
3353 unsigned line = getLineNumber(loc);
3354 unsigned column = getColumnNumber(loc);
3356 // Build the debug-info type for the block literal.
3357 getDeclContextDescriptor(blockDecl);
3359 const llvm::StructLayout *blockLayout =
3360 CGM.getDataLayout().getStructLayout(block.StructureType);
3362 SmallVector<llvm::Metadata *, 16> fields;
3363 fields.push_back(createFieldType("__isa", C.VoidPtrTy, loc, AS_public,
3364 blockLayout->getElementOffsetInBits(0),
3366 fields.push_back(createFieldType("__flags", C.IntTy, loc, AS_public,
3367 blockLayout->getElementOffsetInBits(1),
3369 fields.push_back(createFieldType("__reserved", C.IntTy, loc, AS_public,
3370 blockLayout->getElementOffsetInBits(2),
3372 auto *FnTy = block.getBlockExpr()->getFunctionType();
3373 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3374 fields.push_back(createFieldType("__FuncPtr", FnPtrType, loc, AS_public,
3375 blockLayout->getElementOffsetInBits(3),
3377 fields.push_back(createFieldType(
3378 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3379 ? C.getBlockDescriptorExtendedType()
3380 : C.getBlockDescriptorType()),
3381 loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3383 // We want to sort the captures by offset, not because DWARF
3384 // requires this, but because we're paranoid about debuggers.
3385 SmallVector<BlockLayoutChunk, 8> chunks;
3388 if (blockDecl->capturesCXXThis()) {
3389 BlockLayoutChunk chunk;
3390 chunk.OffsetInBits =
3391 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3392 chunk.Capture = nullptr;
3393 chunks.push_back(chunk);
3396 // Variable captures.
3397 for (const auto &capture : blockDecl->captures()) {
3398 const VarDecl *variable = capture.getVariable();
3399 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3401 // Ignore constant captures.
3402 if (captureInfo.isConstant())
3405 BlockLayoutChunk chunk;
3406 chunk.OffsetInBits =
3407 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3408 chunk.Capture = &capture;
3409 chunks.push_back(chunk);
3413 llvm::array_pod_sort(chunks.begin(), chunks.end());
3415 for (const BlockLayoutChunk &Chunk : chunks) {
3416 uint64_t offsetInBits = Chunk.OffsetInBits;
3417 const BlockDecl::Capture *capture = Chunk.Capture;
3419 // If we have a null capture, this must be the C++ 'this' capture.
3423 cast_or_null<CXXMethodDecl>(blockDecl->getNonClosureContext()))
3424 type = Method->getThisType(C);
3425 else if (auto *RDecl = dyn_cast<CXXRecordDecl>(blockDecl->getParent()))
3426 type = QualType(RDecl->getTypeForDecl(), 0);
3428 llvm_unreachable("unexpected block declcontext");
3430 fields.push_back(createFieldType("this", type, loc, AS_public,
3431 offsetInBits, tunit, tunit));
3435 const VarDecl *variable = capture->getVariable();
3436 StringRef name = variable->getName();
3438 llvm::DIType *fieldType;
3439 if (capture->isByRef()) {
3440 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3442 // FIXME: this creates a second copy of this type!
3444 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3445 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3447 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3448 PtrInfo.Align, offsetInBits, 0, fieldType);
3450 fieldType = createFieldType(name, variable->getType(), loc, AS_public,
3451 offsetInBits, tunit, tunit);
3453 fields.push_back(fieldType);
3456 SmallString<36> typeName;
3457 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3458 << CGM.getUniqueBlockCount();
3460 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3462 llvm::DIType *type = DBuilder.createStructType(
3463 tunit, typeName.str(), tunit, line,
3464 CGM.getContext().toBits(block.BlockSize),
3465 CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
3466 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3468 // Get overall information about the block.
3469 unsigned flags = llvm::DINode::FlagArtificial;
3470 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3472 // Create the descriptor for the parameter.
3473 auto *debugVar = DBuilder.createParameterVariable(
3474 scope, Arg->getName(), ArgNo, tunit, line, type,
3475 CGM.getLangOpts().Optimize, flags);
3478 // Insert an llvm.dbg.value into the current block.
3479 DBuilder.insertDbgValueIntrinsic(
3480 LocalAddr, 0, debugVar, DBuilder.createExpression(),
3481 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3484 // Insert an llvm.dbg.declare into the current block.
3485 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3486 llvm::DebugLoc::get(line, column, scope),
3487 Builder.GetInsertBlock());
3490 llvm::DIDerivedType *
3491 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3492 if (!D->isStaticDataMember())
3495 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3496 if (MI != StaticDataMemberCache.end()) {
3497 assert(MI->second && "Static data member declaration should still exist");
3501 // If the member wasn't found in the cache, lazily construct and add it to the
3502 // type (used when a limited form of the type is emitted).
3503 auto DC = D->getDeclContext();
3504 auto *Ctxt = cast<llvm::DICompositeType>(getDeclContextDescriptor(D));
3505 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3508 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
3509 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3510 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3511 llvm::DIGlobalVariable *GV = nullptr;
3513 for (const auto *Field : RD->fields()) {
3514 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3515 StringRef FieldName = Field->getName();
3517 // Ignore unnamed fields, but recurse into anonymous records.
3518 if (FieldName.empty()) {
3519 if (const auto *RT = dyn_cast<RecordType>(Field->getType()))
3520 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3524 // Use VarDecl's Tag, Scope and Line number.
3525 GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
3527 Var->hasLocalLinkage(), Var, nullptr);
3532 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3534 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3535 if (D->hasAttr<NoDebugAttr>())
3537 // Create global variable debug descriptor.
3538 llvm::DIFile *Unit = nullptr;
3539 llvm::DIScope *DContext = nullptr;
3541 StringRef DeclName, LinkageName;
3543 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3545 // Attempt to store one global variable for the declaration - even if we
3546 // emit a lot of fields.
3547 llvm::DIGlobalVariable *GV = nullptr;
3549 // If this is an anonymous union then we'll want to emit a global
3550 // variable for each member of the anonymous union so that it's possible
3551 // to find the name of any field in the union.
3552 if (T->isUnionType() && DeclName.empty()) {
3553 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
3554 assert(RD->isAnonymousStructOrUnion() &&
3555 "unnamed non-anonymous struct or union?");
3556 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3558 GV = DBuilder.createGlobalVariable(
3559 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3560 Var->hasLocalLinkage(), Var,
3561 getOrCreateStaticDataMemberDeclarationOrNull(D));
3563 DeclCache[D->getCanonicalDecl()].reset(GV);
3566 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3567 llvm::Constant *Init) {
3568 assert(DebugKind >= codegenoptions::LimitedDebugInfo);
3569 if (VD->hasAttr<NoDebugAttr>())
3571 // Create the descriptor for the variable.
3572 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3573 StringRef Name = VD->getName();
3574 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3575 if (const auto *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3576 const auto *ED = cast<EnumDecl>(ECD->getDeclContext());
3577 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3578 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3580 // Do not use global variables for enums.
3583 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3585 // Do not emit separate definitions for function local const/statics.
3586 if (isa<FunctionDecl>(VD->getDeclContext()))
3588 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3589 auto *VarD = cast<VarDecl>(VD);
3590 if (VarD->isStaticDataMember()) {
3591 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3592 getDeclContextDescriptor(VarD);
3593 // Ensure that the type is retained even though it's otherwise unreferenced.
3595 // FIXME: This is probably unnecessary, since Ty should reference RD
3596 // through its scope.
3597 RetainedTypes.push_back(
3598 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3602 llvm::DIScope *DContext = getDeclContextDescriptor(VD);
3604 auto &GV = DeclCache[VD];
3607 GV.reset(DBuilder.createGlobalVariable(
3608 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3609 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3612 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3613 if (!LexicalBlockStack.empty())
3614 return LexicalBlockStack.back();
3615 llvm::DIScope *Mod = getParentModuleOrNull(D);
3616 return getContextDescriptor(D, Mod ? Mod : TheCU);
3619 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3620 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3622 const NamespaceDecl *NSDecl = UD.getNominatedNamespace();
3623 if (!NSDecl->isAnonymousNamespace() ||
3624 CGM.getCodeGenOpts().DebugExplicitImport) {
3625 DBuilder.createImportedModule(
3626 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3627 getOrCreateNameSpace(NSDecl),
3628 getLineNumber(UD.getLocation()));
3632 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3633 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3635 assert(UD.shadow_size() &&
3636 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3637 // Emitting one decl is sufficient - debuggers can detect that this is an
3638 // overloaded name & provide lookup for all the overloads.
3639 const UsingShadowDecl &USD = **UD.shadow_begin();
3641 // FIXME: Skip functions with undeduced auto return type for now since we
3642 // don't currently have the plumbing for separate declarations & definitions
3643 // of free functions and mismatched types (auto in the declaration, concrete
3644 // return type in the definition)
3645 if (const auto *FD = dyn_cast<FunctionDecl>(USD.getUnderlyingDecl()))
3646 if (const auto *AT =
3647 FD->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
3648 if (AT->getDeducedType().isNull())
3650 if (llvm::DINode *Target =
3651 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3652 DBuilder.createImportedDeclaration(
3653 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3654 getLineNumber(USD.getLocation()));
3657 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
3658 if (CGM.getCodeGenOpts().getDebuggerTuning() != llvm::DebuggerKind::LLDB)
3660 if (Module *M = ID.getImportedModule()) {
3661 auto Info = ExternalASTSource::ASTSourceDescriptor(*M);
3662 DBuilder.createImportedDeclaration(
3663 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
3664 getOrCreateModuleRef(Info, DebugTypeExtRefs),
3665 getLineNumber(ID.getLocation()));
3669 llvm::DIImportedEntity *
3670 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3671 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3673 auto &VH = NamespaceAliasCache[&NA];
3675 return cast<llvm::DIImportedEntity>(VH);
3676 llvm::DIImportedEntity *R;
3677 if (const auto *Underlying =
3678 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3679 // This could cache & dedup here rather than relying on metadata deduping.
3680 R = DBuilder.createImportedDeclaration(
3681 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3682 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3685 R = DBuilder.createImportedDeclaration(
3686 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3687 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3688 getLineNumber(NA.getLocation()), NA.getName());
3694 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3695 NSDecl = NSDecl->getCanonicalDecl();
3696 auto I = NameSpaceCache.find(NSDecl);
3697 if (I != NameSpaceCache.end())
3698 return cast<llvm::DINamespace>(I->second);
3700 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3701 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3702 llvm::DIScope *Context = getDeclContextDescriptor(NSDecl);
3703 llvm::DINamespace *NS =
3704 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3705 NameSpaceCache[NSDecl].reset(NS);
3709 void CGDebugInfo::setDwoId(uint64_t Signature) {
3710 assert(TheCU && "no main compile unit");
3711 TheCU->setDWOId(Signature);
3715 void CGDebugInfo::finalize() {
3716 // Creating types might create further types - invalidating the current
3717 // element and the size(), so don't cache/reference them.
3718 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3719 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3720 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3721 ? CreateTypeDefinition(E.Type, E.Unit)
3723 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3726 for (auto p : ReplaceMap) {
3728 auto *Ty = cast<llvm::DIType>(p.second);
3729 assert(Ty->isForwardDecl());
3731 auto it = TypeCache.find(p.first);
3732 assert(it != TypeCache.end());
3735 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3736 cast<llvm::DIType>(it->second));
3739 for (const auto &p : FwdDeclReplaceMap) {
3741 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3742 llvm::Metadata *Repl;
3744 auto it = DeclCache.find(p.first);
3745 // If there has been no definition for the declaration, call RAUW
3746 // with ourselves, that will destroy the temporary MDNode and
3747 // replace it with a standard one, avoiding leaking memory.
3748 if (it == DeclCache.end())
3753 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3756 // We keep our own list of retained types, because we need to look
3757 // up the final type in the type cache.
3758 for (auto &RT : RetainedTypes)
3759 if (auto MD = TypeCache[RT])
3760 DBuilder.retainType(cast<llvm::DIType>(MD));
3762 DBuilder.finalize();
3765 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3766 if (CGM.getCodeGenOpts().getDebugInfo() < codegenoptions::LimitedDebugInfo)
3769 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3770 // Don't ignore in case of explicit cast where it is referenced indirectly.
3771 DBuilder.retainType(DieTy);