1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "clang/Lex/HeaderSearchOptions.h"
31 #include "clang/Lex/PreprocessorOptions.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Intrinsics.h"
39 #include "llvm/IR/Module.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Path.h"
43 using namespace clang;
44 using namespace clang::CodeGen;
46 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
47 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
48 DBuilder(CGM.getModule()) {
52 CGDebugInfo::~CGDebugInfo() {
53 assert(LexicalBlockStack.empty() &&
54 "Region stack mismatch, stack not empty!");
57 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
58 SourceLocation TemporaryLocation)
60 init(TemporaryLocation);
63 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
65 SourceLocation TemporaryLocation)
67 init(TemporaryLocation, DefaultToEmpty);
70 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
71 bool DefaultToEmpty) {
72 if (auto *DI = CGF.getDebugInfo()) {
73 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
74 if (TemporaryLocation.isInvalid()) {
76 CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc());
78 // Construct a location that has a valid scope, but no line info.
79 assert(!DI->LexicalBlockStack.empty());
80 CGF.Builder.SetCurrentDebugLocation(
81 llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
84 DI->EmitLocation(CGF.Builder, TemporaryLocation);
88 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
90 init(E->getExprLoc());
93 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
95 if (CGF.getDebugInfo()) {
96 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
98 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
102 ApplyDebugLocation::~ApplyDebugLocation() {
103 // Query CGF so the location isn't overwritten when location updates are
104 // temporarily disabled (for C++ default function arguments)
105 if (CGF.getDebugInfo())
106 CGF.Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
109 void CGDebugInfo::setLocation(SourceLocation Loc) {
110 // If the new location isn't valid return.
114 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
116 // If we've changed files in the middle of a lexical scope go ahead
117 // and create a new lexical scope with file node if it's different
118 // from the one in the scope.
119 if (LexicalBlockStack.empty())
122 SourceManager &SM = CGM.getContext().getSourceManager();
123 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
124 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
126 if (PCLoc.isInvalid() || Scope->getFilename() == PCLoc.getFilename())
129 if (auto *LBF = dyn_cast<llvm::DILexicalBlockFile>(Scope)) {
130 LexicalBlockStack.pop_back();
131 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlockFile(
132 LBF->getScope(), getOrCreateFile(CurLoc)));
133 } else if (isa<llvm::DILexicalBlock>(Scope) ||
134 isa<llvm::DISubprogram>(Scope)) {
135 LexicalBlockStack.pop_back();
136 LexicalBlockStack.emplace_back(
137 DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc)));
141 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context) {
145 auto I = RegionMap.find(Context);
146 if (I != RegionMap.end()) {
147 llvm::Metadata *V = I->second;
148 return dyn_cast_or_null<llvm::DIScope>(V);
152 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
153 return getOrCreateNameSpace(NSDecl);
155 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
156 if (!RDecl->isDependentType())
157 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
158 getOrCreateMainFile());
162 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
163 assert(FD && "Invalid FunctionDecl!");
164 IdentifierInfo *FII = FD->getIdentifier();
165 FunctionTemplateSpecializationInfo *Info =
166 FD->getTemplateSpecializationInfo();
168 return FII->getName();
170 // Otherwise construct human readable name for debug info.
172 llvm::raw_svector_ostream OS(NS);
175 // Add any template specialization args.
177 const TemplateArgumentList *TArgs = Info->TemplateArguments;
178 const TemplateArgument *Args = TArgs->data();
179 unsigned NumArgs = TArgs->size();
180 PrintingPolicy Policy(CGM.getLangOpts());
181 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
185 // Copy this name on the side and use its reference.
186 return internString(OS.str());
189 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
190 SmallString<256> MethodName;
191 llvm::raw_svector_ostream OS(MethodName);
192 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
193 const DeclContext *DC = OMD->getDeclContext();
194 if (const ObjCImplementationDecl *OID =
195 dyn_cast<const ObjCImplementationDecl>(DC)) {
196 OS << OID->getName();
197 } else if (const ObjCInterfaceDecl *OID =
198 dyn_cast<const ObjCInterfaceDecl>(DC)) {
199 OS << OID->getName();
200 } else if (const ObjCCategoryImplDecl *OCD =
201 dyn_cast<const ObjCCategoryImplDecl>(DC)) {
202 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
203 << OCD->getIdentifier()->getNameStart() << ')';
204 } else if (isa<ObjCProtocolDecl>(DC)) {
205 // We can extract the type of the class from the self pointer.
206 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
208 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
209 ClassTy.print(OS, PrintingPolicy(LangOptions()));
212 OS << ' ' << OMD->getSelector().getAsString() << ']';
214 return internString(OS.str());
217 StringRef CGDebugInfo::getSelectorName(Selector S) {
218 return internString(S.getAsString());
221 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
222 // quick optimization to avoid having to intern strings that are already
223 // stored reliably elsewhere
224 if (!isa<ClassTemplateSpecializationDecl>(RD))
225 return RD->getName();
227 SmallString<128> Name;
229 llvm::raw_svector_ostream OS(Name);
230 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
231 /*Qualified*/ false);
234 // Copy this name on the side and use its reference.
235 return internString(Name);
238 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
240 // If Location is not valid then use main input file.
241 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
243 SourceManager &SM = CGM.getContext().getSourceManager();
244 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
246 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
247 // If the location is not valid then use main input file.
248 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
250 // Cache the results.
251 const char *fname = PLoc.getFilename();
252 auto it = DIFileCache.find(fname);
254 if (it != DIFileCache.end()) {
255 // Verify that the information still exists.
256 if (llvm::Metadata *V = it->second)
257 return cast<llvm::DIFile>(V);
261 DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
263 DIFileCache[fname].reset(F);
267 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
268 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
271 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
272 if (Loc.isInvalid() && CurLoc.isInvalid())
274 SourceManager &SM = CGM.getContext().getSourceManager();
275 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
276 return PLoc.isValid() ? PLoc.getLine() : 0;
279 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
280 // We may not want column information at all.
281 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
284 // If the location is invalid then use the current column.
285 if (Loc.isInvalid() && CurLoc.isInvalid())
287 SourceManager &SM = CGM.getContext().getSourceManager();
288 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
289 return PLoc.isValid() ? PLoc.getColumn() : 0;
292 StringRef CGDebugInfo::getCurrentDirname() {
293 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
294 return CGM.getCodeGenOpts().DebugCompilationDir;
296 if (!CWDName.empty())
298 SmallString<256> CWD;
299 llvm::sys::fs::current_path(CWD);
300 return CWDName = internString(CWD);
303 void CGDebugInfo::CreateCompileUnit() {
305 // Should we be asking the SourceManager for the main file name, instead of
306 // accepting it as an argument? This just causes the main file name to
307 // mismatch with source locations and create extra lexical scopes or
308 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
309 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
310 // because that's what the SourceManager says)
312 // Get absolute path name.
313 SourceManager &SM = CGM.getContext().getSourceManager();
314 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
315 if (MainFileName.empty())
316 MainFileName = "<stdin>";
318 // The main file name provided via the "-main-file-name" option contains just
319 // the file name itself with no path information. This file name may have had
320 // a relative path, so we look into the actual file entry for the main
321 // file to determine the real absolute path for the file.
322 std::string MainFileDir;
323 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
324 MainFileDir = MainFile->getDir()->getName();
325 if (MainFileDir != ".") {
326 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
327 llvm::sys::path::append(MainFileDirSS, MainFileName);
328 MainFileName = MainFileDirSS.str();
332 // Save filename string.
333 StringRef Filename = internString(MainFileName);
335 // Save split dwarf file string.
336 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
337 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
339 llvm::dwarf::SourceLanguage LangTag;
340 const LangOptions &LO = CGM.getLangOpts();
343 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
345 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
346 } else if (LO.ObjC1) {
347 LangTag = llvm::dwarf::DW_LANG_ObjC;
349 LangTag = llvm::dwarf::DW_LANG_C99;
351 LangTag = llvm::dwarf::DW_LANG_C89;
354 std::string Producer = getClangFullVersion();
356 // Figure out which version of the ObjC runtime we have.
357 unsigned RuntimeVers = 0;
359 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
361 // Create new compile unit.
362 // FIXME - Eliminate TheCU.
363 TheCU = DBuilder.createCompileUnit(
364 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
365 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
366 DebugKind <= CodeGenOptions::DebugLineTablesOnly
367 ? llvm::DIBuilder::LineTablesOnly
368 : llvm::DIBuilder::FullDebug,
370 DebugKind != CodeGenOptions::LocTrackingOnly);
373 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
374 llvm::dwarf::TypeKind Encoding;
376 switch (BT->getKind()) {
377 #define BUILTIN_TYPE(Id, SingletonId)
378 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
379 #include "clang/AST/BuiltinTypes.def"
380 case BuiltinType::Dependent:
381 llvm_unreachable("Unexpected builtin type");
382 case BuiltinType::NullPtr:
383 return DBuilder.createNullPtrType();
384 case BuiltinType::Void:
386 case BuiltinType::ObjCClass:
388 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
390 getOrCreateMainFile(), 0);
392 case BuiltinType::ObjCId: {
393 // typedef struct objc_class *Class;
394 // typedef struct objc_object {
402 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
404 getOrCreateMainFile(), 0);
406 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
408 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
411 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
412 0, 0, 0, 0, nullptr, llvm::DINodeArray());
414 DBuilder.replaceArrays(
416 DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
417 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
420 case BuiltinType::ObjCSel: {
422 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
423 "objc_selector", TheCU,
424 getOrCreateMainFile(), 0);
428 case BuiltinType::OCLImage1d:
429 return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
430 case BuiltinType::OCLImage1dArray:
431 return getOrCreateStructPtrType("opencl_image1d_array_t",
432 OCLImage1dArrayDITy);
433 case BuiltinType::OCLImage1dBuffer:
434 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
435 OCLImage1dBufferDITy);
436 case BuiltinType::OCLImage2d:
437 return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
438 case BuiltinType::OCLImage2dArray:
439 return getOrCreateStructPtrType("opencl_image2d_array_t",
440 OCLImage2dArrayDITy);
441 case BuiltinType::OCLImage3d:
442 return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
443 case BuiltinType::OCLSampler:
444 return DBuilder.createBasicType(
445 "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
446 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
447 case BuiltinType::OCLEvent:
448 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
450 case BuiltinType::UChar:
451 case BuiltinType::Char_U:
452 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
454 case BuiltinType::Char_S:
455 case BuiltinType::SChar:
456 Encoding = llvm::dwarf::DW_ATE_signed_char;
458 case BuiltinType::Char16:
459 case BuiltinType::Char32:
460 Encoding = llvm::dwarf::DW_ATE_UTF;
462 case BuiltinType::UShort:
463 case BuiltinType::UInt:
464 case BuiltinType::UInt128:
465 case BuiltinType::ULong:
466 case BuiltinType::WChar_U:
467 case BuiltinType::ULongLong:
468 Encoding = llvm::dwarf::DW_ATE_unsigned;
470 case BuiltinType::Short:
471 case BuiltinType::Int:
472 case BuiltinType::Int128:
473 case BuiltinType::Long:
474 case BuiltinType::WChar_S:
475 case BuiltinType::LongLong:
476 Encoding = llvm::dwarf::DW_ATE_signed;
478 case BuiltinType::Bool:
479 Encoding = llvm::dwarf::DW_ATE_boolean;
481 case BuiltinType::Half:
482 case BuiltinType::Float:
483 case BuiltinType::LongDouble:
484 case BuiltinType::Double:
485 Encoding = llvm::dwarf::DW_ATE_float;
489 switch (BT->getKind()) {
490 case BuiltinType::Long:
493 case BuiltinType::LongLong:
494 BTName = "long long int";
496 case BuiltinType::ULong:
497 BTName = "long unsigned int";
499 case BuiltinType::ULongLong:
500 BTName = "long long unsigned int";
503 BTName = BT->getName(CGM.getLangOpts());
506 // Bit size, align and offset of the type.
507 uint64_t Size = CGM.getContext().getTypeSize(BT);
508 uint64_t Align = CGM.getContext().getTypeAlign(BT);
509 return DBuilder.createBasicType(BTName, Size, Align, Encoding);
512 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
513 // Bit size, align and offset of the type.
514 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
515 if (Ty->isComplexIntegerType())
516 Encoding = llvm::dwarf::DW_ATE_lo_user;
518 uint64_t Size = CGM.getContext().getTypeSize(Ty);
519 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
520 return DBuilder.createBasicType("complex", Size, Align, Encoding);
523 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
524 llvm::DIFile *Unit) {
525 QualifierCollector Qc;
526 const Type *T = Qc.strip(Ty);
528 // Ignore these qualifiers for now.
529 Qc.removeObjCGCAttr();
530 Qc.removeAddressSpace();
531 Qc.removeObjCLifetime();
533 // We will create one Derived type for one qualifier and recurse to handle any
535 llvm::dwarf::Tag Tag;
537 Tag = llvm::dwarf::DW_TAG_const_type;
539 } else if (Qc.hasVolatile()) {
540 Tag = llvm::dwarf::DW_TAG_volatile_type;
542 } else if (Qc.hasRestrict()) {
543 Tag = llvm::dwarf::DW_TAG_restrict_type;
546 assert(Qc.empty() && "Unknown type qualifier for debug info");
547 return getOrCreateType(QualType(T, 0), Unit);
550 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
552 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
553 // CVR derived types.
554 return DBuilder.createQualifiedType(Tag, FromTy);
557 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
558 llvm::DIFile *Unit) {
560 // The frontend treats 'id' as a typedef to an ObjCObjectType,
561 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
562 // debug info, we want to emit 'id' in both cases.
563 if (Ty->isObjCQualifiedIdType())
564 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
566 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
567 Ty->getPointeeType(), Unit);
570 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
571 llvm::DIFile *Unit) {
572 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
573 Ty->getPointeeType(), Unit);
576 /// \return whether a C++ mangling exists for the type defined by TD.
577 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
578 switch (TheCU->getSourceLanguage()) {
579 case llvm::dwarf::DW_LANG_C_plus_plus:
581 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
582 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
588 /// In C++ mode, types have linkage, so we can rely on the ODR and
589 /// on their mangled names, if they're external.
590 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
592 llvm::DICompileUnit *TheCU) {
593 SmallString<256> FullName;
594 const TagDecl *TD = Ty->getDecl();
596 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
599 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
600 if (CGM.getTarget().getCXXABI().isMicrosoft())
603 // TODO: This is using the RTTI name. Is there a better way to get
604 // a unique string for a type?
605 llvm::raw_svector_ostream Out(FullName);
606 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
611 /// \return the approproate DWARF tag for a composite type.
612 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
613 llvm::dwarf::Tag Tag;
614 if (RD->isStruct() || RD->isInterface())
615 Tag = llvm::dwarf::DW_TAG_structure_type;
616 else if (RD->isUnion())
617 Tag = llvm::dwarf::DW_TAG_union_type;
619 // FIXME: This could be a struct type giving a default visibility different
620 // than C++ class type, but needs llvm metadata changes first.
621 assert(RD->isClass());
622 Tag = llvm::dwarf::DW_TAG_class_type;
627 llvm::DICompositeType *
628 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
629 llvm::DIScope *Ctx) {
630 const RecordDecl *RD = Ty->getDecl();
631 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
632 return cast<llvm::DICompositeType>(T);
633 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
634 unsigned Line = getLineNumber(RD->getLocation());
635 StringRef RDName = getClassName(RD);
640 const RecordDecl *D = RD->getDefinition();
641 if (D && D->isCompleteDefinition()) {
642 Size = CGM.getContext().getTypeSize(Ty);
643 Align = CGM.getContext().getTypeAlign(Ty);
647 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
648 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
649 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
650 llvm::DINode::FlagFwdDecl, FullName);
651 ReplaceMap.emplace_back(
652 std::piecewise_construct, std::make_tuple(Ty),
653 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
657 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
660 llvm::DIFile *Unit) {
661 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
662 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
663 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
665 // Bit size, align and offset of the type.
666 // Size is always the size of a pointer. We can't use getTypeSize here
667 // because that does not return the correct value for references.
668 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
669 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
670 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
672 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
676 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
677 llvm::DIType *&Cache) {
680 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
681 TheCU, getOrCreateMainFile(), 0);
682 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
683 Cache = DBuilder.createPointerType(Cache, Size);
687 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
688 llvm::DIFile *Unit) {
689 SmallVector<llvm::Metadata *, 8> EltTys;
691 uint64_t FieldSize, FieldOffset;
693 llvm::DINodeArray Elements;
696 FType = CGM.getContext().UnsignedLongTy;
697 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
698 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
700 Elements = DBuilder.getOrCreateArray(EltTys);
703 unsigned Flags = llvm::DINode::FlagAppleBlock;
707 DBuilder.createStructType(Unit, "__block_descriptor", nullptr, LineNo,
708 FieldOffset, 0, Flags, nullptr, Elements);
710 // Bit size, align and offset of the type.
711 uint64_t Size = CGM.getContext().getTypeSize(Ty);
713 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
716 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
717 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
718 FType = CGM.getContext().IntTy;
719 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
720 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
721 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
722 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
724 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
725 FieldSize = CGM.getContext().getTypeSize(Ty);
726 FieldAlign = CGM.getContext().getTypeAlign(Ty);
727 EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", nullptr, LineNo,
728 FieldSize, FieldAlign, FieldOffset,
731 FieldOffset += FieldSize;
732 Elements = DBuilder.getOrCreateArray(EltTys);
734 // The __block_literal_generic structs are marked with a special
735 // DW_AT_APPLE_BLOCK attribute and are an implementation detail only
736 // the debugger needs to know about. To allow type uniquing, emit
737 // them without a name or a location.
739 DBuilder.createStructType(Unit, "", nullptr, LineNo,
740 FieldOffset, 0, Flags, nullptr, Elements);
742 return DBuilder.createPointerType(EltTy, Size);
745 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
746 llvm::DIFile *Unit) {
747 assert(Ty->isTypeAlias());
748 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
751 llvm::raw_svector_ostream OS(NS);
752 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
753 /*qualified*/ false);
755 TemplateSpecializationType::PrintTemplateArgumentList(
756 OS, Ty->getArgs(), Ty->getNumArgs(),
757 CGM.getContext().getPrintingPolicy());
759 TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
760 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
762 SourceLocation Loc = AliasDecl->getLocation();
763 return DBuilder.createTypedef(
764 Src, internString(OS.str()), getOrCreateFile(Loc), getLineNumber(Loc),
765 getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())));
768 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
769 llvm::DIFile *Unit) {
770 // We don't set size information, but do specify where the typedef was
772 SourceLocation Loc = Ty->getDecl()->getLocation();
774 // Typedefs are derived from some other type.
775 return DBuilder.createTypedef(
776 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
777 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
778 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())));
781 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
782 llvm::DIFile *Unit) {
783 SmallVector<llvm::Metadata *, 16> EltTys;
785 // Add the result type at least.
786 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
788 // Set up remainder of arguments if there is a prototype.
789 // otherwise emit it as a variadic function.
790 if (isa<FunctionNoProtoType>(Ty))
791 EltTys.push_back(DBuilder.createUnspecifiedParameter());
792 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
793 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
794 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
795 if (FPT->isVariadic())
796 EltTys.push_back(DBuilder.createUnspecifiedParameter());
799 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
800 return DBuilder.createSubroutineType(Unit, EltTypeArray);
803 /// Convert an AccessSpecifier into the corresponding DINode flag.
804 /// As an optimization, return 0 if the access specifier equals the
805 /// default for the containing type.
806 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
807 AccessSpecifier Default = clang::AS_none;
808 if (RD && RD->isClass())
809 Default = clang::AS_private;
810 else if (RD && (RD->isStruct() || RD->isUnion()))
811 Default = clang::AS_public;
813 if (Access == Default)
817 case clang::AS_private:
818 return llvm::DINode::FlagPrivate;
819 case clang::AS_protected:
820 return llvm::DINode::FlagProtected;
821 case clang::AS_public:
822 return llvm::DINode::FlagPublic;
826 llvm_unreachable("unexpected access enumerator");
829 llvm::DIType *CGDebugInfo::createFieldType(
830 StringRef name, QualType type, uint64_t sizeInBitsOverride,
831 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
832 llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
833 llvm::DIType *debugType = getOrCreateType(type, tunit);
835 // Get the location for the field.
836 llvm::DIFile *file = getOrCreateFile(loc);
837 unsigned line = getLineNumber(loc);
839 uint64_t SizeInBits = 0;
840 unsigned AlignInBits = 0;
841 if (!type->isIncompleteArrayType()) {
842 TypeInfo TI = CGM.getContext().getTypeInfo(type);
843 SizeInBits = TI.Width;
844 AlignInBits = TI.Align;
846 if (sizeInBitsOverride)
847 SizeInBits = sizeInBitsOverride;
850 unsigned flags = getAccessFlag(AS, RD);
851 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
852 AlignInBits, offsetInBits, flags, debugType);
855 void CGDebugInfo::CollectRecordLambdaFields(
856 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
857 llvm::DIType *RecordTy) {
858 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
859 // has the name and the location of the variable so we should iterate over
860 // both concurrently.
861 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
862 RecordDecl::field_iterator Field = CXXDecl->field_begin();
863 unsigned fieldno = 0;
864 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
865 E = CXXDecl->captures_end();
866 I != E; ++I, ++Field, ++fieldno) {
867 const LambdaCapture &C = *I;
868 if (C.capturesVariable()) {
869 VarDecl *V = C.getCapturedVar();
870 llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
871 StringRef VName = V->getName();
872 uint64_t SizeInBitsOverride = 0;
873 if (Field->isBitField()) {
874 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
875 assert(SizeInBitsOverride && "found named 0-width bitfield");
877 llvm::DIType *fieldType = createFieldType(
878 VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
879 Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
881 elements.push_back(fieldType);
882 } else if (C.capturesThis()) {
883 // TODO: Need to handle 'this' in some way by probably renaming the
884 // this of the lambda class and having a field member of 'this' or
885 // by using AT_object_pointer for the function and having that be
886 // used as 'this' for semantic references.
887 FieldDecl *f = *Field;
888 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
889 QualType type = f->getType();
890 llvm::DIType *fieldType = createFieldType(
891 "this", type, 0, f->getLocation(), f->getAccess(),
892 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
894 elements.push_back(fieldType);
899 llvm::DIDerivedType *
900 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
901 const RecordDecl *RD) {
902 // Create the descriptor for the static variable, with or without
903 // constant initializers.
904 Var = Var->getCanonicalDecl();
905 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
906 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
908 unsigned LineNumber = getLineNumber(Var->getLocation());
909 StringRef VName = Var->getName();
910 llvm::Constant *C = nullptr;
911 if (Var->getInit()) {
912 const APValue *Value = Var->evaluateValue();
915 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
916 if (Value->isFloat())
917 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
921 unsigned Flags = getAccessFlag(Var->getAccess(), RD);
922 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
923 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
924 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
928 void CGDebugInfo::CollectRecordNormalField(
929 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
930 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
931 const RecordDecl *RD) {
932 StringRef name = field->getName();
933 QualType type = field->getType();
935 // Ignore unnamed fields unless they're anonymous structs/unions.
936 if (name.empty() && !type->isRecordType())
939 uint64_t SizeInBitsOverride = 0;
940 if (field->isBitField()) {
941 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
942 assert(SizeInBitsOverride && "found named 0-width bitfield");
945 llvm::DIType *fieldType =
946 createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
947 field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
949 elements.push_back(fieldType);
952 void CGDebugInfo::CollectRecordFields(
953 const RecordDecl *record, llvm::DIFile *tunit,
954 SmallVectorImpl<llvm::Metadata *> &elements,
955 llvm::DICompositeType *RecordTy) {
956 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
958 if (CXXDecl && CXXDecl->isLambda())
959 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
961 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
963 // Field number for non-static fields.
964 unsigned fieldNo = 0;
966 // Static and non-static members should appear in the same order as
967 // the corresponding declarations in the source program.
968 for (const auto *I : record->decls())
969 if (const auto *V = dyn_cast<VarDecl>(I)) {
970 // Reuse the existing static member declaration if one exists
971 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
972 if (MI != StaticDataMemberCache.end()) {
974 "Static data member declaration should still exist");
975 elements.push_back(cast<llvm::DIDerivedTypeBase>(MI->second));
977 auto Field = CreateRecordStaticField(V, RecordTy, record);
978 elements.push_back(Field);
980 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
981 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
982 elements, RecordTy, record);
984 // Bump field number for next field.
990 llvm::DISubroutineType *
991 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
992 llvm::DIFile *Unit) {
993 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
994 if (Method->isStatic())
995 return cast_or_null<llvm::DISubroutineType>(
996 getOrCreateType(QualType(Func, 0), Unit));
997 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1001 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1002 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1003 // Add "this" pointer.
1004 llvm::DITypeRefArray Args(
1005 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1007 assert(Args.size() && "Invalid number of arguments!");
1009 SmallVector<llvm::Metadata *, 16> Elts;
1011 // First element is always return type. For 'void' functions it is NULL.
1012 Elts.push_back(Args[0]);
1014 // "this" pointer is always first argument.
1015 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1016 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1017 // Create pointer type directly in this case.
1018 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1019 QualType PointeeTy = ThisPtrTy->getPointeeType();
1020 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1021 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1022 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1023 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1024 llvm::DIType *ThisPtrType =
1025 DBuilder.createPointerType(PointeeType, Size, Align);
1026 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1027 // TODO: This and the artificial type below are misleading, the
1028 // types aren't artificial the argument is, but the current
1029 // metadata doesn't represent that.
1030 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1031 Elts.push_back(ThisPtrType);
1033 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1034 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1035 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1036 Elts.push_back(ThisPtrType);
1039 // Copy rest of the arguments.
1040 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1041 Elts.push_back(Args[i]);
1043 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1046 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1047 Flags |= llvm::DINode::FlagLValueReference;
1048 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1049 Flags |= llvm::DINode::FlagRValueReference;
1051 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1054 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1055 /// inside a function.
1056 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1057 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1058 return isFunctionLocalClass(NRD);
1059 if (isa<FunctionDecl>(RD->getDeclContext()))
1064 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1065 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1067 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1069 StringRef MethodName = getFunctionName(Method);
1070 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1072 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1073 // make sense to give a single ctor/dtor a linkage name.
1074 StringRef MethodLinkageName;
1075 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1076 MethodLinkageName = CGM.getMangledName(Method);
1078 // Get the location for the method.
1079 llvm::DIFile *MethodDefUnit = nullptr;
1080 unsigned MethodLine = 0;
1081 if (!Method->isImplicit()) {
1082 MethodDefUnit = getOrCreateFile(Method->getLocation());
1083 MethodLine = getLineNumber(Method->getLocation());
1086 // Collect virtual method info.
1087 llvm::DIType *ContainingType = nullptr;
1088 unsigned Virtuality = 0;
1089 unsigned VIndex = 0;
1091 if (Method->isVirtual()) {
1092 if (Method->isPure())
1093 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1095 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1097 // It doesn't make sense to give a virtual destructor a vtable index,
1098 // since a single destructor has two entries in the vtable.
1099 // FIXME: Add proper support for debug info for virtual calls in
1100 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1101 // lookup if we have multiple or virtual inheritance.
1102 if (!isa<CXXDestructorDecl>(Method) &&
1103 !CGM.getTarget().getCXXABI().isMicrosoft())
1104 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1105 ContainingType = RecordTy;
1109 if (Method->isImplicit())
1110 Flags |= llvm::DINode::FlagArtificial;
1111 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1112 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1113 if (CXXC->isExplicit())
1114 Flags |= llvm::DINode::FlagExplicit;
1115 } else if (const CXXConversionDecl *CXXC =
1116 dyn_cast<CXXConversionDecl>(Method)) {
1117 if (CXXC->isExplicit())
1118 Flags |= llvm::DINode::FlagExplicit;
1120 if (Method->hasPrototype())
1121 Flags |= llvm::DINode::FlagPrototyped;
1122 if (Method->getRefQualifier() == RQ_LValue)
1123 Flags |= llvm::DINode::FlagLValueReference;
1124 if (Method->getRefQualifier() == RQ_RValue)
1125 Flags |= llvm::DINode::FlagRValueReference;
1127 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1128 llvm::DISubprogram *SP = DBuilder.createMethod(
1129 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1130 MethodTy, /*isLocalToUnit=*/false,
1131 /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
1132 CGM.getLangOpts().Optimize, nullptr, TParamsArray.get());
1134 SPCache[Method->getCanonicalDecl()].reset(SP);
1139 void CGDebugInfo::CollectCXXMemberFunctions(
1140 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1141 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1143 // Since we want more than just the individual member decls if we
1144 // have templated functions iterate over every declaration to gather
1146 for (const auto *I : RD->decls()) {
1147 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1148 // If the member is implicit, don't add it to the member list. This avoids
1149 // the member being added to type units by LLVM, while still allowing it
1150 // to be emitted into the type declaration/reference inside the compile
1152 // Ditto 'nodebug' methods, for consistency with CodeGenFunction.cpp.
1153 // FIXME: Handle Using(Shadow?)Decls here to create
1154 // DW_TAG_imported_declarations inside the class for base decls brought into
1155 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1156 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1158 if (!Method || Method->isImplicit() || Method->hasAttr<NoDebugAttr>())
1161 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1164 // Reuse the existing member function declaration if it exists.
1165 // It may be associated with the declaration of the type & should be
1166 // reused as we're building the definition.
1168 // This situation can arise in the vtable-based debug info reduction where
1169 // implicit members are emitted in a non-vtable TU.
1170 auto MI = SPCache.find(Method->getCanonicalDecl());
1171 EltTys.push_back(MI == SPCache.end()
1172 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1173 : static_cast<llvm::Metadata *>(MI->second));
1177 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1178 SmallVectorImpl<llvm::Metadata *> &EltTys,
1179 llvm::DIType *RecordTy) {
1180 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1181 for (const auto &BI : RD->bases()) {
1182 unsigned BFlags = 0;
1183 uint64_t BaseOffset;
1185 const CXXRecordDecl *Base =
1186 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1188 if (BI.isVirtual()) {
1189 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1190 // virtual base offset offset is -ve. The code generator emits dwarf
1191 // expression where it expects +ve number.
1192 BaseOffset = 0 - CGM.getItaniumVTableContext()
1193 .getVirtualBaseOffsetOffset(RD, Base)
1196 // In the MS ABI, store the vbtable offset, which is analogous to the
1197 // vbase offset offset in Itanium.
1199 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1201 BFlags = llvm::DINode::FlagVirtual;
1203 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1204 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1205 // BI->isVirtual() and bits when not.
1207 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1208 llvm::DIType *DTy = DBuilder.createInheritance(
1209 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1210 EltTys.push_back(DTy);
1215 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1216 ArrayRef<TemplateArgument> TAList,
1217 llvm::DIFile *Unit) {
1218 SmallVector<llvm::Metadata *, 16> TemplateParams;
1219 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1220 const TemplateArgument &TA = TAList[i];
1223 Name = TPList->getParam(i)->getName();
1224 switch (TA.getKind()) {
1225 case TemplateArgument::Type: {
1226 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1227 TemplateParams.push_back(
1228 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1230 case TemplateArgument::Integral: {
1231 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1232 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1234 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1236 case TemplateArgument::Declaration: {
1237 const ValueDecl *D = TA.getAsDecl();
1238 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1239 llvm::DIType *TTy = getOrCreateType(T, Unit);
1240 llvm::Constant *V = nullptr;
1241 const CXXMethodDecl *MD;
1242 // Variable pointer template parameters have a value that is the address
1244 if (const auto *VD = dyn_cast<VarDecl>(D))
1245 V = CGM.GetAddrOfGlobalVar(VD);
1246 // Member function pointers have special support for building them, though
1247 // this is currently unsupported in LLVM CodeGen.
1248 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1249 V = CGM.getCXXABI().EmitMemberFunctionPointer(MD);
1250 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1251 V = CGM.GetAddrOfFunction(FD);
1252 // Member data pointers have special handling too to compute the fixed
1253 // offset within the object.
1254 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1255 // These five lines (& possibly the above member function pointer
1256 // handling) might be able to be refactored to use similar code in
1257 // CodeGenModule::getMemberPointerConstant
1258 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1260 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1261 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1263 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1265 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1267 case TemplateArgument::NullPtr: {
1268 QualType T = TA.getNullPtrType();
1269 llvm::DIType *TTy = getOrCreateType(T, Unit);
1270 llvm::Constant *V = nullptr;
1271 // Special case member data pointer null values since they're actually -1
1273 if (const MemberPointerType *MPT =
1274 dyn_cast<MemberPointerType>(T.getTypePtr()))
1275 // But treat member function pointers as simple zero integers because
1276 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1277 // CodeGen grows handling for values of non-null member function
1278 // pointers then perhaps we could remove this special case and rely on
1279 // EmitNullMemberPointer for member function pointers.
1280 if (MPT->isMemberDataPointer())
1281 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1283 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1284 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1285 TheCU, Name, TTy, cast<llvm::Constant>(V)));
1287 case TemplateArgument::Template:
1288 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1289 TheCU, Name, nullptr,
1290 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1292 case TemplateArgument::Pack:
1293 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1294 TheCU, Name, nullptr,
1295 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1297 case TemplateArgument::Expression: {
1298 const Expr *E = TA.getAsExpr();
1299 QualType T = E->getType();
1301 T = CGM.getContext().getLValueReferenceType(T);
1302 llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1303 assert(V && "Expression in template argument isn't constant");
1304 llvm::DIType *TTy = getOrCreateType(T, Unit);
1305 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1306 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
1308 // And the following should never occur:
1309 case TemplateArgument::TemplateExpansion:
1310 case TemplateArgument::Null:
1312 "These argument types shouldn't exist in concrete types");
1315 return DBuilder.getOrCreateArray(TemplateParams);
1319 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1320 llvm::DIFile *Unit) {
1321 if (FD->getTemplatedKind() ==
1322 FunctionDecl::TK_FunctionTemplateSpecialization) {
1323 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1325 ->getTemplateParameters();
1326 return CollectTemplateParams(
1327 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1329 return llvm::DINodeArray();
1332 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1333 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1334 // Always get the full list of parameters, not just the ones from
1335 // the specialization.
1336 TemplateParameterList *TPList =
1337 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1338 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1339 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1342 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1344 return VTablePtrType;
1346 ASTContext &Context = CGM.getContext();
1349 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1350 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1351 llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements);
1352 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1353 llvm::DIType *vtbl_ptr_type =
1354 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1355 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1356 return VTablePtrType;
1359 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1360 // Copy the gdb compatible name on the side and use its reference.
1361 return internString("_vptr$", RD->getNameAsString());
1364 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1365 SmallVectorImpl<llvm::Metadata *> &EltTys) {
1366 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1368 // If there is a primary base then it will hold vtable info.
1369 if (RL.getPrimaryBase())
1372 // If this class is not dynamic then there is not any vtable info to collect.
1373 if (!RD->isDynamicClass())
1376 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1377 llvm::DIType *VPTR = DBuilder.createMemberType(
1378 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1379 llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1380 EltTys.push_back(VPTR);
1383 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1384 SourceLocation Loc) {
1385 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1386 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1390 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1391 SourceLocation Loc) {
1392 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1393 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1394 RetainedTypes.push_back(D.getAsOpaquePtr());
1398 void CGDebugInfo::completeType(const EnumDecl *ED) {
1399 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1401 QualType Ty = CGM.getContext().getEnumType(ED);
1402 void *TyPtr = Ty.getAsOpaquePtr();
1403 auto I = TypeCache.find(TyPtr);
1404 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1406 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1407 assert(!Res->isForwardDecl());
1408 TypeCache[TyPtr].reset(Res);
1411 void CGDebugInfo::completeType(const RecordDecl *RD) {
1412 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1413 !CGM.getLangOpts().CPlusPlus)
1414 completeRequiredType(RD);
1417 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1418 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1421 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1422 if (CXXDecl->isDynamicClass())
1425 QualType Ty = CGM.getContext().getRecordType(RD);
1426 llvm::DIType *T = getTypeOrNull(Ty);
1427 if (T && T->isForwardDecl())
1428 completeClassData(RD);
1431 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1432 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1434 QualType Ty = CGM.getContext().getRecordType(RD);
1435 void *TyPtr = Ty.getAsOpaquePtr();
1436 auto I = TypeCache.find(TyPtr);
1437 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1439 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1440 assert(!Res->isForwardDecl());
1441 TypeCache[TyPtr].reset(Res);
1444 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1445 CXXRecordDecl::method_iterator End) {
1446 for (; I != End; ++I)
1447 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1448 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1449 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1454 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1455 const RecordDecl *RD,
1456 const LangOptions &LangOpts) {
1457 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1460 if (!LangOpts.CPlusPlus)
1463 if (!RD->isCompleteDefinitionRequired())
1466 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1471 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1474 TemplateSpecializationKind Spec = TSK_Undeclared;
1475 if (const ClassTemplateSpecializationDecl *SD =
1476 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1477 Spec = SD->getSpecializationKind();
1479 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1480 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1481 CXXDecl->method_end()))
1487 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1488 RecordDecl *RD = Ty->getDecl();
1489 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1490 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1492 T = getOrCreateRecordFwdDecl(
1493 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1497 return CreateTypeDefinition(Ty);
1500 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1501 RecordDecl *RD = Ty->getDecl();
1503 // Get overall information about the record type for the debug info.
1504 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1506 // Records and classes and unions can all be recursive. To handle them, we
1507 // first generate a debug descriptor for the struct as a forward declaration.
1508 // Then (if it is a definition) we go through and get debug info for all of
1509 // its members. Finally, we create a descriptor for the complete type (which
1510 // may refer to the forward decl if the struct is recursive) and replace all
1511 // uses of the forward declaration with the final definition.
1514 cast<llvm::DICompositeType>(getOrCreateLimitedType(Ty, DefUnit));
1516 const RecordDecl *D = RD->getDefinition();
1517 if (!D || !D->isCompleteDefinition())
1520 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1521 CollectContainingType(CXXDecl, FwdDecl);
1523 // Push the struct on region stack.
1524 LexicalBlockStack.emplace_back(&*FwdDecl);
1525 RegionMap[Ty->getDecl()].reset(FwdDecl);
1527 // Convert all the elements.
1528 SmallVector<llvm::Metadata *, 16> EltTys;
1529 // what about nested types?
1531 // Note: The split of CXXDecl information here is intentional, the
1532 // gdb tests will depend on a certain ordering at printout. The debug
1533 // information offsets are still correct if we merge them all together
1535 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1537 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1538 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1541 // Collect data fields (including static variables and any initializers).
1542 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1544 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1546 LexicalBlockStack.pop_back();
1547 RegionMap.erase(Ty->getDecl());
1549 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1550 DBuilder.replaceArrays(FwdDecl, Elements);
1552 if (FwdDecl->isTemporary())
1554 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1556 RegionMap[Ty->getDecl()].reset(FwdDecl);
1560 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1561 llvm::DIFile *Unit) {
1562 // Ignore protocols.
1563 return getOrCreateType(Ty->getBaseType(), Unit);
1566 /// \return true if Getter has the default name for the property PD.
1567 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1568 const ObjCMethodDecl *Getter) {
1573 assert(Getter->getDeclName().isObjCZeroArgSelector());
1574 return PD->getName() ==
1575 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1578 /// \return true if Setter has the default name for the property PD.
1579 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1580 const ObjCMethodDecl *Setter) {
1585 assert(Setter->getDeclName().isObjCOneArgSelector());
1586 return SelectorTable::constructSetterName(PD->getName()) ==
1587 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1590 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1591 llvm::DIFile *Unit) {
1592 ObjCInterfaceDecl *ID = Ty->getDecl();
1596 // Get overall information about the record type for the debug info.
1597 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1598 unsigned Line = getLineNumber(ID->getLocation());
1600 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1602 // If this is just a forward declaration return a special forward-declaration
1603 // debug type since we won't be able to lay out the entire type.
1604 ObjCInterfaceDecl *Def = ID->getDefinition();
1605 if (!Def || !Def->getImplementation()) {
1606 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1607 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1609 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1613 return CreateTypeDefinition(Ty, Unit);
1617 CGDebugInfo::getOrCreateModuleRef(ExternalASTSource::ASTSourceDescriptor Mod) {
1618 auto it = ModuleRefCache.find(Mod.Signature);
1619 if (it != ModuleRefCache.end())
1622 // Macro definitions that were defined with "-D" on the command line.
1623 SmallString<128> ConfigMacros;
1625 llvm::raw_svector_ostream OS(ConfigMacros);
1626 const auto &PPOpts = CGM.getPreprocessorOpts();
1628 // Translate the macro definitions back into a commmand line.
1629 for (auto &M : PPOpts.Macros) {
1632 const std::string &Macro = M.first;
1633 bool Undef = M.second;
1634 OS << "\"-" << (Undef ? 'U' : 'D');
1635 for (char c : Macro)
1637 case '\\' : OS << "\\\\"; break;
1638 case '"' : OS << "\\\""; break;
1644 llvm::DIBuilder DIB(CGM.getModule());
1645 auto *CU = DIB.createCompileUnit(
1646 TheCU->getSourceLanguage(), internString(Mod.ModuleName),
1647 internString(Mod.Path), TheCU->getProducer(), true, StringRef(), 0,
1648 internString(Mod.ASTFile), llvm::DIBuilder::FullDebug, Mod.Signature);
1649 llvm::DIModule *ModuleRef =
1650 DIB.createModule(CU, Mod.ModuleName, ConfigMacros, internString(Mod.Path),
1651 internString(CGM.getHeaderSearchOpts().Sysroot));
1653 ModuleRefCache.insert(std::make_pair(Mod.Signature, ModuleRef));
1657 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1658 llvm::DIFile *Unit) {
1659 ObjCInterfaceDecl *ID = Ty->getDecl();
1660 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1661 unsigned Line = getLineNumber(ID->getLocation());
1662 unsigned RuntimeLang = TheCU->getSourceLanguage();
1664 // Bit size, align and offset of the type.
1665 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1666 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1669 if (ID->getImplementation())
1670 Flags |= llvm::DINode::FlagObjcClassComplete;
1672 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
1673 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr,
1674 llvm::DINodeArray(), RuntimeLang);
1676 QualType QTy(Ty, 0);
1677 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1679 // Push the struct on region stack.
1680 LexicalBlockStack.emplace_back(RealDecl);
1681 RegionMap[Ty->getDecl()].reset(RealDecl);
1683 // Convert all the elements.
1684 SmallVector<llvm::Metadata *, 16> EltTys;
1686 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1688 llvm::DIType *SClassTy =
1689 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1693 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1694 EltTys.push_back(InhTag);
1697 // Create entries for all of the properties.
1698 for (const auto *PD : ID->properties()) {
1699 SourceLocation Loc = PD->getLocation();
1700 llvm::DIFile *PUnit = getOrCreateFile(Loc);
1701 unsigned PLine = getLineNumber(Loc);
1702 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1703 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1704 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1705 PD->getName(), PUnit, PLine,
1706 hasDefaultGetterName(PD, Getter) ? ""
1707 : getSelectorName(PD->getGetterName()),
1708 hasDefaultSetterName(PD, Setter) ? ""
1709 : getSelectorName(PD->getSetterName()),
1710 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1711 EltTys.push_back(PropertyNode);
1714 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1715 unsigned FieldNo = 0;
1716 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1717 Field = Field->getNextIvar(), ++FieldNo) {
1718 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
1722 StringRef FieldName = Field->getName();
1724 // Ignore unnamed fields.
1725 if (FieldName.empty())
1728 // Get the location for the field.
1729 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
1730 unsigned FieldLine = getLineNumber(Field->getLocation());
1731 QualType FType = Field->getType();
1732 uint64_t FieldSize = 0;
1733 unsigned FieldAlign = 0;
1735 if (!FType->isIncompleteArrayType()) {
1737 // Bit size, align and offset of the type.
1738 FieldSize = Field->isBitField()
1739 ? Field->getBitWidthValue(CGM.getContext())
1740 : CGM.getContext().getTypeSize(FType);
1741 FieldAlign = CGM.getContext().getTypeAlign(FType);
1744 uint64_t FieldOffset;
1745 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1746 // We don't know the runtime offset of an ivar if we're using the
1747 // non-fragile ABI. For bitfields, use the bit offset into the first
1748 // byte of storage of the bitfield. For other fields, use zero.
1749 if (Field->isBitField()) {
1751 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1752 FieldOffset %= CGM.getContext().getCharWidth();
1757 FieldOffset = RL.getFieldOffset(FieldNo);
1761 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1762 Flags = llvm::DINode::FlagProtected;
1763 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1764 Flags = llvm::DINode::FlagPrivate;
1765 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
1766 Flags = llvm::DINode::FlagPublic;
1768 llvm::MDNode *PropertyNode = nullptr;
1769 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1770 if (ObjCPropertyImplDecl *PImpD =
1771 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1772 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1773 SourceLocation Loc = PD->getLocation();
1774 llvm::DIFile *PUnit = getOrCreateFile(Loc);
1775 unsigned PLine = getLineNumber(Loc);
1776 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1777 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1778 PropertyNode = DBuilder.createObjCProperty(
1779 PD->getName(), PUnit, PLine,
1780 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
1781 PD->getGetterName()),
1782 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
1783 PD->getSetterName()),
1784 PD->getPropertyAttributes(),
1785 getOrCreateType(PD->getType(), PUnit));
1789 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
1790 FieldSize, FieldAlign, FieldOffset, Flags,
1791 FieldTy, PropertyNode);
1792 EltTys.push_back(FieldTy);
1795 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1796 DBuilder.replaceArrays(RealDecl, Elements);
1798 LexicalBlockStack.pop_back();
1802 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
1803 llvm::DIFile *Unit) {
1804 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1805 int64_t Count = Ty->getNumElements();
1807 // If number of elements are not known then this is an unbounded array.
1808 // Use Count == -1 to express such arrays.
1811 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1812 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1814 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1815 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1817 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1820 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
1824 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1825 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1828 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1829 } else if (Ty->isIncompleteArrayType()) {
1831 if (Ty->getElementType()->isIncompleteType())
1834 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1835 } else if (Ty->isIncompleteType()) {
1839 // Size and align of the whole array, not the element type.
1840 Size = CGM.getContext().getTypeSize(Ty);
1841 Align = CGM.getContext().getTypeAlign(Ty);
1844 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1845 // interior arrays, do we care? Why aren't nested arrays represented the
1846 // obvious/recursive way?
1847 SmallVector<llvm::Metadata *, 8> Subscripts;
1848 QualType EltTy(Ty, 0);
1849 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1850 // If the number of elements is known, then count is that number. Otherwise,
1851 // it's -1. This allows us to represent a subrange with an array of 0
1852 // elements, like this:
1857 int64_t Count = -1; // Count == -1 is an unbounded array.
1858 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1859 Count = CAT->getSize().getZExtValue();
1861 // FIXME: Verify this is right for VLAs.
1862 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1863 EltTy = Ty->getElementType();
1866 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1868 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1872 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1873 llvm::DIFile *Unit) {
1874 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
1875 Ty->getPointeeType(), Unit);
1878 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1879 llvm::DIFile *Unit) {
1880 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
1881 Ty->getPointeeType(), Unit);
1884 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
1886 uint64_t Size = CGM.getCXXABI().isTypeInfoCalculable(QualType(Ty, 0))
1887 ? CGM.getContext().getTypeSize(Ty)
1889 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1890 if (Ty->isMemberDataPointerType())
1891 return DBuilder.createMemberPointerType(
1892 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
1894 const FunctionProtoType *FPT =
1895 Ty->getPointeeType()->getAs<FunctionProtoType>();
1896 return DBuilder.createMemberPointerType(
1897 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
1898 Ty->getClass(), FPT->getTypeQuals())),
1903 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
1904 // Ignore the atomic wrapping
1905 // FIXME: What is the correct representation?
1906 return getOrCreateType(Ty->getValueType(), U);
1909 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1910 const EnumDecl *ED = Ty->getDecl();
1913 if (!ED->getTypeForDecl()->isIncompleteType()) {
1914 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1915 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1918 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1920 // If this is just a forward declaration, construct an appropriately
1921 // marked node and just return it.
1922 if (!ED->getDefinition()) {
1923 llvm::DIScope *EDContext =
1924 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1925 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1926 unsigned Line = getLineNumber(ED->getLocation());
1927 StringRef EDName = ED->getName();
1928 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
1929 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1930 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
1931 ReplaceMap.emplace_back(
1932 std::piecewise_construct, std::make_tuple(Ty),
1933 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1937 return CreateTypeDefinition(Ty);
1940 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1941 const EnumDecl *ED = Ty->getDecl();
1944 if (!ED->getTypeForDecl()->isIncompleteType()) {
1945 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1946 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1949 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1951 // Create elements for each enumerator.
1952 SmallVector<llvm::Metadata *, 16> Enumerators;
1953 ED = ED->getDefinition();
1954 for (const auto *Enum : ED->enumerators()) {
1955 Enumerators.push_back(DBuilder.createEnumerator(
1956 Enum->getName(), Enum->getInitVal().getSExtValue()));
1959 // Return a CompositeType for the enum itself.
1960 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1962 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1963 unsigned Line = getLineNumber(ED->getLocation());
1964 llvm::DIScope *EnumContext =
1965 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1966 llvm::DIType *ClassTy =
1967 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
1968 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
1969 Line, Size, Align, EltArray, ClassTy,
1973 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1976 Qualifiers InnerQuals = T.getLocalQualifiers();
1977 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1978 // that is already there.
1979 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1980 Quals += InnerQuals;
1982 switch (T->getTypeClass()) {
1984 return C.getQualifiedType(T.getTypePtr(), Quals);
1985 case Type::TemplateSpecialization: {
1986 const auto *Spec = cast<TemplateSpecializationType>(T);
1987 if (Spec->isTypeAlias())
1988 return C.getQualifiedType(T.getTypePtr(), Quals);
1989 T = Spec->desugar();
1992 case Type::TypeOfExpr:
1993 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1996 T = cast<TypeOfType>(T)->getUnderlyingType();
1998 case Type::Decltype:
1999 T = cast<DecltypeType>(T)->getUnderlyingType();
2001 case Type::UnaryTransform:
2002 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2004 case Type::Attributed:
2005 T = cast<AttributedType>(T)->getEquivalentType();
2007 case Type::Elaborated:
2008 T = cast<ElaboratedType>(T)->getNamedType();
2011 T = cast<ParenType>(T)->getInnerType();
2013 case Type::SubstTemplateTypeParm:
2014 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2017 QualType DT = cast<AutoType>(T)->getDeducedType();
2018 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2023 assert(T != LastT && "Type unwrapping failed to unwrap!");
2028 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2030 // Unwrap the type as needed for debug information.
2031 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2033 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2034 if (it != TypeCache.end()) {
2035 // Verify that the debug info still exists.
2036 if (llvm::Metadata *V = it->second)
2037 return cast<llvm::DIType>(V);
2043 void CGDebugInfo::completeTemplateDefinition(
2044 const ClassTemplateSpecializationDecl &SD) {
2045 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2048 completeClassData(&SD);
2049 // In case this type has no member function definitions being emitted, ensure
2051 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2054 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2058 // Unwrap the type as needed for debug information.
2059 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2061 if (auto *T = getTypeOrNull(Ty))
2064 // Otherwise create the type.
2065 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2066 void *TyPtr = Ty.getAsOpaquePtr();
2068 // And update the type cache.
2069 TypeCache[TyPtr].reset(Res);
2074 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2075 // The assumption is that the number of ivars can only increase
2076 // monotonically, so it is safe to just use their current number as
2079 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2080 Ivar != nullptr; Ivar = Ivar->getNextIvar())
2086 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2087 switch (Ty->getTypeClass()) {
2088 case Type::ObjCObjectPointer:
2089 return getObjCInterfaceDecl(
2090 cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2091 case Type::ObjCInterface:
2092 return cast<ObjCInterfaceType>(Ty)->getDecl();
2098 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2099 // Handle qualifiers, which recursively handles what they refer to.
2100 if (Ty.hasLocalQualifiers())
2101 return CreateQualifiedType(Ty, Unit);
2103 // Work out details of type.
2104 switch (Ty->getTypeClass()) {
2105 #define TYPE(Class, Base)
2106 #define ABSTRACT_TYPE(Class, Base)
2107 #define NON_CANONICAL_TYPE(Class, Base)
2108 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2109 #include "clang/AST/TypeNodes.def"
2110 llvm_unreachable("Dependent types cannot show up in debug information");
2112 case Type::ExtVector:
2114 return CreateType(cast<VectorType>(Ty), Unit);
2115 case Type::ObjCObjectPointer:
2116 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2117 case Type::ObjCObject:
2118 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2119 case Type::ObjCInterface:
2120 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2122 return CreateType(cast<BuiltinType>(Ty));
2124 return CreateType(cast<ComplexType>(Ty));
2126 return CreateType(cast<PointerType>(Ty), Unit);
2127 case Type::Adjusted:
2129 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2131 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2132 case Type::BlockPointer:
2133 return CreateType(cast<BlockPointerType>(Ty), Unit);
2135 return CreateType(cast<TypedefType>(Ty), Unit);
2137 return CreateType(cast<RecordType>(Ty));
2139 return CreateEnumType(cast<EnumType>(Ty));
2140 case Type::FunctionProto:
2141 case Type::FunctionNoProto:
2142 return CreateType(cast<FunctionType>(Ty), Unit);
2143 case Type::ConstantArray:
2144 case Type::VariableArray:
2145 case Type::IncompleteArray:
2146 return CreateType(cast<ArrayType>(Ty), Unit);
2148 case Type::LValueReference:
2149 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2150 case Type::RValueReference:
2151 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2153 case Type::MemberPointer:
2154 return CreateType(cast<MemberPointerType>(Ty), Unit);
2157 return CreateType(cast<AtomicType>(Ty), Unit);
2159 case Type::TemplateSpecialization:
2160 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2163 case Type::Attributed:
2164 case Type::Elaborated:
2166 case Type::SubstTemplateTypeParm:
2167 case Type::TypeOfExpr:
2169 case Type::Decltype:
2170 case Type::UnaryTransform:
2171 case Type::PackExpansion:
2175 llvm_unreachable("type should have been unwrapped!");
2178 llvm::DIType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2179 llvm::DIFile *Unit) {
2180 QualType QTy(Ty, 0);
2182 auto *T = cast_or_null<llvm::DICompositeTypeBase>(getTypeOrNull(QTy));
2184 // We may have cached a forward decl when we could have created
2185 // a non-forward decl. Go ahead and create a non-forward decl
2187 if (T && !T->isForwardDecl())
2190 // Otherwise create the type.
2191 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2193 // Propagate members from the declaration to the definition
2194 // CreateType(const RecordType*) will overwrite this with the members in the
2195 // correct order if the full type is needed.
2196 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2198 // And update the type cache.
2199 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2203 // TODO: Currently used for context chains when limiting debug info.
2204 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2205 RecordDecl *RD = Ty->getDecl();
2207 // Get overall information about the record type for the debug info.
2208 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2209 unsigned Line = getLineNumber(RD->getLocation());
2210 StringRef RDName = getClassName(RD);
2212 llvm::DIScope *RDContext =
2213 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2215 // If we ended up creating the type during the context chain construction,
2216 // just return that.
2217 auto *T = cast_or_null<llvm::DICompositeType>(
2218 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2219 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2222 // If this is just a forward or incomplete declaration, construct an
2223 // appropriately marked node and just return it.
2224 const RecordDecl *D = RD->getDefinition();
2225 if (!D || !D->isCompleteDefinition())
2226 return getOrCreateRecordFwdDecl(Ty, RDContext);
2228 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2229 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2231 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2233 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2234 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2237 RegionMap[Ty->getDecl()].reset(RealDecl);
2238 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2240 if (const ClassTemplateSpecializationDecl *TSpecial =
2241 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2242 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2243 CollectCXXTemplateParams(TSpecial, DefUnit));
2247 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2248 llvm::DICompositeType *RealDecl) {
2249 // A class's primary base or the class itself contains the vtable.
2250 llvm::DICompositeType *ContainingType = nullptr;
2251 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2252 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2253 // Seek non-virtual primary base root.
2255 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2256 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2257 if (PBT && !BRL.isPrimaryBaseVirtual())
2262 ContainingType = cast<llvm::DICompositeType>(
2263 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2264 getOrCreateFile(RD->getLocation())));
2265 } else if (RD->isDynamicClass())
2266 ContainingType = RealDecl;
2268 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2271 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2272 StringRef Name, uint64_t *Offset) {
2273 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2274 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2275 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2276 llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2277 FieldAlign, *Offset, 0, FieldTy);
2278 *Offset += FieldSize;
2282 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2284 StringRef &LinkageName,
2285 llvm::DIScope *&FDContext,
2286 llvm::DINodeArray &TParamsArray,
2288 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2289 Name = getFunctionName(FD);
2290 // Use mangled name as linkage name for C/C++ functions.
2291 if (FD->hasPrototype()) {
2292 LinkageName = CGM.getMangledName(GD);
2293 Flags |= llvm::DINode::FlagPrototyped;
2295 // No need to replicate the linkage name if it isn't different from the
2296 // subprogram name, no need to have it at all unless coverage is enabled or
2297 // debug is set to more than just line tables.
2298 if (LinkageName == Name ||
2299 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2300 !CGM.getCodeGenOpts().EmitGcovNotes &&
2301 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2302 LinkageName = StringRef();
2304 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2305 if (const NamespaceDecl *NSDecl =
2306 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2307 FDContext = getOrCreateNameSpace(NSDecl);
2308 else if (const RecordDecl *RDecl =
2309 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2310 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2311 // Collect template parameters.
2312 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2316 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2317 unsigned &LineNo, QualType &T,
2318 StringRef &Name, StringRef &LinkageName,
2319 llvm::DIScope *&VDContext) {
2320 Unit = getOrCreateFile(VD->getLocation());
2321 LineNo = getLineNumber(VD->getLocation());
2323 setLocation(VD->getLocation());
2326 if (T->isIncompleteArrayType()) {
2327 // CodeGen turns int[] into int[1] so we'll do the same here.
2328 llvm::APInt ConstVal(32, 1);
2329 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2331 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2332 ArrayType::Normal, 0);
2335 Name = VD->getName();
2336 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2337 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2338 LinkageName = CGM.getMangledName(VD);
2339 if (LinkageName == Name)
2340 LinkageName = StringRef();
2342 // Since we emit declarations (DW_AT_members) for static members, place the
2343 // definition of those static members in the namespace they were declared in
2344 // in the source code (the lexical decl context).
2345 // FIXME: Generalize this for even non-member global variables where the
2346 // declaration and definition may have different lexical decl contexts, once
2347 // we have support for emitting declarations of (non-member) global variables.
2348 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2349 : VD->getDeclContext();
2350 // When a record type contains an in-line initialization of a static data
2351 // member, and the record type is marked as __declspec(dllexport), an implicit
2352 // definition of the member will be created in the record context. DWARF
2353 // doesn't seem to have a nice way to describe this in a form that consumers
2354 // are likely to understand, so fake the "normal" situation of a definition
2355 // outside the class by putting it in the global scope.
2357 DC = CGM.getContext().getTranslationUnitDecl();
2358 VDContext = getContextDescriptor(dyn_cast<Decl>(DC));
2361 llvm::DISubprogram *
2362 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2363 llvm::DINodeArray TParamsArray;
2364 StringRef Name, LinkageName;
2366 SourceLocation Loc = FD->getLocation();
2367 llvm::DIFile *Unit = getOrCreateFile(Loc);
2368 llvm::DIScope *DContext = Unit;
2369 unsigned Line = getLineNumber(Loc);
2371 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2372 TParamsArray, Flags);
2373 // Build function type.
2374 SmallVector<QualType, 16> ArgTypes;
2375 for (const ParmVarDecl *Parm: FD->parameters())
2376 ArgTypes.push_back(Parm->getType());
2378 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
2379 FunctionProtoType::ExtProtoInfo());
2380 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2381 DContext, Name, LinkageName, Unit, Line,
2382 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2383 false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr,
2384 TParamsArray.get(), getFunctionDeclaration(FD));
2385 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2386 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2387 std::make_tuple(CanonDecl),
2388 std::make_tuple(SP));
2392 llvm::DIGlobalVariable *
2393 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2395 StringRef Name, LinkageName;
2396 SourceLocation Loc = VD->getLocation();
2397 llvm::DIFile *Unit = getOrCreateFile(Loc);
2398 llvm::DIScope *DContext = Unit;
2399 unsigned Line = getLineNumber(Loc);
2401 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2402 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2403 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2404 !VD->isExternallyVisible(), nullptr, nullptr);
2405 FwdDeclReplaceMap.emplace_back(
2406 std::piecewise_construct,
2407 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2408 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2412 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2413 // We only need a declaration (not a definition) of the type - so use whatever
2414 // we would otherwise do to get a type for a pointee. (forward declarations in
2415 // limited debug info, full definitions (if the type definition is available)
2416 // in unlimited debug info)
2417 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2418 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2419 getOrCreateFile(TD->getLocation()));
2420 auto I = DeclCache.find(D->getCanonicalDecl());
2422 if (I != DeclCache.end())
2423 return dyn_cast_or_null<llvm::DINode>(I->second);
2425 // No definition for now. Emit a forward definition that might be
2426 // merged with a potential upcoming definition.
2427 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2428 return getFunctionForwardDeclaration(FD);
2429 else if (const auto *VD = dyn_cast<VarDecl>(D))
2430 return getGlobalVariableForwardDeclaration(VD);
2435 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2436 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2439 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2444 auto *S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2446 auto MI = SPCache.find(FD->getCanonicalDecl());
2447 if (MI == SPCache.end()) {
2448 if (const CXXMethodDecl *MD =
2449 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2450 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2451 cast<llvm::DICompositeType>(S));
2454 if (MI != SPCache.end()) {
2455 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2456 if (SP && !SP->isDefinition())
2460 for (auto NextFD : FD->redecls()) {
2461 auto MI = SPCache.find(NextFD->getCanonicalDecl());
2462 if (MI != SPCache.end()) {
2463 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2464 if (SP && !SP->isDefinition())
2471 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2472 // implicit parameter "this".
2473 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2476 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2477 // Create fake but valid subroutine type. Otherwise -verify would fail, and
2478 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2479 return DBuilder.createSubroutineType(F,
2480 DBuilder.getOrCreateTypeArray(None));
2482 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2483 return getOrCreateMethodType(Method, F);
2484 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2485 // Add "self" and "_cmd"
2486 SmallVector<llvm::Metadata *, 16> Elts;
2488 // First element is always return type. For 'void' functions it is NULL.
2489 QualType ResultTy = OMethod->getReturnType();
2491 // Replace the instancetype keyword with the actual type.
2492 if (ResultTy == CGM.getContext().getObjCInstanceType())
2493 ResultTy = CGM.getContext().getPointerType(
2494 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2496 Elts.push_back(getOrCreateType(ResultTy, F));
2497 // "self" pointer is always first argument.
2498 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2499 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2500 // "_cmd" pointer is always second argument.
2501 Elts.push_back(DBuilder.createArtificialType(
2502 getOrCreateType(OMethod->getCmdDecl()->getType(), F)));
2503 // Get rest of the arguments.
2504 for (const auto *PI : OMethod->params())
2505 Elts.push_back(getOrCreateType(PI->getType(), F));
2506 // Variadic methods need a special marker at the end of the type list.
2507 if (OMethod->isVariadic())
2508 Elts.push_back(DBuilder.createUnspecifiedParameter());
2510 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2511 return DBuilder.createSubroutineType(F, EltTypeArray);
2514 // Handle variadic function types; they need an additional
2515 // unspecified parameter.
2516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2517 if (FD->isVariadic()) {
2518 SmallVector<llvm::Metadata *, 16> EltTys;
2519 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2520 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2521 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2522 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2523 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2524 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2525 return DBuilder.createSubroutineType(F, EltTypeArray);
2528 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
2531 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
2532 SourceLocation ScopeLoc, QualType FnType,
2533 llvm::Function *Fn, CGBuilderTy &Builder) {
2536 StringRef LinkageName;
2538 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2540 const Decl *D = GD.getDecl();
2541 bool HasDecl = (D != nullptr);
2544 llvm::DIFile *Unit = getOrCreateFile(Loc);
2545 llvm::DIScope *FDContext = Unit;
2546 llvm::DINodeArray TParamsArray;
2548 // Use llvm function name.
2549 LinkageName = Fn->getName();
2550 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2551 // If there is a subprogram for this function available then use it.
2552 auto FI = SPCache.find(FD->getCanonicalDecl());
2553 if (FI != SPCache.end()) {
2554 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
2555 if (SP && SP->isDefinition()) {
2556 LexicalBlockStack.emplace_back(SP);
2557 RegionMap[D].reset(SP);
2561 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2562 TParamsArray, Flags);
2563 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2564 Name = getObjCMethodName(OMD);
2565 Flags |= llvm::DINode::FlagPrototyped;
2567 // Use llvm function name.
2568 Name = Fn->getName();
2569 Flags |= llvm::DINode::FlagPrototyped;
2571 if (!Name.empty() && Name[0] == '\01')
2572 Name = Name.substr(1);
2574 if (!HasDecl || D->isImplicit()) {
2575 Flags |= llvm::DINode::FlagArtificial;
2576 // Artificial functions without a location should not silently reuse CurLoc.
2577 if (Loc.isInvalid())
2578 CurLoc = SourceLocation();
2580 unsigned LineNo = getLineNumber(Loc);
2581 unsigned ScopeLine = getLineNumber(ScopeLoc);
2583 // FIXME: The function declaration we're constructing here is mostly reusing
2584 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2585 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2586 // all subprograms instead of the actual context since subprogram definitions
2587 // are emitted as CU level entities by the backend.
2588 llvm::DISubprogram *SP = DBuilder.createFunction(
2589 FDContext, Name, LinkageName, Unit, LineNo,
2590 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2591 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn,
2592 TParamsArray.get(), getFunctionDeclaration(D));
2593 // We might get here with a VarDecl in the case we're generating
2594 // code for the initialization of globals. Do not record these decls
2595 // as they will overwrite the actual VarDecl Decl in the cache.
2596 if (HasDecl && isa<FunctionDecl>(D))
2597 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
2599 // Push the function onto the lexical block stack.
2600 LexicalBlockStack.emplace_back(SP);
2603 RegionMap[D].reset(SP);
2606 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2607 // Update our current location
2610 if (CurLoc.isInvalid() || CurLoc.isMacroID())
2613 llvm::MDNode *Scope = LexicalBlockStack.back();
2614 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2615 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2618 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2619 llvm::MDNode *Back = nullptr;
2620 if (!LexicalBlockStack.empty())
2621 Back = LexicalBlockStack.back().get();
2622 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
2623 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2624 getColumnNumber(CurLoc)));
2627 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2628 SourceLocation Loc) {
2629 // Set our current location.
2632 // Emit a line table change for the current location inside the new scope.
2633 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2634 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
2636 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2639 // Create a new lexical block and push it on the stack.
2640 CreateLexicalBlock(Loc);
2643 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2644 SourceLocation Loc) {
2645 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2647 // Provide an entry in the line table for the end of the block.
2648 EmitLocation(Builder, Loc);
2650 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2653 LexicalBlockStack.pop_back();
2656 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2657 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2658 unsigned RCount = FnBeginRegionCount.back();
2659 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2661 // Pop all regions for this function.
2662 while (LexicalBlockStack.size() != RCount) {
2663 // Provide an entry in the line table for the end of the block.
2664 EmitLocation(Builder, CurLoc);
2665 LexicalBlockStack.pop_back();
2667 FnBeginRegionCount.pop_back();
2670 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2671 uint64_t *XOffset) {
2673 SmallVector<llvm::Metadata *, 5> EltTys;
2675 uint64_t FieldSize, FieldOffset;
2676 unsigned FieldAlign;
2678 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2679 QualType Type = VD->getType();
2682 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2683 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2684 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2685 FType = CGM.getContext().IntTy;
2686 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2687 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2689 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2690 if (HasCopyAndDispose) {
2691 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2693 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
2695 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
2697 bool HasByrefExtendedLayout;
2698 Qualifiers::ObjCLifetime Lifetime;
2699 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
2700 HasByrefExtendedLayout) &&
2701 HasByrefExtendedLayout) {
2702 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2704 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
2707 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2708 if (Align > CGM.getContext().toCharUnitsFromBits(
2709 CGM.getTarget().getPointerAlign(0))) {
2710 CharUnits FieldOffsetInBytes =
2711 CGM.getContext().toCharUnitsFromBits(FieldOffset);
2712 CharUnits AlignedOffsetInBytes =
2713 FieldOffsetInBytes.RoundUpToAlignment(Align);
2714 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
2716 if (NumPaddingBytes.isPositive()) {
2717 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2718 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2719 pad, ArrayType::Normal, 0);
2720 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2725 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
2726 FieldSize = CGM.getContext().getTypeSize(FType);
2727 FieldAlign = CGM.getContext().toBits(Align);
2729 *XOffset = FieldOffset;
2730 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
2731 FieldAlign, FieldOffset, 0, FieldTy);
2732 EltTys.push_back(FieldTy);
2733 FieldOffset += FieldSize;
2735 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2737 unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
2739 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2743 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag,
2744 llvm::Value *Storage, unsigned ArgNo,
2745 CGBuilderTy &Builder) {
2746 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2747 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2750 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2751 cast<Decl>(VD->getDeclContext())->isImplicit());
2752 llvm::DIFile *Unit = nullptr;
2754 Unit = getOrCreateFile(VD->getLocation());
2756 uint64_t XOffset = 0;
2757 if (VD->hasAttr<BlocksAttr>())
2758 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2760 Ty = getOrCreateType(VD->getType(), Unit);
2762 // If there is no debug info for this type then do not emit debug info
2763 // for this variable.
2767 // Get location information.
2769 unsigned Column = 0;
2771 Line = getLineNumber(VD->getLocation());
2772 Column = getColumnNumber(VD->getLocation());
2774 SmallVector<int64_t, 9> Expr;
2776 if (VD->isImplicit())
2777 Flags |= llvm::DINode::FlagArtificial;
2778 // If this is the first argument and it is implicit then
2779 // give it an object pointer flag.
2780 // FIXME: There has to be a better way to do this, but for static
2781 // functions there won't be an implicit param at arg1 and
2782 // otherwise it is 'self' or 'this'.
2783 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2784 Flags |= llvm::DINode::FlagObjectPointer;
2785 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2786 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2787 !VD->getType()->isPointerType())
2788 Expr.push_back(llvm::dwarf::DW_OP_deref);
2790 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
2792 StringRef Name = VD->getName();
2793 if (!Name.empty()) {
2794 if (VD->hasAttr<BlocksAttr>()) {
2795 CharUnits offset = CharUnits::fromQuantity(32);
2796 Expr.push_back(llvm::dwarf::DW_OP_plus);
2797 // offset of __forwarding field
2798 offset = CGM.getContext().toCharUnitsFromBits(
2799 CGM.getTarget().getPointerWidth(0));
2800 Expr.push_back(offset.getQuantity());
2801 Expr.push_back(llvm::dwarf::DW_OP_deref);
2802 Expr.push_back(llvm::dwarf::DW_OP_plus);
2803 // offset of x field
2804 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2805 Expr.push_back(offset.getQuantity());
2807 // Create the descriptor for the variable.
2808 auto *D = DBuilder.createLocalVariable(Tag, Scope, VD->getName(), Unit,
2811 // Insert an llvm.dbg.declare into the current block.
2812 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2813 llvm::DebugLoc::get(Line, Column, Scope),
2814 Builder.GetInsertBlock());
2816 } else if (isa<VariableArrayType>(VD->getType()))
2817 Expr.push_back(llvm::dwarf::DW_OP_deref);
2818 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2819 // If VD is an anonymous union then Storage represents value for
2820 // all union fields.
2821 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2822 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2823 // GDB has trouble finding local variables in anonymous unions, so we emit
2824 // artifical local variables for each of the members.
2826 // FIXME: Remove this code as soon as GDB supports this.
2827 // The debug info verifier in LLVM operates based on the assumption that a
2828 // variable has the same size as its storage and we had to disable the check
2829 // for artificial variables.
2830 for (const auto *Field : RD->fields()) {
2831 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2832 StringRef FieldName = Field->getName();
2834 // Ignore unnamed fields. Do not ignore unnamed records.
2835 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2838 // Use VarDecl's Tag, Scope and Line number.
2839 auto *D = DBuilder.createLocalVariable(
2840 Tag, Scope, FieldName, Unit, Line, FieldTy,
2841 CGM.getLangOpts().Optimize, Flags | llvm::DINode::FlagArtificial,
2844 // Insert an llvm.dbg.declare into the current block.
2845 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2846 llvm::DebugLoc::get(Line, Column, Scope),
2847 Builder.GetInsertBlock());
2852 // Create the descriptor for the variable.
2854 DBuilder.createLocalVariable(Tag, Scope, Name, Unit, Line, Ty,
2855 CGM.getLangOpts().Optimize, Flags, ArgNo);
2857 // Insert an llvm.dbg.declare into the current block.
2858 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2859 llvm::DebugLoc::get(Line, Column, Scope),
2860 Builder.GetInsertBlock());
2863 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2864 llvm::Value *Storage,
2865 CGBuilderTy &Builder) {
2866 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2867 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2870 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
2872 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
2875 return DBuilder.createObjectPointerType(Ty);
2878 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2879 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2880 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
2881 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2882 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2884 if (Builder.GetInsertBlock() == nullptr)
2887 bool isByRef = VD->hasAttr<BlocksAttr>();
2889 uint64_t XOffset = 0;
2890 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2893 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2895 Ty = getOrCreateType(VD->getType(), Unit);
2897 // Self is passed along as an implicit non-arg variable in a
2898 // block. Mark it as the object pointer.
2899 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2900 Ty = CreateSelfType(VD->getType(), Ty);
2902 // Get location information.
2903 unsigned Line = getLineNumber(VD->getLocation());
2904 unsigned Column = getColumnNumber(VD->getLocation());
2906 const llvm::DataLayout &target = CGM.getDataLayout();
2908 CharUnits offset = CharUnits::fromQuantity(
2909 target.getStructLayout(blockInfo.StructureType)
2910 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2912 SmallVector<int64_t, 9> addr;
2913 if (isa<llvm::AllocaInst>(Storage))
2914 addr.push_back(llvm::dwarf::DW_OP_deref);
2915 addr.push_back(llvm::dwarf::DW_OP_plus);
2916 addr.push_back(offset.getQuantity());
2918 addr.push_back(llvm::dwarf::DW_OP_deref);
2919 addr.push_back(llvm::dwarf::DW_OP_plus);
2920 // offset of __forwarding field
2922 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
2923 addr.push_back(offset.getQuantity());
2924 addr.push_back(llvm::dwarf::DW_OP_deref);
2925 addr.push_back(llvm::dwarf::DW_OP_plus);
2926 // offset of x field
2927 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2928 addr.push_back(offset.getQuantity());
2931 // Create the descriptor for the variable.
2932 auto *D = DBuilder.createLocalVariable(
2933 llvm::dwarf::DW_TAG_auto_variable,
2934 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
2937 // Insert an llvm.dbg.declare into the current block.
2938 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
2940 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2943 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2944 Builder.GetInsertBlock());
2947 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2949 CGBuilderTy &Builder) {
2950 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2951 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2955 struct BlockLayoutChunk {
2956 uint64_t OffsetInBits;
2957 const BlockDecl::Capture *Capture;
2959 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2960 return l.OffsetInBits < r.OffsetInBits;
2964 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2967 llvm::Value *LocalAddr,
2968 CGBuilderTy &Builder) {
2969 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2970 ASTContext &C = CGM.getContext();
2971 const BlockDecl *blockDecl = block.getBlockDecl();
2973 // Collect some general information about the block's location.
2974 SourceLocation loc = blockDecl->getCaretLocation();
2975 llvm::DIFile *tunit = getOrCreateFile(loc);
2976 unsigned line = getLineNumber(loc);
2977 unsigned column = getColumnNumber(loc);
2979 // Build the debug-info type for the block literal.
2980 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2982 const llvm::StructLayout *blockLayout =
2983 CGM.getDataLayout().getStructLayout(block.StructureType);
2985 SmallVector<llvm::Metadata *, 16> fields;
2986 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2987 blockLayout->getElementOffsetInBits(0),
2989 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2990 blockLayout->getElementOffsetInBits(1),
2992 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2993 blockLayout->getElementOffsetInBits(2),
2995 auto *FnTy = block.getBlockExpr()->getFunctionType();
2996 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
2997 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
2998 blockLayout->getElementOffsetInBits(3),
3000 fields.push_back(createFieldType(
3001 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3002 ? C.getBlockDescriptorExtendedType()
3003 : C.getBlockDescriptorType()),
3004 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3006 // We want to sort the captures by offset, not because DWARF
3007 // requires this, but because we're paranoid about debuggers.
3008 SmallVector<BlockLayoutChunk, 8> chunks;
3011 if (blockDecl->capturesCXXThis()) {
3012 BlockLayoutChunk chunk;
3013 chunk.OffsetInBits =
3014 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3015 chunk.Capture = nullptr;
3016 chunks.push_back(chunk);
3019 // Variable captures.
3020 for (const auto &capture : blockDecl->captures()) {
3021 const VarDecl *variable = capture.getVariable();
3022 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3024 // Ignore constant captures.
3025 if (captureInfo.isConstant())
3028 BlockLayoutChunk chunk;
3029 chunk.OffsetInBits =
3030 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3031 chunk.Capture = &capture;
3032 chunks.push_back(chunk);
3036 llvm::array_pod_sort(chunks.begin(), chunks.end());
3038 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
3041 uint64_t offsetInBits = i->OffsetInBits;
3042 const BlockDecl::Capture *capture = i->Capture;
3044 // If we have a null capture, this must be the C++ 'this' capture.
3046 const CXXMethodDecl *method =
3047 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3048 QualType type = method->getThisType(C);
3050 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3051 offsetInBits, tunit, tunit));
3055 const VarDecl *variable = capture->getVariable();
3056 StringRef name = variable->getName();
3058 llvm::DIType *fieldType;
3059 if (capture->isByRef()) {
3060 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3062 // FIXME: this creates a second copy of this type!
3064 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3065 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3067 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3068 PtrInfo.Align, offsetInBits, 0, fieldType);
3070 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
3071 offsetInBits, tunit, tunit);
3073 fields.push_back(fieldType);
3076 SmallString<36> typeName;
3077 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3078 << CGM.getUniqueBlockCount();
3080 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3082 llvm::DIType *type = DBuilder.createStructType(
3083 tunit, typeName.str(), tunit, line,
3084 CGM.getContext().toBits(block.BlockSize),
3085 CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
3086 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3088 // Get overall information about the block.
3089 unsigned flags = llvm::DINode::FlagArtificial;
3090 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3092 // Create the descriptor for the parameter.
3093 auto *debugVar = DBuilder.createLocalVariable(
3094 llvm::dwarf::DW_TAG_arg_variable, scope, Arg->getName(), tunit, line,
3095 type, CGM.getLangOpts().Optimize, flags, ArgNo);
3098 // Insert an llvm.dbg.value into the current block.
3099 DBuilder.insertDbgValueIntrinsic(
3100 LocalAddr, 0, debugVar, DBuilder.createExpression(),
3101 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3104 // Insert an llvm.dbg.declare into the current block.
3105 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3106 llvm::DebugLoc::get(line, column, scope),
3107 Builder.GetInsertBlock());
3110 llvm::DIDerivedType *
3111 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3112 if (!D->isStaticDataMember())
3115 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3116 if (MI != StaticDataMemberCache.end()) {
3117 assert(MI->second && "Static data member declaration should still exist");
3118 return cast<llvm::DIDerivedType>(MI->second);
3121 // If the member wasn't found in the cache, lazily construct and add it to the
3122 // type (used when a limited form of the type is emitted).
3123 auto DC = D->getDeclContext();
3125 cast<llvm::DICompositeType>(getContextDescriptor(cast<Decl>(DC)));
3126 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3129 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
3130 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3131 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3132 llvm::DIGlobalVariable *GV = nullptr;
3134 for (const auto *Field : RD->fields()) {
3135 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3136 StringRef FieldName = Field->getName();
3138 // Ignore unnamed fields, but recurse into anonymous records.
3139 if (FieldName.empty()) {
3140 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3142 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3146 // Use VarDecl's Tag, Scope and Line number.
3147 GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
3149 Var->hasInternalLinkage(), Var, nullptr);
3154 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3156 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3157 // Create global variable debug descriptor.
3158 llvm::DIFile *Unit = nullptr;
3159 llvm::DIScope *DContext = nullptr;
3161 StringRef DeclName, LinkageName;
3163 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3165 // Attempt to store one global variable for the declaration - even if we
3166 // emit a lot of fields.
3167 llvm::DIGlobalVariable *GV = nullptr;
3169 // If this is an anonymous union then we'll want to emit a global
3170 // variable for each member of the anonymous union so that it's possible
3171 // to find the name of any field in the union.
3172 if (T->isUnionType() && DeclName.empty()) {
3173 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3174 assert(RD->isAnonymousStructOrUnion() &&
3175 "unnamed non-anonymous struct or union?");
3176 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3178 GV = DBuilder.createGlobalVariable(
3179 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3180 Var->hasInternalLinkage(), Var,
3181 getOrCreateStaticDataMemberDeclarationOrNull(D));
3183 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
3186 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3187 llvm::Constant *Init) {
3188 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3189 // Create the descriptor for the variable.
3190 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3191 StringRef Name = VD->getName();
3192 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3193 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3194 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3195 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3196 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3198 // Do not use global variables for enums.
3201 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3203 // Do not emit separate definitions for function local const/statics.
3204 if (isa<FunctionDecl>(VD->getDeclContext()))
3206 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3207 auto *VarD = cast<VarDecl>(VD);
3208 if (VarD->isStaticDataMember()) {
3209 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3210 getContextDescriptor(RD);
3211 // Ensure that the type is retained even though it's otherwise unreferenced.
3212 RetainedTypes.push_back(
3213 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3217 llvm::DIScope *DContext =
3218 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
3220 auto &GV = DeclCache[VD];
3223 GV.reset(DBuilder.createGlobalVariable(
3224 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3225 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3228 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3229 if (!LexicalBlockStack.empty())
3230 return LexicalBlockStack.back();
3231 return getContextDescriptor(D);
3234 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3235 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3237 DBuilder.createImportedModule(
3238 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3239 getOrCreateNameSpace(UD.getNominatedNamespace()),
3240 getLineNumber(UD.getLocation()));
3243 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3244 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3246 assert(UD.shadow_size() &&
3247 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3248 // Emitting one decl is sufficient - debuggers can detect that this is an
3249 // overloaded name & provide lookup for all the overloads.
3250 const UsingShadowDecl &USD = **UD.shadow_begin();
3251 if (llvm::DINode *Target =
3252 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3253 DBuilder.createImportedDeclaration(
3254 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3255 getLineNumber(USD.getLocation()));
3258 void CGDebugInfo::EmitImportDecl(const ImportDecl &ID) {
3259 auto *Reader = CGM.getContext().getExternalSource();
3260 auto Info = Reader->getSourceDescriptor(*ID.getImportedModule());
3261 DBuilder.createImportedDeclaration(
3262 getCurrentContextDescriptor(cast<Decl>(ID.getDeclContext())),
3263 getOrCreateModuleRef(Info),
3264 getLineNumber(ID.getLocation()));
3267 llvm::DIImportedEntity *
3268 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3269 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3271 auto &VH = NamespaceAliasCache[&NA];
3273 return cast<llvm::DIImportedEntity>(VH);
3274 llvm::DIImportedEntity *R;
3275 if (const NamespaceAliasDecl *Underlying =
3276 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3277 // This could cache & dedup here rather than relying on metadata deduping.
3278 R = DBuilder.createImportedDeclaration(
3279 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3280 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3283 R = DBuilder.createImportedDeclaration(
3284 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3285 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3286 getLineNumber(NA.getLocation()), NA.getName());
3292 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3293 NSDecl = NSDecl->getCanonicalDecl();
3294 auto I = NameSpaceCache.find(NSDecl);
3295 if (I != NameSpaceCache.end())
3296 return cast<llvm::DINamespace>(I->second);
3298 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3299 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3300 llvm::DIScope *Context =
3301 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3302 llvm::DINamespace *NS =
3303 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3304 NameSpaceCache[NSDecl].reset(NS);
3308 void CGDebugInfo::finalize() {
3309 // Creating types might create further types - invalidating the current
3310 // element and the size(), so don't cache/reference them.
3311 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3312 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3313 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3314 ? CreateTypeDefinition(E.Type, E.Unit)
3316 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3319 for (auto p : ReplaceMap) {
3321 auto *Ty = cast<llvm::DIType>(p.second);
3322 assert(Ty->isForwardDecl());
3324 auto it = TypeCache.find(p.first);
3325 assert(it != TypeCache.end());
3328 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3329 cast<llvm::DIType>(it->second));
3332 for (const auto &p : FwdDeclReplaceMap) {
3334 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3335 llvm::Metadata *Repl;
3337 auto it = DeclCache.find(p.first);
3338 // If there has been no definition for the declaration, call RAUW
3339 // with ourselves, that will destroy the temporary MDNode and
3340 // replace it with a standard one, avoiding leaking memory.
3341 if (it == DeclCache.end())
3346 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3349 // We keep our own list of retained types, because we need to look
3350 // up the final type in the type cache.
3351 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3352 RE = RetainedTypes.end(); RI != RE; ++RI)
3353 DBuilder.retainType(cast<llvm::DIType>(TypeCache[*RI]));
3355 DBuilder.finalize();
3358 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3359 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3362 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3363 // Don't ignore in case of explicit cast where it is referenced indirectly.
3364 DBuilder.retainType(DieTy);