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::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
96 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97 I = RegionMap.find(Context);
98 if (I != RegionMap.end()) {
99 llvm::Value *V = I->second;
100 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
108 if (!RDecl->isDependentType()) {
109 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110 getOrCreateMainFile());
111 return llvm::DIDescriptor(Ty);
117 /// getFunctionName - Get function name for the given FunctionDecl. If the
118 /// name is constructred on demand (e.g. C++ destructor) then the name
119 /// is stored on the side.
120 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
121 assert (FD && "Invalid FunctionDecl!");
122 IdentifierInfo *FII = FD->getIdentifier();
123 FunctionTemplateSpecializationInfo *Info
124 = FD->getTemplateSpecializationInfo();
126 return FII->getName();
128 // Otherwise construct human readable name for debug info.
130 llvm::raw_svector_ostream OS(NS);
133 // Add any template specialization args.
135 const TemplateArgumentList *TArgs = Info->TemplateArguments;
136 const TemplateArgument *Args = TArgs->data();
137 unsigned NumArgs = TArgs->size();
138 PrintingPolicy Policy(CGM.getLangOpts());
139 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
143 // Copy this name on the side and use its reference.
145 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
146 memcpy(StrPtr, NS.data(), NS.size());
147 return StringRef(StrPtr, NS.size());
150 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
151 SmallString<256> MethodName;
152 llvm::raw_svector_ostream OS(MethodName);
153 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
154 const DeclContext *DC = OMD->getDeclContext();
155 if (const ObjCImplementationDecl *OID =
156 dyn_cast<const ObjCImplementationDecl>(DC)) {
157 OS << OID->getName();
158 } else if (const ObjCInterfaceDecl *OID =
159 dyn_cast<const ObjCInterfaceDecl>(DC)) {
160 OS << OID->getName();
161 } else if (const ObjCCategoryImplDecl *OCD =
162 dyn_cast<const ObjCCategoryImplDecl>(DC)){
163 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
164 OCD->getIdentifier()->getNameStart() << ')';
166 OS << ' ' << OMD->getSelector().getAsString() << ']';
168 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
169 memcpy(StrPtr, MethodName.begin(), OS.tell());
170 return StringRef(StrPtr, OS.tell());
173 /// getSelectorName - Return selector name. This is used for debugging
175 StringRef CGDebugInfo::getSelectorName(Selector S) {
176 const std::string &SName = S.getAsString();
177 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
178 memcpy(StrPtr, SName.data(), SName.size());
179 return StringRef(StrPtr, SName.size());
182 /// getClassName - Get class name including template argument list.
184 CGDebugInfo::getClassName(const RecordDecl *RD) {
185 const ClassTemplateSpecializationDecl *Spec
186 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
188 return RD->getName();
190 const TemplateArgument *Args;
192 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
193 const TemplateSpecializationType *TST =
194 cast<TemplateSpecializationType>(TAW->getType());
195 Args = TST->getArgs();
196 NumArgs = TST->getNumArgs();
198 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
199 Args = TemplateArgs.data();
200 NumArgs = TemplateArgs.size();
202 StringRef Name = RD->getIdentifier()->getName();
203 PrintingPolicy Policy(CGM.getLangOpts());
204 SmallString<128> TemplateArgList;
206 llvm::raw_svector_ostream OS(TemplateArgList);
207 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
211 // Copy this name on the side and use its reference.
212 size_t Length = Name.size() + TemplateArgList.size();
213 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
214 memcpy(StrPtr, Name.data(), Name.size());
215 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
216 return StringRef(StrPtr, Length);
219 /// getOrCreateFile - Get the file debug info descriptor for the input location.
220 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
222 // If Location is not valid then use main input file.
223 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
225 SourceManager &SM = CGM.getContext().getSourceManager();
226 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
228 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
229 // If the location is not valid then use main input file.
230 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
232 // Cache the results.
233 const char *fname = PLoc.getFilename();
234 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
235 DIFileCache.find(fname);
237 if (it != DIFileCache.end()) {
238 // Verify that the information still exists.
239 if (llvm::Value *V = it->second)
240 return llvm::DIFile(cast<llvm::MDNode>(V));
243 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
245 DIFileCache[fname] = F;
249 /// getOrCreateMainFile - Get the file info for main compile unit.
250 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
251 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
254 /// getLineNumber - Get line number for the location. If location is invalid
255 /// then use current location.
256 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
257 if (Loc.isInvalid() && CurLoc.isInvalid())
259 SourceManager &SM = CGM.getContext().getSourceManager();
260 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
261 return PLoc.isValid()? PLoc.getLine() : 0;
264 /// getColumnNumber - Get column number for the location.
265 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
266 // We may not want column information at all.
267 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
270 // If the location is invalid then use the current column.
271 if (Loc.isInvalid() && CurLoc.isInvalid())
273 SourceManager &SM = CGM.getContext().getSourceManager();
274 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
275 return PLoc.isValid()? PLoc.getColumn() : 0;
278 StringRef CGDebugInfo::getCurrentDirname() {
279 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
280 return CGM.getCodeGenOpts().DebugCompilationDir;
282 if (!CWDName.empty())
284 SmallString<256> CWD;
285 llvm::sys::fs::current_path(CWD);
286 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
287 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
288 return CWDName = StringRef(CompDirnamePtr, CWD.size());
291 /// CreateCompileUnit - Create new compile unit.
292 void CGDebugInfo::CreateCompileUnit() {
294 // Get absolute path name.
295 SourceManager &SM = CGM.getContext().getSourceManager();
296 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
297 if (MainFileName.empty())
298 MainFileName = "<unknown>";
300 // The main file name provided via the "-main-file-name" option contains just
301 // the file name itself with no path information. This file name may have had
302 // a relative path, so we look into the actual file entry for the main
303 // file to determine the real absolute path for the file.
304 std::string MainFileDir;
305 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
306 MainFileDir = MainFile->getDir()->getName();
307 if (MainFileDir != ".")
308 MainFileName = MainFileDir + "/" + MainFileName;
311 // Save filename string.
312 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
313 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
314 StringRef Filename(FilenamePtr, MainFileName.length());
316 // Save split dwarf file string.
317 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
318 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
319 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
320 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
323 const LangOptions &LO = CGM.getLangOpts();
326 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
328 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
329 } else if (LO.ObjC1) {
330 LangTag = llvm::dwarf::DW_LANG_ObjC;
332 LangTag = llvm::dwarf::DW_LANG_C99;
334 LangTag = llvm::dwarf::DW_LANG_C89;
337 std::string Producer = getClangFullVersion();
339 // Figure out which version of the ObjC runtime we have.
340 unsigned RuntimeVers = 0;
342 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
344 // Create new compile unit.
345 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
346 Producer, LO.Optimize,
347 CGM.getCodeGenOpts().DwarfDebugFlags,
348 RuntimeVers, SplitDwarfFilename);
349 // FIXME - Eliminate TheCU.
350 TheCU = llvm::DICompileUnit(DBuilder.getCU());
353 /// CreateType - Get the Basic type from the cache or create a new
354 /// one if necessary.
355 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
356 unsigned Encoding = 0;
358 switch (BT->getKind()) {
359 #define BUILTIN_TYPE(Id, SingletonId)
360 #define PLACEHOLDER_TYPE(Id, SingletonId) \
361 case BuiltinType::Id:
362 #include "clang/AST/BuiltinTypes.def"
363 case BuiltinType::Dependent:
364 llvm_unreachable("Unexpected builtin type");
365 case BuiltinType::NullPtr:
367 createNullPtrType(BT->getName(CGM.getLangOpts()));
368 case BuiltinType::Void:
369 return llvm::DIType();
370 case BuiltinType::ObjCClass:
371 if (ClassTy.Verify())
373 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
375 getOrCreateMainFile(), 0);
377 case BuiltinType::ObjCId: {
378 // typedef struct objc_class *Class;
379 // typedef struct objc_object {
386 if (!ClassTy.Verify())
387 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
389 getOrCreateMainFile(), 0);
391 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
393 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
396 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
397 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
399 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
400 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
403 case BuiltinType::ObjCSel: {
407 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
408 "objc_selector", TheCU, getOrCreateMainFile(),
413 case BuiltinType::OCLImage1d:
414 return getOrCreateStructPtrType("opencl_image1d_t",
416 case BuiltinType::OCLImage1dArray:
417 return getOrCreateStructPtrType("opencl_image1d_array_t",
418 OCLImage1dArrayDITy);
419 case BuiltinType::OCLImage1dBuffer:
420 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
421 OCLImage1dBufferDITy);
422 case BuiltinType::OCLImage2d:
423 return getOrCreateStructPtrType("opencl_image2d_t",
425 case BuiltinType::OCLImage2dArray:
426 return getOrCreateStructPtrType("opencl_image2d_array_t",
427 OCLImage2dArrayDITy);
428 case BuiltinType::OCLImage3d:
429 return getOrCreateStructPtrType("opencl_image3d_t",
431 case BuiltinType::OCLSampler:
432 return DBuilder.createBasicType("opencl_sampler_t",
433 CGM.getContext().getTypeSize(BT),
434 CGM.getContext().getTypeAlign(BT),
435 llvm::dwarf::DW_ATE_unsigned);
436 case BuiltinType::OCLEvent:
437 return getOrCreateStructPtrType("opencl_event_t",
440 case BuiltinType::UChar:
441 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
442 case BuiltinType::Char_S:
443 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
444 case BuiltinType::Char16:
445 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
446 case BuiltinType::UShort:
447 case BuiltinType::UInt:
448 case BuiltinType::UInt128:
449 case BuiltinType::ULong:
450 case BuiltinType::WChar_U:
451 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
452 case BuiltinType::Short:
453 case BuiltinType::Int:
454 case BuiltinType::Int128:
455 case BuiltinType::Long:
456 case BuiltinType::WChar_S:
457 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
458 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
459 case BuiltinType::Half:
460 case BuiltinType::Float:
461 case BuiltinType::LongDouble:
462 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
465 switch (BT->getKind()) {
466 case BuiltinType::Long: BTName = "long int"; break;
467 case BuiltinType::LongLong: BTName = "long long int"; break;
468 case BuiltinType::ULong: BTName = "long unsigned int"; break;
469 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
471 BTName = BT->getName(CGM.getLangOpts());
474 // Bit size, align and offset of the type.
475 uint64_t Size = CGM.getContext().getTypeSize(BT);
476 uint64_t Align = CGM.getContext().getTypeAlign(BT);
478 DBuilder.createBasicType(BTName, Size, Align, Encoding);
482 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
483 // Bit size, align and offset of the type.
484 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
485 if (Ty->isComplexIntegerType())
486 Encoding = llvm::dwarf::DW_ATE_lo_user;
488 uint64_t Size = CGM.getContext().getTypeSize(Ty);
489 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
491 DBuilder.createBasicType("complex", Size, Align, Encoding);
496 /// CreateCVRType - Get the qualified type from the cache or create
497 /// a new one if necessary.
498 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
499 QualifierCollector Qc;
500 const Type *T = Qc.strip(Ty);
502 // Ignore these qualifiers for now.
503 Qc.removeObjCGCAttr();
504 Qc.removeAddressSpace();
505 Qc.removeObjCLifetime();
507 // We will create one Derived type for one qualifier and recurse to handle any
511 Tag = llvm::dwarf::DW_TAG_const_type;
513 } else if (Qc.hasVolatile()) {
514 Tag = llvm::dwarf::DW_TAG_volatile_type;
516 } else if (Qc.hasRestrict()) {
517 Tag = llvm::dwarf::DW_TAG_restrict_type;
520 assert(Qc.empty() && "Unknown type qualifier for debug info");
521 return getOrCreateType(QualType(T, 0), Unit);
524 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
526 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
527 // CVR derived types.
528 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
533 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
536 // The frontend treats 'id' as a typedef to an ObjCObjectType,
537 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
538 // debug info, we want to emit 'id' in both cases.
539 if (Ty->isObjCQualifiedIdType())
540 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
543 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
544 Ty->getPointeeType(), Unit);
548 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
550 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
551 Ty->getPointeeType(), Unit);
554 // Creates a forward declaration for a RecordDecl in the given context.
555 llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
556 llvm::DIDescriptor Ctx) {
557 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
558 unsigned Line = getLineNumber(RD->getLocation());
559 StringRef RDName = getClassName(RD);
562 if (RD->isStruct() || RD->isInterface())
563 Tag = llvm::dwarf::DW_TAG_structure_type;
564 else if (RD->isUnion())
565 Tag = llvm::dwarf::DW_TAG_union_type;
567 assert(RD->isClass());
568 Tag = llvm::dwarf::DW_TAG_class_type;
572 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
575 // Walk up the context chain and create forward decls for record decls,
576 // and normal descriptors for namespaces.
577 llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
581 // See if we already have the parent.
582 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
583 I = RegionMap.find(Context);
584 if (I != RegionMap.end()) {
585 llvm::Value *V = I->second;
586 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
590 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
591 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
593 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
594 if (!RD->isDependentType()) {
595 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
596 getOrCreateMainFile());
597 return llvm::DIDescriptor(Ty);
603 /// CreatePointeeType - Create Pointee type. If Pointee is a record
604 /// then emit record's fwd if debug info size reduction is enabled.
605 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
607 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
608 return getOrCreateType(PointeeTy, Unit);
610 // Limit debug info for the pointee type.
612 // If we have an existing type, use that, it's still smaller than creating
614 llvm::DIType Ty = getTypeOrNull(PointeeTy);
615 if (Ty.Verify()) return Ty;
617 // Handle qualifiers.
618 if (PointeeTy.hasLocalQualifiers())
619 return CreateQualifiedType(PointeeTy, Unit);
621 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
622 RecordDecl *RD = RTy->getDecl();
623 llvm::DIDescriptor FDContext =
624 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
625 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
626 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
629 return getOrCreateType(PointeeTy, Unit);
632 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
636 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
637 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
638 return DBuilder.createReferenceType(Tag,
639 CreatePointeeType(PointeeTy, Unit));
641 // Bit size, align and offset of the type.
642 // Size is always the size of a pointer. We can't use getTypeSize here
643 // because that does not return the correct value for references.
644 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
645 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
646 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
648 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
652 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
656 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
657 Name, TheCU, getOrCreateMainFile(),
659 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
660 Cache = DBuilder.createPointerType(Cache, Size);
664 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
666 if (BlockLiteralGenericSet)
667 return BlockLiteralGeneric;
669 SmallVector<llvm::Value *, 8> EltTys;
670 llvm::DIType FieldTy;
672 uint64_t FieldSize, FieldOffset;
674 llvm::DIArray Elements;
675 llvm::DIType EltTy, DescTy;
678 FType = CGM.getContext().UnsignedLongTy;
679 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
680 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
682 Elements = DBuilder.getOrCreateArray(EltTys);
685 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
686 unsigned LineNo = getLineNumber(CurLoc);
688 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
689 Unit, LineNo, FieldOffset, 0,
690 Flags, llvm::DIType(), Elements);
692 // Bit size, align and offset of the type.
693 uint64_t Size = CGM.getContext().getTypeSize(Ty);
695 DescTy = DBuilder.createPointerType(EltTy, Size);
698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
699 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
700 FType = CGM.getContext().IntTy;
701 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
702 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
708 FieldSize = CGM.getContext().getTypeSize(Ty);
709 FieldAlign = CGM.getContext().getTypeAlign(Ty);
710 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
711 LineNo, FieldSize, FieldAlign,
712 FieldOffset, 0, FieldTy);
713 EltTys.push_back(FieldTy);
715 FieldOffset += FieldSize;
716 Elements = DBuilder.getOrCreateArray(EltTys);
718 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
719 Unit, LineNo, FieldOffset, 0,
720 Flags, llvm::DIType(), Elements);
722 BlockLiteralGenericSet = true;
723 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
724 return BlockLiteralGeneric;
727 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
728 // Typedefs are derived from some other type. If we have a typedef of a
729 // typedef, make sure to emit the whole chain.
730 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
732 return llvm::DIType();
733 // We don't set size information, but do specify where the typedef was
735 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
736 const TypedefNameDecl *TyDecl = Ty->getDecl();
738 llvm::DIDescriptor TypedefContext =
739 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
742 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
745 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
747 SmallVector<llvm::Value *, 16> EltTys;
749 // Add the result type at least.
750 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
752 // Set up remainder of arguments if there is a prototype.
753 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
754 if (isa<FunctionNoProtoType>(Ty))
755 EltTys.push_back(DBuilder.createUnspecifiedParameter());
756 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
757 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
758 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
761 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
762 return DBuilder.createSubroutineType(Unit, EltTypeArray);
766 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
768 uint64_t sizeInBitsOverride,
771 uint64_t offsetInBits,
773 llvm::DIDescriptor scope) {
774 llvm::DIType debugType = getOrCreateType(type, tunit);
776 // Get the location for the field.
777 llvm::DIFile file = getOrCreateFile(loc);
778 unsigned line = getLineNumber(loc);
780 uint64_t sizeInBits = 0;
781 unsigned alignInBits = 0;
782 if (!type->isIncompleteArrayType()) {
783 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
785 if (sizeInBitsOverride)
786 sizeInBits = sizeInBitsOverride;
790 if (AS == clang::AS_private)
791 flags |= llvm::DIDescriptor::FlagPrivate;
792 else if (AS == clang::AS_protected)
793 flags |= llvm::DIDescriptor::FlagProtected;
795 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
796 alignInBits, offsetInBits, flags, debugType);
799 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
801 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
802 SmallVectorImpl<llvm::Value *> &elements,
803 llvm::DIType RecordTy) {
804 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
805 // has the name and the location of the variable so we should iterate over
806 // both concurrently.
807 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
808 RecordDecl::field_iterator Field = CXXDecl->field_begin();
809 unsigned fieldno = 0;
810 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
811 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
812 const LambdaExpr::Capture C = *I;
813 if (C.capturesVariable()) {
814 VarDecl *V = C.getCapturedVar();
815 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
816 StringRef VName = V->getName();
817 uint64_t SizeInBitsOverride = 0;
818 if (Field->isBitField()) {
819 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
820 assert(SizeInBitsOverride && "found named 0-width bitfield");
822 llvm::DIType fieldType
823 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
824 C.getLocation(), Field->getAccess(),
825 layout.getFieldOffset(fieldno), VUnit, RecordTy);
826 elements.push_back(fieldType);
828 // TODO: Need to handle 'this' in some way by probably renaming the
829 // this of the lambda class and having a field member of 'this' or
830 // by using AT_object_pointer for the function and having that be
831 // used as 'this' for semantic references.
832 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
833 FieldDecl *f = *Field;
834 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
835 QualType type = f->getType();
836 llvm::DIType fieldType
837 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
838 layout.getFieldOffset(fieldno), VUnit, RecordTy);
840 elements.push_back(fieldType);
845 /// CollectRecordStaticField - Helper for CollectRecordFields.
847 CollectRecordStaticField(const VarDecl *Var,
848 SmallVectorImpl<llvm::Value *> &elements,
849 llvm::DIType RecordTy) {
850 // Create the descriptor for the static variable, with or without
851 // constant initializers.
852 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
853 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
855 // Do not describe enums as static members.
856 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
859 unsigned LineNumber = getLineNumber(Var->getLocation());
860 StringRef VName = Var->getName();
861 llvm::Constant *C = NULL;
862 if (Var->getInit()) {
863 const APValue *Value = Var->evaluateValue();
866 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
867 if (Value->isFloat())
868 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
873 AccessSpecifier Access = Var->getAccess();
874 if (Access == clang::AS_private)
875 Flags |= llvm::DIDescriptor::FlagPrivate;
876 else if (Access == clang::AS_protected)
877 Flags |= llvm::DIDescriptor::FlagProtected;
879 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
880 LineNumber, VTy, Flags, C);
881 elements.push_back(GV);
882 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
885 /// CollectRecordNormalField - Helper for CollectRecordFields.
887 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
889 SmallVectorImpl<llvm::Value *> &elements,
890 llvm::DIType RecordTy) {
891 StringRef name = field->getName();
892 QualType type = field->getType();
894 // Ignore unnamed fields unless they're anonymous structs/unions.
895 if (name.empty() && !type->isRecordType())
898 uint64_t SizeInBitsOverride = 0;
899 if (field->isBitField()) {
900 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
901 assert(SizeInBitsOverride && "found named 0-width bitfield");
904 llvm::DIType fieldType
905 = createFieldType(name, type, SizeInBitsOverride,
906 field->getLocation(), field->getAccess(),
907 OffsetInBits, tunit, RecordTy);
909 elements.push_back(fieldType);
912 /// CollectRecordFields - A helper function to collect debug info for
913 /// record fields. This is used while creating debug info entry for a Record.
915 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
916 SmallVectorImpl<llvm::Value *> &elements,
917 llvm::DIType RecordTy) {
918 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
920 if (CXXDecl && CXXDecl->isLambda())
921 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
923 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
925 // Field number for non-static fields.
926 unsigned fieldNo = 0;
928 // Bookkeeping for an ms struct, which ignores certain fields.
929 bool IsMsStruct = record->isMsStruct(CGM.getContext());
930 const FieldDecl *LastFD = 0;
932 // Static and non-static members should appear in the same order as
933 // the corresponding declarations in the source program.
934 for (RecordDecl::decl_iterator I = record->decls_begin(),
935 E = record->decls_end(); I != E; ++I)
936 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
937 CollectRecordStaticField(V, elements, RecordTy);
938 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
940 // Zero-length bitfields following non-bitfield members are
941 // completely ignored; we don't even count them.
942 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
946 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
947 tunit, elements, RecordTy);
949 // Bump field number for next field.
955 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
956 /// function type is not updated to include implicit "this" pointer. Use this
957 /// routine to get a method type which includes "this" pointer.
959 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
961 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
962 if (Method->isStatic())
963 return getOrCreateType(QualType(Func, 0), Unit);
964 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
968 llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
969 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
970 // Add "this" pointer.
971 llvm::DIArray Args = llvm::DICompositeType(
972 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
973 assert (Args.getNumElements() && "Invalid number of arguments!");
975 SmallVector<llvm::Value *, 16> Elts;
977 // First element is always return type. For 'void' functions it is NULL.
978 Elts.push_back(Args.getElement(0));
980 // "this" pointer is always first argument.
981 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
982 if (isa<ClassTemplateSpecializationDecl>(RD)) {
983 // Create pointer type directly in this case.
984 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
985 QualType PointeeTy = ThisPtrTy->getPointeeType();
986 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
987 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
988 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
989 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
990 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
991 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
992 // TODO: This and the artificial type below are misleading, the
993 // types aren't artificial the argument is, but the current
994 // metadata doesn't represent that.
995 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
996 Elts.push_back(ThisPtrType);
998 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
999 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1000 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1001 Elts.push_back(ThisPtrType);
1004 // Copy rest of the arguments.
1005 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1006 Elts.push_back(Args.getElement(i));
1008 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1010 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1013 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1014 /// inside a function.
1015 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1016 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1017 return isFunctionLocalClass(NRD);
1018 if (isa<FunctionDecl>(RD->getDeclContext()))
1023 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1024 /// a single member function GlobalDecl.
1026 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1028 llvm::DIType RecordTy) {
1030 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1032 StringRef MethodName = getFunctionName(Method);
1033 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1035 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1036 // make sense to give a single ctor/dtor a linkage name.
1037 StringRef MethodLinkageName;
1038 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1039 MethodLinkageName = CGM.getMangledName(Method);
1041 // Get the location for the method.
1042 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1043 unsigned MethodLine = getLineNumber(Method->getLocation());
1045 // Collect virtual method info.
1046 llvm::DIType ContainingType;
1047 unsigned Virtuality = 0;
1048 unsigned VIndex = 0;
1050 if (Method->isVirtual()) {
1051 if (Method->isPure())
1052 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1054 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1056 // It doesn't make sense to give a virtual destructor a vtable index,
1057 // since a single destructor has two entries in the vtable.
1058 if (!isa<CXXDestructorDecl>(Method))
1059 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1060 ContainingType = RecordTy;
1064 if (Method->isImplicit())
1065 Flags |= llvm::DIDescriptor::FlagArtificial;
1066 AccessSpecifier Access = Method->getAccess();
1067 if (Access == clang::AS_private)
1068 Flags |= llvm::DIDescriptor::FlagPrivate;
1069 else if (Access == clang::AS_protected)
1070 Flags |= llvm::DIDescriptor::FlagProtected;
1071 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1072 if (CXXC->isExplicit())
1073 Flags |= llvm::DIDescriptor::FlagExplicit;
1074 } else if (const CXXConversionDecl *CXXC =
1075 dyn_cast<CXXConversionDecl>(Method)) {
1076 if (CXXC->isExplicit())
1077 Flags |= llvm::DIDescriptor::FlagExplicit;
1079 if (Method->hasPrototype())
1080 Flags |= llvm::DIDescriptor::FlagPrototyped;
1082 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1083 llvm::DISubprogram SP =
1084 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1085 MethodDefUnit, MethodLine,
1086 MethodTy, /*isLocalToUnit=*/false,
1087 /* isDefinition=*/ false,
1088 Virtuality, VIndex, ContainingType,
1089 Flags, CGM.getLangOpts().Optimize, NULL,
1092 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1097 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1098 /// C++ member functions. This is used while creating debug info entry for
1101 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1102 SmallVectorImpl<llvm::Value *> &EltTys,
1103 llvm::DIType RecordTy) {
1105 // Since we want more than just the individual member decls if we
1106 // have templated functions iterate over every declaration to gather
1108 for(DeclContext::decl_iterator I = RD->decls_begin(),
1109 E = RD->decls_end(); I != E; ++I) {
1111 if (D->isImplicit() && !D->isUsed())
1114 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1115 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1116 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1117 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1118 SE = FTD->spec_end(); SI != SE; ++SI)
1119 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1124 /// CollectCXXFriends - A helper function to collect debug info for
1125 /// C++ base classes. This is used while creating debug info entry for
1128 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1129 SmallVectorImpl<llvm::Value *> &EltTys,
1130 llvm::DIType RecordTy) {
1131 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1132 BE = RD->friend_end(); BI != BE; ++BI) {
1133 if ((*BI)->isUnsupportedFriend())
1135 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1136 EltTys.push_back(DBuilder.createFriend(RecordTy,
1137 getOrCreateType(TInfo->getType(),
1142 /// CollectCXXBases - A helper function to collect debug info for
1143 /// C++ base classes. This is used while creating debug info entry for
1146 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1147 SmallVectorImpl<llvm::Value *> &EltTys,
1148 llvm::DIType RecordTy) {
1150 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1151 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1152 BE = RD->bases_end(); BI != BE; ++BI) {
1153 unsigned BFlags = 0;
1154 uint64_t BaseOffset;
1156 const CXXRecordDecl *Base =
1157 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1159 if (BI->isVirtual()) {
1160 // virtual base offset offset is -ve. The code generator emits dwarf
1161 // expression where it expects +ve number.
1163 0 - CGM.getVTableContext()
1164 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1165 BFlags = llvm::DIDescriptor::FlagVirtual;
1167 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1168 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1169 // BI->isVirtual() and bits when not.
1171 AccessSpecifier Access = BI->getAccessSpecifier();
1172 if (Access == clang::AS_private)
1173 BFlags |= llvm::DIDescriptor::FlagPrivate;
1174 else if (Access == clang::AS_protected)
1175 BFlags |= llvm::DIDescriptor::FlagProtected;
1178 DBuilder.createInheritance(RecordTy,
1179 getOrCreateType(BI->getType(), Unit),
1180 BaseOffset, BFlags);
1181 EltTys.push_back(DTy);
1185 /// CollectTemplateParams - A helper function to collect template parameters.
1186 llvm::DIArray CGDebugInfo::
1187 CollectTemplateParams(const TemplateParameterList *TPList,
1188 const TemplateArgumentList &TAList,
1189 llvm::DIFile Unit) {
1190 SmallVector<llvm::Value *, 16> TemplateParams;
1191 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1192 const TemplateArgument &TA = TAList[i];
1193 const NamedDecl *ND = TPList->getParam(i);
1194 if (TA.getKind() == TemplateArgument::Type) {
1195 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1196 llvm::DITemplateTypeParameter TTP =
1197 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1198 TemplateParams.push_back(TTP);
1199 } else if (TA.getKind() == TemplateArgument::Integral) {
1200 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1201 llvm::DITemplateValueParameter TVP =
1202 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1203 TA.getAsIntegral().getZExtValue());
1204 TemplateParams.push_back(TVP);
1207 return DBuilder.getOrCreateArray(TemplateParams);
1210 /// CollectFunctionTemplateParams - A helper function to collect debug
1211 /// info for function template parameters.
1212 llvm::DIArray CGDebugInfo::
1213 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1214 if (FD->getTemplatedKind() ==
1215 FunctionDecl::TK_FunctionTemplateSpecialization) {
1216 const TemplateParameterList *TList =
1217 FD->getTemplateSpecializationInfo()->getTemplate()
1218 ->getTemplateParameters();
1220 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1222 return llvm::DIArray();
1225 /// CollectCXXTemplateParams - A helper function to collect debug info for
1226 /// template parameters.
1227 llvm::DIArray CGDebugInfo::
1228 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1229 llvm::DIFile Unit) {
1230 llvm::PointerUnion<ClassTemplateDecl *,
1231 ClassTemplatePartialSpecializationDecl *>
1232 PU = TSpecial->getSpecializedTemplateOrPartial();
1234 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1235 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1236 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1237 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1238 return CollectTemplateParams(TPList, TAList, Unit);
1241 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1242 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1243 if (VTablePtrType.isValid())
1244 return VTablePtrType;
1246 ASTContext &Context = CGM.getContext();
1249 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1250 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1251 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1252 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1253 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1255 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1256 return VTablePtrType;
1259 /// getVTableName - Get vtable name for the given Class.
1260 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1261 // Construct gdb compatible name name.
1262 std::string Name = "_vptr$" + RD->getNameAsString();
1264 // Copy this name on the side and use its reference.
1265 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1266 memcpy(StrPtr, Name.data(), Name.length());
1267 return StringRef(StrPtr, Name.length());
1271 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1272 /// debug info entry in EltTys vector.
1274 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1275 SmallVectorImpl<llvm::Value *> &EltTys) {
1276 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1278 // If there is a primary base then it will hold vtable info.
1279 if (RL.getPrimaryBase())
1282 // If this class is not dynamic then there is not any vtable info to collect.
1283 if (!RD->isDynamicClass())
1286 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1288 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1289 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1290 getOrCreateVTablePtrType(Unit));
1291 EltTys.push_back(VPTR);
1294 /// getOrCreateRecordType - Emit record type's standalone debug info.
1295 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1296 SourceLocation Loc) {
1297 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1298 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1302 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1304 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1305 SourceLocation Loc) {
1306 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1307 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1308 RetainedTypes.push_back(D.getAsOpaquePtr());
1312 /// CreateType - get structure or union type.
1313 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1314 RecordDecl *RD = Ty->getDecl();
1316 // Get overall information about the record type for the debug info.
1317 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1319 // Records and classes and unions can all be recursive. To handle them, we
1320 // first generate a debug descriptor for the struct as a forward declaration.
1321 // Then (if it is a definition) we go through and get debug info for all of
1322 // its members. Finally, we create a descriptor for the complete type (which
1323 // may refer to the forward decl if the struct is recursive) and replace all
1324 // uses of the forward declaration with the final definition.
1326 llvm::DICompositeType FwdDecl(
1327 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1328 assert(FwdDecl.Verify() &&
1329 "The debug type of a RecordType should be a DICompositeType");
1331 if (FwdDecl.isForwardDecl())
1334 // Push the struct on region stack.
1335 LexicalBlockStack.push_back(&*FwdDecl);
1336 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1338 // Add this to the completed-type cache while we're completing it recursively.
1339 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1341 // Convert all the elements.
1342 SmallVector<llvm::Value *, 16> EltTys;
1344 // Note: The split of CXXDecl information here is intentional, the
1345 // gdb tests will depend on a certain ordering at printout. The debug
1346 // information offsets are still correct if we merge them all together
1348 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1350 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1351 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1354 // Collect data fields (including static variables and any initializers).
1355 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1356 llvm::DIArray TParamsArray;
1358 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1359 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1360 if (const ClassTemplateSpecializationDecl *TSpecial
1361 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1362 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1365 LexicalBlockStack.pop_back();
1366 RegionMap.erase(Ty->getDecl());
1368 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1369 FwdDecl.setTypeArray(Elements, TParamsArray);
1371 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1375 /// CreateType - get objective-c object type.
1376 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1377 llvm::DIFile Unit) {
1378 // Ignore protocols.
1379 return getOrCreateType(Ty->getBaseType(), Unit);
1382 /// CreateType - get objective-c interface type.
1383 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1384 llvm::DIFile Unit) {
1385 ObjCInterfaceDecl *ID = Ty->getDecl();
1387 return llvm::DIType();
1389 // Get overall information about the record type for the debug info.
1390 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1391 unsigned Line = getLineNumber(ID->getLocation());
1392 unsigned RuntimeLang = TheCU.getLanguage();
1394 // If this is just a forward declaration return a special forward-declaration
1395 // debug type since we won't be able to lay out the entire type.
1396 ObjCInterfaceDecl *Def = ID->getDefinition();
1398 llvm::DIType FwdDecl =
1399 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1400 ID->getName(), TheCU, DefUnit, Line,
1407 // Bit size, align and offset of the type.
1408 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1409 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1412 if (ID->getImplementation())
1413 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1415 llvm::DICompositeType RealDecl =
1416 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1417 Line, Size, Align, Flags,
1418 llvm::DIType(), llvm::DIArray(), RuntimeLang);
1420 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1421 // will find it and we're emitting the complete type.
1422 QualType QualTy = QualType(Ty, 0);
1423 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1424 // Push the struct on region stack.
1426 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1427 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1429 // Convert all the elements.
1430 SmallVector<llvm::Value *, 16> EltTys;
1432 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1434 llvm::DIType SClassTy =
1435 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1436 if (!SClassTy.isValid())
1437 return llvm::DIType();
1439 llvm::DIType InhTag =
1440 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1441 EltTys.push_back(InhTag);
1444 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1445 E = ID->prop_end(); I != E; ++I) {
1446 const ObjCPropertyDecl *PD = *I;
1447 SourceLocation Loc = PD->getLocation();
1448 llvm::DIFile PUnit = getOrCreateFile(Loc);
1449 unsigned PLine = getLineNumber(Loc);
1450 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1451 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1452 llvm::MDNode *PropertyNode =
1453 DBuilder.createObjCProperty(PD->getName(),
1455 (Getter && Getter->isImplicit()) ? "" :
1456 getSelectorName(PD->getGetterName()),
1457 (Setter && Setter->isImplicit()) ? "" :
1458 getSelectorName(PD->getSetterName()),
1459 PD->getPropertyAttributes(),
1460 getOrCreateType(PD->getType(), PUnit));
1461 EltTys.push_back(PropertyNode);
1464 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1465 unsigned FieldNo = 0;
1466 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1467 Field = Field->getNextIvar(), ++FieldNo) {
1468 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1469 if (!FieldTy.isValid())
1470 return llvm::DIType();
1472 StringRef FieldName = Field->getName();
1474 // Ignore unnamed fields.
1475 if (FieldName.empty())
1478 // Get the location for the field.
1479 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1480 unsigned FieldLine = getLineNumber(Field->getLocation());
1481 QualType FType = Field->getType();
1482 uint64_t FieldSize = 0;
1483 unsigned FieldAlign = 0;
1485 if (!FType->isIncompleteArrayType()) {
1487 // Bit size, align and offset of the type.
1488 FieldSize = Field->isBitField()
1489 ? Field->getBitWidthValue(CGM.getContext())
1490 : CGM.getContext().getTypeSize(FType);
1491 FieldAlign = CGM.getContext().getTypeAlign(FType);
1494 uint64_t FieldOffset;
1495 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1496 // We don't know the runtime offset of an ivar if we're using the
1497 // non-fragile ABI. For bitfields, use the bit offset into the first
1498 // byte of storage of the bitfield. For other fields, use zero.
1499 if (Field->isBitField()) {
1500 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1502 FieldOffset %= CGM.getContext().getCharWidth();
1507 FieldOffset = RL.getFieldOffset(FieldNo);
1511 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1512 Flags = llvm::DIDescriptor::FlagProtected;
1513 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1514 Flags = llvm::DIDescriptor::FlagPrivate;
1516 llvm::MDNode *PropertyNode = NULL;
1517 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1518 if (ObjCPropertyImplDecl *PImpD =
1519 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1520 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1521 SourceLocation Loc = PD->getLocation();
1522 llvm::DIFile PUnit = getOrCreateFile(Loc);
1523 unsigned PLine = getLineNumber(Loc);
1524 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1525 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1527 DBuilder.createObjCProperty(PD->getName(),
1529 (Getter && Getter->isImplicit()) ? "" :
1530 getSelectorName(PD->getGetterName()),
1531 (Setter && Setter->isImplicit()) ? "" :
1532 getSelectorName(PD->getSetterName()),
1533 PD->getPropertyAttributes(),
1534 getOrCreateType(PD->getType(), PUnit));
1538 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1539 FieldLine, FieldSize, FieldAlign,
1540 FieldOffset, Flags, FieldTy,
1542 EltTys.push_back(FieldTy);
1545 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1546 RealDecl.setTypeArray(Elements);
1548 // If the implementation is not yet set, we do not want to mark it
1549 // as complete. An implementation may declare additional
1550 // private ivars that we would miss otherwise.
1551 if (ID->getImplementation() == 0)
1552 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1554 LexicalBlockStack.pop_back();
1558 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1559 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1560 int64_t Count = Ty->getNumElements();
1562 // If number of elements are not known then this is an unbounded array.
1563 // Use Count == -1 to express such arrays.
1566 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1567 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1569 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1570 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1572 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1575 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1576 llvm::DIFile Unit) {
1580 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1581 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1584 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1585 } else if (Ty->isIncompleteArrayType()) {
1587 if (Ty->getElementType()->isIncompleteType())
1590 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1591 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1595 // Size and align of the whole array, not the element type.
1596 Size = CGM.getContext().getTypeSize(Ty);
1597 Align = CGM.getContext().getTypeAlign(Ty);
1600 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1601 // interior arrays, do we care? Why aren't nested arrays represented the
1602 // obvious/recursive way?
1603 SmallVector<llvm::Value *, 8> Subscripts;
1604 QualType EltTy(Ty, 0);
1605 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1606 // If the number of elements is known, then count is that number. Otherwise,
1607 // it's -1. This allows us to represent a subrange with an array of 0
1608 // elements, like this:
1613 int64_t Count = -1; // Count == -1 is an unbounded array.
1614 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1615 Count = CAT->getSize().getZExtValue();
1617 // FIXME: Verify this is right for VLAs.
1618 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1619 EltTy = Ty->getElementType();
1622 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1624 llvm::DIType DbgTy =
1625 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1630 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1631 llvm::DIFile Unit) {
1632 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1633 Ty, Ty->getPointeeType(), Unit);
1636 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1637 llvm::DIFile Unit) {
1638 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1639 Ty, Ty->getPointeeType(), Unit);
1642 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1644 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1645 if (!Ty->getPointeeType()->isFunctionType())
1646 return DBuilder.createMemberPointerType(
1647 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1648 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1649 CGM.getContext().getPointerType(
1650 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1651 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1655 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1657 // Ignore the atomic wrapping
1658 // FIXME: What is the correct representation?
1659 return getOrCreateType(Ty->getValueType(), U);
1662 /// CreateEnumType - get enumeration type.
1663 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1666 if (!ED->getTypeForDecl()->isIncompleteType()) {
1667 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1668 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1671 // If this is just a forward declaration, construct an appropriately
1672 // marked node and just return it.
1673 if (!ED->getDefinition()) {
1674 llvm::DIDescriptor EDContext;
1675 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1676 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1677 unsigned Line = getLineNumber(ED->getLocation());
1678 StringRef EDName = ED->getName();
1679 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1680 EDName, EDContext, DefUnit, Line, 0,
1684 // Create DIEnumerator elements for each enumerator.
1685 SmallVector<llvm::Value *, 16> Enumerators;
1686 ED = ED->getDefinition();
1687 for (EnumDecl::enumerator_iterator
1688 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1689 Enum != EnumEnd; ++Enum) {
1690 Enumerators.push_back(
1691 DBuilder.createEnumerator(Enum->getName(),
1692 Enum->getInitVal().getZExtValue()));
1695 // Return a CompositeType for the enum itself.
1696 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1698 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1699 unsigned Line = getLineNumber(ED->getLocation());
1700 llvm::DIDescriptor EnumContext =
1701 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1702 llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1703 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1704 llvm::DIType DbgTy =
1705 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1706 Size, Align, EltArray,
1711 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1714 Quals += T.getLocalQualifiers();
1716 switch (T->getTypeClass()) {
1718 return C.getQualifiedType(T.getTypePtr(), Quals);
1719 case Type::TemplateSpecialization:
1720 T = cast<TemplateSpecializationType>(T)->desugar();
1722 case Type::TypeOfExpr:
1723 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1726 T = cast<TypeOfType>(T)->getUnderlyingType();
1728 case Type::Decltype:
1729 T = cast<DecltypeType>(T)->getUnderlyingType();
1731 case Type::UnaryTransform:
1732 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1734 case Type::Attributed:
1735 T = cast<AttributedType>(T)->getEquivalentType();
1737 case Type::Elaborated:
1738 T = cast<ElaboratedType>(T)->getNamedType();
1741 T = cast<ParenType>(T)->getInnerType();
1743 case Type::SubstTemplateTypeParm:
1744 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1747 T = cast<AutoType>(T)->getDeducedType();
1751 assert(T != LastT && "Type unwrapping failed to unwrap!");
1756 /// getType - Get the type from the cache or return null type if it doesn't exist.
1757 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1759 // Unwrap the type as needed for debug information.
1760 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1762 // Check for existing entry.
1763 if (Ty->getTypeClass() == Type::ObjCInterface) {
1764 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1766 return llvm::DIType(cast<llvm::MDNode>(V));
1767 else return llvm::DIType();
1770 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1771 TypeCache.find(Ty.getAsOpaquePtr());
1772 if (it != TypeCache.end()) {
1773 // Verify that the debug info still exists.
1774 if (llvm::Value *V = it->second)
1775 return llvm::DIType(cast<llvm::MDNode>(V));
1778 return llvm::DIType();
1781 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1783 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1785 // Unwrap the type as needed for debug information.
1786 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1788 // Check for existing entry.
1790 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1791 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1792 if (it != CompletedTypeCache.end())
1795 V = getCachedInterfaceTypeOrNull(Ty);
1798 // Verify that any cached debug info still exists.
1800 return llvm::DIType(cast<llvm::MDNode>(V));
1802 return llvm::DIType();
1805 /// getCachedInterfaceTypeOrNull - Get the type from the interface
1806 /// cache, unless it needs to regenerated. Otherwise return null.
1807 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1808 // Is there a cached interface that hasn't changed?
1809 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1810 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1812 if (it1 != ObjCInterfaceCache.end())
1813 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1814 if (Checksum(Decl) == it1->second.second)
1815 // Return cached forward declaration.
1816 return it1->second.first;
1821 /// getOrCreateType - Get the type from the cache or create a new
1822 /// one if necessary.
1823 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1825 return llvm::DIType();
1827 // Unwrap the type as needed for debug information.
1828 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1830 llvm::DIType T = getCompletedTypeOrNull(Ty);
1835 // Otherwise create the type.
1836 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1837 void* TyPtr = Ty.getAsOpaquePtr();
1839 // And update the type cache.
1840 TypeCache[TyPtr] = Res;
1842 llvm::DIType TC = getTypeOrNull(Ty);
1843 if (TC.Verify() && TC.isForwardDecl())
1844 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1845 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1846 // Interface types may have elements added to them by a
1847 // subsequent implementation or extension, so we keep them in
1848 // the ObjCInterfaceCache together with a checksum. Instead of
1849 // the (possibly) incomplete interace type, we return a forward
1850 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1851 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1852 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1853 if (it != ObjCInterfaceCache.end())
1854 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1856 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1857 Decl->getName(), TheCU, Unit,
1858 getLineNumber(Decl->getLocation()),
1859 TheCU.getLanguage());
1860 // Store the forward declaration in the cache.
1861 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1863 // Register the type for replacement in finalize().
1864 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1868 if (!Res.isForwardDecl())
1869 CompletedTypeCache[TyPtr] = Res;
1874 /// Currently the checksum merely consists of the number of ivars.
1875 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
1877 unsigned IvarNo = 0;
1878 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1879 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1883 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1884 switch (Ty->getTypeClass()) {
1885 case Type::ObjCObjectPointer:
1886 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1887 case Type::ObjCInterface:
1888 return cast<ObjCInterfaceType>(Ty)->getDecl();
1894 /// CreateTypeNode - Create a new debug type node.
1895 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1896 // Handle qualifiers, which recursively handles what they refer to.
1897 if (Ty.hasLocalQualifiers())
1898 return CreateQualifiedType(Ty, Unit);
1900 const char *Diag = 0;
1902 // Work out details of type.
1903 switch (Ty->getTypeClass()) {
1904 #define TYPE(Class, Base)
1905 #define ABSTRACT_TYPE(Class, Base)
1906 #define NON_CANONICAL_TYPE(Class, Base)
1907 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1908 #include "clang/AST/TypeNodes.def"
1909 llvm_unreachable("Dependent types cannot show up in debug information");
1911 case Type::ExtVector:
1913 return CreateType(cast<VectorType>(Ty), Unit);
1914 case Type::ObjCObjectPointer:
1915 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1916 case Type::ObjCObject:
1917 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1918 case Type::ObjCInterface:
1919 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1921 return CreateType(cast<BuiltinType>(Ty));
1923 return CreateType(cast<ComplexType>(Ty));
1925 return CreateType(cast<PointerType>(Ty), Unit);
1926 case Type::BlockPointer:
1927 return CreateType(cast<BlockPointerType>(Ty), Unit);
1929 return CreateType(cast<TypedefType>(Ty), Unit);
1931 return CreateType(cast<RecordType>(Ty));
1933 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1934 case Type::FunctionProto:
1935 case Type::FunctionNoProto:
1936 return CreateType(cast<FunctionType>(Ty), Unit);
1937 case Type::ConstantArray:
1938 case Type::VariableArray:
1939 case Type::IncompleteArray:
1940 return CreateType(cast<ArrayType>(Ty), Unit);
1942 case Type::LValueReference:
1943 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1944 case Type::RValueReference:
1945 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1947 case Type::MemberPointer:
1948 return CreateType(cast<MemberPointerType>(Ty), Unit);
1951 return CreateType(cast<AtomicType>(Ty), Unit);
1953 case Type::Attributed:
1954 case Type::TemplateSpecialization:
1955 case Type::Elaborated:
1957 case Type::SubstTemplateTypeParm:
1958 case Type::TypeOfExpr:
1960 case Type::Decltype:
1961 case Type::UnaryTransform:
1963 llvm_unreachable("type should have been unwrapped!");
1966 assert(Diag && "Fall through without a diagnostic?");
1967 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1968 "debug information for %0 is not yet supported");
1969 CGM.getDiags().Report(DiagID)
1971 return llvm::DIType();
1974 /// getOrCreateLimitedType - Get the type from the cache or create a new
1975 /// limited type if necessary.
1976 llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1977 llvm::DIFile Unit) {
1979 return llvm::DIType();
1981 // Unwrap the type as needed for debug information.
1982 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1984 llvm::DIType T = getTypeOrNull(Ty);
1986 // We may have cached a forward decl when we could have created
1987 // a non-forward decl. Go ahead and create a non-forward decl
1989 if (T.Verify() && !T.isForwardDecl()) return T;
1991 // Otherwise create the type.
1992 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1994 if (T.Verify() && T.isForwardDecl())
1995 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1996 static_cast<llvm::Value*>(T)));
1998 // And update the type cache.
1999 TypeCache[Ty.getAsOpaquePtr()] = Res;
2003 // TODO: Currently used for context chains when limiting debug info.
2004 llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2005 RecordDecl *RD = Ty->getDecl();
2007 // Get overall information about the record type for the debug info.
2008 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2009 unsigned Line = getLineNumber(RD->getLocation());
2010 StringRef RDName = getClassName(RD);
2012 llvm::DIDescriptor RDContext;
2013 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2014 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2016 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2018 // If this is just a forward declaration, construct an appropriately
2019 // marked node and just return it.
2020 if (!RD->getDefinition())
2021 return createRecordFwdDecl(RD, RDContext);
2023 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2024 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2025 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
2026 llvm::DICompositeType RealDecl;
2029 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2030 Size, Align, 0, llvm::DIArray());
2031 else if (RD->isClass()) {
2032 // FIXME: This could be a struct type giving a default visibility different
2033 // than C++ class type, but needs llvm metadata changes first.
2034 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2035 Size, Align, 0, 0, llvm::DIType(),
2036 llvm::DIArray(), llvm::DIType(),
2039 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2040 Size, Align, 0, llvm::DIType(), llvm::DIArray());
2042 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2043 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2046 // A class's primary base or the class itself contains the vtable.
2047 llvm::DICompositeType ContainingType;
2048 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2049 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2050 // Seek non virtual primary base root.
2052 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2053 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2054 if (PBT && !BRL.isPrimaryBaseVirtual())
2059 ContainingType = llvm::DICompositeType(
2060 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2061 } else if (CXXDecl->isDynamicClass())
2062 ContainingType = RealDecl;
2064 RealDecl.setContainingType(ContainingType);
2066 return llvm::DIType(RealDecl);
2069 /// CreateLimitedTypeNode - Create a new debug type node, but only forward
2070 /// declare composite types that haven't been processed yet.
2071 llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2073 // Work out details of type.
2074 switch (Ty->getTypeClass()) {
2075 #define TYPE(Class, Base)
2076 #define ABSTRACT_TYPE(Class, Base)
2077 #define NON_CANONICAL_TYPE(Class, Base)
2078 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2079 #include "clang/AST/TypeNodes.def"
2080 llvm_unreachable("Dependent types cannot show up in debug information");
2083 return CreateLimitedType(cast<RecordType>(Ty));
2085 return CreateTypeNode(Ty, Unit);
2089 /// CreateMemberType - Create new member and increase Offset by FType's size.
2090 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2093 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2094 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2095 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2096 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2097 FieldSize, FieldAlign,
2098 *Offset, 0, FieldTy);
2099 *Offset += FieldSize;
2103 /// getFunctionDeclaration - Return debug info descriptor to describe method
2104 /// declaration for the given method definition.
2105 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2106 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2107 if (!FD) return llvm::DISubprogram();
2110 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2112 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2113 MI = SPCache.find(FD->getCanonicalDecl());
2114 if (MI != SPCache.end()) {
2115 llvm::Value *V = MI->second;
2116 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2117 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2121 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2122 E = FD->redecls_end(); I != E; ++I) {
2123 const FunctionDecl *NextFD = *I;
2124 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2125 MI = SPCache.find(NextFD->getCanonicalDecl());
2126 if (MI != SPCache.end()) {
2127 llvm::Value *V = MI->second;
2128 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2129 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2133 return llvm::DISubprogram();
2136 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2137 // implicit parameter "this".
2138 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2142 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2143 return getOrCreateMethodType(Method, F);
2144 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2145 // Add "self" and "_cmd"
2146 SmallVector<llvm::Value *, 16> Elts;
2148 // First element is always return type. For 'void' functions it is NULL.
2149 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2150 // "self" pointer is always first argument.
2151 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2152 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2153 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2154 // "_cmd" pointer is always second argument.
2155 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2156 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2157 // Get rest of the arguments.
2158 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2159 PE = OMethod->param_end(); PI != PE; ++PI)
2160 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2162 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2163 return DBuilder.createSubroutineType(F, EltTypeArray);
2165 return getOrCreateType(FnType, F);
2168 /// EmitFunctionStart - Constructs the debug code for entering a function.
2169 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2171 CGBuilderTy &Builder) {
2174 StringRef LinkageName;
2176 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2178 const Decl *D = GD.getDecl();
2179 // Function may lack declaration in source code if it is created by Clang
2180 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2181 bool HasDecl = (D != 0);
2182 // Use the location of the declaration.
2185 Loc = D->getLocation();
2188 llvm::DIFile Unit = getOrCreateFile(Loc);
2189 llvm::DIDescriptor FDContext(Unit);
2190 llvm::DIArray TParamsArray;
2192 // Use llvm function name.
2193 Name = Fn->getName();
2194 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2195 // If there is a DISubprogram for this function available then use it.
2196 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2197 FI = SPCache.find(FD->getCanonicalDecl());
2198 if (FI != SPCache.end()) {
2199 llvm::Value *V = FI->second;
2200 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2201 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2202 llvm::MDNode *SPN = SP;
2203 LexicalBlockStack.push_back(SPN);
2204 RegionMap[D] = llvm::WeakVH(SP);
2208 Name = getFunctionName(FD);
2209 // Use mangled name as linkage name for C/C++ functions.
2210 if (FD->hasPrototype()) {
2211 LinkageName = CGM.getMangledName(GD);
2212 Flags |= llvm::DIDescriptor::FlagPrototyped;
2214 // No need to replicate the linkage name if it isn't different from the
2215 // subprogram name, no need to have it at all unless coverage is enabled or
2216 // debug is set to more than just line tables.
2217 if (LinkageName == Name ||
2218 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2219 !CGM.getCodeGenOpts().EmitGcovNotes &&
2220 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
2221 LinkageName = StringRef();
2223 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2224 if (const NamespaceDecl *NSDecl =
2225 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2226 FDContext = getOrCreateNameSpace(NSDecl);
2227 else if (const RecordDecl *RDecl =
2228 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2229 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2231 // Collect template parameters.
2232 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2234 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2235 Name = getObjCMethodName(OMD);
2236 Flags |= llvm::DIDescriptor::FlagPrototyped;
2238 // Use llvm function name.
2239 Name = Fn->getName();
2240 Flags |= llvm::DIDescriptor::FlagPrototyped;
2242 if (!Name.empty() && Name[0] == '\01')
2243 Name = Name.substr(1);
2245 unsigned LineNo = getLineNumber(Loc);
2246 if (!HasDecl || D->isImplicit())
2247 Flags |= llvm::DIDescriptor::FlagArtificial;
2249 llvm::DIType DIFnType;
2250 llvm::DISubprogram SPDecl;
2252 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2253 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2254 SPDecl = getFunctionDeclaration(D);
2256 // Create fake but valid subroutine type. Otherwise
2257 // llvm::DISubprogram::Verify() would return false, and
2258 // subprogram DIE will miss DW_AT_decl_file and
2259 // DW_AT_decl_line fields.
2260 SmallVector<llvm::Value*, 16> Elts;
2261 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2262 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2264 llvm::DISubprogram SP;
2265 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2267 Fn->hasInternalLinkage(), true/*definition*/,
2268 getLineNumber(CurLoc), Flags,
2269 CGM.getLangOpts().Optimize,
2270 Fn, TParamsArray, SPDecl);
2272 // Push function on region stack.
2273 llvm::MDNode *SPN = SP;
2274 LexicalBlockStack.push_back(SPN);
2276 RegionMap[D] = llvm::WeakVH(SP);
2279 /// EmitLocation - Emit metadata to indicate a change in line/column
2280 /// information in the source file.
2281 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2282 bool ForceColumnInfo) {
2284 // Update our current location
2287 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2289 // Don't bother if things are the same as last time.
2290 SourceManager &SM = CGM.getContext().getSourceManager();
2291 if (CurLoc == PrevLoc ||
2292 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2293 // New Builder may not be in sync with CGDebugInfo.
2294 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2295 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2296 LexicalBlockStack.back())
2299 // Update last state.
2302 llvm::MDNode *Scope = LexicalBlockStack.back();
2303 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2304 (getLineNumber(CurLoc),
2305 getColumnNumber(CurLoc, ForceColumnInfo),
2309 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2311 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2312 llvm::DIDescriptor D =
2313 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2314 llvm::DIDescriptor() :
2315 llvm::DIDescriptor(LexicalBlockStack.back()),
2316 getOrCreateFile(CurLoc),
2317 getLineNumber(CurLoc),
2318 getColumnNumber(CurLoc));
2319 llvm::MDNode *DN = D;
2320 LexicalBlockStack.push_back(DN);
2323 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2324 /// region - beginning of a DW_TAG_lexical_block.
2325 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2326 // Set our current location.
2329 // Create a new lexical block and push it on the stack.
2330 CreateLexicalBlock(Loc);
2332 // Emit a line table change for the current location inside the new scope.
2333 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2334 getColumnNumber(Loc),
2335 LexicalBlockStack.back()));
2338 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2339 /// region - end of a DW_TAG_lexical_block.
2340 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2341 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2343 // Provide an entry in the line table for the end of the block.
2344 EmitLocation(Builder, Loc);
2346 LexicalBlockStack.pop_back();
2349 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2350 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2351 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2352 unsigned RCount = FnBeginRegionCount.back();
2353 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2355 // Pop all regions for this function.
2356 while (LexicalBlockStack.size() != RCount)
2357 EmitLexicalBlockEnd(Builder, CurLoc);
2358 FnBeginRegionCount.pop_back();
2361 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2362 // See BuildByRefType.
2363 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2364 uint64_t *XOffset) {
2366 SmallVector<llvm::Value *, 5> EltTys;
2368 uint64_t FieldSize, FieldOffset;
2369 unsigned FieldAlign;
2371 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2372 QualType Type = VD->getType();
2375 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2376 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2377 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2378 FType = CGM.getContext().IntTy;
2379 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2380 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2382 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2383 if (HasCopyAndDispose) {
2384 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2385 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2387 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2390 bool HasByrefExtendedLayout;
2391 Qualifiers::ObjCLifetime Lifetime;
2392 if (CGM.getContext().getByrefLifetime(Type,
2393 Lifetime, HasByrefExtendedLayout)
2394 && HasByrefExtendedLayout)
2395 EltTys.push_back(CreateMemberType(Unit, FType,
2396 "__byref_variable_layout",
2399 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2400 if (Align > CGM.getContext().toCharUnitsFromBits(
2401 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2402 CharUnits FieldOffsetInBytes
2403 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2404 CharUnits AlignedOffsetInBytes
2405 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2406 CharUnits NumPaddingBytes
2407 = AlignedOffsetInBytes - FieldOffsetInBytes;
2409 if (NumPaddingBytes.isPositive()) {
2410 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2411 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2412 pad, ArrayType::Normal, 0);
2413 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2418 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2419 FieldSize = CGM.getContext().getTypeSize(FType);
2420 FieldAlign = CGM.getContext().toBits(Align);
2422 *XOffset = FieldOffset;
2423 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2424 0, FieldSize, FieldAlign,
2425 FieldOffset, 0, FieldTy);
2426 EltTys.push_back(FieldTy);
2427 FieldOffset += FieldSize;
2429 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2431 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2433 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2434 llvm::DIType(), Elements);
2437 /// EmitDeclare - Emit local variable declaration debug info.
2438 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2439 llvm::Value *Storage,
2440 unsigned ArgNo, CGBuilderTy &Builder) {
2441 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2442 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2444 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2446 uint64_t XOffset = 0;
2447 if (VD->hasAttr<BlocksAttr>())
2448 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2450 Ty = getOrCreateType(VD->getType(), Unit);
2452 // If there is no debug info for this type then do not emit debug info
2453 // for this variable.
2457 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2458 // If Storage is an aggregate returned as 'sret' then let debugger know
2460 if (Arg->hasStructRetAttr())
2461 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2462 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2463 // If an aggregate variable has non trivial destructor or non trivial copy
2464 // constructor than it is pass indirectly. Let debug info know about this
2465 // by using reference of the aggregate type as a argument type.
2466 if (Record->hasNonTrivialCopyConstructor() ||
2467 !Record->hasTrivialDestructor())
2468 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2472 // Get location information.
2473 unsigned Line = getLineNumber(VD->getLocation());
2474 unsigned Column = getColumnNumber(VD->getLocation());
2476 if (VD->isImplicit())
2477 Flags |= llvm::DIDescriptor::FlagArtificial;
2478 // If this is the first argument and it is implicit then
2479 // give it an object pointer flag.
2480 // FIXME: There has to be a better way to do this, but for static
2481 // functions there won't be an implicit param at arg1 and
2482 // otherwise it is 'self' or 'this'.
2483 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2484 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2486 llvm::MDNode *Scope = LexicalBlockStack.back();
2488 StringRef Name = VD->getName();
2489 if (!Name.empty()) {
2490 if (VD->hasAttr<BlocksAttr>()) {
2491 CharUnits offset = CharUnits::fromQuantity(32);
2492 SmallVector<llvm::Value *, 9> addr;
2493 llvm::Type *Int64Ty = CGM.Int64Ty;
2494 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2495 // offset of __forwarding field
2496 offset = CGM.getContext().toCharUnitsFromBits(
2497 CGM.getContext().getTargetInfo().getPointerWidth(0));
2498 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2499 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2500 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2501 // offset of x field
2502 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2503 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2505 // Create the descriptor for the variable.
2506 llvm::DIVariable D =
2507 DBuilder.createComplexVariable(Tag,
2508 llvm::DIDescriptor(Scope),
2509 VD->getName(), Unit, Line, Ty,
2512 // Insert an llvm.dbg.declare into the current block.
2513 llvm::Instruction *Call =
2514 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2515 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2517 } else if (isa<VariableArrayType>(VD->getType())) {
2518 // These are "complex" variables in that they need an op_deref.
2519 // Create the descriptor for the variable.
2520 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2521 llvm::DIBuilder::OpDeref);
2522 llvm::DIVariable D =
2523 DBuilder.createComplexVariable(Tag,
2524 llvm::DIDescriptor(Scope),
2525 Name, Unit, Line, Ty,
2528 // Insert an llvm.dbg.declare into the current block.
2529 llvm::Instruction *Call =
2530 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2531 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2534 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2535 // If VD is an anonymous union then Storage represents value for
2536 // all union fields.
2537 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2538 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2539 for (RecordDecl::field_iterator I = RD->field_begin(),
2540 E = RD->field_end();
2542 FieldDecl *Field = *I;
2543 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2544 StringRef FieldName = Field->getName();
2546 // Ignore unnamed fields. Do not ignore unnamed records.
2547 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2550 // Use VarDecl's Tag, Scope and Line number.
2551 llvm::DIVariable D =
2552 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2553 FieldName, Unit, Line, FieldTy,
2554 CGM.getLangOpts().Optimize, Flags,
2557 // Insert an llvm.dbg.declare into the current block.
2558 llvm::Instruction *Call =
2559 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2560 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2566 // Create the descriptor for the variable.
2567 llvm::DIVariable D =
2568 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2569 Name, Unit, Line, Ty,
2570 CGM.getLangOpts().Optimize, Flags, ArgNo);
2572 // Insert an llvm.dbg.declare into the current block.
2573 llvm::Instruction *Call =
2574 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2575 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2578 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2579 llvm::Value *Storage,
2580 CGBuilderTy &Builder) {
2581 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2582 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2585 /// Look up the completed type for a self pointer in the TypeCache and
2586 /// create a copy of it with the ObjectPointer and Artificial flags
2587 /// set. If the type is not cached, a new one is created. This should
2588 /// never happen though, since creating a type for the implicit self
2589 /// argument implies that we already parsed the interface definition
2590 /// and the ivar declarations in the implementation.
2591 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2592 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2593 if (CachedTy.Verify()) Ty = CachedTy;
2594 else DEBUG(llvm::dbgs() << "No cached type for self.");
2595 return DBuilder.createObjectPointerType(Ty);
2598 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2599 llvm::Value *Storage,
2600 CGBuilderTy &Builder,
2601 const CGBlockInfo &blockInfo) {
2602 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2603 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2605 if (Builder.GetInsertBlock() == 0)
2608 bool isByRef = VD->hasAttr<BlocksAttr>();
2610 uint64_t XOffset = 0;
2611 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2614 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2616 Ty = getOrCreateType(VD->getType(), Unit);
2618 // Self is passed along as an implicit non-arg variable in a
2619 // block. Mark it as the object pointer.
2620 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2621 Ty = CreateSelfType(VD->getType(), Ty);
2623 // Get location information.
2624 unsigned Line = getLineNumber(VD->getLocation());
2625 unsigned Column = getColumnNumber(VD->getLocation());
2627 const llvm::DataLayout &target = CGM.getDataLayout();
2629 CharUnits offset = CharUnits::fromQuantity(
2630 target.getStructLayout(blockInfo.StructureType)
2631 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2633 SmallVector<llvm::Value *, 9> addr;
2634 llvm::Type *Int64Ty = CGM.Int64Ty;
2635 if (isa<llvm::AllocaInst>(Storage))
2636 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2637 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2638 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2640 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2641 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2642 // offset of __forwarding field
2643 offset = CGM.getContext()
2644 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2645 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2646 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2647 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2648 // offset of x field
2649 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2650 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2653 // Create the descriptor for the variable.
2654 llvm::DIVariable D =
2655 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2656 llvm::DIDescriptor(LexicalBlockStack.back()),
2657 VD->getName(), Unit, Line, Ty, addr);
2659 // Insert an llvm.dbg.declare into the current block.
2660 llvm::Instruction *Call =
2661 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2662 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2663 LexicalBlockStack.back()));
2666 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2667 /// variable declaration.
2668 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2670 CGBuilderTy &Builder) {
2671 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2672 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2676 struct BlockLayoutChunk {
2677 uint64_t OffsetInBits;
2678 const BlockDecl::Capture *Capture;
2680 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2681 return l.OffsetInBits < r.OffsetInBits;
2685 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2687 llvm::Value *LocalAddr,
2688 CGBuilderTy &Builder) {
2689 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2690 ASTContext &C = CGM.getContext();
2691 const BlockDecl *blockDecl = block.getBlockDecl();
2693 // Collect some general information about the block's location.
2694 SourceLocation loc = blockDecl->getCaretLocation();
2695 llvm::DIFile tunit = getOrCreateFile(loc);
2696 unsigned line = getLineNumber(loc);
2697 unsigned column = getColumnNumber(loc);
2699 // Build the debug-info type for the block literal.
2700 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2702 const llvm::StructLayout *blockLayout =
2703 CGM.getDataLayout().getStructLayout(block.StructureType);
2705 SmallVector<llvm::Value*, 16> fields;
2706 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2707 blockLayout->getElementOffsetInBits(0),
2709 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2710 blockLayout->getElementOffsetInBits(1),
2712 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2713 blockLayout->getElementOffsetInBits(2),
2715 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2716 blockLayout->getElementOffsetInBits(3),
2718 fields.push_back(createFieldType("__descriptor",
2719 C.getPointerType(block.NeedsCopyDispose ?
2720 C.getBlockDescriptorExtendedType() :
2721 C.getBlockDescriptorType()),
2723 blockLayout->getElementOffsetInBits(4),
2726 // We want to sort the captures by offset, not because DWARF
2727 // requires this, but because we're paranoid about debuggers.
2728 SmallVector<BlockLayoutChunk, 8> chunks;
2731 if (blockDecl->capturesCXXThis()) {
2732 BlockLayoutChunk chunk;
2733 chunk.OffsetInBits =
2734 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2736 chunks.push_back(chunk);
2739 // Variable captures.
2740 for (BlockDecl::capture_const_iterator
2741 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2743 const BlockDecl::Capture &capture = *i;
2744 const VarDecl *variable = capture.getVariable();
2745 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2747 // Ignore constant captures.
2748 if (captureInfo.isConstant())
2751 BlockLayoutChunk chunk;
2752 chunk.OffsetInBits =
2753 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2754 chunk.Capture = &capture;
2755 chunks.push_back(chunk);
2759 llvm::array_pod_sort(chunks.begin(), chunks.end());
2761 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2762 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2763 uint64_t offsetInBits = i->OffsetInBits;
2764 const BlockDecl::Capture *capture = i->Capture;
2766 // If we have a null capture, this must be the C++ 'this' capture.
2768 const CXXMethodDecl *method =
2769 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2770 QualType type = method->getThisType(C);
2772 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2773 offsetInBits, tunit, tunit));
2777 const VarDecl *variable = capture->getVariable();
2778 StringRef name = variable->getName();
2780 llvm::DIType fieldType;
2781 if (capture->isByRef()) {
2782 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2784 // FIXME: this creates a second copy of this type!
2786 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2787 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2788 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2789 ptrInfo.first, ptrInfo.second,
2790 offsetInBits, 0, fieldType);
2792 fieldType = createFieldType(name, variable->getType(), 0,
2793 loc, AS_public, offsetInBits, tunit, tunit);
2795 fields.push_back(fieldType);
2798 SmallString<36> typeName;
2799 llvm::raw_svector_ostream(typeName)
2800 << "__block_literal_" << CGM.getUniqueBlockCount();
2802 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2805 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2806 CGM.getContext().toBits(block.BlockSize),
2807 CGM.getContext().toBits(block.BlockAlign),
2808 0, llvm::DIType(), fieldsArray);
2809 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2811 // Get overall information about the block.
2812 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2813 llvm::MDNode *scope = LexicalBlockStack.back();
2815 // Create the descriptor for the parameter.
2816 llvm::DIVariable debugVar =
2817 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2818 llvm::DIDescriptor(scope),
2819 Arg->getName(), tunit, line, type,
2820 CGM.getLangOpts().Optimize, flags,
2821 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2824 // Insert an llvm.dbg.value into the current block.
2825 llvm::Instruction *DbgVal =
2826 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
2827 Builder.GetInsertBlock());
2828 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2831 // Insert an llvm.dbg.declare into the current block.
2832 llvm::Instruction *DbgDecl =
2833 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2834 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2837 /// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2838 /// a static data member of a class, find its corresponding in-class
2840 llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2841 if (cast<VarDecl>(D)->isStaticDataMember()) {
2842 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2843 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2844 if (MI != StaticDataMemberCache.end())
2845 // Verify the info still exists.
2846 if (llvm::Value *V = MI->second)
2847 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2849 return llvm::DIDerivedType();
2852 /// EmitGlobalVariable - Emit information about a global variable.
2853 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2855 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2856 // Create global variable debug descriptor.
2857 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2858 unsigned LineNo = getLineNumber(D->getLocation());
2860 setLocation(D->getLocation());
2862 QualType T = D->getType();
2863 if (T->isIncompleteArrayType()) {
2865 // CodeGen turns int[] into int[1] so we'll do the same here.
2866 llvm::APInt ConstVal(32, 1);
2867 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2869 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2870 ArrayType::Normal, 0);
2872 StringRef DeclName = D->getName();
2873 StringRef LinkageName;
2874 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2875 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2876 LinkageName = Var->getName();
2877 if (LinkageName == DeclName)
2878 LinkageName = StringRef();
2879 llvm::DIDescriptor DContext =
2880 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2881 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2882 Unit, LineNo, getOrCreateType(T, Unit),
2883 Var->hasInternalLinkage(), Var,
2884 getStaticDataMemberDeclaration(D));
2887 /// EmitGlobalVariable - Emit information about an objective-c interface.
2888 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2889 ObjCInterfaceDecl *ID) {
2890 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2891 // Create global variable debug descriptor.
2892 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2893 unsigned LineNo = getLineNumber(ID->getLocation());
2895 StringRef Name = ID->getName();
2897 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2898 if (T->isIncompleteArrayType()) {
2900 // CodeGen turns int[] into int[1] so we'll do the same here.
2901 llvm::APInt ConstVal(32, 1);
2902 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2904 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2905 ArrayType::Normal, 0);
2908 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2909 getOrCreateType(T, Unit),
2910 Var->hasInternalLinkage(), Var);
2913 /// EmitGlobalVariable - Emit global variable's debug info.
2914 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2915 llvm::Constant *Init) {
2916 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2917 // Create the descriptor for the variable.
2918 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2919 StringRef Name = VD->getName();
2920 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2921 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2922 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2923 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2924 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2926 // Do not use DIGlobalVariable for enums.
2927 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2929 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2930 getLineNumber(VD->getLocation()),
2932 getStaticDataMemberDeclaration(VD));
2935 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2938 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2939 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2940 NameSpaceCache.find(NSDecl);
2941 if (I != NameSpaceCache.end())
2942 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2944 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2945 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2946 llvm::DIDescriptor Context =
2947 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2948 llvm::DINameSpace NS =
2949 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2950 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2954 void CGDebugInfo::finalize() {
2955 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2956 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2957 llvm::DIType Ty, RepTy;
2958 // Verify that the debug info still exists.
2959 if (llvm::Value *V = VI->second)
2960 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2962 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2963 TypeCache.find(VI->first);
2964 if (it != TypeCache.end()) {
2965 // Verify that the debug info still exists.
2966 if (llvm::Value *V = it->second)
2967 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2970 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
2971 Ty.replaceAllUsesWith(RepTy);
2974 // We keep our own list of retained types, because we need to look
2975 // up the final type in the type cache.
2976 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
2977 RE = RetainedTypes.end(); RI != RE; ++RI)
2978 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
2980 DBuilder.finalize();