1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.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/FileManager.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/Version.h"
28 #include "clang/Frontend/CodeGenOptions.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DataLayout.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/FileSystem.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() || Scope.isSubprogram()) {
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::DIScope 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::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105 return getOrCreateNameSpace(NSDecl);
107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
108 if (!RDecl->isDependentType())
109 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110 getOrCreateMainFile());
114 /// getFunctionName - Get function name for the given FunctionDecl. If the
115 /// name is constructred on demand (e.g. C++ destructor) then the name
116 /// is stored on the side.
117 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
118 assert (FD && "Invalid FunctionDecl!");
119 IdentifierInfo *FII = FD->getIdentifier();
120 FunctionTemplateSpecializationInfo *Info
121 = FD->getTemplateSpecializationInfo();
123 return FII->getName();
125 // Otherwise construct human readable name for debug info.
127 llvm::raw_svector_ostream OS(NS);
130 // Add any template specialization args.
132 const TemplateArgumentList *TArgs = Info->TemplateArguments;
133 const TemplateArgument *Args = TArgs->data();
134 unsigned NumArgs = TArgs->size();
135 PrintingPolicy Policy(CGM.getLangOpts());
136 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
140 // Copy this name on the side and use its reference.
142 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
143 memcpy(StrPtr, NS.data(), NS.size());
144 return StringRef(StrPtr, NS.size());
147 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
148 SmallString<256> MethodName;
149 llvm::raw_svector_ostream OS(MethodName);
150 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
151 const DeclContext *DC = OMD->getDeclContext();
152 if (const ObjCImplementationDecl *OID =
153 dyn_cast<const ObjCImplementationDecl>(DC)) {
154 OS << OID->getName();
155 } else if (const ObjCInterfaceDecl *OID =
156 dyn_cast<const ObjCInterfaceDecl>(DC)) {
157 OS << OID->getName();
158 } else if (const ObjCCategoryImplDecl *OCD =
159 dyn_cast<const ObjCCategoryImplDecl>(DC)){
160 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
161 OCD->getIdentifier()->getNameStart() << ')';
163 OS << ' ' << OMD->getSelector().getAsString() << ']';
165 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
166 memcpy(StrPtr, MethodName.begin(), OS.tell());
167 return StringRef(StrPtr, OS.tell());
170 /// getSelectorName - Return selector name. This is used for debugging
172 StringRef CGDebugInfo::getSelectorName(Selector S) {
173 const std::string &SName = S.getAsString();
174 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
175 memcpy(StrPtr, SName.data(), SName.size());
176 return StringRef(StrPtr, SName.size());
179 /// getClassName - Get class name including template argument list.
181 CGDebugInfo::getClassName(const RecordDecl *RD) {
182 const ClassTemplateSpecializationDecl *Spec
183 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 return RD->getName();
187 const TemplateArgument *Args;
189 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
190 const TemplateSpecializationType *TST =
191 cast<TemplateSpecializationType>(TAW->getType());
192 Args = TST->getArgs();
193 NumArgs = TST->getNumArgs();
195 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
196 Args = TemplateArgs.data();
197 NumArgs = TemplateArgs.size();
199 StringRef Name = RD->getIdentifier()->getName();
200 PrintingPolicy Policy(CGM.getLangOpts());
201 SmallString<128> TemplateArgList;
203 llvm::raw_svector_ostream OS(TemplateArgList);
204 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
208 // Copy this name on the side and use its reference.
209 size_t Length = Name.size() + TemplateArgList.size();
210 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
211 memcpy(StrPtr, Name.data(), Name.size());
212 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
213 return StringRef(StrPtr, Length);
216 /// getOrCreateFile - Get the file debug info descriptor for the input location.
217 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
219 // If Location is not valid then use main input file.
220 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
222 SourceManager &SM = CGM.getContext().getSourceManager();
223 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
225 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
226 // If the location is not valid then use main input file.
227 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
229 // Cache the results.
230 const char *fname = PLoc.getFilename();
231 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
232 DIFileCache.find(fname);
234 if (it != DIFileCache.end()) {
235 // Verify that the information still exists.
236 if (llvm::Value *V = it->second)
237 return llvm::DIFile(cast<llvm::MDNode>(V));
240 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
242 DIFileCache[fname] = F;
246 /// getOrCreateMainFile - Get the file info for main compile unit.
247 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
248 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
251 /// getLineNumber - Get line number for the location. If location is invalid
252 /// then use current location.
253 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
254 if (Loc.isInvalid() && CurLoc.isInvalid())
256 SourceManager &SM = CGM.getContext().getSourceManager();
257 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
258 return PLoc.isValid()? PLoc.getLine() : 0;
261 /// getColumnNumber - Get column number for the location.
262 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
263 // We may not want column information at all.
264 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
267 // If the location is invalid then use the current column.
268 if (Loc.isInvalid() && CurLoc.isInvalid())
270 SourceManager &SM = CGM.getContext().getSourceManager();
271 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
272 return PLoc.isValid()? PLoc.getColumn() : 0;
275 StringRef CGDebugInfo::getCurrentDirname() {
276 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
277 return CGM.getCodeGenOpts().DebugCompilationDir;
279 if (!CWDName.empty())
281 SmallString<256> CWD;
282 llvm::sys::fs::current_path(CWD);
283 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
284 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
285 return CWDName = StringRef(CompDirnamePtr, CWD.size());
288 /// CreateCompileUnit - Create new compile unit.
289 void CGDebugInfo::CreateCompileUnit() {
291 // Get absolute path name.
292 SourceManager &SM = CGM.getContext().getSourceManager();
293 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
294 if (MainFileName.empty())
295 MainFileName = "<unknown>";
297 // The main file name provided via the "-main-file-name" option contains just
298 // the file name itself with no path information. This file name may have had
299 // a relative path, so we look into the actual file entry for the main
300 // file to determine the real absolute path for the file.
301 std::string MainFileDir;
302 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
303 MainFileDir = MainFile->getDir()->getName();
304 if (MainFileDir != ".")
305 MainFileName = MainFileDir + "/" + MainFileName;
308 // Save filename string.
309 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
310 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
311 StringRef Filename(FilenamePtr, MainFileName.length());
313 // Save split dwarf file string.
314 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
315 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
316 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
317 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
320 const LangOptions &LO = CGM.getLangOpts();
323 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
325 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
326 } else if (LO.ObjC1) {
327 LangTag = llvm::dwarf::DW_LANG_ObjC;
329 LangTag = llvm::dwarf::DW_LANG_C99;
331 LangTag = llvm::dwarf::DW_LANG_C89;
334 std::string Producer = getClangFullVersion();
336 // Figure out which version of the ObjC runtime we have.
337 unsigned RuntimeVers = 0;
339 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
341 // Create new compile unit.
342 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
343 Producer, LO.Optimize,
344 CGM.getCodeGenOpts().DwarfDebugFlags,
345 RuntimeVers, SplitDwarfFilename);
346 // FIXME - Eliminate TheCU.
347 TheCU = llvm::DICompileUnit(DBuilder.getCU());
350 /// CreateType - Get the Basic type from the cache or create a new
351 /// one if necessary.
352 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
353 unsigned Encoding = 0;
355 switch (BT->getKind()) {
356 #define BUILTIN_TYPE(Id, SingletonId)
357 #define PLACEHOLDER_TYPE(Id, SingletonId) \
358 case BuiltinType::Id:
359 #include "clang/AST/BuiltinTypes.def"
360 case BuiltinType::Dependent:
361 llvm_unreachable("Unexpected builtin type");
362 case BuiltinType::NullPtr:
364 createNullPtrType(BT->getName(CGM.getLangOpts()));
365 case BuiltinType::Void:
366 return llvm::DIType();
367 case BuiltinType::ObjCClass:
368 if (ClassTy.Verify())
370 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
372 getOrCreateMainFile(), 0);
374 case BuiltinType::ObjCId: {
375 // typedef struct objc_class *Class;
376 // typedef struct objc_object {
383 if (!ClassTy.Verify())
384 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
386 getOrCreateMainFile(), 0);
388 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
390 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
393 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
394 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
396 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
397 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
400 case BuiltinType::ObjCSel: {
404 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
405 "objc_selector", TheCU, getOrCreateMainFile(),
410 case BuiltinType::OCLImage1d:
411 return getOrCreateStructPtrType("opencl_image1d_t",
413 case BuiltinType::OCLImage1dArray:
414 return getOrCreateStructPtrType("opencl_image1d_array_t",
415 OCLImage1dArrayDITy);
416 case BuiltinType::OCLImage1dBuffer:
417 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
418 OCLImage1dBufferDITy);
419 case BuiltinType::OCLImage2d:
420 return getOrCreateStructPtrType("opencl_image2d_t",
422 case BuiltinType::OCLImage2dArray:
423 return getOrCreateStructPtrType("opencl_image2d_array_t",
424 OCLImage2dArrayDITy);
425 case BuiltinType::OCLImage3d:
426 return getOrCreateStructPtrType("opencl_image3d_t",
428 case BuiltinType::OCLSampler:
429 return DBuilder.createBasicType("opencl_sampler_t",
430 CGM.getContext().getTypeSize(BT),
431 CGM.getContext().getTypeAlign(BT),
432 llvm::dwarf::DW_ATE_unsigned);
433 case BuiltinType::OCLEvent:
434 return getOrCreateStructPtrType("opencl_event_t",
437 case BuiltinType::UChar:
438 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
439 case BuiltinType::Char_S:
440 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
441 case BuiltinType::Char16:
442 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
443 case BuiltinType::UShort:
444 case BuiltinType::UInt:
445 case BuiltinType::UInt128:
446 case BuiltinType::ULong:
447 case BuiltinType::WChar_U:
448 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
449 case BuiltinType::Short:
450 case BuiltinType::Int:
451 case BuiltinType::Int128:
452 case BuiltinType::Long:
453 case BuiltinType::WChar_S:
454 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
455 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
456 case BuiltinType::Half:
457 case BuiltinType::Float:
458 case BuiltinType::LongDouble:
459 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
462 switch (BT->getKind()) {
463 case BuiltinType::Long: BTName = "long int"; break;
464 case BuiltinType::LongLong: BTName = "long long int"; break;
465 case BuiltinType::ULong: BTName = "long unsigned int"; break;
466 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
468 BTName = BT->getName(CGM.getLangOpts());
471 // Bit size, align and offset of the type.
472 uint64_t Size = CGM.getContext().getTypeSize(BT);
473 uint64_t Align = CGM.getContext().getTypeAlign(BT);
475 DBuilder.createBasicType(BTName, Size, Align, Encoding);
479 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
480 // Bit size, align and offset of the type.
481 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
482 if (Ty->isComplexIntegerType())
483 Encoding = llvm::dwarf::DW_ATE_lo_user;
485 uint64_t Size = CGM.getContext().getTypeSize(Ty);
486 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
488 DBuilder.createBasicType("complex", Size, Align, Encoding);
493 /// CreateCVRType - Get the qualified type from the cache or create
494 /// a new one if necessary.
495 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
496 QualifierCollector Qc;
497 const Type *T = Qc.strip(Ty);
499 // Ignore these qualifiers for now.
500 Qc.removeObjCGCAttr();
501 Qc.removeAddressSpace();
502 Qc.removeObjCLifetime();
504 // We will create one Derived type for one qualifier and recurse to handle any
508 Tag = llvm::dwarf::DW_TAG_const_type;
510 } else if (Qc.hasVolatile()) {
511 Tag = llvm::dwarf::DW_TAG_volatile_type;
513 } else if (Qc.hasRestrict()) {
514 Tag = llvm::dwarf::DW_TAG_restrict_type;
517 assert(Qc.empty() && "Unknown type qualifier for debug info");
518 return getOrCreateType(QualType(T, 0), Unit);
521 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
523 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
524 // CVR derived types.
525 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
530 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
533 // The frontend treats 'id' as a typedef to an ObjCObjectType,
534 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
535 // debug info, we want to emit 'id' in both cases.
536 if (Ty->isObjCQualifiedIdType())
537 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
540 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
541 Ty->getPointeeType(), Unit);
545 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
547 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
548 Ty->getPointeeType(), Unit);
551 // Creates a forward declaration for a RecordDecl in the given context.
552 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
553 llvm::DIDescriptor Ctx) {
554 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
555 unsigned Line = getLineNumber(RD->getLocation());
556 StringRef RDName = getClassName(RD);
559 if (RD->isStruct() || RD->isInterface())
560 Tag = llvm::dwarf::DW_TAG_structure_type;
561 else if (RD->isUnion())
562 Tag = llvm::dwarf::DW_TAG_union_type;
564 assert(RD->isClass());
565 Tag = llvm::dwarf::DW_TAG_class_type;
569 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
572 // Walk up the context chain and create forward decls for record decls,
573 // and normal descriptors for namespaces.
574 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
578 // See if we already have the parent.
579 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
580 I = RegionMap.find(Context);
581 if (I != RegionMap.end()) {
582 llvm::Value *V = I->second;
583 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
587 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
588 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
590 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
591 if (!RD->isDependentType()) {
592 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
593 getOrCreateMainFile());
594 return llvm::DIDescriptor(Ty);
600 /// CreatePointeeType - Create Pointee type. If Pointee is a record
601 /// then emit record's fwd if debug info size reduction is enabled.
602 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
604 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
605 return getOrCreateType(PointeeTy, Unit);
607 // Limit debug info for the pointee type.
609 // If we have an existing type, use that, it's still smaller than creating
611 llvm::DIType Ty = getTypeOrNull(PointeeTy);
612 if (Ty.Verify()) return Ty;
614 // Handle qualifiers.
615 if (PointeeTy.hasLocalQualifiers())
616 return CreateQualifiedType(PointeeTy, Unit);
618 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
619 RecordDecl *RD = RTy->getDecl();
620 llvm::DIDescriptor FDContext =
621 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
622 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
623 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
626 return getOrCreateType(PointeeTy, Unit);
629 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
633 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
634 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
635 return DBuilder.createReferenceType(Tag,
636 CreatePointeeType(PointeeTy, Unit));
638 // Bit size, align and offset of the type.
639 // Size is always the size of a pointer. We can't use getTypeSize here
640 // because that does not return the correct value for references.
641 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
642 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
643 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
645 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
649 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
653 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
654 Name, TheCU, getOrCreateMainFile(),
656 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
657 Cache = DBuilder.createPointerType(Cache, Size);
661 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
663 if (BlockLiteralGenericSet)
664 return BlockLiteralGeneric;
666 SmallVector<llvm::Value *, 8> EltTys;
667 llvm::DIType FieldTy;
669 uint64_t FieldSize, FieldOffset;
671 llvm::DIArray Elements;
672 llvm::DIType EltTy, DescTy;
675 FType = CGM.getContext().UnsignedLongTy;
676 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
677 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
679 Elements = DBuilder.getOrCreateArray(EltTys);
682 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
683 unsigned LineNo = getLineNumber(CurLoc);
685 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
686 Unit, LineNo, FieldOffset, 0,
687 Flags, llvm::DIType(), Elements);
689 // Bit size, align and offset of the type.
690 uint64_t Size = CGM.getContext().getTypeSize(Ty);
692 DescTy = DBuilder.createPointerType(EltTy, Size);
695 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
696 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
697 FType = CGM.getContext().IntTy;
698 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
699 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
700 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
701 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 FieldSize = CGM.getContext().getTypeSize(Ty);
706 FieldAlign = CGM.getContext().getTypeAlign(Ty);
707 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
708 LineNo, FieldSize, FieldAlign,
709 FieldOffset, 0, FieldTy);
710 EltTys.push_back(FieldTy);
712 FieldOffset += FieldSize;
713 Elements = DBuilder.getOrCreateArray(EltTys);
715 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
716 Unit, LineNo, FieldOffset, 0,
717 Flags, llvm::DIType(), Elements);
719 BlockLiteralGenericSet = true;
720 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
721 return BlockLiteralGeneric;
724 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
725 // Typedefs are derived from some other type. If we have a typedef of a
726 // typedef, make sure to emit the whole chain.
727 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
729 return llvm::DIType();
730 // We don't set size information, but do specify where the typedef was
732 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
733 const TypedefNameDecl *TyDecl = Ty->getDecl();
735 llvm::DIDescriptor TypedefContext =
736 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
739 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
742 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
744 SmallVector<llvm::Value *, 16> EltTys;
746 // Add the result type at least.
747 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
749 // Set up remainder of arguments if there is a prototype.
750 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
751 if (isa<FunctionNoProtoType>(Ty))
752 EltTys.push_back(DBuilder.createUnspecifiedParameter());
753 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
754 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
755 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
758 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
759 return DBuilder.createSubroutineType(Unit, EltTypeArray);
763 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
765 uint64_t sizeInBitsOverride,
768 uint64_t offsetInBits,
770 llvm::DIDescriptor scope) {
771 llvm::DIType debugType = getOrCreateType(type, tunit);
773 // Get the location for the field.
774 llvm::DIFile file = getOrCreateFile(loc);
775 unsigned line = getLineNumber(loc);
777 uint64_t sizeInBits = 0;
778 unsigned alignInBits = 0;
779 if (!type->isIncompleteArrayType()) {
780 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
782 if (sizeInBitsOverride)
783 sizeInBits = sizeInBitsOverride;
787 if (AS == clang::AS_private)
788 flags |= llvm::DIDescriptor::FlagPrivate;
789 else if (AS == clang::AS_protected)
790 flags |= llvm::DIDescriptor::FlagProtected;
792 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
793 alignInBits, offsetInBits, flags, debugType);
796 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
798 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
799 SmallVectorImpl<llvm::Value *> &elements,
800 llvm::DIType RecordTy) {
801 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
802 // has the name and the location of the variable so we should iterate over
803 // both concurrently.
804 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
805 RecordDecl::field_iterator Field = CXXDecl->field_begin();
806 unsigned fieldno = 0;
807 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
808 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
809 const LambdaExpr::Capture C = *I;
810 if (C.capturesVariable()) {
811 VarDecl *V = C.getCapturedVar();
812 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
813 StringRef VName = V->getName();
814 uint64_t SizeInBitsOverride = 0;
815 if (Field->isBitField()) {
816 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
817 assert(SizeInBitsOverride && "found named 0-width bitfield");
819 llvm::DIType fieldType
820 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
821 C.getLocation(), Field->getAccess(),
822 layout.getFieldOffset(fieldno), VUnit, RecordTy);
823 elements.push_back(fieldType);
825 // TODO: Need to handle 'this' in some way by probably renaming the
826 // this of the lambda class and having a field member of 'this' or
827 // by using AT_object_pointer for the function and having that be
828 // used as 'this' for semantic references.
829 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
830 FieldDecl *f = *Field;
831 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
832 QualType type = f->getType();
833 llvm::DIType fieldType
834 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
835 layout.getFieldOffset(fieldno), VUnit, RecordTy);
837 elements.push_back(fieldType);
842 /// CollectRecordStaticField - Helper for CollectRecordFields.
844 CollectRecordStaticField(const VarDecl *Var,
845 SmallVectorImpl<llvm::Value *> &elements,
846 llvm::DIType RecordTy) {
847 // Create the descriptor for the static variable, with or without
848 // constant initializers.
849 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
850 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
852 // Do not describe enums as static members.
853 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
856 unsigned LineNumber = getLineNumber(Var->getLocation());
857 StringRef VName = Var->getName();
858 llvm::Constant *C = NULL;
859 if (Var->getInit()) {
860 const APValue *Value = Var->evaluateValue();
863 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
864 if (Value->isFloat())
865 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
870 AccessSpecifier Access = Var->getAccess();
871 if (Access == clang::AS_private)
872 Flags |= llvm::DIDescriptor::FlagPrivate;
873 else if (Access == clang::AS_protected)
874 Flags |= llvm::DIDescriptor::FlagProtected;
876 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
877 LineNumber, VTy, Flags, C);
878 elements.push_back(GV);
879 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
882 /// CollectRecordNormalField - Helper for CollectRecordFields.
884 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
886 SmallVectorImpl<llvm::Value *> &elements,
887 llvm::DIType RecordTy) {
888 StringRef name = field->getName();
889 QualType type = field->getType();
891 // Ignore unnamed fields unless they're anonymous structs/unions.
892 if (name.empty() && !type->isRecordType())
895 uint64_t SizeInBitsOverride = 0;
896 if (field->isBitField()) {
897 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
898 assert(SizeInBitsOverride && "found named 0-width bitfield");
901 llvm::DIType fieldType
902 = createFieldType(name, type, SizeInBitsOverride,
903 field->getLocation(), field->getAccess(),
904 OffsetInBits, tunit, RecordTy);
906 elements.push_back(fieldType);
909 /// CollectRecordFields - A helper function to collect debug info for
910 /// record fields. This is used while creating debug info entry for a Record.
912 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
913 SmallVectorImpl<llvm::Value *> &elements,
914 llvm::DIType RecordTy) {
915 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
917 if (CXXDecl && CXXDecl->isLambda())
918 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
920 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
922 // Field number for non-static fields.
923 unsigned fieldNo = 0;
925 // Bookkeeping for an ms struct, which ignores certain fields.
926 bool IsMsStruct = record->isMsStruct(CGM.getContext());
927 const FieldDecl *LastFD = 0;
929 // Static and non-static members should appear in the same order as
930 // the corresponding declarations in the source program.
931 for (RecordDecl::decl_iterator I = record->decls_begin(),
932 E = record->decls_end(); I != E; ++I)
933 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
934 CollectRecordStaticField(V, elements, RecordTy);
935 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
937 // Zero-length bitfields following non-bitfield members are
938 // completely ignored; we don't even count them.
939 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
943 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
944 tunit, elements, RecordTy);
946 // Bump field number for next field.
952 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
953 /// function type is not updated to include implicit "this" pointer. Use this
954 /// routine to get a method type which includes "this" pointer.
956 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
958 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
959 if (Method->isStatic())
960 return getOrCreateType(QualType(Func, 0), Unit);
961 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
965 llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
966 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
967 // Add "this" pointer.
968 llvm::DIArray Args = llvm::DICompositeType(
969 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
970 assert (Args.getNumElements() && "Invalid number of arguments!");
972 SmallVector<llvm::Value *, 16> Elts;
974 // First element is always return type. For 'void' functions it is NULL.
975 Elts.push_back(Args.getElement(0));
977 // "this" pointer is always first argument.
978 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
979 if (isa<ClassTemplateSpecializationDecl>(RD)) {
980 // Create pointer type directly in this case.
981 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
982 QualType PointeeTy = ThisPtrTy->getPointeeType();
983 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
984 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
985 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
986 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
987 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
988 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
989 // TODO: This and the artificial type below are misleading, the
990 // types aren't artificial the argument is, but the current
991 // metadata doesn't represent that.
992 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
993 Elts.push_back(ThisPtrType);
995 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
996 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
997 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
998 Elts.push_back(ThisPtrType);
1001 // Copy rest of the arguments.
1002 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1003 Elts.push_back(Args.getElement(i));
1005 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1007 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1010 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1011 /// inside a function.
1012 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1013 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1014 return isFunctionLocalClass(NRD);
1015 if (isa<FunctionDecl>(RD->getDeclContext()))
1020 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1021 /// a single member function GlobalDecl.
1023 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1025 llvm::DIType RecordTy) {
1027 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1029 StringRef MethodName = getFunctionName(Method);
1030 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1032 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1033 // make sense to give a single ctor/dtor a linkage name.
1034 StringRef MethodLinkageName;
1035 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1036 MethodLinkageName = CGM.getMangledName(Method);
1038 // Get the location for the method.
1039 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1040 unsigned MethodLine = getLineNumber(Method->getLocation());
1042 // Collect virtual method info.
1043 llvm::DIType ContainingType;
1044 unsigned Virtuality = 0;
1045 unsigned VIndex = 0;
1047 if (Method->isVirtual()) {
1048 if (Method->isPure())
1049 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1051 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1053 // It doesn't make sense to give a virtual destructor a vtable index,
1054 // since a single destructor has two entries in the vtable.
1055 if (!isa<CXXDestructorDecl>(Method))
1056 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1057 ContainingType = RecordTy;
1061 if (Method->isImplicit())
1062 Flags |= llvm::DIDescriptor::FlagArtificial;
1063 AccessSpecifier Access = Method->getAccess();
1064 if (Access == clang::AS_private)
1065 Flags |= llvm::DIDescriptor::FlagPrivate;
1066 else if (Access == clang::AS_protected)
1067 Flags |= llvm::DIDescriptor::FlagProtected;
1068 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1069 if (CXXC->isExplicit())
1070 Flags |= llvm::DIDescriptor::FlagExplicit;
1071 } else if (const CXXConversionDecl *CXXC =
1072 dyn_cast<CXXConversionDecl>(Method)) {
1073 if (CXXC->isExplicit())
1074 Flags |= llvm::DIDescriptor::FlagExplicit;
1076 if (Method->hasPrototype())
1077 Flags |= llvm::DIDescriptor::FlagPrototyped;
1079 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1080 llvm::DISubprogram SP =
1081 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1082 MethodDefUnit, MethodLine,
1083 MethodTy, /*isLocalToUnit=*/false,
1084 /* isDefinition=*/ false,
1085 Virtuality, VIndex, ContainingType,
1086 Flags, CGM.getLangOpts().Optimize, NULL,
1089 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1094 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1095 /// C++ member functions. This is used while creating debug info entry for
1098 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1099 SmallVectorImpl<llvm::Value *> &EltTys,
1100 llvm::DIType RecordTy) {
1102 // Since we want more than just the individual member decls if we
1103 // have templated functions iterate over every declaration to gather
1105 for(DeclContext::decl_iterator I = RD->decls_begin(),
1106 E = RD->decls_end(); I != E; ++I) {
1108 if (D->isImplicit() && !D->isUsed())
1111 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1112 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1113 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1114 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1115 SE = FTD->spec_end(); SI != SE; ++SI)
1116 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1121 /// CollectCXXFriends - A helper function to collect debug info for
1122 /// C++ base classes. This is used while creating debug info entry for
1125 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1126 SmallVectorImpl<llvm::Value *> &EltTys,
1127 llvm::DIType RecordTy) {
1128 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1129 BE = RD->friend_end(); BI != BE; ++BI) {
1130 if ((*BI)->isUnsupportedFriend())
1132 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1133 EltTys.push_back(DBuilder.createFriend(RecordTy,
1134 getOrCreateType(TInfo->getType(),
1139 /// CollectCXXBases - A helper function to collect debug info for
1140 /// C++ base classes. This is used while creating debug info entry for
1143 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1144 SmallVectorImpl<llvm::Value *> &EltTys,
1145 llvm::DIType RecordTy) {
1147 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1148 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1149 BE = RD->bases_end(); BI != BE; ++BI) {
1150 unsigned BFlags = 0;
1151 uint64_t BaseOffset;
1153 const CXXRecordDecl *Base =
1154 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1156 if (BI->isVirtual()) {
1157 // virtual base offset offset is -ve. The code generator emits dwarf
1158 // expression where it expects +ve number.
1160 0 - CGM.getVTableContext()
1161 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1162 BFlags = llvm::DIDescriptor::FlagVirtual;
1164 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1165 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1166 // BI->isVirtual() and bits when not.
1168 AccessSpecifier Access = BI->getAccessSpecifier();
1169 if (Access == clang::AS_private)
1170 BFlags |= llvm::DIDescriptor::FlagPrivate;
1171 else if (Access == clang::AS_protected)
1172 BFlags |= llvm::DIDescriptor::FlagProtected;
1175 DBuilder.createInheritance(RecordTy,
1176 getOrCreateType(BI->getType(), Unit),
1177 BaseOffset, BFlags);
1178 EltTys.push_back(DTy);
1182 /// CollectTemplateParams - A helper function to collect template parameters.
1183 llvm::DIArray CGDebugInfo::
1184 CollectTemplateParams(const TemplateParameterList *TPList,
1185 const TemplateArgumentList &TAList,
1186 llvm::DIFile Unit) {
1187 SmallVector<llvm::Value *, 16> TemplateParams;
1188 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1189 const TemplateArgument &TA = TAList[i];
1190 const NamedDecl *ND = TPList->getParam(i);
1191 if (TA.getKind() == TemplateArgument::Type) {
1192 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1193 llvm::DITemplateTypeParameter TTP =
1194 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1195 TemplateParams.push_back(TTP);
1196 } else if (TA.getKind() == TemplateArgument::Integral) {
1197 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1198 llvm::DITemplateValueParameter TVP =
1199 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1200 TA.getAsIntegral().getZExtValue());
1201 TemplateParams.push_back(TVP);
1204 return DBuilder.getOrCreateArray(TemplateParams);
1207 /// CollectFunctionTemplateParams - A helper function to collect debug
1208 /// info for function template parameters.
1209 llvm::DIArray CGDebugInfo::
1210 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1211 if (FD->getTemplatedKind() ==
1212 FunctionDecl::TK_FunctionTemplateSpecialization) {
1213 const TemplateParameterList *TList =
1214 FD->getTemplateSpecializationInfo()->getTemplate()
1215 ->getTemplateParameters();
1217 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1219 return llvm::DIArray();
1222 /// CollectCXXTemplateParams - A helper function to collect debug info for
1223 /// template parameters.
1224 llvm::DIArray CGDebugInfo::
1225 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1226 llvm::DIFile Unit) {
1227 llvm::PointerUnion<ClassTemplateDecl *,
1228 ClassTemplatePartialSpecializationDecl *>
1229 PU = TSpecial->getSpecializedTemplateOrPartial();
1231 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1232 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1233 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1234 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1235 return CollectTemplateParams(TPList, TAList, Unit);
1238 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1239 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1240 if (VTablePtrType.isValid())
1241 return VTablePtrType;
1243 ASTContext &Context = CGM.getContext();
1246 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1247 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1248 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1249 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1250 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1252 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1253 return VTablePtrType;
1256 /// getVTableName - Get vtable name for the given Class.
1257 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1258 // Construct gdb compatible name name.
1259 std::string Name = "_vptr$" + RD->getNameAsString();
1261 // Copy this name on the side and use its reference.
1262 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1263 memcpy(StrPtr, Name.data(), Name.length());
1264 return StringRef(StrPtr, Name.length());
1268 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1269 /// debug info entry in EltTys vector.
1271 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1272 SmallVectorImpl<llvm::Value *> &EltTys) {
1273 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1275 // If there is a primary base then it will hold vtable info.
1276 if (RL.getPrimaryBase())
1279 // If this class is not dynamic then there is not any vtable info to collect.
1280 if (!RD->isDynamicClass())
1283 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1285 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1286 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1287 getOrCreateVTablePtrType(Unit));
1288 EltTys.push_back(VPTR);
1291 /// getOrCreateRecordType - Emit record type's standalone debug info.
1292 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1293 SourceLocation Loc) {
1294 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1295 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1299 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1301 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1302 SourceLocation Loc) {
1303 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1304 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1305 RetainedTypes.push_back(D.getAsOpaquePtr());
1309 /// CreateType - get structure or union type.
1310 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1311 RecordDecl *RD = Ty->getDecl();
1313 // Get overall information about the record type for the debug info.
1314 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1316 // Records and classes and unions can all be recursive. To handle them, we
1317 // first generate a debug descriptor for the struct as a forward declaration.
1318 // Then (if it is a definition) we go through and get debug info for all of
1319 // its members. Finally, we create a descriptor for the complete type (which
1320 // may refer to the forward decl if the struct is recursive) and replace all
1321 // uses of the forward declaration with the final definition.
1323 llvm::DICompositeType FwdDecl(
1324 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1325 assert(FwdDecl.Verify() &&
1326 "The debug type of a RecordType should be a DICompositeType");
1328 if (FwdDecl.isForwardDecl())
1331 // Push the struct on region stack.
1332 LexicalBlockStack.push_back(&*FwdDecl);
1333 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1335 // Add this to the completed-type cache while we're completing it recursively.
1336 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1338 // Convert all the elements.
1339 SmallVector<llvm::Value *, 16> EltTys;
1341 // Note: The split of CXXDecl information here is intentional, the
1342 // gdb tests will depend on a certain ordering at printout. The debug
1343 // information offsets are still correct if we merge them all together
1345 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1347 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1348 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1351 // Collect data fields (including static variables and any initializers).
1352 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1353 llvm::DIArray TParamsArray;
1355 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1356 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1357 if (const ClassTemplateSpecializationDecl *TSpecial
1358 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1359 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1362 LexicalBlockStack.pop_back();
1363 RegionMap.erase(Ty->getDecl());
1365 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1366 FwdDecl.setTypeArray(Elements, TParamsArray);
1368 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1372 /// CreateType - get objective-c object type.
1373 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1374 llvm::DIFile Unit) {
1375 // Ignore protocols.
1376 return getOrCreateType(Ty->getBaseType(), Unit);
1379 /// CreateType - get objective-c interface type.
1380 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1381 llvm::DIFile Unit) {
1382 ObjCInterfaceDecl *ID = Ty->getDecl();
1384 return llvm::DIType();
1386 // Get overall information about the record type for the debug info.
1387 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1388 unsigned Line = getLineNumber(ID->getLocation());
1389 unsigned RuntimeLang = TheCU.getLanguage();
1391 // If this is just a forward declaration return a special forward-declaration
1392 // debug type since we won't be able to lay out the entire type.
1393 ObjCInterfaceDecl *Def = ID->getDefinition();
1395 llvm::DIType FwdDecl =
1396 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1397 ID->getName(), TheCU, DefUnit, Line,
1404 // Bit size, align and offset of the type.
1405 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1406 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1409 if (ID->getImplementation())
1410 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1412 llvm::DICompositeType RealDecl =
1413 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1414 Line, Size, Align, Flags,
1415 llvm::DIType(), llvm::DIArray(), RuntimeLang);
1417 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1418 // will find it and we're emitting the complete type.
1419 QualType QualTy = QualType(Ty, 0);
1420 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1421 // Push the struct on region stack.
1423 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1424 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1426 // Convert all the elements.
1427 SmallVector<llvm::Value *, 16> EltTys;
1429 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1431 llvm::DIType SClassTy =
1432 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1433 if (!SClassTy.isValid())
1434 return llvm::DIType();
1436 llvm::DIType InhTag =
1437 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1438 EltTys.push_back(InhTag);
1441 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1442 E = ID->prop_end(); I != E; ++I) {
1443 const ObjCPropertyDecl *PD = *I;
1444 SourceLocation Loc = PD->getLocation();
1445 llvm::DIFile PUnit = getOrCreateFile(Loc);
1446 unsigned PLine = getLineNumber(Loc);
1447 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1448 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1449 llvm::MDNode *PropertyNode =
1450 DBuilder.createObjCProperty(PD->getName(),
1452 (Getter && Getter->isImplicit()) ? "" :
1453 getSelectorName(PD->getGetterName()),
1454 (Setter && Setter->isImplicit()) ? "" :
1455 getSelectorName(PD->getSetterName()),
1456 PD->getPropertyAttributes(),
1457 getOrCreateType(PD->getType(), PUnit));
1458 EltTys.push_back(PropertyNode);
1461 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1462 unsigned FieldNo = 0;
1463 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1464 Field = Field->getNextIvar(), ++FieldNo) {
1465 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1466 if (!FieldTy.isValid())
1467 return llvm::DIType();
1469 StringRef FieldName = Field->getName();
1471 // Ignore unnamed fields.
1472 if (FieldName.empty())
1475 // Get the location for the field.
1476 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1477 unsigned FieldLine = getLineNumber(Field->getLocation());
1478 QualType FType = Field->getType();
1479 uint64_t FieldSize = 0;
1480 unsigned FieldAlign = 0;
1482 if (!FType->isIncompleteArrayType()) {
1484 // Bit size, align and offset of the type.
1485 FieldSize = Field->isBitField()
1486 ? Field->getBitWidthValue(CGM.getContext())
1487 : CGM.getContext().getTypeSize(FType);
1488 FieldAlign = CGM.getContext().getTypeAlign(FType);
1491 uint64_t FieldOffset;
1492 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1493 // We don't know the runtime offset of an ivar if we're using the
1494 // non-fragile ABI. For bitfields, use the bit offset into the first
1495 // byte of storage of the bitfield. For other fields, use zero.
1496 if (Field->isBitField()) {
1497 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1499 FieldOffset %= CGM.getContext().getCharWidth();
1504 FieldOffset = RL.getFieldOffset(FieldNo);
1508 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1509 Flags = llvm::DIDescriptor::FlagProtected;
1510 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1511 Flags = llvm::DIDescriptor::FlagPrivate;
1513 llvm::MDNode *PropertyNode = NULL;
1514 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1515 if (ObjCPropertyImplDecl *PImpD =
1516 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1517 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1518 SourceLocation Loc = PD->getLocation();
1519 llvm::DIFile PUnit = getOrCreateFile(Loc);
1520 unsigned PLine = getLineNumber(Loc);
1521 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1522 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1524 DBuilder.createObjCProperty(PD->getName(),
1526 (Getter && Getter->isImplicit()) ? "" :
1527 getSelectorName(PD->getGetterName()),
1528 (Setter && Setter->isImplicit()) ? "" :
1529 getSelectorName(PD->getSetterName()),
1530 PD->getPropertyAttributes(),
1531 getOrCreateType(PD->getType(), PUnit));
1535 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1536 FieldLine, FieldSize, FieldAlign,
1537 FieldOffset, Flags, FieldTy,
1539 EltTys.push_back(FieldTy);
1542 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1543 RealDecl.setTypeArray(Elements);
1545 // If the implementation is not yet set, we do not want to mark it
1546 // as complete. An implementation may declare additional
1547 // private ivars that we would miss otherwise.
1548 if (ID->getImplementation() == 0)
1549 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1551 LexicalBlockStack.pop_back();
1555 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1556 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1557 int64_t Count = Ty->getNumElements();
1559 // If number of elements are not known then this is an unbounded array.
1560 // Use Count == -1 to express such arrays.
1563 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1564 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1566 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1567 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1569 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1572 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1573 llvm::DIFile Unit) {
1577 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1578 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1581 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1582 } else if (Ty->isIncompleteArrayType()) {
1584 if (Ty->getElementType()->isIncompleteType())
1587 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1588 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1592 // Size and align of the whole array, not the element type.
1593 Size = CGM.getContext().getTypeSize(Ty);
1594 Align = CGM.getContext().getTypeAlign(Ty);
1597 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1598 // interior arrays, do we care? Why aren't nested arrays represented the
1599 // obvious/recursive way?
1600 SmallVector<llvm::Value *, 8> Subscripts;
1601 QualType EltTy(Ty, 0);
1602 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1603 // If the number of elements is known, then count is that number. Otherwise,
1604 // it's -1. This allows us to represent a subrange with an array of 0
1605 // elements, like this:
1610 int64_t Count = -1; // Count == -1 is an unbounded array.
1611 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1612 Count = CAT->getSize().getZExtValue();
1614 // FIXME: Verify this is right for VLAs.
1615 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1616 EltTy = Ty->getElementType();
1619 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1621 llvm::DIType DbgTy =
1622 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1627 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1628 llvm::DIFile Unit) {
1629 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1630 Ty, Ty->getPointeeType(), Unit);
1633 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1634 llvm::DIFile Unit) {
1635 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1636 Ty, Ty->getPointeeType(), Unit);
1639 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1641 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1642 if (!Ty->getPointeeType()->isFunctionType())
1643 return DBuilder.createMemberPointerType(
1644 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1645 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1646 CGM.getContext().getPointerType(
1647 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1648 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1652 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1654 // Ignore the atomic wrapping
1655 // FIXME: What is the correct representation?
1656 return getOrCreateType(Ty->getValueType(), U);
1659 /// CreateEnumType - get enumeration type.
1660 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1663 if (!ED->getTypeForDecl()->isIncompleteType()) {
1664 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1665 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1668 // If this is just a forward declaration, construct an appropriately
1669 // marked node and just return it.
1670 if (!ED->getDefinition()) {
1671 llvm::DIDescriptor EDContext;
1672 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1673 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1674 unsigned Line = getLineNumber(ED->getLocation());
1675 StringRef EDName = ED->getName();
1676 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1677 EDName, EDContext, DefUnit, Line, 0,
1681 // Create DIEnumerator elements for each enumerator.
1682 SmallVector<llvm::Value *, 16> Enumerators;
1683 ED = ED->getDefinition();
1684 for (EnumDecl::enumerator_iterator
1685 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1686 Enum != EnumEnd; ++Enum) {
1687 Enumerators.push_back(
1688 DBuilder.createEnumerator(Enum->getName(),
1689 Enum->getInitVal().getZExtValue()));
1692 // Return a CompositeType for the enum itself.
1693 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1695 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1696 unsigned Line = getLineNumber(ED->getLocation());
1697 llvm::DIDescriptor EnumContext =
1698 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1699 llvm::DIType ClassTy = ED->isFixed() ?
1700 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1701 llvm::DIType DbgTy =
1702 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1703 Size, Align, EltArray,
1708 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1711 Quals += T.getLocalQualifiers();
1713 switch (T->getTypeClass()) {
1715 return C.getQualifiedType(T.getTypePtr(), Quals);
1716 case Type::TemplateSpecialization:
1717 T = cast<TemplateSpecializationType>(T)->desugar();
1719 case Type::TypeOfExpr:
1720 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1723 T = cast<TypeOfType>(T)->getUnderlyingType();
1725 case Type::Decltype:
1726 T = cast<DecltypeType>(T)->getUnderlyingType();
1728 case Type::UnaryTransform:
1729 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1731 case Type::Attributed:
1732 T = cast<AttributedType>(T)->getEquivalentType();
1734 case Type::Elaborated:
1735 T = cast<ElaboratedType>(T)->getNamedType();
1738 T = cast<ParenType>(T)->getInnerType();
1740 case Type::SubstTemplateTypeParm:
1741 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1744 T = cast<AutoType>(T)->getDeducedType();
1748 assert(T != LastT && "Type unwrapping failed to unwrap!");
1753 /// getType - Get the type from the cache or return null type if it doesn't exist.
1754 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1756 // Unwrap the type as needed for debug information.
1757 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1759 // Check for existing entry.
1760 if (Ty->getTypeClass() == Type::ObjCInterface) {
1761 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1763 return llvm::DIType(cast<llvm::MDNode>(V));
1764 else return llvm::DIType();
1767 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1768 TypeCache.find(Ty.getAsOpaquePtr());
1769 if (it != TypeCache.end()) {
1770 // Verify that the debug info still exists.
1771 if (llvm::Value *V = it->second)
1772 return llvm::DIType(cast<llvm::MDNode>(V));
1775 return llvm::DIType();
1778 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1780 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1782 // Unwrap the type as needed for debug information.
1783 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1785 // Check for existing entry.
1787 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1788 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1789 if (it != CompletedTypeCache.end())
1792 V = getCachedInterfaceTypeOrNull(Ty);
1795 // Verify that any cached debug info still exists.
1797 return llvm::DIType(cast<llvm::MDNode>(V));
1799 return llvm::DIType();
1802 /// getCachedInterfaceTypeOrNull - Get the type from the interface
1803 /// cache, unless it needs to regenerated. Otherwise return null.
1804 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1805 // Is there a cached interface that hasn't changed?
1806 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1807 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1809 if (it1 != ObjCInterfaceCache.end())
1810 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1811 if (Checksum(Decl) == it1->second.second)
1812 // Return cached forward declaration.
1813 return it1->second.first;
1818 /// getOrCreateType - Get the type from the cache or create a new
1819 /// one if necessary.
1820 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1822 return llvm::DIType();
1824 // Unwrap the type as needed for debug information.
1825 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1827 llvm::DIType T = getCompletedTypeOrNull(Ty);
1832 // Otherwise create the type.
1833 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1834 void* TyPtr = Ty.getAsOpaquePtr();
1836 // And update the type cache.
1837 TypeCache[TyPtr] = Res;
1839 llvm::DIType TC = getTypeOrNull(Ty);
1840 if (TC.Verify() && TC.isForwardDecl())
1841 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1842 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1843 // Interface types may have elements added to them by a
1844 // subsequent implementation or extension, so we keep them in
1845 // the ObjCInterfaceCache together with a checksum. Instead of
1846 // the (possibly) incomplete interace type, we return a forward
1847 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1848 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1849 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1850 if (it != ObjCInterfaceCache.end())
1851 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1853 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1854 Decl->getName(), TheCU, Unit,
1855 getLineNumber(Decl->getLocation()),
1856 TheCU.getLanguage());
1857 // Store the forward declaration in the cache.
1858 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1860 // Register the type for replacement in finalize().
1861 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1865 if (!Res.isForwardDecl())
1866 CompletedTypeCache[TyPtr] = Res;
1871 /// Currently the checksum merely consists of the number of ivars.
1872 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
1874 unsigned IvarNo = 0;
1875 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1876 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1880 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1881 switch (Ty->getTypeClass()) {
1882 case Type::ObjCObjectPointer:
1883 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1884 case Type::ObjCInterface:
1885 return cast<ObjCInterfaceType>(Ty)->getDecl();
1891 /// CreateTypeNode - Create a new debug type node.
1892 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1893 // Handle qualifiers, which recursively handles what they refer to.
1894 if (Ty.hasLocalQualifiers())
1895 return CreateQualifiedType(Ty, Unit);
1897 const char *Diag = 0;
1899 // Work out details of type.
1900 switch (Ty->getTypeClass()) {
1901 #define TYPE(Class, Base)
1902 #define ABSTRACT_TYPE(Class, Base)
1903 #define NON_CANONICAL_TYPE(Class, Base)
1904 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1905 #include "clang/AST/TypeNodes.def"
1906 llvm_unreachable("Dependent types cannot show up in debug information");
1908 case Type::ExtVector:
1910 return CreateType(cast<VectorType>(Ty), Unit);
1911 case Type::ObjCObjectPointer:
1912 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1913 case Type::ObjCObject:
1914 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1915 case Type::ObjCInterface:
1916 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1918 return CreateType(cast<BuiltinType>(Ty));
1920 return CreateType(cast<ComplexType>(Ty));
1922 return CreateType(cast<PointerType>(Ty), Unit);
1923 case Type::BlockPointer:
1924 return CreateType(cast<BlockPointerType>(Ty), Unit);
1926 return CreateType(cast<TypedefType>(Ty), Unit);
1928 return CreateType(cast<RecordType>(Ty));
1930 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1931 case Type::FunctionProto:
1932 case Type::FunctionNoProto:
1933 return CreateType(cast<FunctionType>(Ty), Unit);
1934 case Type::ConstantArray:
1935 case Type::VariableArray:
1936 case Type::IncompleteArray:
1937 return CreateType(cast<ArrayType>(Ty), Unit);
1939 case Type::LValueReference:
1940 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1941 case Type::RValueReference:
1942 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1944 case Type::MemberPointer:
1945 return CreateType(cast<MemberPointerType>(Ty), Unit);
1948 return CreateType(cast<AtomicType>(Ty), Unit);
1950 case Type::Attributed:
1951 case Type::TemplateSpecialization:
1952 case Type::Elaborated:
1954 case Type::SubstTemplateTypeParm:
1955 case Type::TypeOfExpr:
1957 case Type::Decltype:
1958 case Type::UnaryTransform:
1960 llvm_unreachable("type should have been unwrapped!");
1963 assert(Diag && "Fall through without a diagnostic?");
1964 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1965 "debug information for %0 is not yet supported");
1966 CGM.getDiags().Report(DiagID)
1968 return llvm::DIType();
1971 /// getOrCreateLimitedType - Get the type from the cache or create a new
1972 /// limited type if necessary.
1973 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1974 llvm::DIFile Unit) {
1976 return llvm::DIType();
1978 // Unwrap the type as needed for debug information.
1979 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1981 llvm::DIType T = getTypeOrNull(Ty);
1983 // We may have cached a forward decl when we could have created
1984 // a non-forward decl. Go ahead and create a non-forward decl
1986 if (T.Verify() && !T.isForwardDecl()) return T;
1988 // Otherwise create the type.
1989 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1991 if (T.Verify() && T.isForwardDecl())
1992 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1993 static_cast<llvm::Value*>(T)));
1995 // And update the type cache.
1996 TypeCache[Ty.getAsOpaquePtr()] = Res;
2000 // TODO: Currently used for context chains when limiting debug info.
2001 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2002 RecordDecl *RD = Ty->getDecl();
2004 // Get overall information about the record type for the debug info.
2005 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2006 unsigned Line = getLineNumber(RD->getLocation());
2007 StringRef RDName = getClassName(RD);
2009 llvm::DIDescriptor RDContext;
2010 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2011 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2013 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2015 // If this is just a forward declaration, construct an appropriately
2016 // marked node and just return it.
2017 if (!RD->getDefinition())
2018 return createRecordFwdDecl(RD, RDContext);
2020 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2021 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2022 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2023 llvm::DICompositeType RealDecl;
2026 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2027 Size, Align, 0, llvm::DIArray());
2028 else if (RD->isClass()) {
2029 // FIXME: This could be a struct type giving a default visibility different
2030 // than C++ class type, but needs llvm metadata changes first.
2031 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2032 Size, Align, 0, 0, llvm::DIType(),
2033 llvm::DIArray(), llvm::DIType(),
2036 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2037 Size, Align, 0, llvm::DIType(), llvm::DIArray());
2039 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2040 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2043 // A class's primary base or the class itself contains the vtable.
2044 llvm::DICompositeType ContainingType;
2045 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2046 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2047 // Seek non virtual primary base root.
2049 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2050 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2051 if (PBT && !BRL.isPrimaryBaseVirtual())
2056 ContainingType = llvm::DICompositeType(
2057 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2058 } else if (CXXDecl->isDynamicClass())
2059 ContainingType = RealDecl;
2061 RealDecl.setContainingType(ContainingType);
2063 return llvm::DIType(RealDecl);
2066 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
2067 /// declare composite types that haven't been processed yet.
2068 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2070 // Work out details of type.
2071 switch (Ty->getTypeClass()) {
2072 #define TYPE(Class, Base)
2073 #define ABSTRACT_TYPE(Class, Base)
2074 #define NON_CANONICAL_TYPE(Class, Base)
2075 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2076 #include "clang/AST/TypeNodes.def"
2077 llvm_unreachable("Dependent types cannot show up in debug information");
2080 return CreateLimitedType(cast<RecordType>(Ty));
2082 return CreateTypeNode(Ty, Unit);
2086 /// CreateMemberType - Create new member and increase Offset by FType's size.
2087 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2090 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2091 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2092 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2093 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2094 FieldSize, FieldAlign,
2095 *Offset, 0, FieldTy);
2096 *Offset += FieldSize;
2100 /// getFunctionDeclaration - Return debug info descriptor to describe method
2101 /// declaration for the given method definition.
2102 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2103 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2104 if (!FD) return llvm::DISubprogram();
2107 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2109 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2110 MI = SPCache.find(FD->getCanonicalDecl());
2111 if (MI != SPCache.end()) {
2112 llvm::Value *V = MI->second;
2113 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2114 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2118 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2119 E = FD->redecls_end(); I != E; ++I) {
2120 const FunctionDecl *NextFD = *I;
2121 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2122 MI = SPCache.find(NextFD->getCanonicalDecl());
2123 if (MI != SPCache.end()) {
2124 llvm::Value *V = MI->second;
2125 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2126 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2130 return llvm::DISubprogram();
2133 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2134 // implicit parameter "this".
2135 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2139 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2140 return getOrCreateMethodType(Method, F);
2141 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2142 // Add "self" and "_cmd"
2143 SmallVector<llvm::Value *, 16> Elts;
2145 // First element is always return type. For 'void' functions it is NULL.
2146 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2147 // "self" pointer is always first argument.
2148 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2149 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2150 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2151 // "_cmd" pointer is always second argument.
2152 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2153 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2154 // Get rest of the arguments.
2155 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2156 PE = OMethod->param_end(); PI != PE; ++PI)
2157 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2159 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2160 return DBuilder.createSubroutineType(F, EltTypeArray);
2162 return getOrCreateType(FnType, F);
2165 /// EmitFunctionStart - Constructs the debug code for entering a function.
2166 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2168 CGBuilderTy &Builder) {
2171 StringRef LinkageName;
2173 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2175 const Decl *D = GD.getDecl();
2176 // Function may lack declaration in source code if it is created by Clang
2177 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2178 bool HasDecl = (D != 0);
2179 // Use the location of the declaration.
2182 Loc = D->getLocation();
2185 llvm::DIFile Unit = getOrCreateFile(Loc);
2186 llvm::DIDescriptor FDContext(Unit);
2187 llvm::DIArray TParamsArray;
2189 // Use llvm function name.
2190 Name = Fn->getName();
2191 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2192 // If there is a DISubprogram for this function available then use it.
2193 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2194 FI = SPCache.find(FD->getCanonicalDecl());
2195 if (FI != SPCache.end()) {
2196 llvm::Value *V = FI->second;
2197 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2198 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2199 llvm::MDNode *SPN = SP;
2200 LexicalBlockStack.push_back(SPN);
2201 RegionMap[D] = llvm::WeakVH(SP);
2205 Name = getFunctionName(FD);
2206 // Use mangled name as linkage name for C/C++ functions.
2207 if (FD->hasPrototype()) {
2208 LinkageName = CGM.getMangledName(GD);
2209 Flags |= llvm::DIDescriptor::FlagPrototyped;
2211 // No need to replicate the linkage name if it isn't different from the
2212 // subprogram name, no need to have it at all unless coverage is enabled or
2213 // debug is set to more than just line tables.
2214 if (LinkageName == Name ||
2215 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2216 !CGM.getCodeGenOpts().EmitGcovNotes &&
2217 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
2218 LinkageName = StringRef();
2220 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2221 if (const NamespaceDecl *NSDecl =
2222 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2223 FDContext = getOrCreateNameSpace(NSDecl);
2224 else if (const RecordDecl *RDecl =
2225 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2226 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2228 // Collect template parameters.
2229 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2231 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2232 Name = getObjCMethodName(OMD);
2233 Flags |= llvm::DIDescriptor::FlagPrototyped;
2235 // Use llvm function name.
2236 Name = Fn->getName();
2237 Flags |= llvm::DIDescriptor::FlagPrototyped;
2239 if (!Name.empty() && Name[0] == '\01')
2240 Name = Name.substr(1);
2242 unsigned LineNo = getLineNumber(Loc);
2243 if (!HasDecl || D->isImplicit())
2244 Flags |= llvm::DIDescriptor::FlagArtificial;
2246 llvm::DIType DIFnType;
2247 llvm::DISubprogram SPDecl;
2249 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2250 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2251 SPDecl = getFunctionDeclaration(D);
2253 // Create fake but valid subroutine type. Otherwise
2254 // llvm::DISubprogram::Verify() would return false, and
2255 // subprogram DIE will miss DW_AT_decl_file and
2256 // DW_AT_decl_line fields.
2257 SmallVector<llvm::Value*, 16> Elts;
2258 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2259 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2261 llvm::DISubprogram SP;
2262 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2264 Fn->hasInternalLinkage(), true/*definition*/,
2265 getLineNumber(CurLoc), Flags,
2266 CGM.getLangOpts().Optimize,
2267 Fn, TParamsArray, SPDecl);
2269 // Push function on region stack.
2270 llvm::MDNode *SPN = SP;
2271 LexicalBlockStack.push_back(SPN);
2273 RegionMap[D] = llvm::WeakVH(SP);
2276 /// EmitLocation - Emit metadata to indicate a change in line/column
2277 /// information in the source file.
2278 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2279 bool ForceColumnInfo) {
2281 // Update our current location
2284 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2286 // Don't bother if things are the same as last time.
2287 SourceManager &SM = CGM.getContext().getSourceManager();
2288 if (CurLoc == PrevLoc ||
2289 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2290 // New Builder may not be in sync with CGDebugInfo.
2291 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2292 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2293 LexicalBlockStack.back())
2296 // Update last state.
2299 llvm::MDNode *Scope = LexicalBlockStack.back();
2300 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2301 (getLineNumber(CurLoc),
2302 getColumnNumber(CurLoc, ForceColumnInfo),
2306 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2308 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2309 llvm::DIDescriptor D =
2310 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2311 llvm::DIDescriptor() :
2312 llvm::DIDescriptor(LexicalBlockStack.back()),
2313 getOrCreateFile(CurLoc),
2314 getLineNumber(CurLoc),
2315 getColumnNumber(CurLoc));
2316 llvm::MDNode *DN = D;
2317 LexicalBlockStack.push_back(DN);
2320 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2321 /// region - beginning of a DW_TAG_lexical_block.
2322 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2323 // Set our current location.
2326 // Create a new lexical block and push it on the stack.
2327 CreateLexicalBlock(Loc);
2329 // Emit a line table change for the current location inside the new scope.
2330 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2331 getColumnNumber(Loc),
2332 LexicalBlockStack.back()));
2335 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2336 /// region - end of a DW_TAG_lexical_block.
2337 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2338 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2340 // Provide an entry in the line table for the end of the block.
2341 EmitLocation(Builder, Loc);
2343 LexicalBlockStack.pop_back();
2346 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2347 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2348 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2349 unsigned RCount = FnBeginRegionCount.back();
2350 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2352 // Pop all regions for this function.
2353 while (LexicalBlockStack.size() != RCount)
2354 EmitLexicalBlockEnd(Builder, CurLoc);
2355 FnBeginRegionCount.pop_back();
2358 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2359 // See BuildByRefType.
2360 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2361 uint64_t *XOffset) {
2363 SmallVector<llvm::Value *, 5> EltTys;
2365 uint64_t FieldSize, FieldOffset;
2366 unsigned FieldAlign;
2368 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2369 QualType Type = VD->getType();
2372 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2373 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2374 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2375 FType = CGM.getContext().IntTy;
2376 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2377 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2379 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2380 if (HasCopyAndDispose) {
2381 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2382 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2384 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2387 bool HasByrefExtendedLayout;
2388 Qualifiers::ObjCLifetime Lifetime;
2389 if (CGM.getContext().getByrefLifetime(Type,
2390 Lifetime, HasByrefExtendedLayout)
2391 && HasByrefExtendedLayout)
2392 EltTys.push_back(CreateMemberType(Unit, FType,
2393 "__byref_variable_layout",
2396 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2397 if (Align > CGM.getContext().toCharUnitsFromBits(
2398 CGM.getTarget().getPointerAlign(0))) {
2399 CharUnits FieldOffsetInBytes
2400 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2401 CharUnits AlignedOffsetInBytes
2402 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2403 CharUnits NumPaddingBytes
2404 = AlignedOffsetInBytes - FieldOffsetInBytes;
2406 if (NumPaddingBytes.isPositive()) {
2407 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2408 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2409 pad, ArrayType::Normal, 0);
2410 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2415 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2416 FieldSize = CGM.getContext().getTypeSize(FType);
2417 FieldAlign = CGM.getContext().toBits(Align);
2419 *XOffset = FieldOffset;
2420 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2421 0, FieldSize, FieldAlign,
2422 FieldOffset, 0, FieldTy);
2423 EltTys.push_back(FieldTy);
2424 FieldOffset += FieldSize;
2426 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2428 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2430 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2431 llvm::DIType(), Elements);
2434 /// EmitDeclare - Emit local variable declaration debug info.
2435 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2436 llvm::Value *Storage,
2437 unsigned ArgNo, CGBuilderTy &Builder) {
2438 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2439 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2441 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2443 uint64_t XOffset = 0;
2444 if (VD->hasAttr<BlocksAttr>())
2445 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2447 Ty = getOrCreateType(VD->getType(), Unit);
2449 // If there is no debug info for this type then do not emit debug info
2450 // for this variable.
2454 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2455 // If Storage is an aggregate returned as 'sret' then let debugger know
2457 if (Arg->hasStructRetAttr())
2458 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2459 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2460 // If an aggregate variable has non trivial destructor or non trivial copy
2461 // constructor than it is pass indirectly. Let debug info know about this
2462 // by using reference of the aggregate type as a argument type.
2463 if (Record->hasNonTrivialCopyConstructor() ||
2464 !Record->hasTrivialDestructor())
2465 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2469 // Get location information.
2470 unsigned Line = getLineNumber(VD->getLocation());
2471 unsigned Column = getColumnNumber(VD->getLocation());
2473 if (VD->isImplicit())
2474 Flags |= llvm::DIDescriptor::FlagArtificial;
2475 // If this is the first argument and it is implicit then
2476 // give it an object pointer flag.
2477 // FIXME: There has to be a better way to do this, but for static
2478 // functions there won't be an implicit param at arg1 and
2479 // otherwise it is 'self' or 'this'.
2480 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2481 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2483 llvm::MDNode *Scope = LexicalBlockStack.back();
2485 StringRef Name = VD->getName();
2486 if (!Name.empty()) {
2487 if (VD->hasAttr<BlocksAttr>()) {
2488 CharUnits offset = CharUnits::fromQuantity(32);
2489 SmallVector<llvm::Value *, 9> addr;
2490 llvm::Type *Int64Ty = CGM.Int64Ty;
2491 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2492 // offset of __forwarding field
2493 offset = CGM.getContext().toCharUnitsFromBits(
2494 CGM.getTarget().getPointerWidth(0));
2495 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2496 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2497 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2498 // offset of x field
2499 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2500 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2502 // Create the descriptor for the variable.
2503 llvm::DIVariable D =
2504 DBuilder.createComplexVariable(Tag,
2505 llvm::DIDescriptor(Scope),
2506 VD->getName(), Unit, Line, Ty,
2509 // Insert an llvm.dbg.declare into the current block.
2510 llvm::Instruction *Call =
2511 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2512 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2514 } else if (isa<VariableArrayType>(VD->getType())) {
2515 // These are "complex" variables in that they need an op_deref.
2516 // Create the descriptor for the variable.
2517 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2518 llvm::DIBuilder::OpDeref);
2519 llvm::DIVariable D =
2520 DBuilder.createComplexVariable(Tag,
2521 llvm::DIDescriptor(Scope),
2522 Name, Unit, Line, Ty,
2525 // Insert an llvm.dbg.declare into the current block.
2526 llvm::Instruction *Call =
2527 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2528 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2531 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2532 // If VD is an anonymous union then Storage represents value for
2533 // all union fields.
2534 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2535 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2536 for (RecordDecl::field_iterator I = RD->field_begin(),
2537 E = RD->field_end();
2539 FieldDecl *Field = *I;
2540 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2541 StringRef FieldName = Field->getName();
2543 // Ignore unnamed fields. Do not ignore unnamed records.
2544 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2547 // Use VarDecl's Tag, Scope and Line number.
2548 llvm::DIVariable D =
2549 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2550 FieldName, Unit, Line, FieldTy,
2551 CGM.getLangOpts().Optimize, Flags,
2554 // Insert an llvm.dbg.declare into the current block.
2555 llvm::Instruction *Call =
2556 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2557 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2563 // Create the descriptor for the variable.
2564 llvm::DIVariable D =
2565 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2566 Name, Unit, Line, Ty,
2567 CGM.getLangOpts().Optimize, Flags, ArgNo);
2569 // Insert an llvm.dbg.declare into the current block.
2570 llvm::Instruction *Call =
2571 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2572 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2575 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2576 llvm::Value *Storage,
2577 CGBuilderTy &Builder) {
2578 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2579 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2582 /// Look up the completed type for a self pointer in the TypeCache and
2583 /// create a copy of it with the ObjectPointer and Artificial flags
2584 /// set. If the type is not cached, a new one is created. This should
2585 /// never happen though, since creating a type for the implicit self
2586 /// argument implies that we already parsed the interface definition
2587 /// and the ivar declarations in the implementation.
2588 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2589 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2590 if (CachedTy.Verify()) Ty = CachedTy;
2591 else DEBUG(llvm::dbgs() << "No cached type for self.");
2592 return DBuilder.createObjectPointerType(Ty);
2595 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2596 llvm::Value *Storage,
2597 CGBuilderTy &Builder,
2598 const CGBlockInfo &blockInfo) {
2599 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2600 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2602 if (Builder.GetInsertBlock() == 0)
2605 bool isByRef = VD->hasAttr<BlocksAttr>();
2607 uint64_t XOffset = 0;
2608 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2611 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2613 Ty = getOrCreateType(VD->getType(), Unit);
2615 // Self is passed along as an implicit non-arg variable in a
2616 // block. Mark it as the object pointer.
2617 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2618 Ty = CreateSelfType(VD->getType(), Ty);
2620 // Get location information.
2621 unsigned Line = getLineNumber(VD->getLocation());
2622 unsigned Column = getColumnNumber(VD->getLocation());
2624 const llvm::DataLayout &target = CGM.getDataLayout();
2626 CharUnits offset = CharUnits::fromQuantity(
2627 target.getStructLayout(blockInfo.StructureType)
2628 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2630 SmallVector<llvm::Value *, 9> addr;
2631 llvm::Type *Int64Ty = CGM.Int64Ty;
2632 if (isa<llvm::AllocaInst>(Storage))
2633 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2634 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2635 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2637 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2638 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2639 // offset of __forwarding field
2640 offset = CGM.getContext()
2641 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2642 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2643 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2644 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2645 // offset of x field
2646 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2647 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2650 // Create the descriptor for the variable.
2651 llvm::DIVariable D =
2652 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2653 llvm::DIDescriptor(LexicalBlockStack.back()),
2654 VD->getName(), Unit, Line, Ty, addr);
2656 // Insert an llvm.dbg.declare into the current block.
2657 llvm::Instruction *Call =
2658 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2659 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2660 LexicalBlockStack.back()));
2663 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2664 /// variable declaration.
2665 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2667 CGBuilderTy &Builder) {
2668 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2669 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2673 struct BlockLayoutChunk {
2674 uint64_t OffsetInBits;
2675 const BlockDecl::Capture *Capture;
2677 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2678 return l.OffsetInBits < r.OffsetInBits;
2682 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2684 llvm::Value *LocalAddr,
2685 CGBuilderTy &Builder) {
2686 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2687 ASTContext &C = CGM.getContext();
2688 const BlockDecl *blockDecl = block.getBlockDecl();
2690 // Collect some general information about the block's location.
2691 SourceLocation loc = blockDecl->getCaretLocation();
2692 llvm::DIFile tunit = getOrCreateFile(loc);
2693 unsigned line = getLineNumber(loc);
2694 unsigned column = getColumnNumber(loc);
2696 // Build the debug-info type for the block literal.
2697 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2699 const llvm::StructLayout *blockLayout =
2700 CGM.getDataLayout().getStructLayout(block.StructureType);
2702 SmallVector<llvm::Value*, 16> fields;
2703 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2704 blockLayout->getElementOffsetInBits(0),
2706 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2707 blockLayout->getElementOffsetInBits(1),
2709 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2710 blockLayout->getElementOffsetInBits(2),
2712 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2713 blockLayout->getElementOffsetInBits(3),
2715 fields.push_back(createFieldType("__descriptor",
2716 C.getPointerType(block.NeedsCopyDispose ?
2717 C.getBlockDescriptorExtendedType() :
2718 C.getBlockDescriptorType()),
2720 blockLayout->getElementOffsetInBits(4),
2723 // We want to sort the captures by offset, not because DWARF
2724 // requires this, but because we're paranoid about debuggers.
2725 SmallVector<BlockLayoutChunk, 8> chunks;
2728 if (blockDecl->capturesCXXThis()) {
2729 BlockLayoutChunk chunk;
2730 chunk.OffsetInBits =
2731 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2733 chunks.push_back(chunk);
2736 // Variable captures.
2737 for (BlockDecl::capture_const_iterator
2738 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2740 const BlockDecl::Capture &capture = *i;
2741 const VarDecl *variable = capture.getVariable();
2742 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2744 // Ignore constant captures.
2745 if (captureInfo.isConstant())
2748 BlockLayoutChunk chunk;
2749 chunk.OffsetInBits =
2750 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2751 chunk.Capture = &capture;
2752 chunks.push_back(chunk);
2756 llvm::array_pod_sort(chunks.begin(), chunks.end());
2758 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2759 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2760 uint64_t offsetInBits = i->OffsetInBits;
2761 const BlockDecl::Capture *capture = i->Capture;
2763 // If we have a null capture, this must be the C++ 'this' capture.
2765 const CXXMethodDecl *method =
2766 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2767 QualType type = method->getThisType(C);
2769 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2770 offsetInBits, tunit, tunit));
2774 const VarDecl *variable = capture->getVariable();
2775 StringRef name = variable->getName();
2777 llvm::DIType fieldType;
2778 if (capture->isByRef()) {
2779 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2781 // FIXME: this creates a second copy of this type!
2783 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2784 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2785 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2786 ptrInfo.first, ptrInfo.second,
2787 offsetInBits, 0, fieldType);
2789 fieldType = createFieldType(name, variable->getType(), 0,
2790 loc, AS_public, offsetInBits, tunit, tunit);
2792 fields.push_back(fieldType);
2795 SmallString<36> typeName;
2796 llvm::raw_svector_ostream(typeName)
2797 << "__block_literal_" << CGM.getUniqueBlockCount();
2799 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2802 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2803 CGM.getContext().toBits(block.BlockSize),
2804 CGM.getContext().toBits(block.BlockAlign),
2805 0, llvm::DIType(), fieldsArray);
2806 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2808 // Get overall information about the block.
2809 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2810 llvm::MDNode *scope = LexicalBlockStack.back();
2812 // Create the descriptor for the parameter.
2813 llvm::DIVariable debugVar =
2814 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2815 llvm::DIDescriptor(scope),
2816 Arg->getName(), tunit, line, type,
2817 CGM.getLangOpts().Optimize, flags,
2818 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2821 // Insert an llvm.dbg.value into the current block.
2822 llvm::Instruction *DbgVal =
2823 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
2824 Builder.GetInsertBlock());
2825 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2828 // Insert an llvm.dbg.declare into the current block.
2829 llvm::Instruction *DbgDecl =
2830 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2831 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2834 /// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2835 /// a static data member of a class, find its corresponding in-class
2837 llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2838 if (cast<VarDecl>(D)->isStaticDataMember()) {
2839 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2840 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2841 if (MI != StaticDataMemberCache.end())
2842 // Verify the info still exists.
2843 if (llvm::Value *V = MI->second)
2844 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2846 return llvm::DIDerivedType();
2849 /// EmitGlobalVariable - Emit information about a global variable.
2850 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2852 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2853 // Create global variable debug descriptor.
2854 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2855 unsigned LineNo = getLineNumber(D->getLocation());
2857 setLocation(D->getLocation());
2859 QualType T = D->getType();
2860 if (T->isIncompleteArrayType()) {
2862 // CodeGen turns int[] into int[1] so we'll do the same here.
2863 llvm::APInt ConstVal(32, 1);
2864 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2866 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2867 ArrayType::Normal, 0);
2869 StringRef DeclName = D->getName();
2870 StringRef LinkageName;
2871 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2872 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2873 LinkageName = Var->getName();
2874 if (LinkageName == DeclName)
2875 LinkageName = StringRef();
2876 llvm::DIDescriptor DContext =
2877 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2878 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2879 Unit, LineNo, getOrCreateType(T, Unit),
2880 Var->hasInternalLinkage(), Var,
2881 getStaticDataMemberDeclaration(D));
2884 /// EmitGlobalVariable - Emit information about an objective-c interface.
2885 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2886 ObjCInterfaceDecl *ID) {
2887 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2888 // Create global variable debug descriptor.
2889 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2890 unsigned LineNo = getLineNumber(ID->getLocation());
2892 StringRef Name = ID->getName();
2894 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2895 if (T->isIncompleteArrayType()) {
2897 // CodeGen turns int[] into int[1] so we'll do the same here.
2898 llvm::APInt ConstVal(32, 1);
2899 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2901 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2902 ArrayType::Normal, 0);
2905 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2906 getOrCreateType(T, Unit),
2907 Var->hasInternalLinkage(), Var);
2910 /// EmitGlobalVariable - Emit global variable's debug info.
2911 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2912 llvm::Constant *Init) {
2913 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2914 // Create the descriptor for the variable.
2915 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2916 StringRef Name = VD->getName();
2917 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2918 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2919 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2920 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2921 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2923 // Do not use DIGlobalVariable for enums.
2924 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2926 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2927 getLineNumber(VD->getLocation()),
2929 getStaticDataMemberDeclaration(VD));
2932 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
2933 llvm::DIScope Scope =
2934 LexicalBlockStack.empty()
2935 ? getContextDescriptor(cast<Decl>(UD.getDeclContext()))
2936 : llvm::DIScope(LexicalBlockStack.back());
2937 DBuilder.createImportedModule(
2938 Scope, getOrCreateNameSpace(UD.getNominatedNamespace()),
2939 getLineNumber(UD.getLocation()));
2942 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2945 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2946 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2947 NameSpaceCache.find(NSDecl);
2948 if (I != NameSpaceCache.end())
2949 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2951 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2952 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2953 llvm::DIDescriptor Context =
2954 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2955 llvm::DINameSpace NS =
2956 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2957 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2961 void CGDebugInfo::finalize() {
2962 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2963 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2964 llvm::DIType Ty, RepTy;
2965 // Verify that the debug info still exists.
2966 if (llvm::Value *V = VI->second)
2967 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2969 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2970 TypeCache.find(VI->first);
2971 if (it != TypeCache.end()) {
2972 // Verify that the debug info still exists.
2973 if (llvm::Value *V = it->second)
2974 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2977 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
2978 Ty.replaceAllUsesWith(RepTy);
2981 // We keep our own list of retained types, because we need to look
2982 // up the final type in the type cache.
2983 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
2984 RE = RetainedTypes.end(); RI != RE; ++RI)
2985 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
2987 DBuilder.finalize();