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 "CGObjCRuntime.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclFriend.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/Version.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/Intrinsics.h"
33 #include "llvm/Module.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/Support/Dwarf.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/DataLayout.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43 : CGM(CGM), DBuilder(CGM.getModule()),
44 BlockLiteralGenericSet(false) {
48 CGDebugInfo::~CGDebugInfo() {
49 assert(LexicalBlockStack.empty() &&
50 "Region stack mismatch, stack not empty!");
53 void CGDebugInfo::setLocation(SourceLocation Loc) {
54 // If the new location isn't valid return.
55 if (!Loc.isValid()) return;
57 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
59 // If we've changed files in the middle of a lexical scope go ahead
60 // and create a new lexical scope with file node if it's different
61 // from the one in the scope.
62 if (LexicalBlockStack.empty()) return;
64 SourceManager &SM = CGM.getContext().getSourceManager();
65 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
68 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 llvm::MDNode *LB = LexicalBlockStack.back();
73 llvm::DIScope Scope = llvm::DIScope(LB);
74 if (Scope.isLexicalBlockFile()) {
75 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
77 = DBuilder.createLexicalBlockFile(LBF.getScope(),
78 getOrCreateFile(CurLoc));
80 LexicalBlockStack.pop_back();
81 LexicalBlockStack.push_back(N);
82 } else if (Scope.isLexicalBlock()) {
84 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
86 LexicalBlockStack.pop_back();
87 LexicalBlockStack.push_back(N);
91 /// getContextDescriptor - Get context info for the decl.
92 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
96 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97 I = RegionMap.find(Context);
98 if (I != RegionMap.end()) {
99 llvm::Value *V = I->second;
100 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
108 if (!RDecl->isDependentType()) {
109 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110 getOrCreateMainFile());
111 return llvm::DIDescriptor(Ty);
117 /// getFunctionName - Get function name for the given FunctionDecl. If the
118 /// name is constructred on demand (e.g. C++ destructor) then the name
119 /// is stored on the side.
120 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
121 assert (FD && "Invalid FunctionDecl!");
122 IdentifierInfo *FII = FD->getIdentifier();
123 FunctionTemplateSpecializationInfo *Info
124 = FD->getTemplateSpecializationInfo();
126 return FII->getName();
128 // Otherwise construct human readable name for debug info.
129 std::string NS = FD->getNameAsString();
131 // Add any template specialization args.
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
137 NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
142 // Copy this name on the side and use its reference.
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
144 memcpy(StrPtr, NS.data(), NS.length());
145 return StringRef(StrPtr, NS.length());
148 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
153 if (const ObjCImplementationDecl *OID =
154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
156 } else if (const ObjCInterfaceDecl *OID =
157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
159 } else if (const ObjCCategoryImplDecl *OCD =
160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
164 OS << ' ' << OMD->getSelector().getAsString() << ']';
166 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
167 memcpy(StrPtr, MethodName.begin(), OS.tell());
168 return StringRef(StrPtr, OS.tell());
171 /// getSelectorName - Return selector name. This is used for debugging
173 StringRef CGDebugInfo::getSelectorName(Selector S) {
174 const std::string &SName = S.getAsString();
175 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
176 memcpy(StrPtr, SName.data(), SName.size());
177 return StringRef(StrPtr, SName.size());
180 /// getClassName - Get class name including template argument list.
182 CGDebugInfo::getClassName(const RecordDecl *RD) {
183 const ClassTemplateSpecializationDecl *Spec
184 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
186 return RD->getName();
188 const TemplateArgument *Args;
190 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
191 const TemplateSpecializationType *TST =
192 cast<TemplateSpecializationType>(TAW->getType());
193 Args = TST->getArgs();
194 NumArgs = TST->getNumArgs();
196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
197 Args = TemplateArgs.data();
198 NumArgs = TemplateArgs.size();
200 StringRef Name = RD->getIdentifier()->getName();
201 PrintingPolicy Policy(CGM.getLangOpts());
202 std::string TemplateArgList =
203 TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
205 // Copy this name on the side and use its reference.
206 size_t Length = Name.size() + TemplateArgList.size();
207 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
208 memcpy(StrPtr, Name.data(), Name.size());
209 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
210 return StringRef(StrPtr, Length);
213 /// getOrCreateFile - Get the file debug info descriptor for the input location.
214 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
216 // If Location is not valid then use main input file.
217 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
219 SourceManager &SM = CGM.getContext().getSourceManager();
220 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
222 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
223 // If the location is not valid then use main input file.
224 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
226 // Cache the results.
227 const char *fname = PLoc.getFilename();
228 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
229 DIFileCache.find(fname);
231 if (it != DIFileCache.end()) {
232 // Verify that the information still exists.
233 if (llvm::Value *V = it->second)
234 return llvm::DIFile(cast<llvm::MDNode>(V));
237 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
239 DIFileCache[fname] = F;
243 /// getOrCreateMainFile - Get the file info for main compile unit.
244 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
245 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
248 /// getLineNumber - Get line number for the location. If location is invalid
249 /// then use current location.
250 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
251 if (Loc.isInvalid() && CurLoc.isInvalid())
253 SourceManager &SM = CGM.getContext().getSourceManager();
254 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
255 return PLoc.isValid()? PLoc.getLine() : 0;
258 /// getColumnNumber - Get column number for the location.
259 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
260 // We may not want column information at all.
261 if (!CGM.getCodeGenOpts().DebugColumnInfo)
264 // If the location is invalid then use the current column.
265 if (Loc.isInvalid() && CurLoc.isInvalid())
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
269 return PLoc.isValid()? PLoc.getColumn() : 0;
272 StringRef CGDebugInfo::getCurrentDirname() {
273 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
274 return CGM.getCodeGenOpts().DebugCompilationDir;
276 if (!CWDName.empty())
278 SmallString<256> CWD;
279 llvm::sys::fs::current_path(CWD);
280 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
281 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
282 return CWDName = StringRef(CompDirnamePtr, CWD.size());
285 /// CreateCompileUnit - Create new compile unit.
286 void CGDebugInfo::CreateCompileUnit() {
288 // Get absolute path name.
289 SourceManager &SM = CGM.getContext().getSourceManager();
290 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
291 if (MainFileName.empty())
292 MainFileName = "<unknown>";
294 // The main file name provided via the "-main-file-name" option contains just
295 // the file name itself with no path information. This file name may have had
296 // a relative path, so we look into the actual file entry for the main
297 // file to determine the real absolute path for the file.
298 std::string MainFileDir;
299 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
300 MainFileDir = MainFile->getDir()->getName();
301 if (MainFileDir != ".")
302 MainFileName = MainFileDir + "/" + MainFileName;
305 // Save filename string.
306 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
307 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
308 StringRef Filename(FilenamePtr, MainFileName.length());
311 const LangOptions &LO = CGM.getLangOpts();
314 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
316 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
317 } else if (LO.ObjC1) {
318 LangTag = llvm::dwarf::DW_LANG_ObjC;
320 LangTag = llvm::dwarf::DW_LANG_C99;
322 LangTag = llvm::dwarf::DW_LANG_C89;
325 std::string Producer = getClangFullVersion();
327 // Figure out which version of the ObjC runtime we have.
328 unsigned RuntimeVers = 0;
330 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
332 // Create new compile unit.
333 DBuilder.createCompileUnit(
334 LangTag, Filename, getCurrentDirname(),
336 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
337 // FIXME - Eliminate TheCU.
338 TheCU = llvm::DICompileUnit(DBuilder.getCU());
341 /// CreateType - Get the Basic type from the cache or create a new
342 /// one if necessary.
343 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
344 unsigned Encoding = 0;
346 switch (BT->getKind()) {
347 #define BUILTIN_TYPE(Id, SingletonId)
348 #define PLACEHOLDER_TYPE(Id, SingletonId) \
349 case BuiltinType::Id:
350 #include "clang/AST/BuiltinTypes.def"
351 case BuiltinType::Dependent:
352 llvm_unreachable("Unexpected builtin type");
353 case BuiltinType::NullPtr:
355 createNullPtrType(BT->getName(CGM.getLangOpts()));
356 case BuiltinType::Void:
357 return llvm::DIType();
358 case BuiltinType::ObjCClass:
359 if (ClassTy.Verify())
361 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
363 getOrCreateMainFile(), 0);
365 case BuiltinType::ObjCId: {
366 // typedef struct objc_class *Class;
367 // typedef struct objc_object {
374 if (!ClassTy.Verify())
375 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
377 getOrCreateMainFile(), 0);
379 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
381 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
383 llvm::DIType FwdTy = DBuilder.createStructType(TheCU, "objc_object",
384 getOrCreateMainFile(),
388 llvm::TrackingVH<llvm::MDNode> ObjNode(FwdTy);
389 SmallVector<llvm::Value *, 1> EltTys;
390 llvm::DIType FieldTy =
391 DBuilder.createMemberType(llvm::DIDescriptor(ObjNode), "isa",
392 getOrCreateMainFile(), 0, Size,
394 EltTys.push_back(FieldTy);
395 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
397 ObjNode->replaceOperandWith(10, Elements);
398 ObjTy = llvm::DIType(ObjNode);
401 case BuiltinType::ObjCSel: {
405 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
406 "objc_selector", TheCU, getOrCreateMainFile(),
410 case BuiltinType::UChar:
411 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
412 case BuiltinType::Char_S:
413 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
414 case BuiltinType::Char16:
415 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
416 case BuiltinType::UShort:
417 case BuiltinType::UInt:
418 case BuiltinType::UInt128:
419 case BuiltinType::ULong:
420 case BuiltinType::WChar_U:
421 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
422 case BuiltinType::Short:
423 case BuiltinType::Int:
424 case BuiltinType::Int128:
425 case BuiltinType::Long:
426 case BuiltinType::WChar_S:
427 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
428 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
429 case BuiltinType::Half:
430 case BuiltinType::Float:
431 case BuiltinType::LongDouble:
432 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
435 switch (BT->getKind()) {
436 case BuiltinType::Long: BTName = "long int"; break;
437 case BuiltinType::LongLong: BTName = "long long int"; break;
438 case BuiltinType::ULong: BTName = "long unsigned int"; break;
439 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
441 BTName = BT->getName(CGM.getLangOpts());
444 // Bit size, align and offset of the type.
445 uint64_t Size = CGM.getContext().getTypeSize(BT);
446 uint64_t Align = CGM.getContext().getTypeAlign(BT);
448 DBuilder.createBasicType(BTName, Size, Align, Encoding);
452 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
453 // Bit size, align and offset of the type.
454 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
455 if (Ty->isComplexIntegerType())
456 Encoding = llvm::dwarf::DW_ATE_lo_user;
458 uint64_t Size = CGM.getContext().getTypeSize(Ty);
459 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
461 DBuilder.createBasicType("complex", Size, Align, Encoding);
466 /// CreateCVRType - Get the qualified type from the cache or create
467 /// a new one if necessary.
468 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
469 QualifierCollector Qc;
470 const Type *T = Qc.strip(Ty);
472 // Ignore these qualifiers for now.
473 Qc.removeObjCGCAttr();
474 Qc.removeAddressSpace();
475 Qc.removeObjCLifetime();
477 // We will create one Derived type for one qualifier and recurse to handle any
481 Tag = llvm::dwarf::DW_TAG_const_type;
483 } else if (Qc.hasVolatile()) {
484 Tag = llvm::dwarf::DW_TAG_volatile_type;
486 } else if (Qc.hasRestrict()) {
487 Tag = llvm::dwarf::DW_TAG_restrict_type;
490 assert(Qc.empty() && "Unknown type qualifier for debug info");
491 return getOrCreateType(QualType(T, 0), Unit);
494 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
496 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
497 // CVR derived types.
498 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
503 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
506 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
507 Ty->getPointeeType(), Unit);
511 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
513 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
514 Ty->getPointeeType(), Unit);
517 // Creates a forward declaration for a RecordDecl in the given context.
518 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
519 llvm::DIDescriptor Ctx) {
520 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
521 unsigned Line = getLineNumber(RD->getLocation());
522 StringRef RDName = getClassName(RD);
525 if (RD->isStruct() || RD->isInterface())
526 Tag = llvm::dwarf::DW_TAG_structure_type;
527 else if (RD->isUnion())
528 Tag = llvm::dwarf::DW_TAG_union_type;
530 assert(RD->isClass());
531 Tag = llvm::dwarf::DW_TAG_class_type;
535 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
538 // Walk up the context chain and create forward decls for record decls,
539 // and normal descriptors for namespaces.
540 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
544 // See if we already have the parent.
545 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
546 I = RegionMap.find(Context);
547 if (I != RegionMap.end()) {
548 llvm::Value *V = I->second;
549 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
553 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
554 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
556 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
557 if (!RD->isDependentType()) {
558 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
559 getOrCreateMainFile());
560 return llvm::DIDescriptor(Ty);
566 /// CreatePointeeType - Create Pointee type. If Pointee is a record
567 /// then emit record's fwd if debug info size reduction is enabled.
568 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
570 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
571 return getOrCreateType(PointeeTy, Unit);
573 // Limit debug info for the pointee type.
575 // If we have an existing type, use that, it's still smaller than creating
577 llvm::DIType Ty = getTypeOrNull(PointeeTy);
578 if (Ty.Verify()) return Ty;
580 // Handle qualifiers.
581 if (PointeeTy.hasLocalQualifiers())
582 return CreateQualifiedType(PointeeTy, Unit);
584 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
585 RecordDecl *RD = RTy->getDecl();
586 llvm::DIDescriptor FDContext =
587 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
588 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
589 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
592 return getOrCreateType(PointeeTy, Unit);
596 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
600 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
601 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
602 return DBuilder.createReferenceType(Tag,
603 CreatePointeeType(PointeeTy, Unit));
605 // Bit size, align and offset of the type.
606 // Size is always the size of a pointer. We can't use getTypeSize here
607 // because that does not return the correct value for references.
608 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
609 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
610 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
612 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
616 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
618 if (BlockLiteralGenericSet)
619 return BlockLiteralGeneric;
621 SmallVector<llvm::Value *, 8> EltTys;
622 llvm::DIType FieldTy;
624 uint64_t FieldSize, FieldOffset;
626 llvm::DIArray Elements;
627 llvm::DIType EltTy, DescTy;
630 FType = CGM.getContext().UnsignedLongTy;
631 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
632 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
634 Elements = DBuilder.getOrCreateArray(EltTys);
637 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
638 unsigned LineNo = getLineNumber(CurLoc);
640 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
641 Unit, LineNo, FieldOffset, 0,
644 // Bit size, align and offset of the type.
645 uint64_t Size = CGM.getContext().getTypeSize(Ty);
647 DescTy = DBuilder.createPointerType(EltTy, Size);
650 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
651 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
652 FType = CGM.getContext().IntTy;
653 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
654 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
655 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
656 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
658 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
660 FieldSize = CGM.getContext().getTypeSize(Ty);
661 FieldAlign = CGM.getContext().getTypeAlign(Ty);
662 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
663 LineNo, FieldSize, FieldAlign,
664 FieldOffset, 0, FieldTy);
665 EltTys.push_back(FieldTy);
667 FieldOffset += FieldSize;
668 Elements = DBuilder.getOrCreateArray(EltTys);
670 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
671 Unit, LineNo, FieldOffset, 0,
674 BlockLiteralGenericSet = true;
675 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
676 return BlockLiteralGeneric;
679 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
680 // Typedefs are derived from some other type. If we have a typedef of a
681 // typedef, make sure to emit the whole chain.
682 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
684 return llvm::DIType();
685 // We don't set size information, but do specify where the typedef was
687 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
688 const TypedefNameDecl *TyDecl = Ty->getDecl();
690 llvm::DIDescriptor TypedefContext =
691 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
694 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
697 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
699 SmallVector<llvm::Value *, 16> EltTys;
701 // Add the result type at least.
702 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
704 // Set up remainder of arguments if there is a prototype.
705 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
706 if (isa<FunctionNoProtoType>(Ty))
707 EltTys.push_back(DBuilder.createUnspecifiedParameter());
708 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
709 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
710 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
713 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
714 return DBuilder.createSubroutineType(Unit, EltTypeArray);
719 CollectRecordStaticVars(const RecordDecl *RD, llvm::DIType FwdDecl) {
721 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
723 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
725 const APValue *Value = V->evaluateValue();
726 if (Value && Value->isInt()) {
727 llvm::ConstantInt *CI
728 = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
730 // Create the descriptor for static variable.
731 llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
732 StringRef VName = V->getName();
733 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
734 // Do not use DIGlobalVariable for enums.
735 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
736 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
737 getLineNumber(V->getLocation()),
745 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
747 uint64_t sizeInBitsOverride,
750 uint64_t offsetInBits,
752 llvm::DIDescriptor scope) {
753 llvm::DIType debugType = getOrCreateType(type, tunit);
755 // Get the location for the field.
756 llvm::DIFile file = getOrCreateFile(loc);
757 unsigned line = getLineNumber(loc);
759 uint64_t sizeInBits = 0;
760 unsigned alignInBits = 0;
761 if (!type->isIncompleteArrayType()) {
762 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
764 if (sizeInBitsOverride)
765 sizeInBits = sizeInBitsOverride;
769 if (AS == clang::AS_private)
770 flags |= llvm::DIDescriptor::FlagPrivate;
771 else if (AS == clang::AS_protected)
772 flags |= llvm::DIDescriptor::FlagProtected;
774 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
775 alignInBits, offsetInBits, flags, debugType);
778 /// CollectRecordFields - A helper function to collect debug info for
779 /// record fields. This is used while creating debug info entry for a Record.
781 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
782 SmallVectorImpl<llvm::Value *> &elements,
783 llvm::DIType RecordTy) {
784 unsigned fieldNo = 0;
785 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
786 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
788 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
789 // has the name and the location of the variable so we should iterate over
790 // both concurrently.
791 if (CXXDecl && CXXDecl->isLambda()) {
792 RecordDecl::field_iterator Field = CXXDecl->field_begin();
793 unsigned fieldno = 0;
794 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
795 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
796 const LambdaExpr::Capture C = *I;
797 if (C.capturesVariable()) {
798 VarDecl *V = C.getCapturedVar();
799 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
800 StringRef VName = V->getName();
801 uint64_t SizeInBitsOverride = 0;
802 if (Field->isBitField()) {
803 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
804 assert(SizeInBitsOverride && "found named 0-width bitfield");
806 llvm::DIType fieldType
807 = createFieldType(VName, Field->getType(), SizeInBitsOverride, C.getLocation(),
808 Field->getAccess(), layout.getFieldOffset(fieldno),
810 elements.push_back(fieldType);
812 // TODO: Need to handle 'this' in some way by probably renaming the
813 // this of the lambda class and having a field member of 'this' or
814 // by using AT_object_pointer for the function and having that be
815 // used as 'this' for semantic references.
816 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
817 FieldDecl *f = *Field;
818 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
819 QualType type = f->getType();
820 llvm::DIType fieldType
821 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
822 layout.getFieldOffset(fieldNo), VUnit, RecordTy);
824 elements.push_back(fieldType);
828 bool IsMsStruct = record->isMsStruct(CGM.getContext());
829 const FieldDecl *LastFD = 0;
830 for (RecordDecl::field_iterator I = record->field_begin(),
831 E = record->field_end();
832 I != E; ++I, ++fieldNo) {
833 FieldDecl *field = *I;
836 // Zero-length bitfields following non-bitfield members are ignored
837 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
844 StringRef name = field->getName();
845 QualType type = field->getType();
847 // Ignore unnamed fields unless they're anonymous structs/unions.
848 if (name.empty() && !type->isRecordType()) {
853 uint64_t SizeInBitsOverride = 0;
854 if (field->isBitField()) {
855 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
856 assert(SizeInBitsOverride && "found named 0-width bitfield");
859 llvm::DIType fieldType
860 = createFieldType(name, type, SizeInBitsOverride,
861 field->getLocation(), field->getAccess(),
862 layout.getFieldOffset(fieldNo), tunit, RecordTy);
864 elements.push_back(fieldType);
869 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
870 /// function type is not updated to include implicit "this" pointer. Use this
871 /// routine to get a method type which includes "this" pointer.
873 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
876 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
880 // Add "this" pointer.
881 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
882 assert (Args.getNumElements() && "Invalid number of arguments!");
884 SmallVector<llvm::Value *, 16> Elts;
886 // First element is always return type. For 'void' functions it is NULL.
887 Elts.push_back(Args.getElement(0));
889 if (!Method->isStatic()) {
890 // "this" pointer is always first argument.
891 QualType ThisPtr = Method->getThisType(CGM.getContext());
893 const CXXRecordDecl *RD = Method->getParent();
894 if (isa<ClassTemplateSpecializationDecl>(RD)) {
895 // Create pointer type directly in this case.
896 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
897 QualType PointeeTy = ThisPtrTy->getPointeeType();
898 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
899 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
900 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
901 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
902 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
903 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
904 // TODO: This and the artificial type below are misleading, the
905 // types aren't artificial the argument is, but the current
906 // metadata doesn't represent that.
907 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
908 Elts.push_back(ThisPtrType);
910 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
911 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
912 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
913 Elts.push_back(ThisPtrType);
917 // Copy rest of the arguments.
918 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
919 Elts.push_back(Args.getElement(i));
921 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
923 return DBuilder.createSubroutineType(Unit, EltTypeArray);
926 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
927 /// inside a function.
928 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
929 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
930 return isFunctionLocalClass(NRD);
931 if (isa<FunctionDecl>(RD->getDeclContext()))
936 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
937 /// a single member function GlobalDecl.
939 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
941 llvm::DIType RecordTy) {
943 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
945 StringRef MethodName = getFunctionName(Method);
946 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
948 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
949 // make sense to give a single ctor/dtor a linkage name.
950 StringRef MethodLinkageName;
951 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
952 MethodLinkageName = CGM.getMangledName(Method);
954 // Get the location for the method.
955 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
956 unsigned MethodLine = getLineNumber(Method->getLocation());
958 // Collect virtual method info.
959 llvm::DIType ContainingType;
960 unsigned Virtuality = 0;
963 if (Method->isVirtual()) {
964 if (Method->isPure())
965 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
967 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
969 // It doesn't make sense to give a virtual destructor a vtable index,
970 // since a single destructor has two entries in the vtable.
971 if (!isa<CXXDestructorDecl>(Method))
972 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
973 ContainingType = RecordTy;
977 if (Method->isImplicit())
978 Flags |= llvm::DIDescriptor::FlagArtificial;
979 AccessSpecifier Access = Method->getAccess();
980 if (Access == clang::AS_private)
981 Flags |= llvm::DIDescriptor::FlagPrivate;
982 else if (Access == clang::AS_protected)
983 Flags |= llvm::DIDescriptor::FlagProtected;
984 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
985 if (CXXC->isExplicit())
986 Flags |= llvm::DIDescriptor::FlagExplicit;
987 } else if (const CXXConversionDecl *CXXC =
988 dyn_cast<CXXConversionDecl>(Method)) {
989 if (CXXC->isExplicit())
990 Flags |= llvm::DIDescriptor::FlagExplicit;
992 if (Method->hasPrototype())
993 Flags |= llvm::DIDescriptor::FlagPrototyped;
995 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
996 llvm::DISubprogram SP =
997 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
998 MethodDefUnit, MethodLine,
999 MethodTy, /*isLocalToUnit=*/false,
1000 /* isDefinition=*/ false,
1001 Virtuality, VIndex, ContainingType,
1002 Flags, CGM.getLangOpts().Optimize, NULL,
1005 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1010 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1011 /// C++ member functions. This is used while creating debug info entry for
1014 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1015 SmallVectorImpl<llvm::Value *> &EltTys,
1016 llvm::DIType RecordTy) {
1018 // Since we want more than just the individual member decls if we
1019 // have templated functions iterate over every declaration to gather
1021 for(DeclContext::decl_iterator I = RD->decls_begin(),
1022 E = RD->decls_end(); I != E; ++I) {
1024 if (D->isImplicit() && !D->isUsed())
1027 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1028 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1029 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1030 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1031 SE = FTD->spec_end(); SI != SE; ++SI)
1032 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1037 /// CollectCXXFriends - A helper function to collect debug info for
1038 /// C++ base classes. This is used while creating debug info entry for
1041 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1042 SmallVectorImpl<llvm::Value *> &EltTys,
1043 llvm::DIType RecordTy) {
1044 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1045 BE = RD->friend_end(); BI != BE; ++BI) {
1046 if ((*BI)->isUnsupportedFriend())
1048 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1049 EltTys.push_back(DBuilder.createFriend(RecordTy,
1050 getOrCreateType(TInfo->getType(),
1055 /// CollectCXXBases - A helper function to collect debug info for
1056 /// C++ base classes. This is used while creating debug info entry for
1059 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1060 SmallVectorImpl<llvm::Value *> &EltTys,
1061 llvm::DIType RecordTy) {
1063 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1064 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1065 BE = RD->bases_end(); BI != BE; ++BI) {
1066 unsigned BFlags = 0;
1067 uint64_t BaseOffset;
1069 const CXXRecordDecl *Base =
1070 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1072 if (BI->isVirtual()) {
1073 // virtual base offset offset is -ve. The code generator emits dwarf
1074 // expression where it expects +ve number.
1076 0 - CGM.getVTableContext()
1077 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1078 BFlags = llvm::DIDescriptor::FlagVirtual;
1080 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1081 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1082 // BI->isVirtual() and bits when not.
1084 AccessSpecifier Access = BI->getAccessSpecifier();
1085 if (Access == clang::AS_private)
1086 BFlags |= llvm::DIDescriptor::FlagPrivate;
1087 else if (Access == clang::AS_protected)
1088 BFlags |= llvm::DIDescriptor::FlagProtected;
1091 DBuilder.createInheritance(RecordTy,
1092 getOrCreateType(BI->getType(), Unit),
1093 BaseOffset, BFlags);
1094 EltTys.push_back(DTy);
1098 /// CollectTemplateParams - A helper function to collect template parameters.
1099 llvm::DIArray CGDebugInfo::
1100 CollectTemplateParams(const TemplateParameterList *TPList,
1101 const TemplateArgumentList &TAList,
1102 llvm::DIFile Unit) {
1103 SmallVector<llvm::Value *, 16> TemplateParams;
1104 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1105 const TemplateArgument &TA = TAList[i];
1106 const NamedDecl *ND = TPList->getParam(i);
1107 if (TA.getKind() == TemplateArgument::Type) {
1108 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1109 llvm::DITemplateTypeParameter TTP =
1110 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1111 TemplateParams.push_back(TTP);
1112 } else if (TA.getKind() == TemplateArgument::Integral) {
1113 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1114 llvm::DITemplateValueParameter TVP =
1115 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1116 TA.getAsIntegral().getZExtValue());
1117 TemplateParams.push_back(TVP);
1120 return DBuilder.getOrCreateArray(TemplateParams);
1123 /// CollectFunctionTemplateParams - A helper function to collect debug
1124 /// info for function template parameters.
1125 llvm::DIArray CGDebugInfo::
1126 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1127 if (FD->getTemplatedKind() ==
1128 FunctionDecl::TK_FunctionTemplateSpecialization) {
1129 const TemplateParameterList *TList =
1130 FD->getTemplateSpecializationInfo()->getTemplate()
1131 ->getTemplateParameters();
1133 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1135 return llvm::DIArray();
1138 /// CollectCXXTemplateParams - A helper function to collect debug info for
1139 /// template parameters.
1140 llvm::DIArray CGDebugInfo::
1141 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1142 llvm::DIFile Unit) {
1143 llvm::PointerUnion<ClassTemplateDecl *,
1144 ClassTemplatePartialSpecializationDecl *>
1145 PU = TSpecial->getSpecializedTemplateOrPartial();
1147 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1148 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1149 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1150 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1151 return CollectTemplateParams(TPList, TAList, Unit);
1154 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1155 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1156 if (VTablePtrType.isValid())
1157 return VTablePtrType;
1159 ASTContext &Context = CGM.getContext();
1162 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1163 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1164 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1165 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1166 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1168 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1169 return VTablePtrType;
1172 /// getVTableName - Get vtable name for the given Class.
1173 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1174 // Construct gdb compatible name name.
1175 std::string Name = "_vptr$" + RD->getNameAsString();
1177 // Copy this name on the side and use its reference.
1178 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1179 memcpy(StrPtr, Name.data(), Name.length());
1180 return StringRef(StrPtr, Name.length());
1184 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1185 /// debug info entry in EltTys vector.
1187 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1188 SmallVectorImpl<llvm::Value *> &EltTys) {
1189 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1191 // If there is a primary base then it will hold vtable info.
1192 if (RL.getPrimaryBase())
1195 // If this class is not dynamic then there is not any vtable info to collect.
1196 if (!RD->isDynamicClass())
1199 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1201 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1203 getOrCreateVTablePtrType(Unit));
1204 EltTys.push_back(VPTR);
1207 /// getOrCreateRecordType - Emit record type's standalone debug info.
1208 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1209 SourceLocation Loc) {
1210 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1211 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1215 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1217 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1218 SourceLocation Loc) {
1219 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1220 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1221 DBuilder.retainType(T);
1225 /// CreateType - get structure or union type.
1226 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1227 RecordDecl *RD = Ty->getDecl();
1229 // Get overall information about the record type for the debug info.
1230 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1232 // Records and classes and unions can all be recursive. To handle them, we
1233 // first generate a debug descriptor for the struct as a forward declaration.
1234 // Then (if it is a definition) we go through and get debug info for all of
1235 // its members. Finally, we create a descriptor for the complete type (which
1236 // may refer to the forward decl if the struct is recursive) and replace all
1237 // uses of the forward declaration with the final definition.
1239 llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1241 if (FwdDecl.isForwardDecl())
1244 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1246 // Push the struct on region stack.
1247 LexicalBlockStack.push_back(FwdDeclNode);
1248 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1250 // Add this to the completed types cache since we're completing it.
1251 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1253 // Convert all the elements.
1254 SmallVector<llvm::Value *, 16> EltTys;
1256 // Note: The split of CXXDecl information here is intentional, the
1257 // gdb tests will depend on a certain ordering at printout. The debug
1258 // information offsets are still correct if we merge them all together
1260 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1262 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1263 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1266 // Collect static variables with initializers and other fields.
1267 CollectRecordStaticVars(RD, FwdDecl);
1268 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1269 llvm::DIArray TParamsArray;
1271 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1272 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1273 if (const ClassTemplateSpecializationDecl *TSpecial
1274 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1275 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1278 LexicalBlockStack.pop_back();
1279 RegionMap.erase(Ty->getDecl());
1281 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1282 // FIXME: Magic numbers ahoy! These should be changed when we
1283 // get some enums in llvm/Analysis/DebugInfo.h to refer to
1286 FwdDeclNode->replaceOperandWith(10, Elements);
1288 FwdDeclNode->replaceOperandWith(10, Elements);
1289 FwdDeclNode->replaceOperandWith(13, TParamsArray);
1291 FwdDeclNode->replaceOperandWith(10, Elements);
1293 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1294 return llvm::DIType(FwdDeclNode);
1297 /// CreateType - get objective-c object type.
1298 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1299 llvm::DIFile Unit) {
1300 // Ignore protocols.
1301 return getOrCreateType(Ty->getBaseType(), Unit);
1304 /// CreateType - get objective-c interface type.
1305 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1306 llvm::DIFile Unit) {
1307 ObjCInterfaceDecl *ID = Ty->getDecl();
1309 return llvm::DIType();
1311 // Get overall information about the record type for the debug info.
1312 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1313 unsigned Line = getLineNumber(ID->getLocation());
1314 unsigned RuntimeLang = TheCU.getLanguage();
1316 // If this is just a forward declaration return a special forward-declaration
1317 // debug type since we won't be able to lay out the entire type.
1318 ObjCInterfaceDecl *Def = ID->getDefinition();
1320 llvm::DIType FwdDecl =
1321 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1322 ID->getName(), TheCU, DefUnit, Line,
1329 // Bit size, align and offset of the type.
1330 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1331 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1334 if (ID->getImplementation())
1335 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1337 llvm::DIType RealDecl =
1338 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1339 Line, Size, Align, Flags,
1340 llvm::DIArray(), RuntimeLang);
1342 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1343 // will find it and we're emitting the complete type.
1344 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1345 // Push the struct on region stack.
1346 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1348 LexicalBlockStack.push_back(FwdDeclNode);
1349 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1351 // Convert all the elements.
1352 SmallVector<llvm::Value *, 16> EltTys;
1354 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1356 llvm::DIType SClassTy =
1357 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1358 if (!SClassTy.isValid())
1359 return llvm::DIType();
1361 llvm::DIType InhTag =
1362 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1363 EltTys.push_back(InhTag);
1366 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1367 E = ID->prop_end(); I != E; ++I) {
1368 const ObjCPropertyDecl *PD = *I;
1369 SourceLocation Loc = PD->getLocation();
1370 llvm::DIFile PUnit = getOrCreateFile(Loc);
1371 unsigned PLine = getLineNumber(Loc);
1372 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1373 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1374 llvm::MDNode *PropertyNode =
1375 DBuilder.createObjCProperty(PD->getName(),
1377 (Getter && Getter->isImplicit()) ? "" :
1378 getSelectorName(PD->getGetterName()),
1379 (Setter && Setter->isImplicit()) ? "" :
1380 getSelectorName(PD->getSetterName()),
1381 PD->getPropertyAttributes(),
1382 getOrCreateType(PD->getType(), PUnit));
1383 EltTys.push_back(PropertyNode);
1386 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1387 unsigned FieldNo = 0;
1388 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1389 Field = Field->getNextIvar(), ++FieldNo) {
1390 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1391 if (!FieldTy.isValid())
1392 return llvm::DIType();
1394 StringRef FieldName = Field->getName();
1396 // Ignore unnamed fields.
1397 if (FieldName.empty())
1400 // Get the location for the field.
1401 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1402 unsigned FieldLine = getLineNumber(Field->getLocation());
1403 QualType FType = Field->getType();
1404 uint64_t FieldSize = 0;
1405 unsigned FieldAlign = 0;
1407 if (!FType->isIncompleteArrayType()) {
1409 // Bit size, align and offset of the type.
1410 FieldSize = Field->isBitField()
1411 ? Field->getBitWidthValue(CGM.getContext())
1412 : CGM.getContext().getTypeSize(FType);
1413 FieldAlign = CGM.getContext().getTypeAlign(FType);
1416 uint64_t FieldOffset;
1417 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1418 // We don't know the runtime offset of an ivar if we're using the
1419 // non-fragile ABI. For bitfields, use the bit offset into the first
1420 // byte of storage of the bitfield. For other fields, use zero.
1421 if (Field->isBitField()) {
1422 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1424 FieldOffset %= CGM.getContext().getCharWidth();
1429 FieldOffset = RL.getFieldOffset(FieldNo);
1433 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1434 Flags = llvm::DIDescriptor::FlagProtected;
1435 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1436 Flags = llvm::DIDescriptor::FlagPrivate;
1438 llvm::MDNode *PropertyNode = NULL;
1439 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1440 if (ObjCPropertyImplDecl *PImpD =
1441 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1442 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1443 SourceLocation Loc = PD->getLocation();
1444 llvm::DIFile PUnit = getOrCreateFile(Loc);
1445 unsigned PLine = getLineNumber(Loc);
1446 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1447 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1449 DBuilder.createObjCProperty(PD->getName(),
1451 (Getter && Getter->isImplicit()) ? "" :
1452 getSelectorName(PD->getGetterName()),
1453 (Setter && Setter->isImplicit()) ? "" :
1454 getSelectorName(PD->getSetterName()),
1455 PD->getPropertyAttributes(),
1456 getOrCreateType(PD->getType(), PUnit));
1460 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1461 FieldLine, FieldSize, FieldAlign,
1462 FieldOffset, Flags, FieldTy,
1464 EltTys.push_back(FieldTy);
1467 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1468 FwdDeclNode->replaceOperandWith(10, Elements);
1470 LexicalBlockStack.pop_back();
1471 return llvm::DIType(FwdDeclNode);
1474 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1475 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1476 int64_t NumElems = Ty->getNumElements();
1477 int64_t LowerBound = 0;
1479 // If number of elements are not known then this is an unbounded array.
1480 // Use Low = 1, Hi = 0 to express such arrays.
1485 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1486 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1488 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1489 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1492 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1495 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1496 llvm::DIFile Unit) {
1500 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1501 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1504 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1505 } else if (Ty->isIncompleteArrayType()) {
1507 if (Ty->getElementType()->isIncompleteType())
1510 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1511 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1515 // Size and align of the whole array, not the element type.
1516 Size = CGM.getContext().getTypeSize(Ty);
1517 Align = CGM.getContext().getTypeAlign(Ty);
1520 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1521 // interior arrays, do we care? Why aren't nested arrays represented the
1522 // obvious/recursive way?
1523 SmallVector<llvm::Value *, 8> Subscripts;
1524 QualType EltTy(Ty, 0);
1525 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1526 int64_t UpperBound = 0;
1527 int64_t LowerBound = 0;
1528 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1529 if (CAT->getSize().getZExtValue())
1530 UpperBound = CAT->getSize().getZExtValue() - 1;
1532 // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1536 // FIXME: Verify this is right for VLAs.
1537 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1539 EltTy = Ty->getElementType();
1542 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1544 llvm::DIType DbgTy =
1545 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1550 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1551 llvm::DIFile Unit) {
1552 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1553 Ty, Ty->getPointeeType(), Unit);
1556 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1557 llvm::DIFile Unit) {
1558 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1559 Ty, Ty->getPointeeType(), Unit);
1562 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1564 QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1565 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1567 if (!Ty->getPointeeType()->isFunctionType()) {
1568 // We have a data member pointer type.
1569 return PointerDiffDITy;
1572 // We have a member function pointer type. Treat it as a struct with two
1573 // ptrdiff_t members.
1574 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1576 uint64_t FieldOffset = 0;
1577 llvm::Value *ElementTypes[2];
1579 // FIXME: This should be a DW_TAG_pointer_to_member type.
1581 DBuilder.createMemberType(U, "ptr", U, 0,
1582 Info.first, Info.second, FieldOffset, 0,
1584 FieldOffset += Info.first;
1587 DBuilder.createMemberType(U, "ptr", U, 0,
1588 Info.first, Info.second, FieldOffset, 0,
1591 llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1593 return DBuilder.createStructType(U, StringRef("test"),
1598 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1600 // Ignore the atomic wrapping
1601 // FIXME: What is the correct representation?
1602 return getOrCreateType(Ty->getValueType(), U);
1605 /// CreateEnumType - get enumeration type.
1606 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1609 if (!ED->getTypeForDecl()->isIncompleteType()) {
1610 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1611 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1614 // If this is just a forward declaration, construct an appropriately
1615 // marked node and just return it.
1616 if (!ED->getDefinition()) {
1617 llvm::DIDescriptor EDContext;
1618 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1619 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1620 unsigned Line = getLineNumber(ED->getLocation());
1621 StringRef EDName = ED->getName();
1622 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1623 EDName, EDContext, DefUnit, Line, 0,
1627 // Create DIEnumerator elements for each enumerator.
1628 SmallVector<llvm::Value *, 16> Enumerators;
1629 ED = ED->getDefinition();
1630 for (EnumDecl::enumerator_iterator
1631 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1632 Enum != EnumEnd; ++Enum) {
1633 Enumerators.push_back(
1634 DBuilder.createEnumerator(Enum->getName(),
1635 Enum->getInitVal().getZExtValue()));
1638 // Return a CompositeType for the enum itself.
1639 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1641 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1642 unsigned Line = getLineNumber(ED->getLocation());
1643 llvm::DIDescriptor EnumContext =
1644 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1645 llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1646 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1647 llvm::DIType DbgTy =
1648 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1649 Size, Align, EltArray,
1654 static QualType UnwrapTypeForDebugInfo(QualType T) {
1657 switch (T->getTypeClass()) {
1660 case Type::TemplateSpecialization:
1661 T = cast<TemplateSpecializationType>(T)->desugar();
1663 case Type::TypeOfExpr:
1664 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1667 T = cast<TypeOfType>(T)->getUnderlyingType();
1669 case Type::Decltype:
1670 T = cast<DecltypeType>(T)->getUnderlyingType();
1672 case Type::UnaryTransform:
1673 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1675 case Type::Attributed:
1676 T = cast<AttributedType>(T)->getEquivalentType();
1678 case Type::Elaborated:
1679 T = cast<ElaboratedType>(T)->getNamedType();
1682 T = cast<ParenType>(T)->getInnerType();
1684 case Type::SubstTemplateTypeParm: {
1685 // We need to keep the qualifiers handy since getReplacementType()
1686 // will strip them away.
1687 unsigned Quals = T.getLocalFastQualifiers();
1688 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1689 T.addFastQualifiers(Quals);
1693 T = cast<AutoType>(T)->getDeducedType();
1697 assert(T != LastT && "Type unwrapping failed to unwrap!");
1703 /// getType - Get the type from the cache or return null type if it doesn't exist.
1704 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1706 // Unwrap the type as needed for debug information.
1707 Ty = UnwrapTypeForDebugInfo(Ty);
1709 // Check for existing entry.
1710 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1711 TypeCache.find(Ty.getAsOpaquePtr());
1712 if (it != TypeCache.end()) {
1713 // Verify that the debug info still exists.
1714 if (llvm::Value *V = it->second)
1715 return llvm::DIType(cast<llvm::MDNode>(V));
1718 return llvm::DIType();
1721 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1723 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1725 // Unwrap the type as needed for debug information.
1726 Ty = UnwrapTypeForDebugInfo(Ty);
1728 // Check for existing entry.
1729 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1730 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1731 if (it != CompletedTypeCache.end()) {
1732 // Verify that the debug info still exists.
1733 if (llvm::Value *V = it->second)
1734 return llvm::DIType(cast<llvm::MDNode>(V));
1737 return llvm::DIType();
1741 /// getOrCreateType - Get the type from the cache or create a new
1742 /// one if necessary.
1743 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1745 return llvm::DIType();
1747 // Unwrap the type as needed for debug information.
1748 Ty = UnwrapTypeForDebugInfo(Ty);
1750 llvm::DIType T = getCompletedTypeOrNull(Ty);
1755 // Otherwise create the type.
1756 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1758 llvm::DIType TC = getTypeOrNull(Ty);
1759 if (TC.Verify() && TC.isForwardDecl())
1760 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1761 static_cast<llvm::Value*>(TC)));
1763 // And update the type cache.
1764 TypeCache[Ty.getAsOpaquePtr()] = Res;
1766 if (!Res.isForwardDecl())
1767 CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1772 /// CreateTypeNode - Create a new debug type node.
1773 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1774 // Handle qualifiers, which recursively handles what they refer to.
1775 if (Ty.hasLocalQualifiers())
1776 return CreateQualifiedType(Ty, Unit);
1778 const char *Diag = 0;
1780 // Work out details of type.
1781 switch (Ty->getTypeClass()) {
1782 #define TYPE(Class, Base)
1783 #define ABSTRACT_TYPE(Class, Base)
1784 #define NON_CANONICAL_TYPE(Class, Base)
1785 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1786 #include "clang/AST/TypeNodes.def"
1787 llvm_unreachable("Dependent types cannot show up in debug information");
1789 case Type::ExtVector:
1791 return CreateType(cast<VectorType>(Ty), Unit);
1792 case Type::ObjCObjectPointer:
1793 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1794 case Type::ObjCObject:
1795 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1796 case Type::ObjCInterface:
1797 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1799 return CreateType(cast<BuiltinType>(Ty));
1801 return CreateType(cast<ComplexType>(Ty));
1803 return CreateType(cast<PointerType>(Ty), Unit);
1804 case Type::BlockPointer:
1805 return CreateType(cast<BlockPointerType>(Ty), Unit);
1807 return CreateType(cast<TypedefType>(Ty), Unit);
1809 return CreateType(cast<RecordType>(Ty));
1811 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1812 case Type::FunctionProto:
1813 case Type::FunctionNoProto:
1814 return CreateType(cast<FunctionType>(Ty), Unit);
1815 case Type::ConstantArray:
1816 case Type::VariableArray:
1817 case Type::IncompleteArray:
1818 return CreateType(cast<ArrayType>(Ty), Unit);
1820 case Type::LValueReference:
1821 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1822 case Type::RValueReference:
1823 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1825 case Type::MemberPointer:
1826 return CreateType(cast<MemberPointerType>(Ty), Unit);
1829 return CreateType(cast<AtomicType>(Ty), Unit);
1831 case Type::Attributed:
1832 case Type::TemplateSpecialization:
1833 case Type::Elaborated:
1835 case Type::SubstTemplateTypeParm:
1836 case Type::TypeOfExpr:
1838 case Type::Decltype:
1839 case Type::UnaryTransform:
1841 llvm_unreachable("type should have been unwrapped!");
1844 assert(Diag && "Fall through without a diagnostic?");
1845 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1846 "debug information for %0 is not yet supported");
1847 CGM.getDiags().Report(DiagID)
1849 return llvm::DIType();
1852 /// getOrCreateLimitedType - Get the type from the cache or create a new
1853 /// limited type if necessary.
1854 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1855 llvm::DIFile Unit) {
1857 return llvm::DIType();
1859 // Unwrap the type as needed for debug information.
1860 Ty = UnwrapTypeForDebugInfo(Ty);
1862 llvm::DIType T = getTypeOrNull(Ty);
1864 // We may have cached a forward decl when we could have created
1865 // a non-forward decl. Go ahead and create a non-forward decl
1867 if (T.Verify() && !T.isForwardDecl()) return T;
1869 // Otherwise create the type.
1870 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1872 if (T.Verify() && T.isForwardDecl())
1873 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1874 static_cast<llvm::Value*>(T)));
1876 // And update the type cache.
1877 TypeCache[Ty.getAsOpaquePtr()] = Res;
1881 // TODO: Currently used for context chains when limiting debug info.
1882 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1883 RecordDecl *RD = Ty->getDecl();
1885 // Get overall information about the record type for the debug info.
1886 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1887 unsigned Line = getLineNumber(RD->getLocation());
1888 StringRef RDName = getClassName(RD);
1890 llvm::DIDescriptor RDContext;
1891 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
1892 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1894 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1896 // If this is just a forward declaration, construct an appropriately
1897 // marked node and just return it.
1898 if (!RD->getDefinition())
1899 return createRecordFwdDecl(RD, RDContext);
1901 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1902 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1903 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1904 llvm::TrackingVH<llvm::MDNode> RealDecl;
1907 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1908 Size, Align, 0, llvm::DIArray());
1909 else if (RD->isClass()) {
1910 // FIXME: This could be a struct type giving a default visibility different
1911 // than C++ class type, but needs llvm metadata changes first.
1912 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1913 Size, Align, 0, 0, llvm::DIType(),
1914 llvm::DIArray(), llvm::DIType(),
1917 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1918 Size, Align, 0, llvm::DIArray());
1920 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1921 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1924 // A class's primary base or the class itself contains the vtable.
1925 llvm::MDNode *ContainingType = NULL;
1926 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1927 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1928 // Seek non virtual primary base root.
1930 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1931 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1932 if (PBT && !BRL.isPrimaryBaseVirtual())
1938 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1940 else if (CXXDecl->isDynamicClass())
1941 ContainingType = RealDecl;
1943 RealDecl->replaceOperandWith(12, ContainingType);
1945 return llvm::DIType(RealDecl);
1948 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
1949 /// declare composite types that haven't been processed yet.
1950 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1952 // Work out details of type.
1953 switch (Ty->getTypeClass()) {
1954 #define TYPE(Class, Base)
1955 #define ABSTRACT_TYPE(Class, Base)
1956 #define NON_CANONICAL_TYPE(Class, Base)
1957 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1958 #include "clang/AST/TypeNodes.def"
1959 llvm_unreachable("Dependent types cannot show up in debug information");
1962 return CreateLimitedType(cast<RecordType>(Ty));
1964 return CreateTypeNode(Ty, Unit);
1968 /// CreateMemberType - Create new member and increase Offset by FType's size.
1969 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1972 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1973 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1974 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1975 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1976 FieldSize, FieldAlign,
1977 *Offset, 0, FieldTy);
1978 *Offset += FieldSize;
1982 /// getFunctionDeclaration - Return debug info descriptor to describe method
1983 /// declaration for the given method definition.
1984 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1985 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1986 if (!FD) return llvm::DISubprogram();
1989 getContextDescriptor(cast<Decl>(D->getDeclContext()));
1991 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1992 MI = SPCache.find(FD->getCanonicalDecl());
1993 if (MI != SPCache.end()) {
1994 llvm::Value *V = MI->second;
1995 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
1996 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2000 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2001 E = FD->redecls_end(); I != E; ++I) {
2002 const FunctionDecl *NextFD = *I;
2003 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2004 MI = SPCache.find(NextFD->getCanonicalDecl());
2005 if (MI != SPCache.end()) {
2006 llvm::Value *V = MI->second;
2007 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2008 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2012 return llvm::DISubprogram();
2015 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2016 // implicit parameter "this".
2017 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2021 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2022 return getOrCreateMethodType(Method, F);
2023 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2024 // Add "self" and "_cmd"
2025 SmallVector<llvm::Value *, 16> Elts;
2027 // First element is always return type. For 'void' functions it is NULL.
2028 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2029 // "self" pointer is always first argument.
2030 llvm::DIType SelfTy = getOrCreateType(OMethod->getSelfDecl()->getType(), F);
2031 Elts.push_back(DBuilder.createObjectPointerType(SelfTy));
2032 // "_cmd" pointer is always second argument.
2033 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2034 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2035 // Get rest of the arguments.
2036 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2037 PE = OMethod->param_end(); PI != PE; ++PI)
2038 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2040 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2041 return DBuilder.createSubroutineType(F, EltTypeArray);
2043 return getOrCreateType(FnType, F);
2046 /// EmitFunctionStart - Constructs the debug code for entering a function.
2047 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2049 CGBuilderTy &Builder) {
2052 StringRef LinkageName;
2054 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2056 const Decl *D = GD.getDecl();
2057 // Function may lack declaration in source code if it is created by Clang
2058 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2059 bool HasDecl = (D != 0);
2060 // Use the location of the declaration.
2063 Loc = D->getLocation();
2066 llvm::DIFile Unit = getOrCreateFile(Loc);
2067 llvm::DIDescriptor FDContext(Unit);
2068 llvm::DIArray TParamsArray;
2070 // Use llvm function name.
2071 Name = Fn->getName();
2072 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2073 // If there is a DISubprogram for this function available then use it.
2074 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2075 FI = SPCache.find(FD->getCanonicalDecl());
2076 if (FI != SPCache.end()) {
2077 llvm::Value *V = FI->second;
2078 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2079 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2080 llvm::MDNode *SPN = SP;
2081 LexicalBlockStack.push_back(SPN);
2082 RegionMap[D] = llvm::WeakVH(SP);
2086 Name = getFunctionName(FD);
2087 // Use mangled name as linkage name for c/c++ functions.
2088 if (FD->hasPrototype()) {
2089 LinkageName = CGM.getMangledName(GD);
2090 Flags |= llvm::DIDescriptor::FlagPrototyped;
2092 if (LinkageName == Name ||
2093 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)
2094 LinkageName = StringRef();
2096 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2097 if (const NamespaceDecl *NSDecl =
2098 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2099 FDContext = getOrCreateNameSpace(NSDecl);
2100 else if (const RecordDecl *RDecl =
2101 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2102 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2104 // Collect template parameters.
2105 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2107 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2108 Name = getObjCMethodName(OMD);
2109 Flags |= llvm::DIDescriptor::FlagPrototyped;
2111 // Use llvm function name.
2112 Name = Fn->getName();
2113 Flags |= llvm::DIDescriptor::FlagPrototyped;
2115 if (!Name.empty() && Name[0] == '\01')
2116 Name = Name.substr(1);
2118 unsigned LineNo = getLineNumber(Loc);
2119 if (!HasDecl || D->isImplicit())
2120 Flags |= llvm::DIDescriptor::FlagArtificial;
2122 llvm::DIType DIFnType;
2123 llvm::DISubprogram SPDecl;
2125 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2126 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2127 SPDecl = getFunctionDeclaration(D);
2129 // Create fake but valid subroutine type. Otherwise
2130 // llvm::DISubprogram::Verify() would return false, and
2131 // subprogram DIE will miss DW_AT_decl_file and
2132 // DW_AT_decl_line fields.
2133 SmallVector<llvm::Value*, 16> Elts;
2134 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2135 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2137 llvm::DISubprogram SP;
2138 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2140 Fn->hasInternalLinkage(), true/*definition*/,
2141 getLineNumber(CurLoc), Flags,
2142 CGM.getLangOpts().Optimize,
2143 Fn, TParamsArray, SPDecl);
2145 // Push function on region stack.
2146 llvm::MDNode *SPN = SP;
2147 LexicalBlockStack.push_back(SPN);
2149 RegionMap[D] = llvm::WeakVH(SP);
2152 /// EmitLocation - Emit metadata to indicate a change in line/column
2153 /// information in the source file.
2154 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2156 // Update our current location
2159 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2161 // Don't bother if things are the same as last time.
2162 SourceManager &SM = CGM.getContext().getSourceManager();
2163 if (CurLoc == PrevLoc ||
2164 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2165 // New Builder may not be in sync with CGDebugInfo.
2166 if (!Builder.getCurrentDebugLocation().isUnknown())
2169 // Update last state.
2172 llvm::MDNode *Scope = LexicalBlockStack.back();
2173 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2174 getColumnNumber(CurLoc),
2178 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2180 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2181 llvm::DIDescriptor D =
2182 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2183 llvm::DIDescriptor() :
2184 llvm::DIDescriptor(LexicalBlockStack.back()),
2185 getOrCreateFile(CurLoc),
2186 getLineNumber(CurLoc),
2187 getColumnNumber(CurLoc));
2188 llvm::MDNode *DN = D;
2189 LexicalBlockStack.push_back(DN);
2192 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2193 /// region - beginning of a DW_TAG_lexical_block.
2194 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2195 // Set our current location.
2198 // Create a new lexical block and push it on the stack.
2199 CreateLexicalBlock(Loc);
2201 // Emit a line table change for the current location inside the new scope.
2202 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2203 getColumnNumber(Loc),
2204 LexicalBlockStack.back()));
2207 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2208 /// region - end of a DW_TAG_lexical_block.
2209 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2210 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2212 // Provide an entry in the line table for the end of the block.
2213 EmitLocation(Builder, Loc);
2215 LexicalBlockStack.pop_back();
2218 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2219 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2220 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2221 unsigned RCount = FnBeginRegionCount.back();
2222 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2224 // Pop all regions for this function.
2225 while (LexicalBlockStack.size() != RCount)
2226 EmitLexicalBlockEnd(Builder, CurLoc);
2227 FnBeginRegionCount.pop_back();
2230 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2231 // See BuildByRefType.
2232 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
2233 uint64_t *XOffset) {
2235 SmallVector<llvm::Value *, 5> EltTys;
2237 uint64_t FieldSize, FieldOffset;
2238 unsigned FieldAlign;
2240 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2241 QualType Type = VD->getType();
2244 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2245 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2246 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2247 FType = CGM.getContext().IntTy;
2248 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2249 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2251 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
2252 if (HasCopyAndDispose) {
2253 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2254 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2256 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2260 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2261 if (Align > CGM.getContext().toCharUnitsFromBits(
2262 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2263 CharUnits FieldOffsetInBytes
2264 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2265 CharUnits AlignedOffsetInBytes
2266 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2267 CharUnits NumPaddingBytes
2268 = AlignedOffsetInBytes - FieldOffsetInBytes;
2270 if (NumPaddingBytes.isPositive()) {
2271 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2272 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2273 pad, ArrayType::Normal, 0);
2274 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2279 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2280 FieldSize = CGM.getContext().getTypeSize(FType);
2281 FieldAlign = CGM.getContext().toBits(Align);
2283 *XOffset = FieldOffset;
2284 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2285 0, FieldSize, FieldAlign,
2286 FieldOffset, 0, FieldTy);
2287 EltTys.push_back(FieldTy);
2288 FieldOffset += FieldSize;
2290 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2292 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2294 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2298 /// EmitDeclare - Emit local variable declaration debug info.
2299 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2300 llvm::Value *Storage,
2301 unsigned ArgNo, CGBuilderTy &Builder) {
2302 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2303 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2305 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2307 uint64_t XOffset = 0;
2308 if (VD->hasAttr<BlocksAttr>())
2309 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2311 Ty = getOrCreateType(VD->getType(), Unit);
2313 // If there is no debug info for this type then do not emit debug info
2314 // for this variable.
2318 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2319 // If Storage is an aggregate returned as 'sret' then let debugger know
2321 if (Arg->hasStructRetAttr())
2322 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2323 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2324 // If an aggregate variable has non trivial destructor or non trivial copy
2325 // constructor than it is pass indirectly. Let debug info know about this
2326 // by using reference of the aggregate type as a argument type.
2327 if (!Record->hasTrivialCopyConstructor() ||
2328 !Record->hasTrivialDestructor())
2329 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2333 // Get location information.
2334 unsigned Line = getLineNumber(VD->getLocation());
2335 unsigned Column = getColumnNumber(VD->getLocation());
2337 if (VD->isImplicit())
2338 Flags |= llvm::DIDescriptor::FlagArtificial;
2339 // If this is the first argument and it is implicit then
2340 // give it an object pointer flag.
2341 // FIXME: There has to be a better way to do this, but for static
2342 // functions there won't be an implicit param at arg1 and
2343 // otherwise it is 'self' or 'this'.
2344 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2345 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2347 llvm::MDNode *Scope = LexicalBlockStack.back();
2349 StringRef Name = VD->getName();
2350 if (!Name.empty()) {
2351 if (VD->hasAttr<BlocksAttr>()) {
2352 CharUnits offset = CharUnits::fromQuantity(32);
2353 SmallVector<llvm::Value *, 9> addr;
2354 llvm::Type *Int64Ty = CGM.Int64Ty;
2355 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2356 // offset of __forwarding field
2357 offset = CGM.getContext().toCharUnitsFromBits(
2358 CGM.getContext().getTargetInfo().getPointerWidth(0));
2359 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2360 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2361 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2362 // offset of x field
2363 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2364 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2366 // Create the descriptor for the variable.
2367 llvm::DIVariable D =
2368 DBuilder.createComplexVariable(Tag,
2369 llvm::DIDescriptor(Scope),
2370 VD->getName(), Unit, Line, Ty,
2373 // Insert an llvm.dbg.declare into the current block.
2374 llvm::Instruction *Call =
2375 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2376 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2378 } else if (isa<VariableArrayType>(VD->getType())) {
2379 // These are "complex" variables in that they need an op_deref.
2380 // Create the descriptor for the variable.
2381 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2382 llvm::DIBuilder::OpDeref);
2383 llvm::DIVariable D =
2384 DBuilder.createComplexVariable(Tag,
2385 llvm::DIDescriptor(Scope),
2386 Name, Unit, Line, Ty,
2389 // Insert an llvm.dbg.declare into the current block.
2390 llvm::Instruction *Call =
2391 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2392 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2396 // Create the descriptor for the variable.
2397 llvm::DIVariable D =
2398 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2399 Name, Unit, Line, Ty,
2400 CGM.getLangOpts().Optimize, Flags, ArgNo);
2402 // Insert an llvm.dbg.declare into the current block.
2403 llvm::Instruction *Call =
2404 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2405 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2409 // If VD is an anonymous union then Storage represents value for
2410 // all union fields.
2411 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2412 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2413 if (RD->isUnion()) {
2414 for (RecordDecl::field_iterator I = RD->field_begin(),
2415 E = RD->field_end();
2417 FieldDecl *Field = *I;
2418 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2419 StringRef FieldName = Field->getName();
2421 // Ignore unnamed fields. Do not ignore unnamed records.
2422 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2425 // Use VarDecl's Tag, Scope and Line number.
2426 llvm::DIVariable D =
2427 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2428 FieldName, Unit, Line, FieldTy,
2429 CGM.getLangOpts().Optimize, Flags,
2432 // Insert an llvm.dbg.declare into the current block.
2433 llvm::Instruction *Call =
2434 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2435 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2441 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2442 llvm::Value *Storage,
2443 CGBuilderTy &Builder) {
2444 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2445 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2448 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2449 llvm::Value *Storage,
2450 CGBuilderTy &Builder,
2451 const CGBlockInfo &blockInfo) {
2452 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2453 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2455 if (Builder.GetInsertBlock() == 0)
2458 bool isByRef = VD->hasAttr<BlocksAttr>();
2460 uint64_t XOffset = 0;
2461 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2464 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2466 Ty = getOrCreateType(VD->getType(), Unit);
2468 // Self is passed along as an implicit non-arg variable in a
2469 // block. Mark it as the object pointer.
2470 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2471 Ty = DBuilder.createObjectPointerType(Ty);
2473 // Get location information.
2474 unsigned Line = getLineNumber(VD->getLocation());
2475 unsigned Column = getColumnNumber(VD->getLocation());
2477 const llvm::DataLayout &target = CGM.getDataLayout();
2479 CharUnits offset = CharUnits::fromQuantity(
2480 target.getStructLayout(blockInfo.StructureType)
2481 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2483 SmallVector<llvm::Value *, 9> addr;
2484 llvm::Type *Int64Ty = CGM.Int64Ty;
2485 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2486 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2488 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2489 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2490 // offset of __forwarding field
2491 offset = CGM.getContext()
2492 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2493 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2494 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2495 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2496 // offset of x field
2497 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2498 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2501 // Create the descriptor for the variable.
2502 llvm::DIVariable D =
2503 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2504 llvm::DIDescriptor(LexicalBlockStack.back()),
2505 VD->getName(), Unit, Line, Ty, addr);
2506 // Insert an llvm.dbg.declare into the current block.
2507 llvm::Instruction *Call =
2508 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2509 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2510 LexicalBlockStack.back()));
2513 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2514 /// variable declaration.
2515 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2517 CGBuilderTy &Builder) {
2518 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2519 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2523 struct BlockLayoutChunk {
2524 uint64_t OffsetInBits;
2525 const BlockDecl::Capture *Capture;
2527 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2528 return l.OffsetInBits < r.OffsetInBits;
2532 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2534 CGBuilderTy &Builder) {
2535 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2536 ASTContext &C = CGM.getContext();
2537 const BlockDecl *blockDecl = block.getBlockDecl();
2539 // Collect some general information about the block's location.
2540 SourceLocation loc = blockDecl->getCaretLocation();
2541 llvm::DIFile tunit = getOrCreateFile(loc);
2542 unsigned line = getLineNumber(loc);
2543 unsigned column = getColumnNumber(loc);
2545 // Build the debug-info type for the block literal.
2546 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2548 const llvm::StructLayout *blockLayout =
2549 CGM.getDataLayout().getStructLayout(block.StructureType);
2551 SmallVector<llvm::Value*, 16> fields;
2552 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2553 blockLayout->getElementOffsetInBits(0),
2555 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2556 blockLayout->getElementOffsetInBits(1),
2558 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2559 blockLayout->getElementOffsetInBits(2),
2561 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2562 blockLayout->getElementOffsetInBits(3),
2564 fields.push_back(createFieldType("__descriptor",
2565 C.getPointerType(block.NeedsCopyDispose ?
2566 C.getBlockDescriptorExtendedType() :
2567 C.getBlockDescriptorType()),
2569 blockLayout->getElementOffsetInBits(4),
2572 // We want to sort the captures by offset, not because DWARF
2573 // requires this, but because we're paranoid about debuggers.
2574 SmallVector<BlockLayoutChunk, 8> chunks;
2577 if (blockDecl->capturesCXXThis()) {
2578 BlockLayoutChunk chunk;
2579 chunk.OffsetInBits =
2580 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2582 chunks.push_back(chunk);
2585 // Variable captures.
2586 for (BlockDecl::capture_const_iterator
2587 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2589 const BlockDecl::Capture &capture = *i;
2590 const VarDecl *variable = capture.getVariable();
2591 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2593 // Ignore constant captures.
2594 if (captureInfo.isConstant())
2597 BlockLayoutChunk chunk;
2598 chunk.OffsetInBits =
2599 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2600 chunk.Capture = &capture;
2601 chunks.push_back(chunk);
2605 llvm::array_pod_sort(chunks.begin(), chunks.end());
2607 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2608 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2609 uint64_t offsetInBits = i->OffsetInBits;
2610 const BlockDecl::Capture *capture = i->Capture;
2612 // If we have a null capture, this must be the C++ 'this' capture.
2614 const CXXMethodDecl *method =
2615 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2616 QualType type = method->getThisType(C);
2618 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2619 offsetInBits, tunit, tunit));
2623 const VarDecl *variable = capture->getVariable();
2624 StringRef name = variable->getName();
2626 llvm::DIType fieldType;
2627 if (capture->isByRef()) {
2628 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2630 // FIXME: this creates a second copy of this type!
2632 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2633 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2634 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2635 ptrInfo.first, ptrInfo.second,
2636 offsetInBits, 0, fieldType);
2638 fieldType = createFieldType(name, variable->getType(), 0,
2639 loc, AS_public, offsetInBits, tunit, tunit);
2641 fields.push_back(fieldType);
2644 SmallString<36> typeName;
2645 llvm::raw_svector_ostream(typeName)
2646 << "__block_literal_" << CGM.getUniqueBlockCount();
2648 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2651 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2652 CGM.getContext().toBits(block.BlockSize),
2653 CGM.getContext().toBits(block.BlockAlign),
2655 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2657 // Get overall information about the block.
2658 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2659 llvm::MDNode *scope = LexicalBlockStack.back();
2660 StringRef name = ".block_descriptor";
2662 // Create the descriptor for the parameter.
2663 llvm::DIVariable debugVar =
2664 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2665 llvm::DIDescriptor(scope),
2666 name, tunit, line, type,
2667 CGM.getLangOpts().Optimize, flags,
2668 cast<llvm::Argument>(addr)->getArgNo() + 1);
2670 // Insert an llvm.dbg.value into the current block.
2671 llvm::Instruction *declare =
2672 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2673 Builder.GetInsertBlock());
2674 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2677 /// EmitGlobalVariable - Emit information about a global variable.
2678 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2680 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2681 // Create global variable debug descriptor.
2682 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2683 unsigned LineNo = getLineNumber(D->getLocation());
2685 setLocation(D->getLocation());
2687 QualType T = D->getType();
2688 if (T->isIncompleteArrayType()) {
2690 // CodeGen turns int[] into int[1] so we'll do the same here.
2691 llvm::APInt ConstVal(32, 1);
2692 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2694 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2695 ArrayType::Normal, 0);
2697 StringRef DeclName = D->getName();
2698 StringRef LinkageName;
2699 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2700 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2701 LinkageName = Var->getName();
2702 if (LinkageName == DeclName)
2703 LinkageName = StringRef();
2704 llvm::DIDescriptor DContext =
2705 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2706 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2707 Unit, LineNo, getOrCreateType(T, Unit),
2708 Var->hasInternalLinkage(), Var);
2711 /// EmitGlobalVariable - Emit information about an objective-c interface.
2712 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2713 ObjCInterfaceDecl *ID) {
2714 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2715 // Create global variable debug descriptor.
2716 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2717 unsigned LineNo = getLineNumber(ID->getLocation());
2719 StringRef Name = ID->getName();
2721 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2722 if (T->isIncompleteArrayType()) {
2724 // CodeGen turns int[] into int[1] so we'll do the same here.
2725 llvm::APInt ConstVal(32, 1);
2726 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2728 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2729 ArrayType::Normal, 0);
2732 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2733 getOrCreateType(T, Unit),
2734 Var->hasInternalLinkage(), Var);
2737 /// EmitGlobalVariable - Emit global variable's debug info.
2738 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2739 llvm::Constant *Init) {
2740 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2741 // Create the descriptor for the variable.
2742 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2743 StringRef Name = VD->getName();
2744 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2745 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2746 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2747 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2748 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2750 // Do not use DIGlobalVariable for enums.
2751 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2753 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2754 getLineNumber(VD->getLocation()),
2758 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2761 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2762 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2763 NameSpaceCache.find(NSDecl);
2764 if (I != NameSpaceCache.end())
2765 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2767 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2768 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2769 llvm::DIDescriptor Context =
2770 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2771 llvm::DINameSpace NS =
2772 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2773 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2777 void CGDebugInfo::finalize(void) {
2778 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2779 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2780 llvm::DIType Ty, RepTy;
2781 // Verify that the debug info still exists.
2782 if (llvm::Value *V = VI->second)
2783 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2785 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2786 TypeCache.find(VI->first);
2787 if (it != TypeCache.end()) {
2788 // Verify that the debug info still exists.
2789 if (llvm::Value *V = it->second)
2790 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2793 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2794 Ty.replaceAllUsesWith(RepTy);
2797 DBuilder.finalize();