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"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Target/TargetData.h"
38 using namespace clang;
39 using namespace clang::CodeGen;
41 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
42 : CGM(CGM), DBuilder(CGM.getModule()),
43 BlockLiteralGenericSet(false) {
47 CGDebugInfo::~CGDebugInfo() {
48 assert(LexicalBlockStack.empty() &&
49 "Region stack mismatch, stack not empty!");
52 void CGDebugInfo::setLocation(SourceLocation Loc) {
53 // If the new location isn't valid return.
54 if (!Loc.isValid()) return;
56 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58 // If we've changed files in the middle of a lexical scope go ahead
59 // and create a new lexical scope with file node if it's different
60 // from the one in the scope.
61 if (LexicalBlockStack.empty()) return;
63 SourceManager &SM = CGM.getContext().getSourceManager();
64 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
65 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
67 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
68 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
71 llvm::MDNode *LB = LexicalBlockStack.back();
72 llvm::DIScope Scope = llvm::DIScope(LB);
73 if (Scope.isLexicalBlockFile()) {
74 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
76 = DBuilder.createLexicalBlockFile(LBF.getScope(),
77 getOrCreateFile(CurLoc));
79 LexicalBlockStack.pop_back();
80 LexicalBlockStack.push_back(N);
81 } else if (Scope.isLexicalBlock()) {
83 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
85 LexicalBlockStack.pop_back();
86 LexicalBlockStack.push_back(N);
90 /// getContextDescriptor - Get context info for the decl.
91 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
95 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
96 I = RegionMap.find(Context);
97 if (I != RegionMap.end()) {
98 llvm::Value *V = I->second;
99 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
103 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
104 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
106 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
107 if (!RDecl->isDependentType()) {
108 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
109 getOrCreateMainFile());
110 return llvm::DIDescriptor(Ty);
116 /// getFunctionName - Get function name for the given FunctionDecl. If the
117 /// name is constructred on demand (e.g. C++ destructor) then the name
118 /// is stored on the side.
119 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
120 assert (FD && "Invalid FunctionDecl!");
121 IdentifierInfo *FII = FD->getIdentifier();
122 FunctionTemplateSpecializationInfo *Info
123 = FD->getTemplateSpecializationInfo();
125 return FII->getName();
127 // Otherwise construct human readable name for debug info.
128 std::string NS = FD->getNameAsString();
130 // Add any template specialization args.
132 const TemplateArgumentList *TArgs = Info->TemplateArguments;
133 const TemplateArgument *Args = TArgs->data();
134 unsigned NumArgs = TArgs->size();
135 PrintingPolicy Policy(CGM.getLangOpts());
136 NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
141 // Copy this name on the side and use its reference.
142 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
143 memcpy(StrPtr, NS.data(), NS.length());
144 return StringRef(StrPtr, NS.length());
147 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
148 SmallString<256> MethodName;
149 llvm::raw_svector_ostream OS(MethodName);
150 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
151 const DeclContext *DC = OMD->getDeclContext();
152 if (const ObjCImplementationDecl *OID =
153 dyn_cast<const ObjCImplementationDecl>(DC)) {
154 OS << OID->getName();
155 } else if (const ObjCInterfaceDecl *OID =
156 dyn_cast<const ObjCInterfaceDecl>(DC)) {
157 OS << OID->getName();
158 } else if (const ObjCCategoryImplDecl *OCD =
159 dyn_cast<const ObjCCategoryImplDecl>(DC)){
160 OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
161 OCD->getIdentifier()->getNameStart() << ')';
163 OS << ' ' << OMD->getSelector().getAsString() << ']';
165 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
166 memcpy(StrPtr, MethodName.begin(), OS.tell());
167 return StringRef(StrPtr, OS.tell());
170 /// getSelectorName - Return selector name. This is used for debugging
172 StringRef CGDebugInfo::getSelectorName(Selector S) {
173 const std::string &SName = S.getAsString();
174 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
175 memcpy(StrPtr, SName.data(), SName.size());
176 return StringRef(StrPtr, SName.size());
179 /// getClassName - Get class name including template argument list.
181 CGDebugInfo::getClassName(const RecordDecl *RD) {
182 const ClassTemplateSpecializationDecl *Spec
183 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 return RD->getName();
187 const TemplateArgument *Args;
189 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
190 const TemplateSpecializationType *TST =
191 cast<TemplateSpecializationType>(TAW->getType());
192 Args = TST->getArgs();
193 NumArgs = TST->getNumArgs();
195 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
196 Args = TemplateArgs.data();
197 NumArgs = TemplateArgs.size();
199 StringRef Name = RD->getIdentifier()->getName();
200 PrintingPolicy Policy(CGM.getLangOpts());
201 std::string TemplateArgList =
202 TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
204 // Copy this name on the side and use its reference.
205 size_t Length = Name.size() + TemplateArgList.size();
206 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
207 memcpy(StrPtr, Name.data(), Name.size());
208 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
209 return StringRef(StrPtr, Length);
212 /// getOrCreateFile - Get the file debug info descriptor for the input location.
213 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
215 // If Location is not valid then use main input file.
216 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
218 SourceManager &SM = CGM.getContext().getSourceManager();
219 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
221 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
222 // If the location is not valid then use main input file.
223 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
225 // Cache the results.
226 const char *fname = PLoc.getFilename();
227 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
228 DIFileCache.find(fname);
230 if (it != DIFileCache.end()) {
231 // Verify that the information still exists.
232 if (llvm::Value *V = it->second)
233 return llvm::DIFile(cast<llvm::MDNode>(V));
236 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
238 DIFileCache[fname] = F;
242 /// getOrCreateMainFile - Get the file info for main compile unit.
243 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
244 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
247 /// getLineNumber - Get line number for the location. If location is invalid
248 /// then use current location.
249 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
250 if (Loc.isInvalid() && CurLoc.isInvalid())
252 SourceManager &SM = CGM.getContext().getSourceManager();
253 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
254 return PLoc.isValid()? PLoc.getLine() : 0;
257 /// getColumnNumber - Get column number for the location. If location is
258 /// invalid then use current location.
259 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
260 if (Loc.isInvalid() && CurLoc.isInvalid())
262 SourceManager &SM = CGM.getContext().getSourceManager();
263 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
264 return PLoc.isValid()? PLoc.getColumn() : 0;
267 StringRef CGDebugInfo::getCurrentDirname() {
268 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
269 return CGM.getCodeGenOpts().DebugCompilationDir;
271 if (!CWDName.empty())
273 SmallString<256> CWD;
274 llvm::sys::fs::current_path(CWD);
275 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
276 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
277 return CWDName = StringRef(CompDirnamePtr, CWD.size());
280 /// CreateCompileUnit - Create new compile unit.
281 void CGDebugInfo::CreateCompileUnit() {
283 // Get absolute path name.
284 SourceManager &SM = CGM.getContext().getSourceManager();
285 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
286 if (MainFileName.empty())
287 MainFileName = "<unknown>";
289 // The main file name provided via the "-main-file-name" option contains just
290 // the file name itself with no path information. This file name may have had
291 // a relative path, so we look into the actual file entry for the main
292 // file to determine the real absolute path for the file.
293 std::string MainFileDir;
294 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
295 MainFileDir = MainFile->getDir()->getName();
296 if (MainFileDir != ".")
297 MainFileName = MainFileDir + "/" + MainFileName;
300 // Save filename string.
301 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
302 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
303 StringRef Filename(FilenamePtr, MainFileName.length());
306 const LangOptions &LO = CGM.getLangOpts();
309 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
311 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
312 } else if (LO.ObjC1) {
313 LangTag = llvm::dwarf::DW_LANG_ObjC;
315 LangTag = llvm::dwarf::DW_LANG_C99;
317 LangTag = llvm::dwarf::DW_LANG_C89;
320 std::string Producer = getClangFullVersion();
322 // Figure out which version of the ObjC runtime we have.
323 unsigned RuntimeVers = 0;
325 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
327 // Create new compile unit.
328 DBuilder.createCompileUnit(
329 LangTag, Filename, getCurrentDirname(),
331 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
332 // FIXME - Eliminate TheCU.
333 TheCU = llvm::DICompileUnit(DBuilder.getCU());
336 /// CreateType - Get the Basic type from the cache or create a new
337 /// one if necessary.
338 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
339 unsigned Encoding = 0;
341 switch (BT->getKind()) {
342 #define BUILTIN_TYPE(Id, SingletonId)
343 #define PLACEHOLDER_TYPE(Id, SingletonId) \
344 case BuiltinType::Id:
345 #include "clang/AST/BuiltinTypes.def"
346 case BuiltinType::Dependent:
347 llvm_unreachable("Unexpected builtin type");
348 case BuiltinType::NullPtr:
350 createNullPtrType(BT->getName(CGM.getContext().getLangOpts()));
351 case BuiltinType::Void:
352 return llvm::DIType();
353 case BuiltinType::ObjCClass:
354 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
356 getOrCreateMainFile(), 0);
357 case BuiltinType::ObjCId: {
358 // typedef struct objc_class *Class;
359 // typedef struct objc_object {
363 // TODO: Cache these two types to avoid duplicates.
365 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
366 "objc_class", TheCU, getOrCreateMainFile(), 0);
367 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
369 llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
371 SmallVector<llvm::Value *, 16> EltTys;
372 llvm::DIType FieldTy =
373 DBuilder.createMemberType(getOrCreateMainFile(), "isa",
374 getOrCreateMainFile(), 0, Size,
376 EltTys.push_back(FieldTy);
377 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
379 return DBuilder.createStructType(TheCU, "objc_object",
380 getOrCreateMainFile(),
381 0, 0, 0, 0, Elements);
383 case BuiltinType::ObjCSel: {
385 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
386 "objc_selector", TheCU, getOrCreateMainFile(),
389 case BuiltinType::UChar:
390 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
391 case BuiltinType::Char_S:
392 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
393 case BuiltinType::Char16:
394 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
395 case BuiltinType::UShort:
396 case BuiltinType::UInt:
397 case BuiltinType::UInt128:
398 case BuiltinType::ULong:
399 case BuiltinType::WChar_U:
400 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
401 case BuiltinType::Short:
402 case BuiltinType::Int:
403 case BuiltinType::Int128:
404 case BuiltinType::Long:
405 case BuiltinType::WChar_S:
406 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
407 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
408 case BuiltinType::Half:
409 case BuiltinType::Float:
410 case BuiltinType::LongDouble:
411 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
414 switch (BT->getKind()) {
415 case BuiltinType::Long: BTName = "long int"; break;
416 case BuiltinType::LongLong: BTName = "long long int"; break;
417 case BuiltinType::ULong: BTName = "long unsigned int"; break;
418 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
420 BTName = BT->getName(CGM.getContext().getLangOpts());
423 // Bit size, align and offset of the type.
424 uint64_t Size = CGM.getContext().getTypeSize(BT);
425 uint64_t Align = CGM.getContext().getTypeAlign(BT);
427 DBuilder.createBasicType(BTName, Size, Align, Encoding);
431 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
432 // Bit size, align and offset of the type.
433 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
434 if (Ty->isComplexIntegerType())
435 Encoding = llvm::dwarf::DW_ATE_lo_user;
437 uint64_t Size = CGM.getContext().getTypeSize(Ty);
438 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
440 DBuilder.createBasicType("complex", Size, Align, Encoding);
445 /// CreateCVRType - Get the qualified type from the cache or create
446 /// a new one if necessary.
447 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
448 QualifierCollector Qc;
449 const Type *T = Qc.strip(Ty);
451 // Ignore these qualifiers for now.
452 Qc.removeObjCGCAttr();
453 Qc.removeAddressSpace();
454 Qc.removeObjCLifetime();
456 // We will create one Derived type for one qualifier and recurse to handle any
460 Tag = llvm::dwarf::DW_TAG_const_type;
462 } else if (Qc.hasVolatile()) {
463 Tag = llvm::dwarf::DW_TAG_volatile_type;
465 } else if (Qc.hasRestrict()) {
466 Tag = llvm::dwarf::DW_TAG_restrict_type;
469 assert(Qc.empty() && "Unknown type qualifier for debug info");
470 return getOrCreateType(QualType(T, 0), Unit);
473 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
475 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
476 // CVR derived types.
477 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
482 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
485 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
486 Ty->getPointeeType(), Unit);
490 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
492 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
493 Ty->getPointeeType(), Unit);
496 // Creates a forward declaration for a RecordDecl in the given context.
497 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
498 llvm::DIDescriptor Ctx) {
499 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
500 unsigned Line = getLineNumber(RD->getLocation());
501 StringRef RDName = RD->getName();
504 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
507 RDName = getClassName(RD);
508 Tag = llvm::dwarf::DW_TAG_class_type;
510 else if (RD->isStruct())
511 Tag = llvm::dwarf::DW_TAG_structure_type;
512 else if (RD->isUnion())
513 Tag = llvm::dwarf::DW_TAG_union_type;
515 llvm_unreachable("Unknown RecordDecl type!");
518 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
521 // Walk up the context chain and create forward decls for record decls,
522 // and normal descriptors for namespaces.
523 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
527 // See if we already have the parent.
528 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
529 I = RegionMap.find(Context);
530 if (I != RegionMap.end()) {
531 llvm::Value *V = I->second;
532 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
536 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
537 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
539 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
540 if (!RD->isDependentType()) {
541 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
542 getOrCreateMainFile());
543 return llvm::DIDescriptor(Ty);
549 /// CreatePointeeType - Create Pointee type. If Pointee is a record
550 /// then emit record's fwd if debug info size reduction is enabled.
551 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
553 if (CGM.getCodeGenOpts().DebugInfo != CodeGenOptions::LimitedDebugInfo)
554 return getOrCreateType(PointeeTy, Unit);
556 // Limit debug info for the pointee type.
558 // If we have an existing type, use that, it's still smaller than creating
560 llvm::DIType Ty = getTypeOrNull(PointeeTy);
561 if (Ty.Verify()) return Ty;
563 // Handle qualifiers.
564 if (PointeeTy.hasLocalQualifiers())
565 return CreateQualifiedType(PointeeTy, Unit);
567 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
568 RecordDecl *RD = RTy->getDecl();
569 llvm::DIDescriptor FDContext =
570 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
571 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
572 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
575 return getOrCreateType(PointeeTy, Unit);
579 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
583 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
584 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
585 return DBuilder.createReferenceType(Tag,
586 CreatePointeeType(PointeeTy, Unit));
588 // Bit size, align and offset of the type.
589 // Size is always the size of a pointer. We can't use getTypeSize here
590 // because that does not return the correct value for references.
591 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
592 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
593 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
595 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
599 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
601 if (BlockLiteralGenericSet)
602 return BlockLiteralGeneric;
604 SmallVector<llvm::Value *, 8> EltTys;
605 llvm::DIType FieldTy;
607 uint64_t FieldSize, FieldOffset;
609 llvm::DIArray Elements;
610 llvm::DIType EltTy, DescTy;
613 FType = CGM.getContext().UnsignedLongTy;
614 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
615 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
617 Elements = DBuilder.getOrCreateArray(EltTys);
620 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
621 unsigned LineNo = getLineNumber(CurLoc);
623 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
624 Unit, LineNo, FieldOffset, 0,
627 // Bit size, align and offset of the type.
628 uint64_t Size = CGM.getContext().getTypeSize(Ty);
630 DescTy = DBuilder.createPointerType(EltTy, Size);
633 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
634 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
635 FType = CGM.getContext().IntTy;
636 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
637 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
638 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
639 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
641 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
643 FieldSize = CGM.getContext().getTypeSize(Ty);
644 FieldAlign = CGM.getContext().getTypeAlign(Ty);
645 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
646 LineNo, FieldSize, FieldAlign,
647 FieldOffset, 0, FieldTy);
648 EltTys.push_back(FieldTy);
650 FieldOffset += FieldSize;
651 Elements = DBuilder.getOrCreateArray(EltTys);
653 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
654 Unit, LineNo, FieldOffset, 0,
657 BlockLiteralGenericSet = true;
658 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
659 return BlockLiteralGeneric;
662 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
663 // Typedefs are derived from some other type. If we have a typedef of a
664 // typedef, make sure to emit the whole chain.
665 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
667 return llvm::DIType();
668 // We don't set size information, but do specify where the typedef was
670 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
671 const TypedefNameDecl *TyDecl = Ty->getDecl();
673 llvm::DIDescriptor TypedefContext =
674 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
677 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
680 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
682 SmallVector<llvm::Value *, 16> EltTys;
684 // Add the result type at least.
685 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
687 // Set up remainder of arguments if there is a prototype.
688 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
689 if (isa<FunctionNoProtoType>(Ty))
690 EltTys.push_back(DBuilder.createUnspecifiedParameter());
691 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
692 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
693 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
696 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
697 return DBuilder.createSubroutineType(Unit, EltTypeArray);
702 CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
704 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
706 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
708 const APValue *Value = V->evaluateValue();
709 if (Value && Value->isInt()) {
710 llvm::ConstantInt *CI
711 = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
713 // Create the descriptor for static variable.
714 llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
715 StringRef VName = V->getName();
716 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
717 // Do not use DIGlobalVariable for enums.
718 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
719 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
720 getLineNumber(V->getLocation()),
728 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
730 uint64_t sizeInBitsOverride,
733 uint64_t offsetInBits,
735 llvm::DIDescriptor scope) {
736 llvm::DIType debugType = getOrCreateType(type, tunit);
738 // Get the location for the field.
739 llvm::DIFile file = getOrCreateFile(loc);
740 unsigned line = getLineNumber(loc);
742 uint64_t sizeInBits = 0;
743 unsigned alignInBits = 0;
744 if (!type->isIncompleteArrayType()) {
745 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
747 if (sizeInBitsOverride)
748 sizeInBits = sizeInBitsOverride;
752 if (AS == clang::AS_private)
753 flags |= llvm::DIDescriptor::FlagPrivate;
754 else if (AS == clang::AS_protected)
755 flags |= llvm::DIDescriptor::FlagProtected;
757 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
758 alignInBits, offsetInBits, flags, debugType);
761 /// CollectRecordFields - A helper function to collect debug info for
762 /// record fields. This is used while creating debug info entry for a Record.
764 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
765 SmallVectorImpl<llvm::Value *> &elements,
766 llvm::DIType RecordTy) {
767 unsigned fieldNo = 0;
768 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
769 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
771 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
772 // has the name and the location of the variable so we should iterate over
773 // both concurrently.
774 if (CXXDecl && CXXDecl->isLambda()) {
775 RecordDecl::field_iterator Field = CXXDecl->field_begin();
776 unsigned fieldno = 0;
777 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
778 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
779 const LambdaExpr::Capture C = *I;
780 // TODO: Need to handle 'this' in some way by probably renaming the
781 // this of the lambda class and having a field member of 'this'.
782 if (C.capturesVariable()) {
783 VarDecl *V = C.getCapturedVar();
784 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
785 StringRef VName = V->getName();
786 uint64_t SizeInBitsOverride = 0;
787 if (Field->isBitField()) {
788 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
789 assert(SizeInBitsOverride && "found named 0-width bitfield");
791 llvm::DIType fieldType
792 = createFieldType(VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
793 Field->getAccess(), layout.getFieldOffset(fieldno),
795 elements.push_back(fieldType);
799 bool IsMsStruct = record->hasAttr<MsStructAttr>();
800 const FieldDecl *LastFD = 0;
801 for (RecordDecl::field_iterator I = record->field_begin(),
802 E = record->field_end();
803 I != E; ++I, ++fieldNo) {
804 FieldDecl *field = *I;
807 // Zero-length bitfields following non-bitfield members are ignored
808 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
815 StringRef name = field->getName();
816 QualType type = field->getType();
818 // Ignore unnamed fields unless they're anonymous structs/unions.
819 if (name.empty() && !type->isRecordType()) {
824 uint64_t SizeInBitsOverride = 0;
825 if (field->isBitField()) {
826 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
827 assert(SizeInBitsOverride && "found named 0-width bitfield");
830 llvm::DIType fieldType
831 = createFieldType(name, type, SizeInBitsOverride,
832 field->getLocation(), field->getAccess(),
833 layout.getFieldOffset(fieldNo), tunit, RecordTy);
835 elements.push_back(fieldType);
840 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
841 /// function type is not updated to include implicit "this" pointer. Use this
842 /// routine to get a method type which includes "this" pointer.
844 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
847 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
851 // Add "this" pointer.
852 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
853 assert (Args.getNumElements() && "Invalid number of arguments!");
855 SmallVector<llvm::Value *, 16> Elts;
857 // First element is always return type. For 'void' functions it is NULL.
858 Elts.push_back(Args.getElement(0));
860 if (!Method->isStatic()) {
861 // "this" pointer is always first argument.
862 QualType ThisPtr = Method->getThisType(CGM.getContext());
864 const CXXRecordDecl *RD = Method->getParent();
865 if (isa<ClassTemplateSpecializationDecl>(RD)) {
866 // Create pointer type directly in this case.
867 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
868 QualType PointeeTy = ThisPtrTy->getPointeeType();
869 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
870 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
871 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
872 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
873 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
874 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
875 // TODO: This and the artificial type below are misleading, the
876 // types aren't artificial the argument is, but the current
877 // metadata doesn't represent that.
878 ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
879 Elts.push_back(ThisPtrType);
881 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
882 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
883 ThisPtrType = DBuilder.createArtificialType(ThisPtrType);
884 Elts.push_back(ThisPtrType);
888 // Copy rest of the arguments.
889 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
890 Elts.push_back(Args.getElement(i));
892 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
894 return DBuilder.createSubroutineType(Unit, EltTypeArray);
897 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
898 /// inside a function.
899 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
900 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
901 return isFunctionLocalClass(NRD);
902 if (isa<FunctionDecl>(RD->getDeclContext()))
907 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
908 /// a single member function GlobalDecl.
910 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
912 llvm::DIType RecordTy) {
914 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
916 StringRef MethodName = getFunctionName(Method);
917 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
919 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
920 // make sense to give a single ctor/dtor a linkage name.
921 StringRef MethodLinkageName;
922 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
923 MethodLinkageName = CGM.getMangledName(Method);
925 // Get the location for the method.
926 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
927 unsigned MethodLine = getLineNumber(Method->getLocation());
929 // Collect virtual method info.
930 llvm::DIType ContainingType;
931 unsigned Virtuality = 0;
934 if (Method->isVirtual()) {
935 if (Method->isPure())
936 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
938 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
940 // It doesn't make sense to give a virtual destructor a vtable index,
941 // since a single destructor has two entries in the vtable.
942 if (!isa<CXXDestructorDecl>(Method))
943 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
944 ContainingType = RecordTy;
948 if (Method->isImplicit())
949 Flags |= llvm::DIDescriptor::FlagArtificial;
950 AccessSpecifier Access = Method->getAccess();
951 if (Access == clang::AS_private)
952 Flags |= llvm::DIDescriptor::FlagPrivate;
953 else if (Access == clang::AS_protected)
954 Flags |= llvm::DIDescriptor::FlagProtected;
955 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
956 if (CXXC->isExplicit())
957 Flags |= llvm::DIDescriptor::FlagExplicit;
958 } else if (const CXXConversionDecl *CXXC =
959 dyn_cast<CXXConversionDecl>(Method)) {
960 if (CXXC->isExplicit())
961 Flags |= llvm::DIDescriptor::FlagExplicit;
963 if (Method->hasPrototype())
964 Flags |= llvm::DIDescriptor::FlagPrototyped;
966 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
967 llvm::DISubprogram SP =
968 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
969 MethodDefUnit, MethodLine,
970 MethodTy, /*isLocalToUnit=*/false,
971 /* isDefinition=*/ false,
972 Virtuality, VIndex, ContainingType,
973 Flags, CGM.getLangOpts().Optimize, NULL,
976 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
981 /// CollectCXXMemberFunctions - A helper function to collect debug info for
982 /// C++ member functions. This is used while creating debug info entry for
985 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
986 SmallVectorImpl<llvm::Value *> &EltTys,
987 llvm::DIType RecordTy) {
989 // Since we want more than just the individual member decls if we
990 // have templated functions iterate over every declaration to gather
992 for(DeclContext::decl_iterator I = RD->decls_begin(),
993 E = RD->decls_end(); I != E; ++I) {
995 if (D->isImplicit() && !D->isUsed())
998 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
999 // Only emit debug information for user provided functions, we're
1000 // unlikely to want info for artificial functions.
1001 if (Method->isUserProvided())
1002 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1004 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1005 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1006 SE = FTD->spec_end(); SI != SE; ++SI)
1007 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1012 /// CollectCXXFriends - A helper function to collect debug info for
1013 /// C++ base classes. This is used while creating debug info entry for
1016 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1017 SmallVectorImpl<llvm::Value *> &EltTys,
1018 llvm::DIType RecordTy) {
1019 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1020 BE = RD->friend_end(); BI != BE; ++BI) {
1021 if ((*BI)->isUnsupportedFriend())
1023 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1024 EltTys.push_back(DBuilder.createFriend(RecordTy,
1025 getOrCreateType(TInfo->getType(),
1030 /// CollectCXXBases - A helper function to collect debug info for
1031 /// C++ base classes. This is used while creating debug info entry for
1034 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1035 SmallVectorImpl<llvm::Value *> &EltTys,
1036 llvm::DIType RecordTy) {
1038 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1039 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1040 BE = RD->bases_end(); BI != BE; ++BI) {
1041 unsigned BFlags = 0;
1042 uint64_t BaseOffset;
1044 const CXXRecordDecl *Base =
1045 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1047 if (BI->isVirtual()) {
1048 // virtual base offset offset is -ve. The code generator emits dwarf
1049 // expression where it expects +ve number.
1051 0 - CGM.getVTableContext()
1052 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1053 BFlags = llvm::DIDescriptor::FlagVirtual;
1055 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1056 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1057 // BI->isVirtual() and bits when not.
1059 AccessSpecifier Access = BI->getAccessSpecifier();
1060 if (Access == clang::AS_private)
1061 BFlags |= llvm::DIDescriptor::FlagPrivate;
1062 else if (Access == clang::AS_protected)
1063 BFlags |= llvm::DIDescriptor::FlagProtected;
1066 DBuilder.createInheritance(RecordTy,
1067 getOrCreateType(BI->getType(), Unit),
1068 BaseOffset, BFlags);
1069 EltTys.push_back(DTy);
1073 /// CollectTemplateParams - A helper function to collect template parameters.
1074 llvm::DIArray CGDebugInfo::
1075 CollectTemplateParams(const TemplateParameterList *TPList,
1076 const TemplateArgumentList &TAList,
1077 llvm::DIFile Unit) {
1078 SmallVector<llvm::Value *, 16> TemplateParams;
1079 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1080 const TemplateArgument &TA = TAList[i];
1081 const NamedDecl *ND = TPList->getParam(i);
1082 if (TA.getKind() == TemplateArgument::Type) {
1083 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1084 llvm::DITemplateTypeParameter TTP =
1085 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1086 TemplateParams.push_back(TTP);
1087 } else if (TA.getKind() == TemplateArgument::Integral) {
1088 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1089 llvm::DITemplateValueParameter TVP =
1090 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1091 TA.getAsIntegral().getZExtValue());
1092 TemplateParams.push_back(TVP);
1095 return DBuilder.getOrCreateArray(TemplateParams);
1098 /// CollectFunctionTemplateParams - A helper function to collect debug
1099 /// info for function template parameters.
1100 llvm::DIArray CGDebugInfo::
1101 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1102 if (FD->getTemplatedKind() ==
1103 FunctionDecl::TK_FunctionTemplateSpecialization) {
1104 const TemplateParameterList *TList =
1105 FD->getTemplateSpecializationInfo()->getTemplate()
1106 ->getTemplateParameters();
1108 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1110 return llvm::DIArray();
1113 /// CollectCXXTemplateParams - A helper function to collect debug info for
1114 /// template parameters.
1115 llvm::DIArray CGDebugInfo::
1116 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1117 llvm::DIFile Unit) {
1118 llvm::PointerUnion<ClassTemplateDecl *,
1119 ClassTemplatePartialSpecializationDecl *>
1120 PU = TSpecial->getSpecializedTemplateOrPartial();
1122 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1123 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1124 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1125 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1126 return CollectTemplateParams(TPList, TAList, Unit);
1129 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1130 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1131 if (VTablePtrType.isValid())
1132 return VTablePtrType;
1134 ASTContext &Context = CGM.getContext();
1137 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1138 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1139 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1140 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1141 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1143 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1144 return VTablePtrType;
1147 /// getVTableName - Get vtable name for the given Class.
1148 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1149 // Construct gdb compatible name name.
1150 std::string Name = "_vptr$" + RD->getNameAsString();
1152 // Copy this name on the side and use its reference.
1153 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1154 memcpy(StrPtr, Name.data(), Name.length());
1155 return StringRef(StrPtr, Name.length());
1159 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1160 /// debug info entry in EltTys vector.
1162 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1163 SmallVectorImpl<llvm::Value *> &EltTys) {
1164 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1166 // If there is a primary base then it will hold vtable info.
1167 if (RL.getPrimaryBase())
1170 // If this class is not dynamic then there is not any vtable info to collect.
1171 if (!RD->isDynamicClass())
1174 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1176 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1178 getOrCreateVTablePtrType(Unit));
1179 EltTys.push_back(VPTR);
1182 /// getOrCreateRecordType - Emit record type's standalone debug info.
1183 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1184 SourceLocation Loc) {
1185 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1186 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1190 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1192 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1193 SourceLocation Loc) {
1194 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
1195 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1196 DBuilder.retainType(T);
1200 /// CreateType - get structure or union type.
1201 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1202 RecordDecl *RD = Ty->getDecl();
1204 // Get overall information about the record type for the debug info.
1205 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1207 // Records and classes and unions can all be recursive. To handle them, we
1208 // first generate a debug descriptor for the struct as a forward declaration.
1209 // Then (if it is a definition) we go through and get debug info for all of
1210 // its members. Finally, we create a descriptor for the complete type (which
1211 // may refer to the forward decl if the struct is recursive) and replace all
1212 // uses of the forward declaration with the final definition.
1214 llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1216 if (FwdDecl.isForwardDecl())
1219 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1221 // Push the struct on region stack.
1222 LexicalBlockStack.push_back(FwdDeclNode);
1223 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1225 // Add this to the completed types cache since we're completing it.
1226 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1228 // Convert all the elements.
1229 SmallVector<llvm::Value *, 16> EltTys;
1231 // Note: The split of CXXDecl information here is intentional, the
1232 // gdb tests will depend on a certain ordering at printout. The debug
1233 // information offsets are still correct if we merge them all together
1235 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1237 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1238 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1241 // Collect static variables with initializers and other fields.
1242 CollectRecordStaticVars(RD, FwdDecl);
1243 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1244 llvm::DIArray TParamsArray;
1246 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1247 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1248 if (const ClassTemplateSpecializationDecl *TSpecial
1249 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1250 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1253 LexicalBlockStack.pop_back();
1254 RegionMap.erase(Ty->getDecl());
1256 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1257 // FIXME: Magic numbers ahoy! These should be changed when we
1258 // get some enums in llvm/Analysis/DebugInfo.h to refer to
1261 FwdDeclNode->replaceOperandWith(10, Elements);
1263 FwdDeclNode->replaceOperandWith(10, Elements);
1264 FwdDeclNode->replaceOperandWith(13, TParamsArray);
1266 FwdDeclNode->replaceOperandWith(10, Elements);
1268 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1269 return llvm::DIType(FwdDeclNode);
1272 /// CreateType - get objective-c object type.
1273 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1274 llvm::DIFile Unit) {
1275 // Ignore protocols.
1276 return getOrCreateType(Ty->getBaseType(), Unit);
1279 /// CreateType - get objective-c interface type.
1280 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1281 llvm::DIFile Unit) {
1282 ObjCInterfaceDecl *ID = Ty->getDecl();
1284 return llvm::DIType();
1286 // Get overall information about the record type for the debug info.
1287 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1288 unsigned Line = getLineNumber(ID->getLocation());
1289 unsigned RuntimeLang = TheCU.getLanguage();
1291 // If this is just a forward declaration return a special forward-declaration
1292 // debug type since we won't be able to lay out the entire type.
1293 ObjCInterfaceDecl *Def = ID->getDefinition();
1295 llvm::DIType FwdDecl =
1296 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1297 ID->getName(), TheCU, DefUnit, Line,
1304 // Bit size, align and offset of the type.
1305 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1306 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1309 if (ID->getImplementation())
1310 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1312 llvm::DIType RealDecl =
1313 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1314 Line, Size, Align, Flags,
1315 llvm::DIArray(), RuntimeLang);
1317 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1318 // will find it and we're emitting the complete type.
1319 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1320 // Push the struct on region stack.
1321 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1323 LexicalBlockStack.push_back(FwdDeclNode);
1324 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1326 // Convert all the elements.
1327 SmallVector<llvm::Value *, 16> EltTys;
1329 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1331 llvm::DIType SClassTy =
1332 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1333 if (!SClassTy.isValid())
1334 return llvm::DIType();
1336 llvm::DIType InhTag =
1337 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1338 EltTys.push_back(InhTag);
1341 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1342 E = ID->prop_end(); I != E; ++I) {
1343 const ObjCPropertyDecl *PD = *I;
1344 SourceLocation Loc = PD->getLocation();
1345 llvm::DIFile PUnit = getOrCreateFile(Loc);
1346 unsigned PLine = getLineNumber(Loc);
1347 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1348 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1349 llvm::MDNode *PropertyNode =
1350 DBuilder.createObjCProperty(PD->getName(),
1352 (Getter && Getter->isImplicit()) ? "" :
1353 getSelectorName(PD->getGetterName()),
1354 (Setter && Setter->isImplicit()) ? "" :
1355 getSelectorName(PD->getSetterName()),
1356 PD->getPropertyAttributes(),
1357 getOrCreateType(PD->getType(), PUnit));
1358 EltTys.push_back(PropertyNode);
1361 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1362 unsigned FieldNo = 0;
1363 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1364 Field = Field->getNextIvar(), ++FieldNo) {
1365 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1366 if (!FieldTy.isValid())
1367 return llvm::DIType();
1369 StringRef FieldName = Field->getName();
1371 // Ignore unnamed fields.
1372 if (FieldName.empty())
1375 // Get the location for the field.
1376 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1377 unsigned FieldLine = getLineNumber(Field->getLocation());
1378 QualType FType = Field->getType();
1379 uint64_t FieldSize = 0;
1380 unsigned FieldAlign = 0;
1382 if (!FType->isIncompleteArrayType()) {
1384 // Bit size, align and offset of the type.
1385 FieldSize = Field->isBitField()
1386 ? Field->getBitWidthValue(CGM.getContext())
1387 : CGM.getContext().getTypeSize(FType);
1388 FieldAlign = CGM.getContext().getTypeAlign(FType);
1391 // We can't know the offset of our ivar in the structure if we're using
1392 // the non-fragile abi and the debugger should ignore the value anyways.
1393 // Call it the FieldNo+1 due to how debuggers use the information,
1394 // e.g. negating the value when it needs a lookup in the dynamic table.
1395 uint64_t FieldOffset = CGM.getLangOpts().ObjCRuntime.isNonFragile()
1396 ? FieldNo+1 : RL.getFieldOffset(FieldNo);
1399 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1400 Flags = llvm::DIDescriptor::FlagProtected;
1401 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1402 Flags = llvm::DIDescriptor::FlagPrivate;
1404 llvm::MDNode *PropertyNode = NULL;
1405 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1406 if (ObjCPropertyImplDecl *PImpD =
1407 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1408 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1409 SourceLocation Loc = PD->getLocation();
1410 llvm::DIFile PUnit = getOrCreateFile(Loc);
1411 unsigned PLine = getLineNumber(Loc);
1412 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1413 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1415 DBuilder.createObjCProperty(PD->getName(),
1417 (Getter && Getter->isImplicit()) ? "" :
1418 getSelectorName(PD->getGetterName()),
1419 (Setter && Setter->isImplicit()) ? "" :
1420 getSelectorName(PD->getSetterName()),
1421 PD->getPropertyAttributes(),
1422 getOrCreateType(PD->getType(), PUnit));
1426 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1427 FieldLine, FieldSize, FieldAlign,
1428 FieldOffset, Flags, FieldTy,
1430 EltTys.push_back(FieldTy);
1433 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1434 FwdDeclNode->replaceOperandWith(10, Elements);
1436 LexicalBlockStack.pop_back();
1437 return llvm::DIType(FwdDeclNode);
1440 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1441 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1442 int64_t NumElems = Ty->getNumElements();
1443 int64_t LowerBound = 0;
1445 // If number of elements are not known then this is an unbounded array.
1446 // Use Low = 1, Hi = 0 to express such arrays.
1451 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1452 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1454 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1455 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1458 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1461 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1462 llvm::DIFile Unit) {
1466 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1467 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1470 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1471 } else if (Ty->isIncompleteArrayType()) {
1473 if (Ty->getElementType()->isIncompleteType())
1476 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1477 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1481 // Size and align of the whole array, not the element type.
1482 Size = CGM.getContext().getTypeSize(Ty);
1483 Align = CGM.getContext().getTypeAlign(Ty);
1486 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1487 // interior arrays, do we care? Why aren't nested arrays represented the
1488 // obvious/recursive way?
1489 SmallVector<llvm::Value *, 8> Subscripts;
1490 QualType EltTy(Ty, 0);
1491 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1492 int64_t UpperBound = 0;
1493 int64_t LowerBound = 0;
1494 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1495 if (CAT->getSize().getZExtValue())
1496 UpperBound = CAT->getSize().getZExtValue() - 1;
1498 // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1502 // FIXME: Verify this is right for VLAs.
1503 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1505 EltTy = Ty->getElementType();
1508 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1510 llvm::DIType DbgTy =
1511 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1516 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1517 llvm::DIFile Unit) {
1518 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1519 Ty, Ty->getPointeeType(), Unit);
1522 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1523 llvm::DIFile Unit) {
1524 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1525 Ty, Ty->getPointeeType(), Unit);
1528 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1530 QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1531 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1533 if (!Ty->getPointeeType()->isFunctionType()) {
1534 // We have a data member pointer type.
1535 return PointerDiffDITy;
1538 // We have a member function pointer type. Treat it as a struct with two
1539 // ptrdiff_t members.
1540 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1542 uint64_t FieldOffset = 0;
1543 llvm::Value *ElementTypes[2];
1545 // FIXME: This should be a DW_TAG_pointer_to_member type.
1547 DBuilder.createMemberType(U, "ptr", U, 0,
1548 Info.first, Info.second, FieldOffset, 0,
1550 FieldOffset += Info.first;
1553 DBuilder.createMemberType(U, "ptr", U, 0,
1554 Info.first, Info.second, FieldOffset, 0,
1557 llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1559 return DBuilder.createStructType(U, StringRef("test"),
1564 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1566 // Ignore the atomic wrapping
1567 // FIXME: What is the correct representation?
1568 return getOrCreateType(Ty->getValueType(), U);
1571 /// CreateEnumType - get enumeration type.
1572 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1573 SmallVector<llvm::Value *, 16> Enumerators;
1575 // Create DIEnumerator elements for each enumerator.
1576 for (EnumDecl::enumerator_iterator
1577 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1578 Enum != EnumEnd; ++Enum) {
1579 Enumerators.push_back(
1580 DBuilder.createEnumerator(Enum->getName(),
1581 Enum->getInitVal().getZExtValue()));
1584 // Return a CompositeType for the enum itself.
1585 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1587 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1588 unsigned Line = getLineNumber(ED->getLocation());
1591 if (!ED->getTypeForDecl()->isIncompleteType()) {
1592 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1593 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1595 llvm::DIDescriptor EnumContext =
1596 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1597 llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1598 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1599 unsigned Flags = !ED->isCompleteDefinition() ? llvm::DIDescriptor::FlagFwdDecl : 0;
1600 llvm::DIType DbgTy =
1601 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1602 Size, Align, EltArray,
1607 static QualType UnwrapTypeForDebugInfo(QualType T) {
1610 switch (T->getTypeClass()) {
1613 case Type::TemplateSpecialization:
1614 T = cast<TemplateSpecializationType>(T)->desugar();
1616 case Type::TypeOfExpr:
1617 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1620 T = cast<TypeOfType>(T)->getUnderlyingType();
1622 case Type::Decltype:
1623 T = cast<DecltypeType>(T)->getUnderlyingType();
1625 case Type::UnaryTransform:
1626 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1628 case Type::Attributed:
1629 T = cast<AttributedType>(T)->getEquivalentType();
1631 case Type::Elaborated:
1632 T = cast<ElaboratedType>(T)->getNamedType();
1635 T = cast<ParenType>(T)->getInnerType();
1637 case Type::SubstTemplateTypeParm: {
1638 // We need to keep the qualifiers handy since getReplacementType()
1639 // will strip them away.
1640 unsigned Quals = T.getLocalFastQualifiers();
1641 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1642 T.addFastQualifiers(Quals);
1646 T = cast<AutoType>(T)->getDeducedType();
1650 assert(T != LastT && "Type unwrapping failed to unwrap!");
1656 /// getType - Get the type from the cache or return null type if it doesn't exist.
1657 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1659 // Unwrap the type as needed for debug information.
1660 Ty = UnwrapTypeForDebugInfo(Ty);
1662 // Check for existing entry.
1663 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1664 TypeCache.find(Ty.getAsOpaquePtr());
1665 if (it != TypeCache.end()) {
1666 // Verify that the debug info still exists.
1667 if (llvm::Value *V = it->second)
1668 return llvm::DIType(cast<llvm::MDNode>(V));
1671 return llvm::DIType();
1674 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1676 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1678 // Unwrap the type as needed for debug information.
1679 Ty = UnwrapTypeForDebugInfo(Ty);
1681 // Check for existing entry.
1682 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1683 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1684 if (it != CompletedTypeCache.end()) {
1685 // Verify that the debug info still exists.
1686 if (llvm::Value *V = it->second)
1687 return llvm::DIType(cast<llvm::MDNode>(V));
1690 return llvm::DIType();
1694 /// getOrCreateType - Get the type from the cache or create a new
1695 /// one if necessary.
1696 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1698 return llvm::DIType();
1700 // Unwrap the type as needed for debug information.
1701 Ty = UnwrapTypeForDebugInfo(Ty);
1703 llvm::DIType T = getCompletedTypeOrNull(Ty);
1708 // Otherwise create the type.
1709 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1711 llvm::DIType TC = getTypeOrNull(Ty);
1712 if (TC.Verify() && TC.isForwardDecl())
1713 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1714 static_cast<llvm::Value*>(TC)));
1716 // And update the type cache.
1717 TypeCache[Ty.getAsOpaquePtr()] = Res;
1719 if (!Res.isForwardDecl())
1720 CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1725 /// CreateTypeNode - Create a new debug type node.
1726 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1727 // Handle qualifiers, which recursively handles what they refer to.
1728 if (Ty.hasLocalQualifiers())
1729 return CreateQualifiedType(Ty, Unit);
1731 const char *Diag = 0;
1733 // Work out details of type.
1734 switch (Ty->getTypeClass()) {
1735 #define TYPE(Class, Base)
1736 #define ABSTRACT_TYPE(Class, Base)
1737 #define NON_CANONICAL_TYPE(Class, Base)
1738 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1739 #include "clang/AST/TypeNodes.def"
1740 llvm_unreachable("Dependent types cannot show up in debug information");
1742 case Type::ExtVector:
1744 return CreateType(cast<VectorType>(Ty), Unit);
1745 case Type::ObjCObjectPointer:
1746 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1747 case Type::ObjCObject:
1748 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1749 case Type::ObjCInterface:
1750 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1752 return CreateType(cast<BuiltinType>(Ty));
1754 return CreateType(cast<ComplexType>(Ty));
1756 return CreateType(cast<PointerType>(Ty), Unit);
1757 case Type::BlockPointer:
1758 return CreateType(cast<BlockPointerType>(Ty), Unit);
1760 return CreateType(cast<TypedefType>(Ty), Unit);
1762 return CreateType(cast<RecordType>(Ty));
1764 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1765 case Type::FunctionProto:
1766 case Type::FunctionNoProto:
1767 return CreateType(cast<FunctionType>(Ty), Unit);
1768 case Type::ConstantArray:
1769 case Type::VariableArray:
1770 case Type::IncompleteArray:
1771 return CreateType(cast<ArrayType>(Ty), Unit);
1773 case Type::LValueReference:
1774 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1775 case Type::RValueReference:
1776 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1778 case Type::MemberPointer:
1779 return CreateType(cast<MemberPointerType>(Ty), Unit);
1782 return CreateType(cast<AtomicType>(Ty), Unit);
1784 case Type::Attributed:
1785 case Type::TemplateSpecialization:
1786 case Type::Elaborated:
1788 case Type::SubstTemplateTypeParm:
1789 case Type::TypeOfExpr:
1791 case Type::Decltype:
1792 case Type::UnaryTransform:
1794 llvm_unreachable("type should have been unwrapped!");
1797 assert(Diag && "Fall through without a diagnostic?");
1798 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1799 "debug information for %0 is not yet supported");
1800 CGM.getDiags().Report(DiagID)
1802 return llvm::DIType();
1805 /// getOrCreateLimitedType - Get the type from the cache or create a new
1806 /// limited type if necessary.
1807 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1808 llvm::DIFile Unit) {
1810 return llvm::DIType();
1812 // Unwrap the type as needed for debug information.
1813 Ty = UnwrapTypeForDebugInfo(Ty);
1815 llvm::DIType T = getTypeOrNull(Ty);
1817 // We may have cached a forward decl when we could have created
1818 // a non-forward decl. Go ahead and create a non-forward decl
1820 if (T.Verify() && !T.isForwardDecl()) return T;
1822 // Otherwise create the type.
1823 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1825 if (T.Verify() && T.isForwardDecl())
1826 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1827 static_cast<llvm::Value*>(T)));
1829 // And update the type cache.
1830 TypeCache[Ty.getAsOpaquePtr()] = Res;
1834 // TODO: Currently used for context chains when limiting debug info.
1835 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1836 RecordDecl *RD = Ty->getDecl();
1838 // Get overall information about the record type for the debug info.
1839 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1840 unsigned Line = getLineNumber(RD->getLocation());
1841 StringRef RDName = RD->getName();
1843 llvm::DIDescriptor RDContext;
1844 if (CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo)
1845 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1847 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1849 // If this is just a forward declaration, construct an appropriately
1850 // marked node and just return it.
1851 if (!RD->getDefinition())
1852 return createRecordFwdDecl(RD, RDContext);
1854 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1855 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1856 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1857 llvm::TrackingVH<llvm::MDNode> RealDecl;
1860 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1861 Size, Align, 0, llvm::DIArray());
1863 RDName = getClassName(RD);
1865 // FIXME: This could be a struct type giving a default visibility different
1866 // than C++ class type, but needs llvm metadata changes first.
1867 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1868 Size, Align, 0, 0, llvm::DIType(),
1869 llvm::DIArray(), llvm::DIType(),
1872 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1873 Size, Align, 0, llvm::DIArray());
1875 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1876 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1879 // A class's primary base or the class itself contains the vtable.
1880 llvm::MDNode *ContainingType = NULL;
1881 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1882 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1883 // Seek non virtual primary base root.
1885 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1886 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1887 if (PBT && !BRL.isPrimaryBaseVirtual())
1893 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1895 else if (CXXDecl->isDynamicClass())
1896 ContainingType = RealDecl;
1898 RealDecl->replaceOperandWith(12, ContainingType);
1900 return llvm::DIType(RealDecl);
1903 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1904 /// declare composite types that haven't been processed yet.
1905 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1907 // Work out details of type.
1908 switch (Ty->getTypeClass()) {
1909 #define TYPE(Class, Base)
1910 #define ABSTRACT_TYPE(Class, Base)
1911 #define NON_CANONICAL_TYPE(Class, Base)
1912 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1913 #include "clang/AST/TypeNodes.def"
1914 llvm_unreachable("Dependent types cannot show up in debug information");
1917 return CreateLimitedType(cast<RecordType>(Ty));
1919 return CreateTypeNode(Ty, Unit);
1923 /// CreateMemberType - Create new member and increase Offset by FType's size.
1924 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1927 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1928 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1929 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1930 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1931 FieldSize, FieldAlign,
1932 *Offset, 0, FieldTy);
1933 *Offset += FieldSize;
1937 /// getFunctionDeclaration - Return debug info descriptor to describe method
1938 /// declaration for the given method definition.
1939 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1940 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1941 if (!FD) return llvm::DISubprogram();
1944 getContextDescriptor(cast<Decl>(D->getDeclContext()));
1946 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1947 MI = SPCache.find(FD->getCanonicalDecl());
1948 if (MI != SPCache.end()) {
1949 llvm::Value *V = MI->second;
1950 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1951 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1955 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1956 E = FD->redecls_end(); I != E; ++I) {
1957 const FunctionDecl *NextFD = *I;
1958 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1959 MI = SPCache.find(NextFD->getCanonicalDecl());
1960 if (MI != SPCache.end()) {
1961 llvm::Value *V = MI->second;
1962 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1963 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1967 return llvm::DISubprogram();
1970 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1971 // implicit parameter "this".
1972 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1976 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1977 return getOrCreateMethodType(Method, F);
1978 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1979 // Add "self" and "_cmd"
1980 SmallVector<llvm::Value *, 16> Elts;
1982 // First element is always return type. For 'void' functions it is NULL.
1983 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1984 // "self" pointer is always first argument.
1985 Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1986 // "cmd" pointer is always second argument.
1987 Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1988 // Get rest of the arguments.
1989 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1990 PE = OMethod->param_end(); PI != PE; ++PI)
1991 Elts.push_back(getOrCreateType((*PI)->getType(), F));
1993 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1994 return DBuilder.createSubroutineType(F, EltTypeArray);
1996 return getOrCreateType(FnType, F);
1999 /// EmitFunctionStart - Constructs the debug code for entering a function.
2000 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2002 CGBuilderTy &Builder) {
2005 StringRef LinkageName;
2007 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2009 const Decl *D = GD.getDecl();
2010 // Use the location of the declaration.
2011 SourceLocation Loc = D->getLocation();
2014 llvm::DIFile Unit = getOrCreateFile(Loc);
2015 llvm::DIDescriptor FDContext(Unit);
2016 llvm::DIArray TParamsArray;
2017 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2018 // If there is a DISubprogram for this function available then use it.
2019 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2020 FI = SPCache.find(FD->getCanonicalDecl());
2021 if (FI != SPCache.end()) {
2022 llvm::Value *V = FI->second;
2023 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2024 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2025 llvm::MDNode *SPN = SP;
2026 LexicalBlockStack.push_back(SPN);
2027 RegionMap[D] = llvm::WeakVH(SP);
2031 Name = getFunctionName(FD);
2032 // Use mangled name as linkage name for c/c++ functions.
2033 if (FD->hasPrototype()) {
2034 LinkageName = CGM.getMangledName(GD);
2035 Flags |= llvm::DIDescriptor::FlagPrototyped;
2037 if (LinkageName == Name ||
2038 CGM.getCodeGenOpts().DebugInfo <= CodeGenOptions::DebugLineTablesOnly)
2039 LinkageName = StringRef();
2041 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2042 if (const NamespaceDecl *NSDecl =
2043 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2044 FDContext = getOrCreateNameSpace(NSDecl);
2045 else if (const RecordDecl *RDecl =
2046 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2047 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2049 // Collect template parameters.
2050 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2052 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2053 Name = getObjCMethodName(OMD);
2054 Flags |= llvm::DIDescriptor::FlagPrototyped;
2056 // Use llvm function name.
2057 Name = Fn->getName();
2058 Flags |= llvm::DIDescriptor::FlagPrototyped;
2060 if (!Name.empty() && Name[0] == '\01')
2061 Name = Name.substr(1);
2063 unsigned LineNo = getLineNumber(Loc);
2064 if (D->isImplicit())
2065 Flags |= llvm::DIDescriptor::FlagArtificial;
2067 llvm::DIType DIFnType;
2068 llvm::DISubprogram SPDecl;
2069 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) {
2070 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2071 SPDecl = getFunctionDeclaration(D);
2073 // Create fake but valid subroutine type. Otherwise
2074 // llvm::DISubprogram::Verify() would return false, and
2075 // subprogram DIE will miss DW_AT_decl_file and
2076 // DW_AT_decl_line fields.
2077 SmallVector<llvm::Value*, 16> Elts;
2078 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2079 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2081 llvm::DISubprogram SP;
2082 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2084 Fn->hasInternalLinkage(), true/*definition*/,
2085 getLineNumber(CurLoc), Flags,
2086 CGM.getLangOpts().Optimize,
2087 Fn, TParamsArray, SPDecl);
2089 // Push function on region stack.
2090 llvm::MDNode *SPN = SP;
2091 LexicalBlockStack.push_back(SPN);
2092 RegionMap[D] = llvm::WeakVH(SP);
2095 /// EmitLocation - Emit metadata to indicate a change in line/column
2096 /// information in the source file.
2097 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2099 // Update our current location
2102 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2104 // Don't bother if things are the same as last time.
2105 SourceManager &SM = CGM.getContext().getSourceManager();
2106 if (CurLoc == PrevLoc ||
2107 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2108 // New Builder may not be in sync with CGDebugInfo.
2109 if (!Builder.getCurrentDebugLocation().isUnknown())
2112 // Update last state.
2115 llvm::MDNode *Scope = LexicalBlockStack.back();
2116 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2117 getColumnNumber(CurLoc),
2121 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2123 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2124 llvm::DIDescriptor D =
2125 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2126 llvm::DIDescriptor() :
2127 llvm::DIDescriptor(LexicalBlockStack.back()),
2128 getOrCreateFile(CurLoc),
2129 getLineNumber(CurLoc),
2130 getColumnNumber(CurLoc));
2131 llvm::MDNode *DN = D;
2132 LexicalBlockStack.push_back(DN);
2135 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2136 /// region - beginning of a DW_TAG_lexical_block.
2137 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2138 // Set our current location.
2141 // Create a new lexical block and push it on the stack.
2142 CreateLexicalBlock(Loc);
2144 // Emit a line table change for the current location inside the new scope.
2145 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2146 getColumnNumber(Loc),
2147 LexicalBlockStack.back()));
2150 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2151 /// region - end of a DW_TAG_lexical_block.
2152 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2153 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2155 // Provide an entry in the line table for the end of the block.
2156 EmitLocation(Builder, Loc);
2158 LexicalBlockStack.pop_back();
2161 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2162 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2163 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2164 unsigned RCount = FnBeginRegionCount.back();
2165 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2167 // Pop all regions for this function.
2168 while (LexicalBlockStack.size() != RCount)
2169 EmitLexicalBlockEnd(Builder, CurLoc);
2170 FnBeginRegionCount.pop_back();
2173 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2174 // See BuildByRefType.
2175 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2176 uint64_t *XOffset) {
2178 SmallVector<llvm::Value *, 5> EltTys;
2180 uint64_t FieldSize, FieldOffset;
2181 unsigned FieldAlign;
2183 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2184 QualType Type = VD->getType();
2187 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2188 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2189 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2190 FType = CGM.getContext().IntTy;
2191 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2192 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2194 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2195 if (HasCopyAndDispose) {
2196 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2197 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2199 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2203 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2204 if (Align > CGM.getContext().toCharUnitsFromBits(
2205 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2206 CharUnits FieldOffsetInBytes
2207 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2208 CharUnits AlignedOffsetInBytes
2209 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2210 CharUnits NumPaddingBytes
2211 = AlignedOffsetInBytes - FieldOffsetInBytes;
2213 if (NumPaddingBytes.isPositive()) {
2214 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2215 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2216 pad, ArrayType::Normal, 0);
2217 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2222 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2223 FieldSize = CGM.getContext().getTypeSize(FType);
2224 FieldAlign = CGM.getContext().toBits(Align);
2226 *XOffset = FieldOffset;
2227 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2228 0, FieldSize, FieldAlign,
2229 FieldOffset, 0, FieldTy);
2230 EltTys.push_back(FieldTy);
2231 FieldOffset += FieldSize;
2233 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2235 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2237 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2241 /// EmitDeclare - Emit local variable declaration debug info.
2242 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2243 llvm::Value *Storage,
2244 unsigned ArgNo, CGBuilderTy &Builder) {
2245 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2246 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2248 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2250 uint64_t XOffset = 0;
2251 if (VD->hasAttr<BlocksAttr>())
2252 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2254 Ty = getOrCreateType(VD->getType(), Unit);
2256 // If there is not any debug info for type then do not emit debug info
2257 // for this variable.
2261 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2262 // If Storage is an aggregate returned as 'sret' then let debugger know
2264 if (Arg->hasStructRetAttr())
2265 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2266 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2267 // If an aggregate variable has non trivial destructor or non trivial copy
2268 // constructor than it is pass indirectly. Let debug info know about this
2269 // by using reference of the aggregate type as a argument type.
2270 if (!Record->hasTrivialCopyConstructor() ||
2271 !Record->hasTrivialDestructor())
2272 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2276 // Get location information.
2277 unsigned Line = getLineNumber(VD->getLocation());
2278 unsigned Column = getColumnNumber(VD->getLocation());
2280 if (VD->isImplicit())
2281 Flags |= llvm::DIDescriptor::FlagArtificial;
2282 llvm::MDNode *Scope = LexicalBlockStack.back();
2284 StringRef Name = VD->getName();
2285 if (!Name.empty()) {
2286 if (VD->hasAttr<BlocksAttr>()) {
2287 CharUnits offset = CharUnits::fromQuantity(32);
2288 SmallVector<llvm::Value *, 9> addr;
2289 llvm::Type *Int64Ty = CGM.Int64Ty;
2290 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2291 // offset of __forwarding field
2292 offset = CGM.getContext().toCharUnitsFromBits(
2293 CGM.getContext().getTargetInfo().getPointerWidth(0));
2294 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2295 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2296 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2297 // offset of x field
2298 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2299 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2301 // Create the descriptor for the variable.
2302 llvm::DIVariable D =
2303 DBuilder.createComplexVariable(Tag,
2304 llvm::DIDescriptor(Scope),
2305 VD->getName(), Unit, Line, Ty,
2308 // Insert an llvm.dbg.declare into the current block.
2309 llvm::Instruction *Call =
2310 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2311 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2313 } else if (isa<VariableArrayType>(VD->getType())) {
2314 // These are "complex" variables in that they need an op_deref.
2315 // Create the descriptor for the variable.
2316 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2317 llvm::DIBuilder::OpDeref);
2318 llvm::DIVariable D =
2319 DBuilder.createComplexVariable(Tag,
2320 llvm::DIDescriptor(Scope),
2321 Name, Unit, Line, Ty,
2324 // Insert an llvm.dbg.declare into the current block.
2325 llvm::Instruction *Call =
2326 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2327 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2331 // Create the descriptor for the variable.
2332 llvm::DIVariable D =
2333 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2334 Name, Unit, Line, Ty,
2335 CGM.getLangOpts().Optimize, Flags, ArgNo);
2337 // Insert an llvm.dbg.declare into the current block.
2338 llvm::Instruction *Call =
2339 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2340 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2344 // If VD is an anonymous union then Storage represents value for
2345 // all union fields.
2346 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2347 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2348 if (RD->isUnion()) {
2349 for (RecordDecl::field_iterator I = RD->field_begin(),
2350 E = RD->field_end();
2352 FieldDecl *Field = *I;
2353 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2354 StringRef FieldName = Field->getName();
2356 // Ignore unnamed fields. Do not ignore unnamed records.
2357 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2360 // Use VarDecl's Tag, Scope and Line number.
2361 llvm::DIVariable D =
2362 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2363 FieldName, Unit, Line, FieldTy,
2364 CGM.getLangOpts().Optimize, Flags,
2367 // Insert an llvm.dbg.declare into the current block.
2368 llvm::Instruction *Call =
2369 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2370 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2376 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2377 llvm::Value *Storage,
2378 CGBuilderTy &Builder) {
2379 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2380 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2383 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2384 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2385 const CGBlockInfo &blockInfo) {
2386 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2387 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2389 if (Builder.GetInsertBlock() == 0)
2392 bool isByRef = VD->hasAttr<BlocksAttr>();
2394 uint64_t XOffset = 0;
2395 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2398 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2400 Ty = getOrCreateType(VD->getType(), Unit);
2402 // Get location information.
2403 unsigned Line = getLineNumber(VD->getLocation());
2404 unsigned Column = getColumnNumber(VD->getLocation());
2406 const llvm::TargetData &target = CGM.getTargetData();
2408 CharUnits offset = CharUnits::fromQuantity(
2409 target.getStructLayout(blockInfo.StructureType)
2410 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2412 SmallVector<llvm::Value *, 9> addr;
2413 llvm::Type *Int64Ty = CGM.Int64Ty;
2414 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2415 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2417 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2418 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2419 // offset of __forwarding field
2420 offset = CGM.getContext()
2421 .toCharUnitsFromBits(target.getPointerSizeInBits());
2422 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2423 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2424 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2425 // offset of x field
2426 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2427 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2430 // Create the descriptor for the variable.
2431 llvm::DIVariable D =
2432 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2433 llvm::DIDescriptor(LexicalBlockStack.back()),
2434 VD->getName(), Unit, Line, Ty, addr);
2435 // Insert an llvm.dbg.declare into the current block.
2436 llvm::Instruction *Call =
2437 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2438 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2439 LexicalBlockStack.back()));
2442 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2443 /// variable declaration.
2444 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2446 CGBuilderTy &Builder) {
2447 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2448 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2452 struct BlockLayoutChunk {
2453 uint64_t OffsetInBits;
2454 const BlockDecl::Capture *Capture;
2456 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2457 return l.OffsetInBits < r.OffsetInBits;
2461 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2463 CGBuilderTy &Builder) {
2464 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2465 ASTContext &C = CGM.getContext();
2466 const BlockDecl *blockDecl = block.getBlockDecl();
2468 // Collect some general information about the block's location.
2469 SourceLocation loc = blockDecl->getCaretLocation();
2470 llvm::DIFile tunit = getOrCreateFile(loc);
2471 unsigned line = getLineNumber(loc);
2472 unsigned column = getColumnNumber(loc);
2474 // Build the debug-info type for the block literal.
2475 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2477 const llvm::StructLayout *blockLayout =
2478 CGM.getTargetData().getStructLayout(block.StructureType);
2480 SmallVector<llvm::Value*, 16> fields;
2481 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2482 blockLayout->getElementOffsetInBits(0),
2484 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2485 blockLayout->getElementOffsetInBits(1),
2487 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2488 blockLayout->getElementOffsetInBits(2),
2490 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2491 blockLayout->getElementOffsetInBits(3),
2493 fields.push_back(createFieldType("__descriptor",
2494 C.getPointerType(block.NeedsCopyDispose ?
2495 C.getBlockDescriptorExtendedType() :
2496 C.getBlockDescriptorType()),
2498 blockLayout->getElementOffsetInBits(4),
2501 // We want to sort the captures by offset, not because DWARF
2502 // requires this, but because we're paranoid about debuggers.
2503 SmallVector<BlockLayoutChunk, 8> chunks;
2506 if (blockDecl->capturesCXXThis()) {
2507 BlockLayoutChunk chunk;
2508 chunk.OffsetInBits =
2509 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2511 chunks.push_back(chunk);
2514 // Variable captures.
2515 for (BlockDecl::capture_const_iterator
2516 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2518 const BlockDecl::Capture &capture = *i;
2519 const VarDecl *variable = capture.getVariable();
2520 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2522 // Ignore constant captures.
2523 if (captureInfo.isConstant())
2526 BlockLayoutChunk chunk;
2527 chunk.OffsetInBits =
2528 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2529 chunk.Capture = &capture;
2530 chunks.push_back(chunk);
2534 llvm::array_pod_sort(chunks.begin(), chunks.end());
2536 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2537 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2538 uint64_t offsetInBits = i->OffsetInBits;
2539 const BlockDecl::Capture *capture = i->Capture;
2541 // If we have a null capture, this must be the C++ 'this' capture.
2543 const CXXMethodDecl *method =
2544 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2545 QualType type = method->getThisType(C);
2547 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2548 offsetInBits, tunit, tunit));
2552 const VarDecl *variable = capture->getVariable();
2553 StringRef name = variable->getName();
2555 llvm::DIType fieldType;
2556 if (capture->isByRef()) {
2557 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2559 // FIXME: this creates a second copy of this type!
2561 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2562 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2563 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2564 ptrInfo.first, ptrInfo.second,
2565 offsetInBits, 0, fieldType);
2567 fieldType = createFieldType(name, variable->getType(), 0,
2568 loc, AS_public, offsetInBits, tunit, tunit);
2570 fields.push_back(fieldType);
2573 SmallString<36> typeName;
2574 llvm::raw_svector_ostream(typeName)
2575 << "__block_literal_" << CGM.getUniqueBlockCount();
2577 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2580 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2581 CGM.getContext().toBits(block.BlockSize),
2582 CGM.getContext().toBits(block.BlockAlign),
2584 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2586 // Get overall information about the block.
2587 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2588 llvm::MDNode *scope = LexicalBlockStack.back();
2589 StringRef name = ".block_descriptor";
2591 // Create the descriptor for the parameter.
2592 llvm::DIVariable debugVar =
2593 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2594 llvm::DIDescriptor(scope),
2595 name, tunit, line, type,
2596 CGM.getLangOpts().Optimize, flags,
2597 cast<llvm::Argument>(addr)->getArgNo() + 1);
2599 // Insert an llvm.dbg.value into the current block.
2600 llvm::Instruction *declare =
2601 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2602 Builder.GetInsertBlock());
2603 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2606 /// EmitGlobalVariable - Emit information about a global variable.
2607 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2609 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2610 // Create global variable debug descriptor.
2611 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2612 unsigned LineNo = getLineNumber(D->getLocation());
2614 setLocation(D->getLocation());
2616 QualType T = D->getType();
2617 if (T->isIncompleteArrayType()) {
2619 // CodeGen turns int[] into int[1] so we'll do the same here.
2620 llvm::APInt ConstVal(32, 1);
2621 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2623 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2624 ArrayType::Normal, 0);
2626 StringRef DeclName = D->getName();
2627 StringRef LinkageName;
2628 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2629 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2630 LinkageName = Var->getName();
2631 if (LinkageName == DeclName)
2632 LinkageName = StringRef();
2633 llvm::DIDescriptor DContext =
2634 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2635 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2636 Unit, LineNo, getOrCreateType(T, Unit),
2637 Var->hasInternalLinkage(), Var);
2640 /// EmitGlobalVariable - Emit information about an objective-c interface.
2641 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2642 ObjCInterfaceDecl *ID) {
2643 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2644 // Create global variable debug descriptor.
2645 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2646 unsigned LineNo = getLineNumber(ID->getLocation());
2648 StringRef Name = ID->getName();
2650 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2651 if (T->isIncompleteArrayType()) {
2653 // CodeGen turns int[] into int[1] so we'll do the same here.
2654 llvm::APInt ConstVal(32, 1);
2655 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2657 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2658 ArrayType::Normal, 0);
2661 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2662 getOrCreateType(T, Unit),
2663 Var->hasInternalLinkage(), Var);
2666 /// EmitGlobalVariable - Emit global variable's debug info.
2667 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2668 llvm::Constant *Init) {
2669 assert(CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo);
2670 // Create the descriptor for the variable.
2671 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2672 StringRef Name = VD->getName();
2673 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2674 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2675 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2676 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2677 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2679 // Do not use DIGlobalVariable for enums.
2680 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2682 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2683 getLineNumber(VD->getLocation()),
2687 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2690 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2691 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2692 NameSpaceCache.find(NSDecl);
2693 if (I != NameSpaceCache.end())
2694 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2696 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2697 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2698 llvm::DIDescriptor Context =
2699 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2700 llvm::DINameSpace NS =
2701 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2702 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2706 void CGDebugInfo::finalize(void) {
2707 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2708 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2709 llvm::DIType Ty, RepTy;
2710 // Verify that the debug info still exists.
2711 if (llvm::Value *V = VI->second)
2712 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2714 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2715 TypeCache.find(VI->first);
2716 if (it != TypeCache.end()) {
2717 // Verify that the debug info still exists.
2718 if (llvm::Value *V = it->second)
2719 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2722 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2723 Ty.replaceAllUsesWith(RepTy);
2726 DBuilder.finalize();