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 "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 using namespace clang;
42 using namespace clang::CodeGen;
44 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
45 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
50 CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
55 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
56 SourceLocation TemporaryLocation)
58 init(TemporaryLocation);
61 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF,
63 SourceLocation TemporaryLocation)
65 init(TemporaryLocation, DefaultToEmpty);
68 void ApplyDebugLocation::init(SourceLocation TemporaryLocation,
69 bool DefaultToEmpty) {
70 if (auto *DI = CGF.getDebugInfo()) {
71 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
72 if (TemporaryLocation.isInvalid()) {
74 CGF.Builder.SetCurrentDebugLocation(llvm::DebugLoc());
76 // Construct a location that has a valid scope, but no line info.
77 assert(!DI->LexicalBlockStack.empty());
78 CGF.Builder.SetCurrentDebugLocation(
79 llvm::DebugLoc::get(0, 0, DI->LexicalBlockStack.back()));
82 DI->EmitLocation(CGF.Builder, TemporaryLocation);
86 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, const Expr *E)
88 init(E->getExprLoc());
91 ApplyDebugLocation::ApplyDebugLocation(CodeGenFunction &CGF, llvm::DebugLoc Loc)
93 if (CGF.getDebugInfo()) {
94 OriginalLocation = CGF.Builder.getCurrentDebugLocation();
96 CGF.Builder.SetCurrentDebugLocation(std::move(Loc));
100 ApplyDebugLocation::~ApplyDebugLocation() {
101 // Query CGF so the location isn't overwritten when location updates are
102 // temporarily disabled (for C++ default function arguments)
103 if (CGF.getDebugInfo())
104 CGF.Builder.SetCurrentDebugLocation(std::move(OriginalLocation));
107 /// ArtificialLocation - An RAII object that temporarily switches to
108 /// an artificial debug location that has a valid scope, but no line
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 /// getContextDescriptor - Get context info for the decl.
142 llvm::DIScope *CGDebugInfo::getContextDescriptor(const Decl *Context) {
146 auto I = RegionMap.find(Context);
147 if (I != RegionMap.end()) {
148 llvm::Metadata *V = I->second;
149 return dyn_cast_or_null<llvm::DIScope>(V);
153 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
154 return getOrCreateNameSpace(NSDecl);
156 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
157 if (!RDecl->isDependentType())
158 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
159 getOrCreateMainFile());
163 /// getFunctionName - Get function name for the given FunctionDecl. If the
164 /// name is constructed on demand (e.g. C++ destructor) then the name
165 /// is stored on the side.
166 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
167 assert(FD && "Invalid FunctionDecl!");
168 IdentifierInfo *FII = FD->getIdentifier();
169 FunctionTemplateSpecializationInfo *Info =
170 FD->getTemplateSpecializationInfo();
172 return FII->getName();
174 // Otherwise construct human readable name for debug info.
176 llvm::raw_svector_ostream OS(NS);
179 // Add any template specialization args.
181 const TemplateArgumentList *TArgs = Info->TemplateArguments;
182 const TemplateArgument *Args = TArgs->data();
183 unsigned NumArgs = TArgs->size();
184 PrintingPolicy Policy(CGM.getLangOpts());
185 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
189 // Copy this name on the side and use its reference.
190 return internString(OS.str());
193 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
194 SmallString<256> MethodName;
195 llvm::raw_svector_ostream OS(MethodName);
196 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
197 const DeclContext *DC = OMD->getDeclContext();
198 if (const ObjCImplementationDecl *OID =
199 dyn_cast<const ObjCImplementationDecl>(DC)) {
200 OS << OID->getName();
201 } else if (const ObjCInterfaceDecl *OID =
202 dyn_cast<const ObjCInterfaceDecl>(DC)) {
203 OS << OID->getName();
204 } else if (const ObjCCategoryImplDecl *OCD =
205 dyn_cast<const ObjCCategoryImplDecl>(DC)) {
206 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '('
207 << OCD->getIdentifier()->getNameStart() << ')';
208 } else if (isa<ObjCProtocolDecl>(DC)) {
209 // We can extract the type of the class from the self pointer.
210 if (ImplicitParamDecl *SelfDecl = OMD->getSelfDecl()) {
212 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
213 ClassTy.print(OS, PrintingPolicy(LangOptions()));
216 OS << ' ' << OMD->getSelector().getAsString() << ']';
218 return internString(OS.str());
221 /// getSelectorName - Return selector name. This is used for debugging
223 StringRef CGDebugInfo::getSelectorName(Selector S) {
224 return internString(S.getAsString());
227 /// getClassName - Get class name including template argument list.
228 StringRef CGDebugInfo::getClassName(const RecordDecl *RD) {
229 // quick optimization to avoid having to intern strings that are already
230 // stored reliably elsewhere
231 if (!isa<ClassTemplateSpecializationDecl>(RD))
232 return RD->getName();
234 SmallString<128> Name;
236 llvm::raw_svector_ostream OS(Name);
237 RD->getNameForDiagnostic(OS, CGM.getContext().getPrintingPolicy(),
238 /*Qualified*/ false);
241 // Copy this name on the side and use its reference.
242 return internString(Name);
245 /// getOrCreateFile - Get the file debug info descriptor for the input location.
246 llvm::DIFile *CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
248 // If Location is not valid then use main input file.
249 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
251 SourceManager &SM = CGM.getContext().getSourceManager();
252 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
254 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
255 // If the location is not valid then use main input file.
256 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
258 // Cache the results.
259 const char *fname = PLoc.getFilename();
260 auto it = DIFileCache.find(fname);
262 if (it != DIFileCache.end()) {
263 // Verify that the information still exists.
264 if (llvm::Metadata *V = it->second)
265 return cast<llvm::DIFile>(V);
269 DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
271 DIFileCache[fname].reset(F);
275 /// getOrCreateMainFile - Get the file info for main compile unit.
276 llvm::DIFile *CGDebugInfo::getOrCreateMainFile() {
277 return DBuilder.createFile(TheCU->getFilename(), TheCU->getDirectory());
280 /// getLineNumber - Get line number for the location. If location is invalid
281 /// then use current location.
282 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
283 if (Loc.isInvalid() && CurLoc.isInvalid())
285 SourceManager &SM = CGM.getContext().getSourceManager();
286 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
287 return PLoc.isValid() ? PLoc.getLine() : 0;
290 /// getColumnNumber - Get column number for the location.
291 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
292 // We may not want column information at all.
293 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
296 // If the location is invalid then use the current column.
297 if (Loc.isInvalid() && CurLoc.isInvalid())
299 SourceManager &SM = CGM.getContext().getSourceManager();
300 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
301 return PLoc.isValid() ? PLoc.getColumn() : 0;
304 StringRef CGDebugInfo::getCurrentDirname() {
305 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
306 return CGM.getCodeGenOpts().DebugCompilationDir;
308 if (!CWDName.empty())
310 SmallString<256> CWD;
311 llvm::sys::fs::current_path(CWD);
312 return CWDName = internString(CWD);
315 /// CreateCompileUnit - Create new compile unit.
316 void CGDebugInfo::CreateCompileUnit() {
318 // Should we be asking the SourceManager for the main file name, instead of
319 // accepting it as an argument? This just causes the main file name to
320 // mismatch with source locations and create extra lexical scopes or
321 // mismatched debug info (a CU with a DW_AT_file of "-", because that's what
322 // the driver passed, but functions/other things have DW_AT_file of "<stdin>"
323 // because that's what the SourceManager says)
325 // Get absolute path name.
326 SourceManager &SM = CGM.getContext().getSourceManager();
327 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
328 if (MainFileName.empty())
329 MainFileName = "<stdin>";
331 // The main file name provided via the "-main-file-name" option contains just
332 // the file name itself with no path information. This file name may have had
333 // a relative path, so we look into the actual file entry for the main
334 // file to determine the real absolute path for the file.
335 std::string MainFileDir;
336 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
337 MainFileDir = MainFile->getDir()->getName();
338 if (MainFileDir != ".") {
339 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
340 llvm::sys::path::append(MainFileDirSS, MainFileName);
341 MainFileName = MainFileDirSS.str();
345 // Save filename string.
346 StringRef Filename = internString(MainFileName);
348 // Save split dwarf file string.
349 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
350 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
352 llvm::dwarf::SourceLanguage LangTag;
353 const LangOptions &LO = CGM.getLangOpts();
356 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
358 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
359 } else if (LO.ObjC1) {
360 LangTag = llvm::dwarf::DW_LANG_ObjC;
362 LangTag = llvm::dwarf::DW_LANG_C99;
364 LangTag = llvm::dwarf::DW_LANG_C89;
367 std::string Producer = getClangFullVersion();
369 // Figure out which version of the ObjC runtime we have.
370 unsigned RuntimeVers = 0;
372 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
374 // Create new compile unit.
375 // FIXME - Eliminate TheCU.
376 TheCU = DBuilder.createCompileUnit(
377 LangTag, Filename, getCurrentDirname(), Producer, LO.Optimize,
378 CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers, SplitDwarfFilename,
379 DebugKind <= CodeGenOptions::DebugLineTablesOnly
380 ? llvm::DIBuilder::LineTablesOnly
381 : llvm::DIBuilder::FullDebug,
383 DebugKind != CodeGenOptions::LocTrackingOnly);
386 /// CreateType - Get the Basic type from the cache or create a new
387 /// one if necessary.
388 llvm::DIType *CGDebugInfo::CreateType(const BuiltinType *BT) {
389 llvm::dwarf::TypeKind Encoding;
391 switch (BT->getKind()) {
392 #define BUILTIN_TYPE(Id, SingletonId)
393 #define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
394 #include "clang/AST/BuiltinTypes.def"
395 case BuiltinType::Dependent:
396 llvm_unreachable("Unexpected builtin type");
397 case BuiltinType::NullPtr:
398 return DBuilder.createNullPtrType();
399 case BuiltinType::Void:
401 case BuiltinType::ObjCClass:
403 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
405 getOrCreateMainFile(), 0);
407 case BuiltinType::ObjCId: {
408 // typedef struct objc_class *Class;
409 // typedef struct objc_object {
417 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
419 getOrCreateMainFile(), 0);
421 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
423 auto *ISATy = DBuilder.createPointerType(ClassTy, Size);
426 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
427 0, 0, 0, 0, nullptr, llvm::DINodeArray());
429 DBuilder.replaceArrays(
431 DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
432 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
435 case BuiltinType::ObjCSel: {
437 SelTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
438 "objc_selector", TheCU,
439 getOrCreateMainFile(), 0);
443 case BuiltinType::OCLImage1d:
444 return getOrCreateStructPtrType("opencl_image1d_t", OCLImage1dDITy);
445 case BuiltinType::OCLImage1dArray:
446 return getOrCreateStructPtrType("opencl_image1d_array_t",
447 OCLImage1dArrayDITy);
448 case BuiltinType::OCLImage1dBuffer:
449 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
450 OCLImage1dBufferDITy);
451 case BuiltinType::OCLImage2d:
452 return getOrCreateStructPtrType("opencl_image2d_t", OCLImage2dDITy);
453 case BuiltinType::OCLImage2dArray:
454 return getOrCreateStructPtrType("opencl_image2d_array_t",
455 OCLImage2dArrayDITy);
456 case BuiltinType::OCLImage3d:
457 return getOrCreateStructPtrType("opencl_image3d_t", OCLImage3dDITy);
458 case BuiltinType::OCLSampler:
459 return DBuilder.createBasicType(
460 "opencl_sampler_t", CGM.getContext().getTypeSize(BT),
461 CGM.getContext().getTypeAlign(BT), llvm::dwarf::DW_ATE_unsigned);
462 case BuiltinType::OCLEvent:
463 return getOrCreateStructPtrType("opencl_event_t", OCLEventDITy);
465 case BuiltinType::UChar:
466 case BuiltinType::Char_U:
467 Encoding = llvm::dwarf::DW_ATE_unsigned_char;
469 case BuiltinType::Char_S:
470 case BuiltinType::SChar:
471 Encoding = llvm::dwarf::DW_ATE_signed_char;
473 case BuiltinType::Char16:
474 case BuiltinType::Char32:
475 Encoding = llvm::dwarf::DW_ATE_UTF;
477 case BuiltinType::UShort:
478 case BuiltinType::UInt:
479 case BuiltinType::UInt128:
480 case BuiltinType::ULong:
481 case BuiltinType::WChar_U:
482 case BuiltinType::ULongLong:
483 Encoding = llvm::dwarf::DW_ATE_unsigned;
485 case BuiltinType::Short:
486 case BuiltinType::Int:
487 case BuiltinType::Int128:
488 case BuiltinType::Long:
489 case BuiltinType::WChar_S:
490 case BuiltinType::LongLong:
491 Encoding = llvm::dwarf::DW_ATE_signed;
493 case BuiltinType::Bool:
494 Encoding = llvm::dwarf::DW_ATE_boolean;
496 case BuiltinType::Half:
497 case BuiltinType::Float:
498 case BuiltinType::LongDouble:
499 case BuiltinType::Double:
500 Encoding = llvm::dwarf::DW_ATE_float;
504 switch (BT->getKind()) {
505 case BuiltinType::Long:
508 case BuiltinType::LongLong:
509 BTName = "long long int";
511 case BuiltinType::ULong:
512 BTName = "long unsigned int";
514 case BuiltinType::ULongLong:
515 BTName = "long long unsigned int";
518 BTName = BT->getName(CGM.getLangOpts());
521 // Bit size, align and offset of the type.
522 uint64_t Size = CGM.getContext().getTypeSize(BT);
523 uint64_t Align = CGM.getContext().getTypeAlign(BT);
524 return DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 llvm::DIType *CGDebugInfo::CreateType(const ComplexType *Ty) {
528 // Bit size, align and offset of the type.
529 llvm::dwarf::TypeKind Encoding = llvm::dwarf::DW_ATE_complex_float;
530 if (Ty->isComplexIntegerType())
531 Encoding = llvm::dwarf::DW_ATE_lo_user;
533 uint64_t Size = CGM.getContext().getTypeSize(Ty);
534 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
535 return DBuilder.createBasicType("complex", Size, Align, Encoding);
538 /// CreateCVRType - Get the qualified type from the cache or create
539 /// a new one if necessary.
540 llvm::DIType *CGDebugInfo::CreateQualifiedType(QualType Ty,
541 llvm::DIFile *Unit) {
542 QualifierCollector Qc;
543 const Type *T = Qc.strip(Ty);
545 // Ignore these qualifiers for now.
546 Qc.removeObjCGCAttr();
547 Qc.removeAddressSpace();
548 Qc.removeObjCLifetime();
550 // We will create one Derived type for one qualifier and recurse to handle any
552 llvm::dwarf::Tag Tag;
554 Tag = llvm::dwarf::DW_TAG_const_type;
556 } else if (Qc.hasVolatile()) {
557 Tag = llvm::dwarf::DW_TAG_volatile_type;
559 } else if (Qc.hasRestrict()) {
560 Tag = llvm::dwarf::DW_TAG_restrict_type;
563 assert(Qc.empty() && "Unknown type qualifier for debug info");
564 return getOrCreateType(QualType(T, 0), Unit);
567 auto *FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
569 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
570 // CVR derived types.
571 return DBuilder.createQualifiedType(Tag, FromTy);
574 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
575 llvm::DIFile *Unit) {
577 // The frontend treats 'id' as a typedef to an ObjCObjectType,
578 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
579 // debug info, we want to emit 'id' in both cases.
580 if (Ty->isObjCQualifiedIdType())
581 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
583 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
584 Ty->getPointeeType(), Unit);
587 llvm::DIType *CGDebugInfo::CreateType(const PointerType *Ty,
588 llvm::DIFile *Unit) {
589 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
590 Ty->getPointeeType(), Unit);
593 /// \return whether a C++ mangling exists for the type defined by TD.
594 static bool hasCXXMangling(const TagDecl *TD, llvm::DICompileUnit *TheCU) {
595 switch (TheCU->getSourceLanguage()) {
596 case llvm::dwarf::DW_LANG_C_plus_plus:
598 case llvm::dwarf::DW_LANG_ObjC_plus_plus:
599 return isa<CXXRecordDecl>(TD) || isa<EnumDecl>(TD);
605 /// In C++ mode, types have linkage, so we can rely on the ODR and
606 /// on their mangled names, if they're external.
607 static SmallString<256> getUniqueTagTypeName(const TagType *Ty,
609 llvm::DICompileUnit *TheCU) {
610 SmallString<256> FullName;
611 const TagDecl *TD = Ty->getDecl();
613 if (!hasCXXMangling(TD, TheCU) || !TD->isExternallyVisible())
616 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
617 if (CGM.getTarget().getCXXABI().isMicrosoft())
620 // TODO: This is using the RTTI name. Is there a better way to get
621 // a unique string for a type?
622 llvm::raw_svector_ostream Out(FullName);
623 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
628 static llvm::dwarf::Tag getTagForRecord(const RecordDecl *RD) {
629 llvm::dwarf::Tag Tag;
630 if (RD->isStruct() || RD->isInterface())
631 Tag = llvm::dwarf::DW_TAG_structure_type;
632 else if (RD->isUnion())
633 Tag = llvm::dwarf::DW_TAG_union_type;
635 // FIXME: This could be a struct type giving a default visibility different
636 // than C++ class type, but needs llvm metadata changes first.
637 assert(RD->isClass());
638 Tag = llvm::dwarf::DW_TAG_class_type;
643 // Creates a forward declaration for a RecordDecl in the given context.
644 llvm::DICompositeType *
645 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
646 llvm::DIScope *Ctx) {
647 const RecordDecl *RD = Ty->getDecl();
648 if (llvm::DIType *T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
649 return cast<llvm::DICompositeType>(T);
650 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
651 unsigned Line = getLineNumber(RD->getLocation());
652 StringRef RDName = getClassName(RD);
657 const RecordDecl *D = RD->getDefinition();
658 if (D && D->isCompleteDefinition()) {
659 Size = CGM.getContext().getTypeSize(Ty);
660 Align = CGM.getContext().getTypeAlign(Ty);
664 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
665 llvm::DICompositeType *RetTy = DBuilder.createReplaceableCompositeType(
666 getTagForRecord(RD), RDName, Ctx, DefUnit, Line, 0, Size, Align,
667 llvm::DINode::FlagFwdDecl, FullName);
668 ReplaceMap.emplace_back(
669 std::piecewise_construct, std::make_tuple(Ty),
670 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
674 llvm::DIType *CGDebugInfo::CreatePointerLikeType(llvm::dwarf::Tag Tag,
677 llvm::DIFile *Unit) {
678 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
679 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
680 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
682 // Bit size, align and offset of the type.
683 // Size is always the size of a pointer. We can't use getTypeSize here
684 // because that does not return the correct value for references.
685 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
686 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
687 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
689 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
693 llvm::DIType *CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
694 llvm::DIType *&Cache) {
697 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
698 TheCU, getOrCreateMainFile(), 0);
699 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
700 Cache = DBuilder.createPointerType(Cache, Size);
704 llvm::DIType *CGDebugInfo::CreateType(const BlockPointerType *Ty,
705 llvm::DIFile *Unit) {
706 if (BlockLiteralGeneric)
707 return BlockLiteralGeneric;
709 SmallVector<llvm::Metadata *, 8> EltTys;
711 uint64_t FieldSize, FieldOffset;
713 llvm::DINodeArray Elements;
716 FType = CGM.getContext().UnsignedLongTy;
717 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
718 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
720 Elements = DBuilder.getOrCreateArray(EltTys);
723 unsigned Flags = llvm::DINode::FlagAppleBlock;
724 unsigned LineNo = getLineNumber(CurLoc);
727 DBuilder.createStructType(Unit, "__block_descriptor", Unit, LineNo,
728 FieldOffset, 0, Flags, nullptr, Elements);
730 // Bit size, align and offset of the type.
731 uint64_t Size = CGM.getContext().getTypeSize(Ty);
733 auto *DescTy = DBuilder.createPointerType(EltTy, Size);
736 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
737 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
738 FType = CGM.getContext().IntTy;
739 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
740 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
741 FType = CGM.getContext().getPointerType(Ty->getPointeeType());
742 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
744 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
745 FieldSize = CGM.getContext().getTypeSize(Ty);
746 FieldAlign = CGM.getContext().getTypeAlign(Ty);
747 EltTys.push_back(DBuilder.createMemberType(Unit, "__descriptor", Unit, LineNo,
748 FieldSize, FieldAlign, FieldOffset,
751 FieldOffset += FieldSize;
752 Elements = DBuilder.getOrCreateArray(EltTys);
755 DBuilder.createStructType(Unit, "__block_literal_generic", Unit, LineNo,
756 FieldOffset, 0, Flags, nullptr, Elements);
758 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
759 return BlockLiteralGeneric;
762 llvm::DIType *CGDebugInfo::CreateType(const TemplateSpecializationType *Ty,
763 llvm::DIFile *Unit) {
764 assert(Ty->isTypeAlias());
765 llvm::DIType *Src = getOrCreateType(Ty->getAliasedType(), Unit);
768 llvm::raw_svector_ostream OS(NS);
769 Ty->getTemplateName().print(OS, CGM.getContext().getPrintingPolicy(),
770 /*qualified*/ false);
772 TemplateSpecializationType::PrintTemplateArgumentList(
773 OS, Ty->getArgs(), Ty->getNumArgs(),
774 CGM.getContext().getPrintingPolicy());
776 TypeAliasDecl *AliasDecl = cast<TypeAliasTemplateDecl>(
777 Ty->getTemplateName().getAsTemplateDecl())->getTemplatedDecl();
779 SourceLocation Loc = AliasDecl->getLocation();
780 return DBuilder.createTypedef(
781 Src, internString(OS.str()), getOrCreateFile(Loc), getLineNumber(Loc),
782 getContextDescriptor(cast<Decl>(AliasDecl->getDeclContext())));
785 llvm::DIType *CGDebugInfo::CreateType(const TypedefType *Ty,
786 llvm::DIFile *Unit) {
787 // We don't set size information, but do specify where the typedef was
789 SourceLocation Loc = Ty->getDecl()->getLocation();
791 // Typedefs are derived from some other type.
792 return DBuilder.createTypedef(
793 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit),
794 Ty->getDecl()->getName(), getOrCreateFile(Loc), getLineNumber(Loc),
795 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext())));
798 llvm::DIType *CGDebugInfo::CreateType(const FunctionType *Ty,
799 llvm::DIFile *Unit) {
800 SmallVector<llvm::Metadata *, 16> EltTys;
802 // Add the result type at least.
803 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
805 // Set up remainder of arguments if there is a prototype.
806 // otherwise emit it as a variadic function.
807 if (isa<FunctionNoProtoType>(Ty))
808 EltTys.push_back(DBuilder.createUnspecifiedParameter());
809 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
810 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
811 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
812 if (FPT->isVariadic())
813 EltTys.push_back(DBuilder.createUnspecifiedParameter());
816 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
817 return DBuilder.createSubroutineType(Unit, EltTypeArray);
820 /// Convert an AccessSpecifier into the corresponding DINode flag.
821 /// As an optimization, return 0 if the access specifier equals the
822 /// default for the containing type.
823 static unsigned getAccessFlag(AccessSpecifier Access, const RecordDecl *RD) {
824 AccessSpecifier Default = clang::AS_none;
825 if (RD && RD->isClass())
826 Default = clang::AS_private;
827 else if (RD && (RD->isStruct() || RD->isUnion()))
828 Default = clang::AS_public;
830 if (Access == Default)
834 case clang::AS_private:
835 return llvm::DINode::FlagPrivate;
836 case clang::AS_protected:
837 return llvm::DINode::FlagProtected;
838 case clang::AS_public:
839 return llvm::DINode::FlagPublic;
843 llvm_unreachable("unexpected access enumerator");
846 llvm::DIType *CGDebugInfo::createFieldType(
847 StringRef name, QualType type, uint64_t sizeInBitsOverride,
848 SourceLocation loc, AccessSpecifier AS, uint64_t offsetInBits,
849 llvm::DIFile *tunit, llvm::DIScope *scope, const RecordDecl *RD) {
850 llvm::DIType *debugType = getOrCreateType(type, tunit);
852 // Get the location for the field.
853 llvm::DIFile *file = getOrCreateFile(loc);
854 unsigned line = getLineNumber(loc);
856 uint64_t SizeInBits = 0;
857 unsigned AlignInBits = 0;
858 if (!type->isIncompleteArrayType()) {
859 TypeInfo TI = CGM.getContext().getTypeInfo(type);
860 SizeInBits = TI.Width;
861 AlignInBits = TI.Align;
863 if (sizeInBitsOverride)
864 SizeInBits = sizeInBitsOverride;
867 unsigned flags = getAccessFlag(AS, RD);
868 return DBuilder.createMemberType(scope, name, file, line, SizeInBits,
869 AlignInBits, offsetInBits, flags, debugType);
872 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
873 void CGDebugInfo::CollectRecordLambdaFields(
874 const CXXRecordDecl *CXXDecl, SmallVectorImpl<llvm::Metadata *> &elements,
875 llvm::DIType *RecordTy) {
876 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
877 // has the name and the location of the variable so we should iterate over
878 // both concurrently.
879 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
880 RecordDecl::field_iterator Field = CXXDecl->field_begin();
881 unsigned fieldno = 0;
882 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
883 E = CXXDecl->captures_end();
884 I != E; ++I, ++Field, ++fieldno) {
885 const LambdaCapture &C = *I;
886 if (C.capturesVariable()) {
887 VarDecl *V = C.getCapturedVar();
888 llvm::DIFile *VUnit = getOrCreateFile(C.getLocation());
889 StringRef VName = V->getName();
890 uint64_t SizeInBitsOverride = 0;
891 if (Field->isBitField()) {
892 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
893 assert(SizeInBitsOverride && "found named 0-width bitfield");
895 llvm::DIType *fieldType = createFieldType(
896 VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
897 Field->getAccess(), layout.getFieldOffset(fieldno), VUnit, RecordTy,
899 elements.push_back(fieldType);
900 } else if (C.capturesThis()) {
901 // TODO: Need to handle 'this' in some way by probably renaming the
902 // this of the lambda class and having a field member of 'this' or
903 // by using AT_object_pointer for the function and having that be
904 // used as 'this' for semantic references.
905 FieldDecl *f = *Field;
906 llvm::DIFile *VUnit = getOrCreateFile(f->getLocation());
907 QualType type = f->getType();
908 llvm::DIType *fieldType = createFieldType(
909 "this", type, 0, f->getLocation(), f->getAccess(),
910 layout.getFieldOffset(fieldno), VUnit, RecordTy, CXXDecl);
912 elements.push_back(fieldType);
917 /// Helper for CollectRecordFields.
918 llvm::DIDerivedType *
919 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var, llvm::DIType *RecordTy,
920 const RecordDecl *RD) {
921 // Create the descriptor for the static variable, with or without
922 // constant initializers.
923 Var = Var->getCanonicalDecl();
924 llvm::DIFile *VUnit = getOrCreateFile(Var->getLocation());
925 llvm::DIType *VTy = getOrCreateType(Var->getType(), VUnit);
927 unsigned LineNumber = getLineNumber(Var->getLocation());
928 StringRef VName = Var->getName();
929 llvm::Constant *C = nullptr;
930 if (Var->getInit()) {
931 const APValue *Value = Var->evaluateValue();
934 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
935 if (Value->isFloat())
936 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
940 unsigned Flags = getAccessFlag(Var->getAccess(), RD);
941 llvm::DIDerivedType *GV = DBuilder.createStaticMemberType(
942 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
943 StaticDataMemberCache[Var->getCanonicalDecl()].reset(GV);
947 /// CollectRecordNormalField - Helper for CollectRecordFields.
948 void CGDebugInfo::CollectRecordNormalField(
949 const FieldDecl *field, uint64_t OffsetInBits, llvm::DIFile *tunit,
950 SmallVectorImpl<llvm::Metadata *> &elements, llvm::DIType *RecordTy,
951 const RecordDecl *RD) {
952 StringRef name = field->getName();
953 QualType type = field->getType();
955 // Ignore unnamed fields unless they're anonymous structs/unions.
956 if (name.empty() && !type->isRecordType())
959 uint64_t SizeInBitsOverride = 0;
960 if (field->isBitField()) {
961 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
962 assert(SizeInBitsOverride && "found named 0-width bitfield");
965 llvm::DIType *fieldType =
966 createFieldType(name, type, SizeInBitsOverride, field->getLocation(),
967 field->getAccess(), OffsetInBits, tunit, RecordTy, RD);
969 elements.push_back(fieldType);
972 /// CollectRecordFields - A helper function to collect debug info for
973 /// record fields. This is used while creating debug info entry for a Record.
974 void CGDebugInfo::CollectRecordFields(
975 const RecordDecl *record, llvm::DIFile *tunit,
976 SmallVectorImpl<llvm::Metadata *> &elements,
977 llvm::DICompositeType *RecordTy) {
978 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
980 if (CXXDecl && CXXDecl->isLambda())
981 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
983 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
985 // Field number for non-static fields.
986 unsigned fieldNo = 0;
988 // Static and non-static members should appear in the same order as
989 // the corresponding declarations in the source program.
990 for (const auto *I : record->decls())
991 if (const auto *V = dyn_cast<VarDecl>(I)) {
992 // Reuse the existing static member declaration if one exists
993 auto MI = StaticDataMemberCache.find(V->getCanonicalDecl());
994 if (MI != StaticDataMemberCache.end()) {
996 "Static data member declaration should still exist");
997 elements.push_back(cast<llvm::DIDerivedTypeBase>(MI->second));
999 auto Field = CreateRecordStaticField(V, RecordTy, record);
1000 elements.push_back(Field);
1002 } else if (const auto *field = dyn_cast<FieldDecl>(I)) {
1003 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo), tunit,
1004 elements, RecordTy, record);
1006 // Bump field number for next field.
1012 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
1013 /// function type is not updated to include implicit "this" pointer. Use this
1014 /// routine to get a method type which includes "this" pointer.
1015 llvm::DISubroutineType *
1016 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
1017 llvm::DIFile *Unit) {
1018 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
1019 if (Method->isStatic())
1020 return cast_or_null<llvm::DISubroutineType>(
1021 getOrCreateType(QualType(Func, 0), Unit));
1022 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
1026 llvm::DISubroutineType *CGDebugInfo::getOrCreateInstanceMethodType(
1027 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile *Unit) {
1028 // Add "this" pointer.
1029 llvm::DITypeRefArray Args(
1030 cast<llvm::DISubroutineType>(getOrCreateType(QualType(Func, 0), Unit))
1032 assert(Args.size() && "Invalid number of arguments!");
1034 SmallVector<llvm::Metadata *, 16> Elts;
1036 // First element is always return type. For 'void' functions it is NULL.
1037 Elts.push_back(Args[0]);
1039 // "this" pointer is always first argument.
1040 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
1041 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1042 // Create pointer type directly in this case.
1043 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1044 QualType PointeeTy = ThisPtrTy->getPointeeType();
1045 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
1046 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
1047 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1048 llvm::DIType *PointeeType = getOrCreateType(PointeeTy, Unit);
1049 llvm::DIType *ThisPtrType =
1050 DBuilder.createPointerType(PointeeType, Size, Align);
1051 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1052 // TODO: This and the artificial type below are misleading, the
1053 // types aren't artificial the argument is, but the current
1054 // metadata doesn't represent that.
1055 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1056 Elts.push_back(ThisPtrType);
1058 llvm::DIType *ThisPtrType = getOrCreateType(ThisPtr, Unit);
1059 TypeCache[ThisPtr.getAsOpaquePtr()].reset(ThisPtrType);
1060 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1061 Elts.push_back(ThisPtrType);
1064 // Copy rest of the arguments.
1065 for (unsigned i = 1, e = Args.size(); i != e; ++i)
1066 Elts.push_back(Args[i]);
1068 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
1071 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1072 Flags |= llvm::DINode::FlagLValueReference;
1073 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1074 Flags |= llvm::DINode::FlagRValueReference;
1076 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
1079 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1080 /// inside a function.
1081 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1082 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1083 return isFunctionLocalClass(NRD);
1084 if (isa<FunctionDecl>(RD->getDeclContext()))
1089 /// CreateCXXMemberFunction - A helper function to create a subprogram for
1090 /// a single member function GlobalDecl.
1091 llvm::DISubprogram *CGDebugInfo::CreateCXXMemberFunction(
1092 const CXXMethodDecl *Method, llvm::DIFile *Unit, llvm::DIType *RecordTy) {
1094 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1096 StringRef MethodName = getFunctionName(Method);
1097 llvm::DISubroutineType *MethodTy = getOrCreateMethodType(Method, Unit);
1099 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1100 // make sense to give a single ctor/dtor a linkage name.
1101 StringRef MethodLinkageName;
1102 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1103 MethodLinkageName = CGM.getMangledName(Method);
1105 // Get the location for the method.
1106 llvm::DIFile *MethodDefUnit = nullptr;
1107 unsigned MethodLine = 0;
1108 if (!Method->isImplicit()) {
1109 MethodDefUnit = getOrCreateFile(Method->getLocation());
1110 MethodLine = getLineNumber(Method->getLocation());
1113 // Collect virtual method info.
1114 llvm::DIType *ContainingType = nullptr;
1115 unsigned Virtuality = 0;
1116 unsigned VIndex = 0;
1118 if (Method->isVirtual()) {
1119 if (Method->isPure())
1120 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1122 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1124 // It doesn't make sense to give a virtual destructor a vtable index,
1125 // since a single destructor has two entries in the vtable.
1126 // FIXME: Add proper support for debug info for virtual calls in
1127 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1128 // lookup if we have multiple or virtual inheritance.
1129 if (!isa<CXXDestructorDecl>(Method) &&
1130 !CGM.getTarget().getCXXABI().isMicrosoft())
1131 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1132 ContainingType = RecordTy;
1136 if (Method->isImplicit())
1137 Flags |= llvm::DINode::FlagArtificial;
1138 Flags |= getAccessFlag(Method->getAccess(), Method->getParent());
1139 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1140 if (CXXC->isExplicit())
1141 Flags |= llvm::DINode::FlagExplicit;
1142 } else if (const CXXConversionDecl *CXXC =
1143 dyn_cast<CXXConversionDecl>(Method)) {
1144 if (CXXC->isExplicit())
1145 Flags |= llvm::DINode::FlagExplicit;
1147 if (Method->hasPrototype())
1148 Flags |= llvm::DINode::FlagPrototyped;
1149 if (Method->getRefQualifier() == RQ_LValue)
1150 Flags |= llvm::DINode::FlagLValueReference;
1151 if (Method->getRefQualifier() == RQ_RValue)
1152 Flags |= llvm::DINode::FlagRValueReference;
1154 llvm::DINodeArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1155 llvm::DISubprogram *SP = DBuilder.createMethod(
1156 RecordTy, MethodName, MethodLinkageName, MethodDefUnit, MethodLine,
1157 MethodTy, /*isLocalToUnit=*/false,
1158 /* isDefinition=*/false, Virtuality, VIndex, ContainingType, Flags,
1159 CGM.getLangOpts().Optimize, nullptr, TParamsArray.get());
1161 SPCache[Method->getCanonicalDecl()].reset(SP);
1166 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1167 /// C++ member functions. This is used while creating debug info entry for
1169 void CGDebugInfo::CollectCXXMemberFunctions(
1170 const CXXRecordDecl *RD, llvm::DIFile *Unit,
1171 SmallVectorImpl<llvm::Metadata *> &EltTys, llvm::DIType *RecordTy) {
1173 // Since we want more than just the individual member decls if we
1174 // have templated functions iterate over every declaration to gather
1176 for (const auto *I : RD->decls()) {
1177 const auto *Method = dyn_cast<CXXMethodDecl>(I);
1178 // If the member is implicit, don't add it to the member list. This avoids
1179 // the member being added to type units by LLVM, while still allowing it
1180 // to be emitted into the type declaration/reference inside the compile
1182 // FIXME: Handle Using(Shadow?)Decls here to create
1183 // DW_TAG_imported_declarations inside the class for base decls brought into
1184 // derived classes. GDB doesn't seem to notice/leverage these when I tried
1185 // it, so I'm not rushing to fix this. (GCC seems to produce them, if
1187 if (!Method || Method->isImplicit())
1190 if (Method->getType()->getAs<FunctionProtoType>()->getContainedAutoType())
1193 // Reuse the existing member function declaration if it exists.
1194 // It may be associated with the declaration of the type & should be
1195 // reused as we're building the definition.
1197 // This situation can arise in the vtable-based debug info reduction where
1198 // implicit members are emitted in a non-vtable TU.
1199 auto MI = SPCache.find(Method->getCanonicalDecl());
1200 EltTys.push_back(MI == SPCache.end()
1201 ? CreateCXXMemberFunction(Method, Unit, RecordTy)
1202 : static_cast<llvm::Metadata *>(MI->second));
1206 /// CollectCXXBases - A helper function to collect debug info for
1207 /// C++ base classes. This is used while creating debug info entry for
1209 void CGDebugInfo::CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1210 SmallVectorImpl<llvm::Metadata *> &EltTys,
1211 llvm::DIType *RecordTy) {
1212 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1213 for (const auto &BI : RD->bases()) {
1214 unsigned BFlags = 0;
1215 uint64_t BaseOffset;
1217 const CXXRecordDecl *Base =
1218 cast<CXXRecordDecl>(BI.getType()->getAs<RecordType>()->getDecl());
1220 if (BI.isVirtual()) {
1221 if (CGM.getTarget().getCXXABI().isItaniumFamily()) {
1222 // virtual base offset offset is -ve. The code generator emits dwarf
1223 // expression where it expects +ve number.
1224 BaseOffset = 0 - CGM.getItaniumVTableContext()
1225 .getVirtualBaseOffsetOffset(RD, Base)
1228 // In the MS ABI, store the vbtable offset, which is analogous to the
1229 // vbase offset offset in Itanium.
1231 4 * CGM.getMicrosoftVTableContext().getVBTableIndex(RD, Base);
1233 BFlags = llvm::DINode::FlagVirtual;
1235 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1236 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1237 // BI->isVirtual() and bits when not.
1239 BFlags |= getAccessFlag(BI.getAccessSpecifier(), RD);
1240 llvm::DIType *DTy = DBuilder.createInheritance(
1241 RecordTy, getOrCreateType(BI.getType(), Unit), BaseOffset, BFlags);
1242 EltTys.push_back(DTy);
1246 /// CollectTemplateParams - A helper function to collect template parameters.
1248 CGDebugInfo::CollectTemplateParams(const TemplateParameterList *TPList,
1249 ArrayRef<TemplateArgument> TAList,
1250 llvm::DIFile *Unit) {
1251 SmallVector<llvm::Metadata *, 16> TemplateParams;
1252 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1253 const TemplateArgument &TA = TAList[i];
1256 Name = TPList->getParam(i)->getName();
1257 switch (TA.getKind()) {
1258 case TemplateArgument::Type: {
1259 llvm::DIType *TTy = getOrCreateType(TA.getAsType(), Unit);
1260 TemplateParams.push_back(
1261 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy));
1263 case TemplateArgument::Integral: {
1264 llvm::DIType *TTy = getOrCreateType(TA.getIntegralType(), Unit);
1265 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1267 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral())));
1269 case TemplateArgument::Declaration: {
1270 const ValueDecl *D = TA.getAsDecl();
1271 QualType T = TA.getParamTypeForDecl().getDesugaredType(CGM.getContext());
1272 llvm::DIType *TTy = getOrCreateType(T, Unit);
1273 llvm::Constant *V = nullptr;
1274 const CXXMethodDecl *MD;
1275 // Variable pointer template parameters have a value that is the address
1277 if (const auto *VD = dyn_cast<VarDecl>(D))
1278 V = CGM.GetAddrOfGlobalVar(VD);
1279 // Member function pointers have special support for building them, though
1280 // this is currently unsupported in LLVM CodeGen.
1281 else if ((MD = dyn_cast<CXXMethodDecl>(D)) && MD->isInstance())
1282 V = CGM.getCXXABI().EmitMemberPointer(MD);
1283 else if (const auto *FD = dyn_cast<FunctionDecl>(D))
1284 V = CGM.GetAddrOfFunction(FD);
1285 // Member data pointers have special handling too to compute the fixed
1286 // offset within the object.
1287 else if (const auto *MPT = dyn_cast<MemberPointerType>(T.getTypePtr())) {
1288 // These five lines (& possibly the above member function pointer
1289 // handling) might be able to be refactored to use similar code in
1290 // CodeGenModule::getMemberPointerConstant
1291 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1293 CGM.getContext().toCharUnitsFromBits((int64_t)fieldOffset);
1294 V = CGM.getCXXABI().EmitMemberDataPointer(MPT, chars);
1296 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1298 cast_or_null<llvm::Constant>(V->stripPointerCasts())));
1300 case TemplateArgument::NullPtr: {
1301 QualType T = TA.getNullPtrType();
1302 llvm::DIType *TTy = getOrCreateType(T, Unit);
1303 llvm::Constant *V = nullptr;
1304 // Special case member data pointer null values since they're actually -1
1306 if (const MemberPointerType *MPT =
1307 dyn_cast<MemberPointerType>(T.getTypePtr()))
1308 // But treat member function pointers as simple zero integers because
1309 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1310 // CodeGen grows handling for values of non-null member function
1311 // pointers then perhaps we could remove this special case and rely on
1312 // EmitNullMemberPointer for member function pointers.
1313 if (MPT->isMemberDataPointer())
1314 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1316 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1317 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1318 TheCU, Name, TTy, cast<llvm::Constant>(V)));
1320 case TemplateArgument::Template:
1321 TemplateParams.push_back(DBuilder.createTemplateTemplateParameter(
1322 TheCU, Name, nullptr,
1323 TA.getAsTemplate().getAsTemplateDecl()->getQualifiedNameAsString()));
1325 case TemplateArgument::Pack:
1326 TemplateParams.push_back(DBuilder.createTemplateParameterPack(
1327 TheCU, Name, nullptr,
1328 CollectTemplateParams(nullptr, TA.getPackAsArray(), Unit)));
1330 case TemplateArgument::Expression: {
1331 const Expr *E = TA.getAsExpr();
1332 QualType T = E->getType();
1334 T = CGM.getContext().getLValueReferenceType(T);
1335 llvm::Constant *V = CGM.EmitConstantExpr(E, T);
1336 assert(V && "Expression in template argument isn't constant");
1337 llvm::DIType *TTy = getOrCreateType(T, Unit);
1338 TemplateParams.push_back(DBuilder.createTemplateValueParameter(
1339 TheCU, Name, TTy, cast<llvm::Constant>(V->stripPointerCasts())));
1341 // And the following should never occur:
1342 case TemplateArgument::TemplateExpansion:
1343 case TemplateArgument::Null:
1345 "These argument types shouldn't exist in concrete types");
1348 return DBuilder.getOrCreateArray(TemplateParams);
1351 /// CollectFunctionTemplateParams - A helper function to collect debug
1352 /// info for function template parameters.
1354 CGDebugInfo::CollectFunctionTemplateParams(const FunctionDecl *FD,
1355 llvm::DIFile *Unit) {
1356 if (FD->getTemplatedKind() ==
1357 FunctionDecl::TK_FunctionTemplateSpecialization) {
1358 const TemplateParameterList *TList = FD->getTemplateSpecializationInfo()
1360 ->getTemplateParameters();
1361 return CollectTemplateParams(
1362 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1364 return llvm::DINodeArray();
1367 /// CollectCXXTemplateParams - A helper function to collect debug info for
1368 /// template parameters.
1369 llvm::DINodeArray CGDebugInfo::CollectCXXTemplateParams(
1370 const ClassTemplateSpecializationDecl *TSpecial, llvm::DIFile *Unit) {
1371 // Always get the full list of parameters, not just the ones from
1372 // the specialization.
1373 TemplateParameterList *TPList =
1374 TSpecial->getSpecializedTemplate()->getTemplateParameters();
1375 const TemplateArgumentList &TAList = TSpecial->getTemplateArgs();
1376 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1379 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1380 llvm::DIType *CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile *Unit) {
1382 return VTablePtrType;
1384 ASTContext &Context = CGM.getContext();
1387 llvm::Metadata *STy = getOrCreateType(Context.IntTy, Unit);
1388 llvm::DITypeRefArray SElements = DBuilder.getOrCreateTypeArray(STy);
1389 llvm::DIType *SubTy = DBuilder.createSubroutineType(Unit, SElements);
1390 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1391 llvm::DIType *vtbl_ptr_type =
1392 DBuilder.createPointerType(SubTy, Size, 0, "__vtbl_ptr_type");
1393 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1394 return VTablePtrType;
1397 /// getVTableName - Get vtable name for the given Class.
1398 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1399 // Copy the gdb compatible name on the side and use its reference.
1400 return internString("_vptr$", RD->getNameAsString());
1403 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1404 /// debug info entry in EltTys vector.
1405 void CGDebugInfo::CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile *Unit,
1406 SmallVectorImpl<llvm::Metadata *> &EltTys) {
1407 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1409 // If there is a primary base then it will hold vtable info.
1410 if (RL.getPrimaryBase())
1413 // If this class is not dynamic then there is not any vtable info to collect.
1414 if (!RD->isDynamicClass())
1417 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1418 llvm::DIType *VPTR = DBuilder.createMemberType(
1419 Unit, getVTableName(RD), Unit, 0, Size, 0, 0,
1420 llvm::DINode::FlagArtificial, getOrCreateVTablePtrType(Unit));
1421 EltTys.push_back(VPTR);
1424 /// getOrCreateRecordType - Emit record type's standalone debug info.
1425 llvm::DIType *CGDebugInfo::getOrCreateRecordType(QualType RTy,
1426 SourceLocation Loc) {
1427 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1428 llvm::DIType *T = getOrCreateType(RTy, getOrCreateFile(Loc));
1432 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1434 llvm::DIType *CGDebugInfo::getOrCreateInterfaceType(QualType D,
1435 SourceLocation Loc) {
1436 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1437 llvm::DIType *T = getOrCreateType(D, getOrCreateFile(Loc));
1438 RetainedTypes.push_back(D.getAsOpaquePtr());
1442 void CGDebugInfo::completeType(const EnumDecl *ED) {
1443 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1445 QualType Ty = CGM.getContext().getEnumType(ED);
1446 void *TyPtr = Ty.getAsOpaquePtr();
1447 auto I = TypeCache.find(TyPtr);
1448 if (I == TypeCache.end() || !cast<llvm::DIType>(I->second)->isForwardDecl())
1450 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<EnumType>());
1451 assert(!Res->isForwardDecl());
1452 TypeCache[TyPtr].reset(Res);
1455 void CGDebugInfo::completeType(const RecordDecl *RD) {
1456 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1457 !CGM.getLangOpts().CPlusPlus)
1458 completeRequiredType(RD);
1461 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1462 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1465 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1466 if (CXXDecl->isDynamicClass())
1469 QualType Ty = CGM.getContext().getRecordType(RD);
1470 llvm::DIType *T = getTypeOrNull(Ty);
1471 if (T && T->isForwardDecl())
1472 completeClassData(RD);
1475 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1476 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1478 QualType Ty = CGM.getContext().getRecordType(RD);
1479 void *TyPtr = Ty.getAsOpaquePtr();
1480 auto I = TypeCache.find(TyPtr);
1481 if (I != TypeCache.end() && !cast<llvm::DIType>(I->second)->isForwardDecl())
1483 llvm::DIType *Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1484 assert(!Res->isForwardDecl());
1485 TypeCache[TyPtr].reset(Res);
1488 static bool hasExplicitMemberDefinition(CXXRecordDecl::method_iterator I,
1489 CXXRecordDecl::method_iterator End) {
1490 for (; I != End; ++I)
1491 if (FunctionDecl *Tmpl = I->getInstantiatedFromMemberFunction())
1492 if (!Tmpl->isImplicit() && Tmpl->isThisDeclarationADefinition() &&
1493 !I->getMemberSpecializationInfo()->isExplicitSpecialization())
1498 static bool shouldOmitDefinition(CodeGenOptions::DebugInfoKind DebugKind,
1499 const RecordDecl *RD,
1500 const LangOptions &LangOpts) {
1501 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
1504 if (!LangOpts.CPlusPlus)
1507 if (!RD->isCompleteDefinitionRequired())
1510 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1515 if (CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())
1518 TemplateSpecializationKind Spec = TSK_Undeclared;
1519 if (const ClassTemplateSpecializationDecl *SD =
1520 dyn_cast<ClassTemplateSpecializationDecl>(RD))
1521 Spec = SD->getSpecializationKind();
1523 if (Spec == TSK_ExplicitInstantiationDeclaration &&
1524 hasExplicitMemberDefinition(CXXDecl->method_begin(),
1525 CXXDecl->method_end()))
1531 /// CreateType - get structure or union type.
1532 llvm::DIType *CGDebugInfo::CreateType(const RecordType *Ty) {
1533 RecordDecl *RD = Ty->getDecl();
1534 llvm::DIType *T = cast_or_null<llvm::DIType>(getTypeOrNull(QualType(Ty, 0)));
1535 if (T || shouldOmitDefinition(DebugKind, RD, CGM.getLangOpts())) {
1537 T = getOrCreateRecordFwdDecl(
1538 Ty, getContextDescriptor(cast<Decl>(RD->getDeclContext())));
1542 return CreateTypeDefinition(Ty);
1545 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1546 RecordDecl *RD = Ty->getDecl();
1548 // Get overall information about the record type for the debug info.
1549 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
1551 // Records and classes and unions can all be recursive. To handle them, we
1552 // first generate a debug descriptor for the struct as a forward declaration.
1553 // Then (if it is a definition) we go through and get debug info for all of
1554 // its members. Finally, we create a descriptor for the complete type (which
1555 // may refer to the forward decl if the struct is recursive) and replace all
1556 // uses of the forward declaration with the final definition.
1559 cast<llvm::DICompositeType>(getOrCreateLimitedType(Ty, DefUnit));
1561 const RecordDecl *D = RD->getDefinition();
1562 if (!D || !D->isCompleteDefinition())
1565 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1566 CollectContainingType(CXXDecl, FwdDecl);
1568 // Push the struct on region stack.
1569 LexicalBlockStack.emplace_back(&*FwdDecl);
1570 RegionMap[Ty->getDecl()].reset(FwdDecl);
1572 // Convert all the elements.
1573 SmallVector<llvm::Metadata *, 16> EltTys;
1574 // what about nested types?
1576 // Note: The split of CXXDecl information here is intentional, the
1577 // gdb tests will depend on a certain ordering at printout. The debug
1578 // information offsets are still correct if we merge them all together
1580 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1582 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1583 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1586 // Collect data fields (including static variables and any initializers).
1587 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1589 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1591 LexicalBlockStack.pop_back();
1592 RegionMap.erase(Ty->getDecl());
1594 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1595 DBuilder.replaceArrays(FwdDecl, Elements);
1597 if (FwdDecl->isTemporary())
1599 llvm::MDNode::replaceWithPermanent(llvm::TempDICompositeType(FwdDecl));
1601 RegionMap[Ty->getDecl()].reset(FwdDecl);
1605 /// CreateType - get objective-c object type.
1606 llvm::DIType *CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1607 llvm::DIFile *Unit) {
1608 // Ignore protocols.
1609 return getOrCreateType(Ty->getBaseType(), Unit);
1612 /// \return true if Getter has the default name for the property PD.
1613 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1614 const ObjCMethodDecl *Getter) {
1619 assert(Getter->getDeclName().isObjCZeroArgSelector());
1620 return PD->getName() ==
1621 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1624 /// \return true if Setter has the default name for the property PD.
1625 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1626 const ObjCMethodDecl *Setter) {
1631 assert(Setter->getDeclName().isObjCOneArgSelector());
1632 return SelectorTable::constructSetterName(PD->getName()) ==
1633 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1636 /// CreateType - get objective-c interface type.
1637 llvm::DIType *CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1638 llvm::DIFile *Unit) {
1639 ObjCInterfaceDecl *ID = Ty->getDecl();
1643 // Get overall information about the record type for the debug info.
1644 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1645 unsigned Line = getLineNumber(ID->getLocation());
1647 static_cast<llvm::dwarf::SourceLanguage>(TheCU->getSourceLanguage());
1649 // If this is just a forward declaration return a special forward-declaration
1650 // debug type since we won't be able to lay out the entire type.
1651 ObjCInterfaceDecl *Def = ID->getDefinition();
1652 if (!Def || !Def->getImplementation()) {
1653 llvm::DIType *FwdDecl = DBuilder.createReplaceableCompositeType(
1654 llvm::dwarf::DW_TAG_structure_type, ID->getName(), TheCU, DefUnit, Line,
1656 ObjCInterfaceCache.push_back(ObjCInterfaceCacheEntry(Ty, FwdDecl, Unit));
1660 return CreateTypeDefinition(Ty, Unit);
1663 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const ObjCInterfaceType *Ty,
1664 llvm::DIFile *Unit) {
1665 ObjCInterfaceDecl *ID = Ty->getDecl();
1666 llvm::DIFile *DefUnit = getOrCreateFile(ID->getLocation());
1667 unsigned Line = getLineNumber(ID->getLocation());
1668 unsigned RuntimeLang = TheCU->getSourceLanguage();
1670 // Bit size, align and offset of the type.
1671 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1672 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1675 if (ID->getImplementation())
1676 Flags |= llvm::DINode::FlagObjcClassComplete;
1678 llvm::DICompositeType *RealDecl = DBuilder.createStructType(
1679 Unit, ID->getName(), DefUnit, Line, Size, Align, Flags, nullptr,
1680 llvm::DINodeArray(), RuntimeLang);
1682 QualType QTy(Ty, 0);
1683 TypeCache[QTy.getAsOpaquePtr()].reset(RealDecl);
1685 // Push the struct on region stack.
1686 LexicalBlockStack.emplace_back(RealDecl);
1687 RegionMap[Ty->getDecl()].reset(RealDecl);
1689 // Convert all the elements.
1690 SmallVector<llvm::Metadata *, 16> EltTys;
1692 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1694 llvm::DIType *SClassTy =
1695 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1699 llvm::DIType *InhTag = DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1700 EltTys.push_back(InhTag);
1703 // Create entries for all of the properties.
1704 for (const auto *PD : ID->properties()) {
1705 SourceLocation Loc = PD->getLocation();
1706 llvm::DIFile *PUnit = getOrCreateFile(Loc);
1707 unsigned PLine = getLineNumber(Loc);
1708 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1709 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1710 llvm::MDNode *PropertyNode = DBuilder.createObjCProperty(
1711 PD->getName(), PUnit, PLine,
1712 hasDefaultGetterName(PD, Getter) ? ""
1713 : getSelectorName(PD->getGetterName()),
1714 hasDefaultSetterName(PD, Setter) ? ""
1715 : getSelectorName(PD->getSetterName()),
1716 PD->getPropertyAttributes(), getOrCreateType(PD->getType(), PUnit));
1717 EltTys.push_back(PropertyNode);
1720 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1721 unsigned FieldNo = 0;
1722 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1723 Field = Field->getNextIvar(), ++FieldNo) {
1724 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
1728 StringRef FieldName = Field->getName();
1730 // Ignore unnamed fields.
1731 if (FieldName.empty())
1734 // Get the location for the field.
1735 llvm::DIFile *FieldDefUnit = getOrCreateFile(Field->getLocation());
1736 unsigned FieldLine = getLineNumber(Field->getLocation());
1737 QualType FType = Field->getType();
1738 uint64_t FieldSize = 0;
1739 unsigned FieldAlign = 0;
1741 if (!FType->isIncompleteArrayType()) {
1743 // Bit size, align and offset of the type.
1744 FieldSize = Field->isBitField()
1745 ? Field->getBitWidthValue(CGM.getContext())
1746 : CGM.getContext().getTypeSize(FType);
1747 FieldAlign = CGM.getContext().getTypeAlign(FType);
1750 uint64_t FieldOffset;
1751 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1752 // We don't know the runtime offset of an ivar if we're using the
1753 // non-fragile ABI. For bitfields, use the bit offset into the first
1754 // byte of storage of the bitfield. For other fields, use zero.
1755 if (Field->isBitField()) {
1757 CGM.getObjCRuntime().ComputeBitfieldBitOffset(CGM, ID, Field);
1758 FieldOffset %= CGM.getContext().getCharWidth();
1763 FieldOffset = RL.getFieldOffset(FieldNo);
1767 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1768 Flags = llvm::DINode::FlagProtected;
1769 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1770 Flags = llvm::DINode::FlagPrivate;
1771 else if (Field->getAccessControl() == ObjCIvarDecl::Public)
1772 Flags = llvm::DINode::FlagPublic;
1774 llvm::MDNode *PropertyNode = nullptr;
1775 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1776 if (ObjCPropertyImplDecl *PImpD =
1777 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1778 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1779 SourceLocation Loc = PD->getLocation();
1780 llvm::DIFile *PUnit = getOrCreateFile(Loc);
1781 unsigned PLine = getLineNumber(Loc);
1782 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1783 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1784 PropertyNode = DBuilder.createObjCProperty(
1785 PD->getName(), PUnit, PLine,
1786 hasDefaultGetterName(PD, Getter) ? "" : getSelectorName(
1787 PD->getGetterName()),
1788 hasDefaultSetterName(PD, Setter) ? "" : getSelectorName(
1789 PD->getSetterName()),
1790 PD->getPropertyAttributes(),
1791 getOrCreateType(PD->getType(), PUnit));
1795 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit, FieldLine,
1796 FieldSize, FieldAlign, FieldOffset, Flags,
1797 FieldTy, PropertyNode);
1798 EltTys.push_back(FieldTy);
1801 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
1802 DBuilder.replaceArrays(RealDecl, Elements);
1804 LexicalBlockStack.pop_back();
1808 llvm::DIType *CGDebugInfo::CreateType(const VectorType *Ty,
1809 llvm::DIFile *Unit) {
1810 llvm::DIType *ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1811 int64_t Count = Ty->getNumElements();
1813 // If number of elements are not known then this is an unbounded array.
1814 // Use Count == -1 to express such arrays.
1817 llvm::Metadata *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1818 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1820 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1821 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1823 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1826 llvm::DIType *CGDebugInfo::CreateType(const ArrayType *Ty, llvm::DIFile *Unit) {
1830 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1831 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1834 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1835 } else if (Ty->isIncompleteArrayType()) {
1837 if (Ty->getElementType()->isIncompleteType())
1840 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1841 } else if (Ty->isIncompleteType()) {
1845 // Size and align of the whole array, not the element type.
1846 Size = CGM.getContext().getTypeSize(Ty);
1847 Align = CGM.getContext().getTypeAlign(Ty);
1850 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1851 // interior arrays, do we care? Why aren't nested arrays represented the
1852 // obvious/recursive way?
1853 SmallVector<llvm::Metadata *, 8> Subscripts;
1854 QualType EltTy(Ty, 0);
1855 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1856 // If the number of elements is known, then count is that number. Otherwise,
1857 // it's -1. This allows us to represent a subrange with an array of 0
1858 // elements, like this:
1863 int64_t Count = -1; // Count == -1 is an unbounded array.
1864 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1865 Count = CAT->getSize().getZExtValue();
1867 // FIXME: Verify this is right for VLAs.
1868 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1869 EltTy = Ty->getElementType();
1872 llvm::DINodeArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1874 return DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1878 llvm::DIType *CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1879 llvm::DIFile *Unit) {
1880 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type, Ty,
1881 Ty->getPointeeType(), Unit);
1884 llvm::DIType *CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1885 llvm::DIFile *Unit) {
1886 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type, Ty,
1887 Ty->getPointeeType(), Unit);
1890 llvm::DIType *CGDebugInfo::CreateType(const MemberPointerType *Ty,
1892 uint64_t Size = CGM.getCXXABI().isTypeInfoCalculable(QualType(Ty, 0))
1893 ? CGM.getContext().getTypeSize(Ty)
1895 llvm::DIType *ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1896 if (Ty->isMemberDataPointerType())
1897 return DBuilder.createMemberPointerType(
1898 getOrCreateType(Ty->getPointeeType(), U), ClassType, Size);
1900 const FunctionProtoType *FPT =
1901 Ty->getPointeeType()->getAs<FunctionProtoType>();
1902 return DBuilder.createMemberPointerType(
1903 getOrCreateInstanceMethodType(CGM.getContext().getPointerType(QualType(
1904 Ty->getClass(), FPT->getTypeQuals())),
1909 llvm::DIType *CGDebugInfo::CreateType(const AtomicType *Ty, llvm::DIFile *U) {
1910 // Ignore the atomic wrapping
1911 // FIXME: What is the correct representation?
1912 return getOrCreateType(Ty->getValueType(), U);
1915 /// CreateEnumType - get enumeration type.
1916 llvm::DIType *CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1917 const EnumDecl *ED = Ty->getDecl();
1920 if (!ED->getTypeForDecl()->isIncompleteType()) {
1921 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1922 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1925 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1927 // If this is just a forward declaration, construct an appropriately
1928 // marked node and just return it.
1929 if (!ED->getDefinition()) {
1930 llvm::DIScope *EDContext =
1931 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1932 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1933 unsigned Line = getLineNumber(ED->getLocation());
1934 StringRef EDName = ED->getName();
1935 llvm::DIType *RetTy = DBuilder.createReplaceableCompositeType(
1936 llvm::dwarf::DW_TAG_enumeration_type, EDName, EDContext, DefUnit, Line,
1937 0, Size, Align, llvm::DINode::FlagFwdDecl, FullName);
1938 ReplaceMap.emplace_back(
1939 std::piecewise_construct, std::make_tuple(Ty),
1940 std::make_tuple(static_cast<llvm::Metadata *>(RetTy)));
1944 return CreateTypeDefinition(Ty);
1947 llvm::DIType *CGDebugInfo::CreateTypeDefinition(const EnumType *Ty) {
1948 const EnumDecl *ED = Ty->getDecl();
1951 if (!ED->getTypeForDecl()->isIncompleteType()) {
1952 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1953 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1956 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1958 // Create elements for each enumerator.
1959 SmallVector<llvm::Metadata *, 16> Enumerators;
1960 ED = ED->getDefinition();
1961 for (const auto *Enum : ED->enumerators()) {
1962 Enumerators.push_back(DBuilder.createEnumerator(
1963 Enum->getName(), Enum->getInitVal().getSExtValue()));
1966 // Return a CompositeType for the enum itself.
1967 llvm::DINodeArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1969 llvm::DIFile *DefUnit = getOrCreateFile(ED->getLocation());
1970 unsigned Line = getLineNumber(ED->getLocation());
1971 llvm::DIScope *EnumContext =
1972 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1973 llvm::DIType *ClassTy =
1974 ED->isFixed() ? getOrCreateType(ED->getIntegerType(), DefUnit) : nullptr;
1975 return DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit,
1976 Line, Size, Align, EltArray, ClassTy,
1980 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1983 Qualifiers InnerQuals = T.getLocalQualifiers();
1984 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1985 // that is already there.
1986 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1987 Quals += InnerQuals;
1989 switch (T->getTypeClass()) {
1991 return C.getQualifiedType(T.getTypePtr(), Quals);
1992 case Type::TemplateSpecialization: {
1993 const auto *Spec = cast<TemplateSpecializationType>(T);
1994 if (Spec->isTypeAlias())
1995 return C.getQualifiedType(T.getTypePtr(), Quals);
1996 T = Spec->desugar();
1999 case Type::TypeOfExpr:
2000 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
2003 T = cast<TypeOfType>(T)->getUnderlyingType();
2005 case Type::Decltype:
2006 T = cast<DecltypeType>(T)->getUnderlyingType();
2008 case Type::UnaryTransform:
2009 T = cast<UnaryTransformType>(T)->getUnderlyingType();
2011 case Type::Attributed:
2012 T = cast<AttributedType>(T)->getEquivalentType();
2014 case Type::Elaborated:
2015 T = cast<ElaboratedType>(T)->getNamedType();
2018 T = cast<ParenType>(T)->getInnerType();
2020 case Type::SubstTemplateTypeParm:
2021 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
2024 QualType DT = cast<AutoType>(T)->getDeducedType();
2025 assert(!DT.isNull() && "Undeduced types shouldn't reach here.");
2030 assert(T != LastT && "Type unwrapping failed to unwrap!");
2035 /// getType - Get the type from the cache or return null type if it doesn't
2037 llvm::DIType *CGDebugInfo::getTypeOrNull(QualType Ty) {
2039 // Unwrap the type as needed for debug information.
2040 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2042 auto it = TypeCache.find(Ty.getAsOpaquePtr());
2043 if (it != TypeCache.end()) {
2044 // Verify that the debug info still exists.
2045 if (llvm::Metadata *V = it->second)
2046 return cast<llvm::DIType>(V);
2052 void CGDebugInfo::completeTemplateDefinition(
2053 const ClassTemplateSpecializationDecl &SD) {
2054 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2057 completeClassData(&SD);
2058 // In case this type has no member function definitions being emitted, ensure
2060 RetainedTypes.push_back(CGM.getContext().getRecordType(&SD).getAsOpaquePtr());
2063 /// getOrCreateType - Get the type from the cache or create a new
2064 /// one if necessary.
2065 llvm::DIType *CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile *Unit) {
2069 // Unwrap the type as needed for debug information.
2070 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2072 if (auto *T = getTypeOrNull(Ty))
2075 // Otherwise create the type.
2076 llvm::DIType *Res = CreateTypeNode(Ty, Unit);
2077 void *TyPtr = Ty.getAsOpaquePtr();
2079 // And update the type cache.
2080 TypeCache[TyPtr].reset(Res);
2085 /// Currently the checksum of an interface includes the number of
2086 /// ivars and property accessors.
2087 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2088 // The assumption is that the number of ivars can only increase
2089 // monotonically, so it is safe to just use their current number as
2092 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2093 Ivar != nullptr; Ivar = Ivar->getNextIvar())
2099 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2100 switch (Ty->getTypeClass()) {
2101 case Type::ObjCObjectPointer:
2102 return getObjCInterfaceDecl(
2103 cast<ObjCObjectPointerType>(Ty)->getPointeeType());
2104 case Type::ObjCInterface:
2105 return cast<ObjCInterfaceType>(Ty)->getDecl();
2111 /// CreateTypeNode - Create a new debug type node.
2112 llvm::DIType *CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile *Unit) {
2113 // Handle qualifiers, which recursively handles what they refer to.
2114 if (Ty.hasLocalQualifiers())
2115 return CreateQualifiedType(Ty, Unit);
2117 // Work out details of type.
2118 switch (Ty->getTypeClass()) {
2119 #define TYPE(Class, Base)
2120 #define ABSTRACT_TYPE(Class, Base)
2121 #define NON_CANONICAL_TYPE(Class, Base)
2122 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2123 #include "clang/AST/TypeNodes.def"
2124 llvm_unreachable("Dependent types cannot show up in debug information");
2126 case Type::ExtVector:
2128 return CreateType(cast<VectorType>(Ty), Unit);
2129 case Type::ObjCObjectPointer:
2130 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2131 case Type::ObjCObject:
2132 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2133 case Type::ObjCInterface:
2134 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2136 return CreateType(cast<BuiltinType>(Ty));
2138 return CreateType(cast<ComplexType>(Ty));
2140 return CreateType(cast<PointerType>(Ty), Unit);
2141 case Type::Adjusted:
2143 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
2145 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
2146 case Type::BlockPointer:
2147 return CreateType(cast<BlockPointerType>(Ty), Unit);
2149 return CreateType(cast<TypedefType>(Ty), Unit);
2151 return CreateType(cast<RecordType>(Ty));
2153 return CreateEnumType(cast<EnumType>(Ty));
2154 case Type::FunctionProto:
2155 case Type::FunctionNoProto:
2156 return CreateType(cast<FunctionType>(Ty), Unit);
2157 case Type::ConstantArray:
2158 case Type::VariableArray:
2159 case Type::IncompleteArray:
2160 return CreateType(cast<ArrayType>(Ty), Unit);
2162 case Type::LValueReference:
2163 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2164 case Type::RValueReference:
2165 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2167 case Type::MemberPointer:
2168 return CreateType(cast<MemberPointerType>(Ty), Unit);
2171 return CreateType(cast<AtomicType>(Ty), Unit);
2173 case Type::TemplateSpecialization:
2174 return CreateType(cast<TemplateSpecializationType>(Ty), Unit);
2177 case Type::Attributed:
2178 case Type::Elaborated:
2180 case Type::SubstTemplateTypeParm:
2181 case Type::TypeOfExpr:
2183 case Type::Decltype:
2184 case Type::UnaryTransform:
2185 case Type::PackExpansion:
2189 llvm_unreachable("type should have been unwrapped!");
2192 /// getOrCreateLimitedType - Get the type from the cache or create a new
2193 /// limited type if necessary.
2194 llvm::DIType *CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2195 llvm::DIFile *Unit) {
2196 QualType QTy(Ty, 0);
2198 auto *T = cast_or_null<llvm::DICompositeTypeBase>(getTypeOrNull(QTy));
2200 // We may have cached a forward decl when we could have created
2201 // a non-forward decl. Go ahead and create a non-forward decl
2203 if (T && !T->isForwardDecl())
2206 // Otherwise create the type.
2207 llvm::DICompositeType *Res = CreateLimitedType(Ty);
2209 // Propagate members from the declaration to the definition
2210 // CreateType(const RecordType*) will overwrite this with the members in the
2211 // correct order if the full type is needed.
2212 DBuilder.replaceArrays(Res, T ? T->getElements() : llvm::DINodeArray());
2214 // And update the type cache.
2215 TypeCache[QTy.getAsOpaquePtr()].reset(Res);
2219 // TODO: Currently used for context chains when limiting debug info.
2220 llvm::DICompositeType *CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2221 RecordDecl *RD = Ty->getDecl();
2223 // Get overall information about the record type for the debug info.
2224 llvm::DIFile *DefUnit = getOrCreateFile(RD->getLocation());
2225 unsigned Line = getLineNumber(RD->getLocation());
2226 StringRef RDName = getClassName(RD);
2228 llvm::DIScope *RDContext =
2229 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2231 // If we ended up creating the type during the context chain construction,
2232 // just return that.
2233 auto *T = cast_or_null<llvm::DICompositeType>(
2234 getTypeOrNull(CGM.getContext().getRecordType(RD)));
2235 if (T && (!T->isForwardDecl() || !RD->getDefinition()))
2238 // If this is just a forward or incomplete declaration, construct an
2239 // appropriately marked node and just return it.
2240 const RecordDecl *D = RD->getDefinition();
2241 if (!D || !D->isCompleteDefinition())
2242 return getOrCreateRecordFwdDecl(Ty, RDContext);
2244 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2245 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2247 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2249 llvm::DICompositeType *RealDecl = DBuilder.createReplaceableCompositeType(
2250 getTagForRecord(RD), RDName, RDContext, DefUnit, Line, 0, Size, Align, 0,
2253 RegionMap[Ty->getDecl()].reset(RealDecl);
2254 TypeCache[QualType(Ty, 0).getAsOpaquePtr()].reset(RealDecl);
2256 if (const ClassTemplateSpecializationDecl *TSpecial =
2257 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2258 DBuilder.replaceArrays(RealDecl, llvm::DINodeArray(),
2259 CollectCXXTemplateParams(TSpecial, DefUnit));
2263 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2264 llvm::DICompositeType *RealDecl) {
2265 // A class's primary base or the class itself contains the vtable.
2266 llvm::DICompositeType *ContainingType = nullptr;
2267 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2268 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2269 // Seek non-virtual primary base root.
2271 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2272 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2273 if (PBT && !BRL.isPrimaryBaseVirtual())
2278 ContainingType = cast<llvm::DICompositeType>(
2279 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2280 getOrCreateFile(RD->getLocation())));
2281 } else if (RD->isDynamicClass())
2282 ContainingType = RealDecl;
2284 DBuilder.replaceVTableHolder(RealDecl, ContainingType);
2287 /// CreateMemberType - Create new member and increase Offset by FType's size.
2288 llvm::DIType *CGDebugInfo::CreateMemberType(llvm::DIFile *Unit, QualType FType,
2289 StringRef Name, uint64_t *Offset) {
2290 llvm::DIType *FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2291 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2292 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2293 llvm::DIType *Ty = DBuilder.createMemberType(Unit, Name, Unit, 0, FieldSize,
2294 FieldAlign, *Offset, 0, FieldTy);
2295 *Offset += FieldSize;
2299 void CGDebugInfo::collectFunctionDeclProps(GlobalDecl GD, llvm::DIFile *Unit,
2301 StringRef &LinkageName,
2302 llvm::DIScope *&FDContext,
2303 llvm::DINodeArray &TParamsArray,
2305 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2306 Name = getFunctionName(FD);
2307 // Use mangled name as linkage name for C/C++ functions.
2308 if (FD->hasPrototype()) {
2309 LinkageName = CGM.getMangledName(GD);
2310 Flags |= llvm::DINode::FlagPrototyped;
2312 // No need to replicate the linkage name if it isn't different from the
2313 // subprogram name, no need to have it at all unless coverage is enabled or
2314 // debug is set to more than just line tables.
2315 if (LinkageName == Name ||
2316 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2317 !CGM.getCodeGenOpts().EmitGcovNotes &&
2318 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2319 LinkageName = StringRef();
2321 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2322 if (const NamespaceDecl *NSDecl =
2323 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2324 FDContext = getOrCreateNameSpace(NSDecl);
2325 else if (const RecordDecl *RDecl =
2326 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2327 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2328 // Collect template parameters.
2329 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2333 void CGDebugInfo::collectVarDeclProps(const VarDecl *VD, llvm::DIFile *&Unit,
2334 unsigned &LineNo, QualType &T,
2335 StringRef &Name, StringRef &LinkageName,
2336 llvm::DIScope *&VDContext) {
2337 Unit = getOrCreateFile(VD->getLocation());
2338 LineNo = getLineNumber(VD->getLocation());
2340 setLocation(VD->getLocation());
2343 if (T->isIncompleteArrayType()) {
2344 // CodeGen turns int[] into int[1] so we'll do the same here.
2345 llvm::APInt ConstVal(32, 1);
2346 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2348 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2349 ArrayType::Normal, 0);
2352 Name = VD->getName();
2353 if (VD->getDeclContext() && !isa<FunctionDecl>(VD->getDeclContext()) &&
2354 !isa<ObjCMethodDecl>(VD->getDeclContext()))
2355 LinkageName = CGM.getMangledName(VD);
2356 if (LinkageName == Name)
2357 LinkageName = StringRef();
2359 // Since we emit declarations (DW_AT_members) for static members, place the
2360 // definition of those static members in the namespace they were declared in
2361 // in the source code (the lexical decl context).
2362 // FIXME: Generalize this for even non-member global variables where the
2363 // declaration and definition may have different lexical decl contexts, once
2364 // we have support for emitting declarations of (non-member) global variables.
2365 const DeclContext *DC = VD->isStaticDataMember() ? VD->getLexicalDeclContext()
2366 : VD->getDeclContext();
2367 // When a record type contains an in-line initialization of a static data
2368 // member, and the record type is marked as __declspec(dllexport), an implicit
2369 // definition of the member will be created in the record context. DWARF
2370 // doesn't seem to have a nice way to describe this in a form that consumers
2371 // are likely to understand, so fake the "normal" situation of a definition
2372 // outside the class by putting it in the global scope.
2374 DC = CGM.getContext().getTranslationUnitDecl();
2375 VDContext = getContextDescriptor(dyn_cast<Decl>(DC));
2378 llvm::DISubprogram *
2379 CGDebugInfo::getFunctionForwardDeclaration(const FunctionDecl *FD) {
2380 llvm::DINodeArray TParamsArray;
2381 StringRef Name, LinkageName;
2383 SourceLocation Loc = FD->getLocation();
2384 llvm::DIFile *Unit = getOrCreateFile(Loc);
2385 llvm::DIScope *DContext = Unit;
2386 unsigned Line = getLineNumber(Loc);
2388 collectFunctionDeclProps(FD, Unit, Name, LinkageName, DContext,
2389 TParamsArray, Flags);
2390 // Build function type.
2391 SmallVector<QualType, 16> ArgTypes;
2392 for (const ParmVarDecl *Parm: FD->parameters())
2393 ArgTypes.push_back(Parm->getType());
2395 CGM.getContext().getFunctionType(FD->getReturnType(), ArgTypes,
2396 FunctionProtoType::ExtProtoInfo());
2397 llvm::DISubprogram *SP = DBuilder.createTempFunctionFwdDecl(
2398 DContext, Name, LinkageName, Unit, Line,
2399 getOrCreateFunctionType(FD, FnType, Unit), !FD->isExternallyVisible(),
2400 false /*declaration*/, 0, Flags, CGM.getLangOpts().Optimize, nullptr,
2401 TParamsArray.get(), getFunctionDeclaration(FD));
2402 const FunctionDecl *CanonDecl = cast<FunctionDecl>(FD->getCanonicalDecl());
2403 FwdDeclReplaceMap.emplace_back(std::piecewise_construct,
2404 std::make_tuple(CanonDecl),
2405 std::make_tuple(SP));
2409 llvm::DIGlobalVariable *
2410 CGDebugInfo::getGlobalVariableForwardDeclaration(const VarDecl *VD) {
2412 StringRef Name, LinkageName;
2413 SourceLocation Loc = VD->getLocation();
2414 llvm::DIFile *Unit = getOrCreateFile(Loc);
2415 llvm::DIScope *DContext = Unit;
2416 unsigned Line = getLineNumber(Loc);
2418 collectVarDeclProps(VD, Unit, Line, T, Name, LinkageName, DContext);
2419 auto *GV = DBuilder.createTempGlobalVariableFwdDecl(
2420 DContext, Name, LinkageName, Unit, Line, getOrCreateType(T, Unit),
2421 !VD->isExternallyVisible(), nullptr, nullptr);
2422 FwdDeclReplaceMap.emplace_back(
2423 std::piecewise_construct,
2424 std::make_tuple(cast<VarDecl>(VD->getCanonicalDecl())),
2425 std::make_tuple(static_cast<llvm::Metadata *>(GV)));
2429 llvm::DINode *CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2430 // We only need a declaration (not a definition) of the type - so use whatever
2431 // we would otherwise do to get a type for a pointee. (forward declarations in
2432 // limited debug info, full definitions (if the type definition is available)
2433 // in unlimited debug info)
2434 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2435 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2436 getOrCreateFile(TD->getLocation()));
2437 auto I = DeclCache.find(D->getCanonicalDecl());
2439 if (I != DeclCache.end())
2440 return dyn_cast_or_null<llvm::DINode>(I->second);
2442 // No definition for now. Emit a forward definition that might be
2443 // merged with a potential upcoming definition.
2444 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D))
2445 return getFunctionForwardDeclaration(FD);
2446 else if (const auto *VD = dyn_cast<VarDecl>(D))
2447 return getGlobalVariableForwardDeclaration(VD);
2452 /// getFunctionDeclaration - Return debug info descriptor to describe method
2453 /// declaration for the given method definition.
2454 llvm::DISubprogram *CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2455 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2458 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2463 auto *S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2465 auto MI = SPCache.find(FD->getCanonicalDecl());
2466 if (MI == SPCache.end()) {
2467 if (const CXXMethodDecl *MD =
2468 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2469 return CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()),
2470 cast<llvm::DICompositeType>(S));
2473 if (MI != SPCache.end()) {
2474 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2475 if (SP && !SP->isDefinition())
2479 for (auto NextFD : FD->redecls()) {
2480 auto MI = SPCache.find(NextFD->getCanonicalDecl());
2481 if (MI != SPCache.end()) {
2482 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(MI->second);
2483 if (SP && !SP->isDefinition())
2490 // getOrCreateFunctionType - Construct type. If it is a c++ method, include
2491 // implicit parameter "this".
2492 llvm::DISubroutineType *CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2495 if (!D || DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2496 // Create fake but valid subroutine type. Otherwise -verify would fail, and
2497 // subprogram DIE will miss DW_AT_decl_file and DW_AT_decl_line fields.
2498 return DBuilder.createSubroutineType(F,
2499 DBuilder.getOrCreateTypeArray(None));
2501 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2502 return getOrCreateMethodType(Method, F);
2503 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2504 // Add "self" and "_cmd"
2505 SmallVector<llvm::Metadata *, 16> Elts;
2507 // First element is always return type. For 'void' functions it is NULL.
2508 QualType ResultTy = OMethod->getReturnType();
2510 // Replace the instancetype keyword with the actual type.
2511 if (ResultTy == CGM.getContext().getObjCInstanceType())
2512 ResultTy = CGM.getContext().getPointerType(
2513 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2515 Elts.push_back(getOrCreateType(ResultTy, F));
2516 // "self" pointer is always first argument.
2517 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2518 Elts.push_back(CreateSelfType(SelfDeclTy, getOrCreateType(SelfDeclTy, F)));
2519 // "_cmd" pointer is always second argument.
2520 Elts.push_back(DBuilder.createArtificialType(
2521 getOrCreateType(OMethod->getCmdDecl()->getType(), F)));
2522 // Get rest of the arguments.
2523 for (const auto *PI : OMethod->params())
2524 Elts.push_back(getOrCreateType(PI->getType(), F));
2525 // Variadic methods need a special marker at the end of the type list.
2526 if (OMethod->isVariadic())
2527 Elts.push_back(DBuilder.createUnspecifiedParameter());
2529 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(Elts);
2530 return DBuilder.createSubroutineType(F, EltTypeArray);
2533 // Handle variadic function types; they need an additional
2534 // unspecified parameter.
2535 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2536 if (FD->isVariadic()) {
2537 SmallVector<llvm::Metadata *, 16> EltTys;
2538 EltTys.push_back(getOrCreateType(FD->getReturnType(), F));
2539 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2540 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
2541 EltTys.push_back(getOrCreateType(FPT->getParamType(i), F));
2542 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2543 llvm::DITypeRefArray EltTypeArray = DBuilder.getOrCreateTypeArray(EltTys);
2544 return DBuilder.createSubroutineType(F, EltTypeArray);
2547 return cast<llvm::DISubroutineType>(getOrCreateType(FnType, F));
2550 /// EmitFunctionStart - Constructs the debug code for entering a function.
2551 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, SourceLocation Loc,
2552 SourceLocation ScopeLoc, QualType FnType,
2553 llvm::Function *Fn, CGBuilderTy &Builder) {
2556 StringRef LinkageName;
2558 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2560 const Decl *D = GD.getDecl();
2561 bool HasDecl = (D != nullptr);
2564 llvm::DIFile *Unit = getOrCreateFile(Loc);
2565 llvm::DIScope *FDContext = Unit;
2566 llvm::DINodeArray TParamsArray;
2568 // Use llvm function name.
2569 LinkageName = Fn->getName();
2570 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2571 // If there is a subprogram for this function available then use it.
2572 auto FI = SPCache.find(FD->getCanonicalDecl());
2573 if (FI != SPCache.end()) {
2574 auto *SP = dyn_cast_or_null<llvm::DISubprogram>(FI->second);
2575 if (SP && SP->isDefinition()) {
2576 LexicalBlockStack.emplace_back(SP);
2577 RegionMap[D].reset(SP);
2581 collectFunctionDeclProps(GD, Unit, Name, LinkageName, FDContext,
2582 TParamsArray, Flags);
2583 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2584 Name = getObjCMethodName(OMD);
2585 Flags |= llvm::DINode::FlagPrototyped;
2587 // Use llvm function name.
2588 Name = Fn->getName();
2589 Flags |= llvm::DINode::FlagPrototyped;
2591 if (!Name.empty() && Name[0] == '\01')
2592 Name = Name.substr(1);
2594 if (!HasDecl || D->isImplicit()) {
2595 Flags |= llvm::DINode::FlagArtificial;
2596 // Artificial functions without a location should not silently reuse CurLoc.
2597 if (Loc.isInvalid())
2598 CurLoc = SourceLocation();
2600 unsigned LineNo = getLineNumber(Loc);
2601 unsigned ScopeLine = getLineNumber(ScopeLoc);
2603 // FIXME: The function declaration we're constructing here is mostly reusing
2604 // declarations from CXXMethodDecl and not constructing new ones for arbitrary
2605 // FunctionDecls. When/if we fix this we can have FDContext be TheCU/null for
2606 // all subprograms instead of the actual context since subprogram definitions
2607 // are emitted as CU level entities by the backend.
2608 llvm::DISubprogram *SP = DBuilder.createFunction(
2609 FDContext, Name, LinkageName, Unit, LineNo,
2610 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2611 true /*definition*/, ScopeLine, Flags, CGM.getLangOpts().Optimize, Fn,
2612 TParamsArray.get(), getFunctionDeclaration(D));
2613 // We might get here with a VarDecl in the case we're generating
2614 // code for the initialization of globals. Do not record these decls
2615 // as they will overwrite the actual VarDecl Decl in the cache.
2616 if (HasDecl && isa<FunctionDecl>(D))
2617 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(SP));
2619 // Push the function onto the lexical block stack.
2620 LexicalBlockStack.emplace_back(SP);
2623 RegionMap[D].reset(SP);
2626 /// EmitLocation - Emit metadata to indicate a change in line/column
2627 /// information in the source file. If the location is invalid, the
2628 /// previous location will be reused.
2629 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2630 // Update our current location
2633 if (CurLoc.isInvalid() || CurLoc.isMacroID())
2636 llvm::MDNode *Scope = LexicalBlockStack.back();
2637 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2638 getLineNumber(CurLoc), getColumnNumber(CurLoc), Scope));
2641 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2643 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2644 llvm::MDNode *Back = nullptr;
2645 if (!LexicalBlockStack.empty())
2646 Back = LexicalBlockStack.back().get();
2647 LexicalBlockStack.emplace_back(DBuilder.createLexicalBlock(
2648 cast<llvm::DIScope>(Back), getOrCreateFile(CurLoc), getLineNumber(CurLoc),
2649 getColumnNumber(CurLoc)));
2652 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2653 /// region - beginning of a DW_TAG_lexical_block.
2654 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2655 SourceLocation Loc) {
2656 // Set our current location.
2659 // Emit a line table change for the current location inside the new scope.
2660 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(
2661 getLineNumber(Loc), getColumnNumber(Loc), LexicalBlockStack.back()));
2663 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2666 // Create a new lexical block and push it on the stack.
2667 CreateLexicalBlock(Loc);
2670 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2671 /// region - end of a DW_TAG_lexical_block.
2672 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2673 SourceLocation Loc) {
2674 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2676 // Provide an entry in the line table for the end of the block.
2677 EmitLocation(Builder, Loc);
2679 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
2682 LexicalBlockStack.pop_back();
2685 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2686 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2687 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2688 unsigned RCount = FnBeginRegionCount.back();
2689 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2691 // Pop all regions for this function.
2692 while (LexicalBlockStack.size() != RCount) {
2693 // Provide an entry in the line table for the end of the block.
2694 EmitLocation(Builder, CurLoc);
2695 LexicalBlockStack.pop_back();
2697 FnBeginRegionCount.pop_back();
2700 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2701 // See BuildByRefType.
2702 llvm::DIType *CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2703 uint64_t *XOffset) {
2705 SmallVector<llvm::Metadata *, 5> EltTys;
2707 uint64_t FieldSize, FieldOffset;
2708 unsigned FieldAlign;
2710 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2711 QualType Type = VD->getType();
2714 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2715 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2716 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2717 FType = CGM.getContext().IntTy;
2718 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2719 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2721 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2722 if (HasCopyAndDispose) {
2723 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2725 CreateMemberType(Unit, FType, "__copy_helper", &FieldOffset));
2727 CreateMemberType(Unit, FType, "__destroy_helper", &FieldOffset));
2729 bool HasByrefExtendedLayout;
2730 Qualifiers::ObjCLifetime Lifetime;
2731 if (CGM.getContext().getByrefLifetime(Type, Lifetime,
2732 HasByrefExtendedLayout) &&
2733 HasByrefExtendedLayout) {
2734 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2736 CreateMemberType(Unit, FType, "__byref_variable_layout", &FieldOffset));
2739 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2740 if (Align > CGM.getContext().toCharUnitsFromBits(
2741 CGM.getTarget().getPointerAlign(0))) {
2742 CharUnits FieldOffsetInBytes =
2743 CGM.getContext().toCharUnitsFromBits(FieldOffset);
2744 CharUnits AlignedOffsetInBytes =
2745 FieldOffsetInBytes.RoundUpToAlignment(Align);
2746 CharUnits NumPaddingBytes = AlignedOffsetInBytes - FieldOffsetInBytes;
2748 if (NumPaddingBytes.isPositive()) {
2749 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2750 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2751 pad, ArrayType::Normal, 0);
2752 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2757 llvm::DIType *FieldTy = getOrCreateType(FType, Unit);
2758 FieldSize = CGM.getContext().getTypeSize(FType);
2759 FieldAlign = CGM.getContext().toBits(Align);
2761 *XOffset = FieldOffset;
2762 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit, 0, FieldSize,
2763 FieldAlign, FieldOffset, 0, FieldTy);
2764 EltTys.push_back(FieldTy);
2765 FieldOffset += FieldSize;
2767 llvm::DINodeArray Elements = DBuilder.getOrCreateArray(EltTys);
2769 unsigned Flags = llvm::DINode::FlagBlockByrefStruct;
2771 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2775 /// EmitDeclare - Emit local variable declaration debug info.
2776 void CGDebugInfo::EmitDeclare(const VarDecl *VD, llvm::dwarf::Tag Tag,
2777 llvm::Value *Storage, unsigned ArgNo,
2778 CGBuilderTy &Builder) {
2779 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2780 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2783 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2784 cast<Decl>(VD->getDeclContext())->isImplicit());
2785 llvm::DIFile *Unit = nullptr;
2787 Unit = getOrCreateFile(VD->getLocation());
2789 uint64_t XOffset = 0;
2790 if (VD->hasAttr<BlocksAttr>())
2791 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2793 Ty = getOrCreateType(VD->getType(), Unit);
2795 // If there is no debug info for this type then do not emit debug info
2796 // for this variable.
2800 // Get location information.
2802 unsigned Column = 0;
2804 Line = getLineNumber(VD->getLocation());
2805 Column = getColumnNumber(VD->getLocation());
2807 SmallVector<int64_t, 9> Expr;
2809 if (VD->isImplicit())
2810 Flags |= llvm::DINode::FlagArtificial;
2811 // If this is the first argument and it is implicit then
2812 // give it an object pointer flag.
2813 // FIXME: There has to be a better way to do this, but for static
2814 // functions there won't be an implicit param at arg1 and
2815 // otherwise it is 'self' or 'this'.
2816 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2817 Flags |= llvm::DINode::FlagObjectPointer;
2818 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2819 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2820 !VD->getType()->isPointerType())
2821 Expr.push_back(llvm::dwarf::DW_OP_deref);
2823 auto *Scope = cast<llvm::DIScope>(LexicalBlockStack.back());
2825 StringRef Name = VD->getName();
2826 if (!Name.empty()) {
2827 if (VD->hasAttr<BlocksAttr>()) {
2828 CharUnits offset = CharUnits::fromQuantity(32);
2829 Expr.push_back(llvm::dwarf::DW_OP_plus);
2830 // offset of __forwarding field
2831 offset = CGM.getContext().toCharUnitsFromBits(
2832 CGM.getTarget().getPointerWidth(0));
2833 Expr.push_back(offset.getQuantity());
2834 Expr.push_back(llvm::dwarf::DW_OP_deref);
2835 Expr.push_back(llvm::dwarf::DW_OP_plus);
2836 // offset of x field
2837 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2838 Expr.push_back(offset.getQuantity());
2840 // Create the descriptor for the variable.
2841 auto *D = DBuilder.createLocalVariable(Tag, Scope, VD->getName(), Unit,
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());
2849 } else if (isa<VariableArrayType>(VD->getType()))
2850 Expr.push_back(llvm::dwarf::DW_OP_deref);
2851 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2852 // If VD is an anonymous union then Storage represents value for
2853 // all union fields.
2854 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2855 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2856 // GDB has trouble finding local variables in anonymous unions, so we emit
2857 // artifical local variables for each of the members.
2859 // FIXME: Remove this code as soon as GDB supports this.
2860 // The debug info verifier in LLVM operates based on the assumption that a
2861 // variable has the same size as its storage and we had to disable the check
2862 // for artificial variables.
2863 for (const auto *Field : RD->fields()) {
2864 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
2865 StringRef FieldName = Field->getName();
2867 // Ignore unnamed fields. Do not ignore unnamed records.
2868 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2871 // Use VarDecl's Tag, Scope and Line number.
2872 auto *D = DBuilder.createLocalVariable(
2873 Tag, Scope, FieldName, Unit, Line, FieldTy,
2874 CGM.getLangOpts().Optimize, Flags | llvm::DINode::FlagArtificial,
2877 // Insert an llvm.dbg.declare into the current block.
2878 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2879 llvm::DebugLoc::get(Line, Column, Scope),
2880 Builder.GetInsertBlock());
2885 // Create the descriptor for the variable.
2887 DBuilder.createLocalVariable(Tag, Scope, Name, Unit, Line, Ty,
2888 CGM.getLangOpts().Optimize, Flags, ArgNo);
2890 // Insert an llvm.dbg.declare into the current block.
2891 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(Expr),
2892 llvm::DebugLoc::get(Line, Column, Scope),
2893 Builder.GetInsertBlock());
2896 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2897 llvm::Value *Storage,
2898 CGBuilderTy &Builder) {
2899 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2900 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2903 /// Look up the completed type for a self pointer in the TypeCache and
2904 /// create a copy of it with the ObjectPointer and Artificial flags
2905 /// set. If the type is not cached, a new one is created. This should
2906 /// never happen though, since creating a type for the implicit self
2907 /// argument implies that we already parsed the interface definition
2908 /// and the ivar declarations in the implementation.
2909 llvm::DIType *CGDebugInfo::CreateSelfType(const QualType &QualTy,
2911 llvm::DIType *CachedTy = getTypeOrNull(QualTy);
2914 return DBuilder.createObjectPointerType(Ty);
2917 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2918 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2919 const CGBlockInfo &blockInfo, llvm::Instruction *InsertPoint) {
2920 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2921 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2923 if (Builder.GetInsertBlock() == nullptr)
2926 bool isByRef = VD->hasAttr<BlocksAttr>();
2928 uint64_t XOffset = 0;
2929 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
2932 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2934 Ty = getOrCreateType(VD->getType(), Unit);
2936 // Self is passed along as an implicit non-arg variable in a
2937 // block. Mark it as the object pointer.
2938 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2939 Ty = CreateSelfType(VD->getType(), Ty);
2941 // Get location information.
2942 unsigned Line = getLineNumber(VD->getLocation());
2943 unsigned Column = getColumnNumber(VD->getLocation());
2945 const llvm::DataLayout &target = CGM.getDataLayout();
2947 CharUnits offset = CharUnits::fromQuantity(
2948 target.getStructLayout(blockInfo.StructureType)
2949 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2951 SmallVector<int64_t, 9> addr;
2952 if (isa<llvm::AllocaInst>(Storage))
2953 addr.push_back(llvm::dwarf::DW_OP_deref);
2954 addr.push_back(llvm::dwarf::DW_OP_plus);
2955 addr.push_back(offset.getQuantity());
2957 addr.push_back(llvm::dwarf::DW_OP_deref);
2958 addr.push_back(llvm::dwarf::DW_OP_plus);
2959 // offset of __forwarding field
2961 CGM.getContext().toCharUnitsFromBits(target.getPointerSizeInBits(0));
2962 addr.push_back(offset.getQuantity());
2963 addr.push_back(llvm::dwarf::DW_OP_deref);
2964 addr.push_back(llvm::dwarf::DW_OP_plus);
2965 // offset of x field
2966 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2967 addr.push_back(offset.getQuantity());
2970 // Create the descriptor for the variable.
2971 auto *D = DBuilder.createLocalVariable(
2972 llvm::dwarf::DW_TAG_auto_variable,
2973 cast<llvm::DILocalScope>(LexicalBlockStack.back()), VD->getName(), Unit,
2976 // Insert an llvm.dbg.declare into the current block.
2977 auto DL = llvm::DebugLoc::get(Line, Column, LexicalBlockStack.back());
2979 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2982 DBuilder.insertDeclare(Storage, D, DBuilder.createExpression(addr), DL,
2983 Builder.GetInsertBlock());
2986 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2987 /// variable declaration.
2988 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2990 CGBuilderTy &Builder) {
2991 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2992 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2996 struct BlockLayoutChunk {
2997 uint64_t OffsetInBits;
2998 const BlockDecl::Capture *Capture;
3000 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
3001 return l.OffsetInBits < r.OffsetInBits;
3005 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
3008 llvm::Value *LocalAddr,
3009 CGBuilderTy &Builder) {
3010 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3011 ASTContext &C = CGM.getContext();
3012 const BlockDecl *blockDecl = block.getBlockDecl();
3014 // Collect some general information about the block's location.
3015 SourceLocation loc = blockDecl->getCaretLocation();
3016 llvm::DIFile *tunit = getOrCreateFile(loc);
3017 unsigned line = getLineNumber(loc);
3018 unsigned column = getColumnNumber(loc);
3020 // Build the debug-info type for the block literal.
3021 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
3023 const llvm::StructLayout *blockLayout =
3024 CGM.getDataLayout().getStructLayout(block.StructureType);
3026 SmallVector<llvm::Metadata *, 16> fields;
3027 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
3028 blockLayout->getElementOffsetInBits(0),
3030 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
3031 blockLayout->getElementOffsetInBits(1),
3033 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
3034 blockLayout->getElementOffsetInBits(2),
3036 auto *FnTy = block.getBlockExpr()->getFunctionType();
3037 auto FnPtrType = CGM.getContext().getPointerType(FnTy->desugar());
3038 fields.push_back(createFieldType("__FuncPtr", FnPtrType, 0, loc, AS_public,
3039 blockLayout->getElementOffsetInBits(3),
3041 fields.push_back(createFieldType(
3042 "__descriptor", C.getPointerType(block.NeedsCopyDispose
3043 ? C.getBlockDescriptorExtendedType()
3044 : C.getBlockDescriptorType()),
3045 0, loc, AS_public, blockLayout->getElementOffsetInBits(4), tunit, tunit));
3047 // We want to sort the captures by offset, not because DWARF
3048 // requires this, but because we're paranoid about debuggers.
3049 SmallVector<BlockLayoutChunk, 8> chunks;
3052 if (blockDecl->capturesCXXThis()) {
3053 BlockLayoutChunk chunk;
3054 chunk.OffsetInBits =
3055 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
3056 chunk.Capture = nullptr;
3057 chunks.push_back(chunk);
3060 // Variable captures.
3061 for (const auto &capture : blockDecl->captures()) {
3062 const VarDecl *variable = capture.getVariable();
3063 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
3065 // Ignore constant captures.
3066 if (captureInfo.isConstant())
3069 BlockLayoutChunk chunk;
3070 chunk.OffsetInBits =
3071 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3072 chunk.Capture = &capture;
3073 chunks.push_back(chunk);
3077 llvm::array_pod_sort(chunks.begin(), chunks.end());
3079 for (SmallVectorImpl<BlockLayoutChunk>::iterator i = chunks.begin(),
3082 uint64_t offsetInBits = i->OffsetInBits;
3083 const BlockDecl::Capture *capture = i->Capture;
3085 // If we have a null capture, this must be the C++ 'this' capture.
3087 const CXXMethodDecl *method =
3088 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3089 QualType type = method->getThisType(C);
3091 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3092 offsetInBits, tunit, tunit));
3096 const VarDecl *variable = capture->getVariable();
3097 StringRef name = variable->getName();
3099 llvm::DIType *fieldType;
3100 if (capture->isByRef()) {
3101 TypeInfo PtrInfo = C.getTypeInfo(C.VoidPtrTy);
3103 // FIXME: this creates a second copy of this type!
3105 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3106 fieldType = DBuilder.createPointerType(fieldType, PtrInfo.Width);
3108 DBuilder.createMemberType(tunit, name, tunit, line, PtrInfo.Width,
3109 PtrInfo.Align, offsetInBits, 0, fieldType);
3111 fieldType = createFieldType(name, variable->getType(), 0, loc, AS_public,
3112 offsetInBits, tunit, tunit);
3114 fields.push_back(fieldType);
3117 SmallString<36> typeName;
3118 llvm::raw_svector_ostream(typeName) << "__block_literal_"
3119 << CGM.getUniqueBlockCount();
3121 llvm::DINodeArray fieldsArray = DBuilder.getOrCreateArray(fields);
3123 llvm::DIType *type = DBuilder.createStructType(
3124 tunit, typeName.str(), tunit, line,
3125 CGM.getContext().toBits(block.BlockSize),
3126 CGM.getContext().toBits(block.BlockAlign), 0, nullptr, fieldsArray);
3127 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3129 // Get overall information about the block.
3130 unsigned flags = llvm::DINode::FlagArtificial;
3131 auto *scope = cast<llvm::DILocalScope>(LexicalBlockStack.back());
3133 // Create the descriptor for the parameter.
3134 auto *debugVar = DBuilder.createLocalVariable(
3135 llvm::dwarf::DW_TAG_arg_variable, scope, Arg->getName(), tunit, line,
3136 type, CGM.getLangOpts().Optimize, flags, ArgNo);
3139 // Insert an llvm.dbg.value into the current block.
3140 DBuilder.insertDbgValueIntrinsic(
3141 LocalAddr, 0, debugVar, DBuilder.createExpression(),
3142 llvm::DebugLoc::get(line, column, scope), Builder.GetInsertBlock());
3145 // Insert an llvm.dbg.declare into the current block.
3146 DBuilder.insertDeclare(Arg, debugVar, DBuilder.createExpression(),
3147 llvm::DebugLoc::get(line, column, scope),
3148 Builder.GetInsertBlock());
3151 /// If D is an out-of-class definition of a static data member of a class, find
3152 /// its corresponding in-class declaration.
3153 llvm::DIDerivedType *
3154 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3155 if (!D->isStaticDataMember())
3158 auto MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3159 if (MI != StaticDataMemberCache.end()) {
3160 assert(MI->second && "Static data member declaration should still exist");
3161 return cast<llvm::DIDerivedType>(MI->second);
3164 // If the member wasn't found in the cache, lazily construct and add it to the
3165 // type (used when a limited form of the type is emitted).
3166 auto DC = D->getDeclContext();
3168 cast<llvm::DICompositeType>(getContextDescriptor(cast<Decl>(DC)));
3169 return CreateRecordStaticField(D, Ctxt, cast<RecordDecl>(DC));
3172 /// Recursively collect all of the member fields of a global anonymous decl and
3173 /// create static variables for them. The first time this is called it needs
3174 /// to be on a union and then from there we can have additional unnamed fields.
3175 llvm::DIGlobalVariable *CGDebugInfo::CollectAnonRecordDecls(
3176 const RecordDecl *RD, llvm::DIFile *Unit, unsigned LineNo,
3177 StringRef LinkageName, llvm::GlobalVariable *Var, llvm::DIScope *DContext) {
3178 llvm::DIGlobalVariable *GV = nullptr;
3180 for (const auto *Field : RD->fields()) {
3181 llvm::DIType *FieldTy = getOrCreateType(Field->getType(), Unit);
3182 StringRef FieldName = Field->getName();
3184 // Ignore unnamed fields, but recurse into anonymous records.
3185 if (FieldName.empty()) {
3186 const RecordType *RT = dyn_cast<RecordType>(Field->getType());
3188 GV = CollectAnonRecordDecls(RT->getDecl(), Unit, LineNo, LinkageName,
3192 // Use VarDecl's Tag, Scope and Line number.
3193 GV = DBuilder.createGlobalVariable(DContext, FieldName, LinkageName, Unit,
3195 Var->hasInternalLinkage(), Var, nullptr);
3200 /// EmitGlobalVariable - Emit information about a global variable.
3201 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3203 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3204 // Create global variable debug descriptor.
3205 llvm::DIFile *Unit = nullptr;
3206 llvm::DIScope *DContext = nullptr;
3208 StringRef DeclName, LinkageName;
3210 collectVarDeclProps(D, Unit, LineNo, T, DeclName, LinkageName, DContext);
3212 // Attempt to store one global variable for the declaration - even if we
3213 // emit a lot of fields.
3214 llvm::DIGlobalVariable *GV = nullptr;
3216 // If this is an anonymous union then we'll want to emit a global
3217 // variable for each member of the anonymous union so that it's possible
3218 // to find the name of any field in the union.
3219 if (T->isUnionType() && DeclName.empty()) {
3220 const RecordDecl *RD = cast<RecordType>(T)->getDecl();
3221 assert(RD->isAnonymousStructOrUnion() &&
3222 "unnamed non-anonymous struct or union?");
3223 GV = CollectAnonRecordDecls(RD, Unit, LineNo, LinkageName, Var, DContext);
3225 GV = DBuilder.createGlobalVariable(
3226 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3227 Var->hasInternalLinkage(), Var,
3228 getOrCreateStaticDataMemberDeclarationOrNull(D));
3230 DeclCache[D->getCanonicalDecl()].reset(static_cast<llvm::Metadata *>(GV));
3233 /// EmitGlobalVariable - Emit global variable's debug info.
3234 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3235 llvm::Constant *Init) {
3236 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3237 // Create the descriptor for the variable.
3238 llvm::DIFile *Unit = getOrCreateFile(VD->getLocation());
3239 StringRef Name = VD->getName();
3240 llvm::DIType *Ty = getOrCreateType(VD->getType(), Unit);
3241 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3242 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3243 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3244 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3246 // Do not use global variables for enums.
3249 if (Ty->getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3251 // Do not emit separate definitions for function local const/statics.
3252 if (isa<FunctionDecl>(VD->getDeclContext()))
3254 VD = cast<ValueDecl>(VD->getCanonicalDecl());
3255 auto *VarD = cast<VarDecl>(VD);
3256 if (VarD->isStaticDataMember()) {
3257 auto *RD = cast<RecordDecl>(VarD->getDeclContext());
3258 getContextDescriptor(RD);
3259 // Ensure that the type is retained even though it's otherwise unreferenced.
3260 RetainedTypes.push_back(
3261 CGM.getContext().getRecordType(RD).getAsOpaquePtr());
3265 llvm::DIScope *DContext =
3266 getContextDescriptor(dyn_cast<Decl>(VD->getDeclContext()));
3268 auto &GV = DeclCache[VD];
3271 GV.reset(DBuilder.createGlobalVariable(
3272 DContext, Name, StringRef(), Unit, getLineNumber(VD->getLocation()), Ty,
3273 true, Init, getOrCreateStaticDataMemberDeclarationOrNull(VarD)));
3276 llvm::DIScope *CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3277 if (!LexicalBlockStack.empty())
3278 return LexicalBlockStack.back();
3279 return getContextDescriptor(D);
3282 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3283 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3285 DBuilder.createImportedModule(
3286 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3287 getOrCreateNameSpace(UD.getNominatedNamespace()),
3288 getLineNumber(UD.getLocation()));
3291 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3292 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3294 assert(UD.shadow_size() &&
3295 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3296 // Emitting one decl is sufficient - debuggers can detect that this is an
3297 // overloaded name & provide lookup for all the overloads.
3298 const UsingShadowDecl &USD = **UD.shadow_begin();
3299 if (llvm::DINode *Target =
3300 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3301 DBuilder.createImportedDeclaration(
3302 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3303 getLineNumber(USD.getLocation()));
3306 llvm::DIImportedEntity *
3307 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3308 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3310 auto &VH = NamespaceAliasCache[&NA];
3312 return cast<llvm::DIImportedEntity>(VH);
3313 llvm::DIImportedEntity *R;
3314 if (const NamespaceAliasDecl *Underlying =
3315 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3316 // This could cache & dedup here rather than relying on metadata deduping.
3317 R = DBuilder.createImportedDeclaration(
3318 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3319 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3322 R = DBuilder.createImportedDeclaration(
3323 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3324 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3325 getLineNumber(NA.getLocation()), NA.getName());
3330 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3333 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3334 NSDecl = NSDecl->getCanonicalDecl();
3335 auto I = NameSpaceCache.find(NSDecl);
3336 if (I != NameSpaceCache.end())
3337 return cast<llvm::DINamespace>(I->second);
3339 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3340 llvm::DIFile *FileD = getOrCreateFile(NSDecl->getLocation());
3341 llvm::DIScope *Context =
3342 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3343 llvm::DINamespace *NS =
3344 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3345 NameSpaceCache[NSDecl].reset(NS);
3349 void CGDebugInfo::finalize() {
3350 // Creating types might create further types - invalidating the current
3351 // element and the size(), so don't cache/reference them.
3352 for (size_t i = 0; i != ObjCInterfaceCache.size(); ++i) {
3353 ObjCInterfaceCacheEntry E = ObjCInterfaceCache[i];
3354 llvm::DIType *Ty = E.Type->getDecl()->getDefinition()
3355 ? CreateTypeDefinition(E.Type, E.Unit)
3357 DBuilder.replaceTemporary(llvm::TempDIType(E.Decl), Ty);
3360 for (auto p : ReplaceMap) {
3362 auto *Ty = cast<llvm::DIType>(p.second);
3363 assert(Ty->isForwardDecl());
3365 auto it = TypeCache.find(p.first);
3366 assert(it != TypeCache.end());
3369 DBuilder.replaceTemporary(llvm::TempDIType(Ty),
3370 cast<llvm::DIType>(it->second));
3373 for (const auto &p : FwdDeclReplaceMap) {
3375 llvm::TempMDNode FwdDecl(cast<llvm::MDNode>(p.second));
3376 llvm::Metadata *Repl;
3378 auto it = DeclCache.find(p.first);
3379 // If there has been no definition for the declaration, call RAUW
3380 // with ourselves, that will destroy the temporary MDNode and
3381 // replace it with a standard one, avoiding leaking memory.
3382 if (it == DeclCache.end())
3387 DBuilder.replaceTemporary(std::move(FwdDecl), cast<llvm::MDNode>(Repl));
3390 // We keep our own list of retained types, because we need to look
3391 // up the final type in the type cache.
3392 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3393 RE = RetainedTypes.end(); RI != RE; ++RI)
3394 DBuilder.retainType(cast<llvm::DIType>(TypeCache[*RI]));
3396 DBuilder.finalize();
3399 void CGDebugInfo::EmitExplicitCastType(QualType Ty) {
3400 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3403 if (auto *DieTy = getOrCreateType(Ty, getOrCreateMainFile()))
3404 // Don't ignore in case of explicit cast where it is referenced indirectly.
3405 DBuilder.retainType(DieTy);