1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenFunction.h"
19 #include "CodeGenModule.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/RecordLayout.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "clang/Basic/Version.h"
29 #include "clang/Frontend/CodeGenOptions.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/Intrinsics.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Path.h"
41 using namespace clang;
42 using namespace clang::CodeGen;
44 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
45 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
50 CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
56 NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
57 : DI(CGF.getDebugInfo()), Builder(B) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
61 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
65 NoLocation::~NoLocation() {
67 assert(Builder.getCurrentDebugLocation().isUnknown());
68 DI->CurLoc = SavedLoc;
72 ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
73 : DI(CGF.getDebugInfo()), Builder(B) {
75 SavedLoc = DI->getLocation();
76 DI->CurLoc = SourceLocation();
77 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
81 void ArtificialLocation::Emit() {
84 DI->EmitLocation(Builder, SavedLoc);
85 DI->CurLoc = SourceLocation();
86 // Construct a location that has a valid scope, but no line info.
87 assert(!DI->LexicalBlockStack.empty());
88 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
89 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
93 ArtificialLocation::~ArtificialLocation() {
95 assert(Builder.getCurrentDebugLocation().getLine() == 0);
96 DI->CurLoc = SavedLoc;
100 void CGDebugInfo::setLocation(SourceLocation Loc) {
101 // If the new location isn't valid return.
102 if (Loc.isInvalid()) return;
104 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
106 // If we've changed files in the middle of a lexical scope go ahead
107 // and create a new lexical scope with file node if it's different
108 // from the one in the scope.
109 if (LexicalBlockStack.empty()) return;
111 SourceManager &SM = CGM.getContext().getSourceManager();
112 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
113 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
115 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
116 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
119 llvm::MDNode *LB = LexicalBlockStack.back();
120 llvm::DIScope Scope = llvm::DIScope(LB);
121 if (Scope.isLexicalBlockFile()) {
122 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
124 = DBuilder.createLexicalBlockFile(LBF.getScope(),
125 getOrCreateFile(CurLoc));
127 LexicalBlockStack.pop_back();
128 LexicalBlockStack.push_back(N);
129 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
131 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
133 LexicalBlockStack.pop_back();
134 LexicalBlockStack.push_back(N);
138 /// getContextDescriptor - Get context info for the decl.
139 llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
143 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
144 I = RegionMap.find(Context);
145 if (I != RegionMap.end()) {
146 llvm::Value *V = I->second;
147 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
151 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
152 return getOrCreateNameSpace(NSDecl);
154 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
155 if (!RDecl->isDependentType())
156 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
157 getOrCreateMainFile());
161 /// getFunctionName - Get function name for the given FunctionDecl. If the
162 /// name is constructed on demand (e.g. C++ destructor) then the name
163 /// is stored on the side.
164 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
165 assert (FD && "Invalid FunctionDecl!");
166 IdentifierInfo *FII = FD->getIdentifier();
167 FunctionTemplateSpecializationInfo *Info
168 = FD->getTemplateSpecializationInfo();
170 return FII->getName();
172 // Otherwise construct human readable name for debug info.
174 llvm::raw_svector_ostream OS(NS);
177 // Add any template specialization args.
179 const TemplateArgumentList *TArgs = Info->TemplateArguments;
180 const TemplateArgument *Args = TArgs->data();
181 unsigned NumArgs = TArgs->size();
182 PrintingPolicy Policy(CGM.getLangOpts());
183 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187 // Copy this name on the side and use its reference.
188 return internString(OS.str());
191 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
192 SmallString<256> MethodName;
193 llvm::raw_svector_ostream OS(MethodName);
194 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
195 const DeclContext *DC = OMD->getDeclContext();
196 if (const ObjCImplementationDecl *OID =
197 dyn_cast<const ObjCImplementationDecl>(DC)) {
198 OS << OID->getName();
199 } else if (const ObjCInterfaceDecl *OID =
200 dyn_cast<const ObjCInterfaceDecl>(DC)) {
201 OS << OID->getName();
202 } else if (const ObjCCategoryImplDecl *OCD =
203 dyn_cast<const ObjCCategoryImplDecl>(DC)){
204 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
205 OCD->getIdentifier()->getNameStart() << ')';
206 } else if (isa<ObjCProtocolDecl>(DC)) {
207 // We can extract the type of the class from the self pointer.
208 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
210 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
211 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 OS << ' ' << OMD->getSelector().getAsString() << ']';
216 return internString(OS.str());
219 /// getSelectorName - Return selector name. This is used for debugging
221 StringRef CGDebugInfo::getSelectorName(Selector S) {
222 return internString(S.getAsString());
225 /// getClassName - Get class name including template argument list.
227 CGDebugInfo::getClassName(const RecordDecl *RD) {
228 const ClassTemplateSpecializationDecl *Spec
229 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
231 return RD->getName();
233 const TemplateArgument *Args;
235 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
236 const TemplateSpecializationType *TST =
237 cast<TemplateSpecializationType>(TAW->getType());
238 Args = TST->getArgs();
239 NumArgs = TST->getNumArgs();
241 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
242 Args = TemplateArgs.data();
243 NumArgs = TemplateArgs.size();
245 StringRef Name = RD->getIdentifier()->getName();
246 PrintingPolicy Policy(CGM.getLangOpts());
247 SmallString<128> TemplateArgList;
249 llvm::raw_svector_ostream OS(TemplateArgList);
250 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254 // Copy this name on the side and use its reference.
255 return internString(Name, TemplateArgList);
258 /// getOrCreateFile - Get the file debug info descriptor for the input location.
259 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
261 // If Location is not valid then use main input file.
262 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
264 SourceManager &SM = CGM.getContext().getSourceManager();
265 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
267 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
268 // If the location is not valid then use main input file.
269 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
271 // Cache the results.
272 const char *fname = PLoc.getFilename();
273 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
274 DIFileCache.find(fname);
276 if (it != DIFileCache.end()) {
277 // Verify that the information still exists.
278 if (llvm::Value *V = it->second)
279 return llvm::DIFile(cast<llvm::MDNode>(V));
282 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
284 DIFileCache[fname] = F;
288 /// getOrCreateMainFile - Get the file info for main compile unit.
289 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
290 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
293 /// getLineNumber - Get line number for the location. If location is invalid
294 /// then use current location.
295 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
296 if (Loc.isInvalid() && CurLoc.isInvalid())
298 SourceManager &SM = CGM.getContext().getSourceManager();
299 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
300 return PLoc.isValid()? PLoc.getLine() : 0;
303 /// getColumnNumber - Get column number for the location.
304 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
305 // We may not want column information at all.
306 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
309 // If the location is invalid then use the current column.
310 if (Loc.isInvalid() && CurLoc.isInvalid())
312 SourceManager &SM = CGM.getContext().getSourceManager();
313 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
314 return PLoc.isValid()? PLoc.getColumn() : 0;
317 StringRef CGDebugInfo::getCurrentDirname() {
318 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
319 return CGM.getCodeGenOpts().DebugCompilationDir;
321 if (!CWDName.empty())
323 SmallString<256> CWD;
324 llvm::sys::fs::current_path(CWD);
325 return CWDName = internString(CWD);
328 /// CreateCompileUnit - Create new compile unit.
329 void CGDebugInfo::CreateCompileUnit() {
331 // Get absolute path name.
332 SourceManager &SM = CGM.getContext().getSourceManager();
333 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
334 if (MainFileName.empty())
335 MainFileName = "<unknown>";
337 // The main file name provided via the "-main-file-name" option contains just
338 // the file name itself with no path information. This file name may have had
339 // a relative path, so we look into the actual file entry for the main
340 // file to determine the real absolute path for the file.
341 std::string MainFileDir;
342 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
343 MainFileDir = MainFile->getDir()->getName();
344 if (MainFileDir != ".") {
345 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
346 llvm::sys::path::append(MainFileDirSS, MainFileName);
347 MainFileName = MainFileDirSS.str();
351 // Save filename string.
352 StringRef Filename = internString(MainFileName);
354 // Save split dwarf file string.
355 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
356 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
359 const LangOptions &LO = CGM.getLangOpts();
362 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
364 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
365 } else if (LO.ObjC1) {
366 LangTag = llvm::dwarf::DW_LANG_ObjC;
368 LangTag = llvm::dwarf::DW_LANG_C99;
370 LangTag = llvm::dwarf::DW_LANG_C89;
373 std::string Producer = getClangFullVersion();
375 // Figure out which version of the ObjC runtime we have.
376 unsigned RuntimeVers = 0;
378 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
380 // Create new compile unit.
381 // FIXME - Eliminate TheCU.
382 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
383 Producer, LO.Optimize,
384 CGM.getCodeGenOpts().DwarfDebugFlags,
385 RuntimeVers, SplitDwarfFilename);
388 /// CreateType - Get the Basic type from the cache or create a new
389 /// one if necessary.
390 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
391 unsigned Encoding = 0;
393 switch (BT->getKind()) {
394 #define BUILTIN_TYPE(Id, SingletonId)
395 #define PLACEHOLDER_TYPE(Id, SingletonId) \
396 case BuiltinType::Id:
397 #include "clang/AST/BuiltinTypes.def"
398 case BuiltinType::Dependent:
399 llvm_unreachable("Unexpected builtin type");
400 case BuiltinType::NullPtr:
401 return DBuilder.createNullPtrType();
402 case BuiltinType::Void:
403 return llvm::DIType();
404 case BuiltinType::ObjCClass:
407 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
409 getOrCreateMainFile(), 0);
411 case BuiltinType::ObjCId: {
412 // typedef struct objc_class *Class;
413 // typedef struct objc_object {
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
423 getOrCreateMainFile(), 0);
425 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
427 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
430 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
431 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
433 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
434 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
437 case BuiltinType::ObjCSel: {
441 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
442 "objc_selector", TheCU, getOrCreateMainFile(),
447 case BuiltinType::OCLImage1d:
448 return getOrCreateStructPtrType("opencl_image1d_t",
450 case BuiltinType::OCLImage1dArray:
451 return getOrCreateStructPtrType("opencl_image1d_array_t",
452 OCLImage1dArrayDITy);
453 case BuiltinType::OCLImage1dBuffer:
454 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
455 OCLImage1dBufferDITy);
456 case BuiltinType::OCLImage2d:
457 return getOrCreateStructPtrType("opencl_image2d_t",
459 case BuiltinType::OCLImage2dArray:
460 return getOrCreateStructPtrType("opencl_image2d_array_t",
461 OCLImage2dArrayDITy);
462 case BuiltinType::OCLImage3d:
463 return getOrCreateStructPtrType("opencl_image3d_t",
465 case BuiltinType::OCLSampler:
466 return DBuilder.createBasicType("opencl_sampler_t",
467 CGM.getContext().getTypeSize(BT),
468 CGM.getContext().getTypeAlign(BT),
469 llvm::dwarf::DW_ATE_unsigned);
470 case BuiltinType::OCLEvent:
471 return getOrCreateStructPtrType("opencl_event_t",
474 case BuiltinType::UChar:
475 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
476 case BuiltinType::Char_S:
477 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
478 case BuiltinType::Char16:
479 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
480 case BuiltinType::UShort:
481 case BuiltinType::UInt:
482 case BuiltinType::UInt128:
483 case BuiltinType::ULong:
484 case BuiltinType::WChar_U:
485 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
486 case BuiltinType::Short:
487 case BuiltinType::Int:
488 case BuiltinType::Int128:
489 case BuiltinType::Long:
490 case BuiltinType::WChar_S:
491 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
492 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
493 case BuiltinType::Half:
494 case BuiltinType::Float:
495 case BuiltinType::LongDouble:
496 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
499 switch (BT->getKind()) {
500 case BuiltinType::Long: BTName = "long int"; break;
501 case BuiltinType::LongLong: BTName = "long long int"; break;
502 case BuiltinType::ULong: BTName = "long unsigned int"; break;
503 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
505 BTName = BT->getName(CGM.getLangOpts());
508 // Bit size, align and offset of the type.
509 uint64_t Size = CGM.getContext().getTypeSize(BT);
510 uint64_t Align = CGM.getContext().getTypeAlign(BT);
512 DBuilder.createBasicType(BTName, Size, Align, Encoding);
516 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
517 // Bit size, align and offset of the type.
518 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
519 if (Ty->isComplexIntegerType())
520 Encoding = llvm::dwarf::DW_ATE_lo_user;
522 uint64_t Size = CGM.getContext().getTypeSize(Ty);
523 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
525 DBuilder.createBasicType("complex", Size, Align, Encoding);
530 /// CreateCVRType - Get the qualified type from the cache or create
531 /// a new one if necessary.
532 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
533 QualifierCollector Qc;
534 const Type *T = Qc.strip(Ty);
536 // Ignore these qualifiers for now.
537 Qc.removeObjCGCAttr();
538 Qc.removeAddressSpace();
539 Qc.removeObjCLifetime();
541 // We will create one Derived type for one qualifier and recurse to handle any
545 Tag = llvm::dwarf::DW_TAG_const_type;
547 } else if (Qc.hasVolatile()) {
548 Tag = llvm::dwarf::DW_TAG_volatile_type;
550 } else if (Qc.hasRestrict()) {
551 Tag = llvm::dwarf::DW_TAG_restrict_type;
554 assert(Qc.empty() && "Unknown type qualifier for debug info");
555 return getOrCreateType(QualType(T, 0), Unit);
558 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
560 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
561 // CVR derived types.
562 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
567 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
570 // The frontend treats 'id' as a typedef to an ObjCObjectType,
571 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
572 // debug info, we want to emit 'id' in both cases.
573 if (Ty->isObjCQualifiedIdType())
574 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
577 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
578 Ty->getPointeeType(), Unit);
582 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
584 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
585 Ty->getPointeeType(), Unit);
588 /// In C++ mode, types have linkage, so we can rely on the ODR and
589 /// on their mangled names, if they're external.
590 static SmallString<256>
591 getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
592 llvm::DICompileUnit TheCU) {
593 SmallString<256> FullName;
594 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
595 // For now, only apply ODR with C++.
596 const TagDecl *TD = Ty->getDecl();
597 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
598 !TD->isExternallyVisible())
600 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
601 if (CGM.getTarget().getCXXABI().isMicrosoft())
604 // TODO: This is using the RTTI name. Is there a better way to get
605 // a unique string for a type?
606 llvm::raw_svector_ostream Out(FullName);
607 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
612 // Creates a forward declaration for a RecordDecl in the given context.
613 llvm::DICompositeType
614 CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
615 llvm::DIDescriptor Ctx) {
616 const RecordDecl *RD = Ty->getDecl();
617 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
618 return llvm::DICompositeType(T);
619 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
620 unsigned Line = getLineNumber(RD->getLocation());
621 StringRef RDName = getClassName(RD);
624 if (RD->isStruct() || RD->isInterface())
625 Tag = llvm::dwarf::DW_TAG_structure_type;
626 else if (RD->isUnion())
627 Tag = llvm::dwarf::DW_TAG_union_type;
629 assert(RD->isClass());
630 Tag = llvm::dwarf::DW_TAG_class_type;
634 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
635 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
639 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
643 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
644 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
645 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
647 // Bit size, align and offset of the type.
648 // Size is always the size of a pointer. We can't use getTypeSize here
649 // because that does not return the correct value for references.
650 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
651 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
652 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
654 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
658 llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
659 llvm::DIType &Cache) {
662 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
663 TheCU, getOrCreateMainFile(), 0);
664 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
665 Cache = DBuilder.createPointerType(Cache, Size);
669 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
671 if (BlockLiteralGeneric)
672 return BlockLiteralGeneric;
674 SmallVector<llvm::Value *, 8> EltTys;
675 llvm::DIType FieldTy;
677 uint64_t FieldSize, FieldOffset;
679 llvm::DIArray Elements;
680 llvm::DIType EltTy, DescTy;
683 FType = CGM.getContext().UnsignedLongTy;
684 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
685 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
687 Elements = DBuilder.getOrCreateArray(EltTys);
690 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
691 unsigned LineNo = getLineNumber(CurLoc);
693 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
694 Unit, LineNo, FieldOffset, 0,
695 Flags, llvm::DIType(), Elements);
697 // Bit size, align and offset of the type.
698 uint64_t Size = CGM.getContext().getTypeSize(Ty);
700 DescTy = DBuilder.createPointerType(EltTy, Size);
703 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
704 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
705 FType = CGM.getContext().IntTy;
706 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
707 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
708 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
709 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
713 FieldSize = CGM.getContext().getTypeSize(Ty);
714 FieldAlign = CGM.getContext().getTypeAlign(Ty);
715 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
716 LineNo, FieldSize, FieldAlign,
717 FieldOffset, 0, FieldTy);
718 EltTys.push_back(FieldTy);
720 FieldOffset += FieldSize;
721 Elements = DBuilder.getOrCreateArray(EltTys);
723 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
724 Unit, LineNo, FieldOffset, 0,
725 Flags, llvm::DIType(), Elements);
727 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
728 return BlockLiteralGeneric;
731 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
732 // Typedefs are derived from some other type. If we have a typedef of a
733 // typedef, make sure to emit the whole chain.
734 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
736 return llvm::DIType();
737 // We don't set size information, but do specify where the typedef was
739 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
740 const TypedefNameDecl *TyDecl = Ty->getDecl();
742 llvm::DIDescriptor TypedefContext =
743 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
746 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
749 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
751 SmallVector<llvm::Value *, 16> EltTys;
753 // Add the result type at least.
754 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
756 // Set up remainder of arguments if there is a prototype.
757 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
758 if (isa<FunctionNoProtoType>(Ty))
759 EltTys.push_back(DBuilder.createUnspecifiedParameter());
760 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
761 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
762 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
763 if (FPT->isVariadic())
764 EltTys.push_back(DBuilder.createUnspecifiedParameter());
767 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
768 return DBuilder.createSubroutineType(Unit, EltTypeArray);
772 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
774 uint64_t sizeInBitsOverride,
777 uint64_t offsetInBits,
779 llvm::DIScope scope) {
780 llvm::DIType debugType = getOrCreateType(type, tunit);
782 // Get the location for the field.
783 llvm::DIFile file = getOrCreateFile(loc);
784 unsigned line = getLineNumber(loc);
786 uint64_t sizeInBits = 0;
787 unsigned alignInBits = 0;
788 if (!type->isIncompleteArrayType()) {
789 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
791 if (sizeInBitsOverride)
792 sizeInBits = sizeInBitsOverride;
796 if (AS == clang::AS_private)
797 flags |= llvm::DIDescriptor::FlagPrivate;
798 else if (AS == clang::AS_protected)
799 flags |= llvm::DIDescriptor::FlagProtected;
801 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
802 alignInBits, offsetInBits, flags, debugType);
805 /// CollectRecordLambdaFields - Helper for CollectRecordFields.
807 CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
808 SmallVectorImpl<llvm::Value *> &elements,
809 llvm::DIType RecordTy) {
810 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
811 // has the name and the location of the variable so we should iterate over
812 // both concurrently.
813 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
814 RecordDecl::field_iterator Field = CXXDecl->field_begin();
815 unsigned fieldno = 0;
816 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
817 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
818 const LambdaExpr::Capture C = *I;
819 if (C.capturesVariable()) {
820 VarDecl *V = C.getCapturedVar();
821 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
822 StringRef VName = V->getName();
823 uint64_t SizeInBitsOverride = 0;
824 if (Field->isBitField()) {
825 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
826 assert(SizeInBitsOverride && "found named 0-width bitfield");
828 llvm::DIType fieldType
829 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
830 C.getLocation(), Field->getAccess(),
831 layout.getFieldOffset(fieldno), VUnit, RecordTy);
832 elements.push_back(fieldType);
834 // TODO: Need to handle 'this' in some way by probably renaming the
835 // this of the lambda class and having a field member of 'this' or
836 // by using AT_object_pointer for the function and having that be
837 // used as 'this' for semantic references.
838 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
839 FieldDecl *f = *Field;
840 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
841 QualType type = f->getType();
842 llvm::DIType fieldType
843 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
844 layout.getFieldOffset(fieldno), VUnit, RecordTy);
846 elements.push_back(fieldType);
851 /// Helper for CollectRecordFields.
853 CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
854 llvm::DIType RecordTy) {
855 // Create the descriptor for the static variable, with or without
856 // constant initializers.
857 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
858 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
860 unsigned LineNumber = getLineNumber(Var->getLocation());
861 StringRef VName = Var->getName();
862 llvm::Constant *C = NULL;
863 if (Var->getInit()) {
864 const APValue *Value = Var->evaluateValue();
867 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
868 if (Value->isFloat())
869 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
874 AccessSpecifier Access = Var->getAccess();
875 if (Access == clang::AS_private)
876 Flags |= llvm::DIDescriptor::FlagPrivate;
877 else if (Access == clang::AS_protected)
878 Flags |= llvm::DIDescriptor::FlagProtected;
880 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
881 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
882 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
886 /// CollectRecordNormalField - Helper for CollectRecordFields.
888 CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
890 SmallVectorImpl<llvm::Value *> &elements,
891 llvm::DIType RecordTy) {
892 StringRef name = field->getName();
893 QualType type = field->getType();
895 // Ignore unnamed fields unless they're anonymous structs/unions.
896 if (name.empty() && !type->isRecordType())
899 uint64_t SizeInBitsOverride = 0;
900 if (field->isBitField()) {
901 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
902 assert(SizeInBitsOverride && "found named 0-width bitfield");
905 llvm::DIType fieldType
906 = createFieldType(name, type, SizeInBitsOverride,
907 field->getLocation(), field->getAccess(),
908 OffsetInBits, tunit, RecordTy);
910 elements.push_back(fieldType);
913 /// CollectRecordFields - A helper function to collect debug info for
914 /// record fields. This is used while creating debug info entry for a Record.
915 void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
917 SmallVectorImpl<llvm::Value *> &elements,
918 llvm::DICompositeType RecordTy) {
919 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
921 if (CXXDecl && CXXDecl->isLambda())
922 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
924 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
926 // Field number for non-static fields.
927 unsigned fieldNo = 0;
929 // Static and non-static members should appear in the same order as
930 // the corresponding declarations in the source program.
931 for (RecordDecl::decl_iterator I = record->decls_begin(),
932 E = record->decls_end(); I != E; ++I)
933 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
934 // Reuse the existing static member declaration if one exists
935 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
936 StaticDataMemberCache.find(V->getCanonicalDecl());
937 if (MI != StaticDataMemberCache.end()) {
939 "Static data member declaration should still exist");
941 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
943 elements.push_back(CreateRecordStaticField(V, RecordTy));
944 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
945 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
946 tunit, elements, RecordTy);
948 // Bump field number for next field.
954 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
955 /// function type is not updated to include implicit "this" pointer. Use this
956 /// routine to get a method type which includes "this" pointer.
957 llvm::DICompositeType
958 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
960 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
961 if (Method->isStatic())
962 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
963 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
967 llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
968 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
969 // Add "this" pointer.
970 llvm::DIArray Args = llvm::DICompositeType(
971 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
972 assert (Args.getNumElements() && "Invalid number of arguments!");
974 SmallVector<llvm::Value *, 16> Elts;
976 // First element is always return type. For 'void' functions it is NULL.
977 Elts.push_back(Args.getElement(0));
979 // "this" pointer is always first argument.
980 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
981 if (isa<ClassTemplateSpecializationDecl>(RD)) {
982 // Create pointer type directly in this case.
983 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
984 QualType PointeeTy = ThisPtrTy->getPointeeType();
985 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
986 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
987 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
988 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
989 llvm::DIType ThisPtrType =
990 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::DICompositeType 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;
1043 unsigned MethodLine = 0;
1044 if (!Method->isImplicit()) {
1045 MethodDefUnit = getOrCreateFile(Method->getLocation());
1046 MethodLine = getLineNumber(Method->getLocation());
1049 // Collect virtual method info.
1050 llvm::DIType ContainingType;
1051 unsigned Virtuality = 0;
1052 unsigned VIndex = 0;
1054 if (Method->isVirtual()) {
1055 if (Method->isPure())
1056 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1058 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1060 // It doesn't make sense to give a virtual destructor a vtable index,
1061 // since a single destructor has two entries in the vtable.
1062 // FIXME: Add proper support for debug info for virtual calls in
1063 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1064 // lookup if we have multiple or virtual inheritance.
1065 if (!isa<CXXDestructorDecl>(Method) &&
1066 !CGM.getTarget().getCXXABI().isMicrosoft())
1067 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
1068 ContainingType = RecordTy;
1072 if (Method->isImplicit())
1073 Flags |= llvm::DIDescriptor::FlagArtificial;
1074 AccessSpecifier Access = Method->getAccess();
1075 if (Access == clang::AS_private)
1076 Flags |= llvm::DIDescriptor::FlagPrivate;
1077 else if (Access == clang::AS_protected)
1078 Flags |= llvm::DIDescriptor::FlagProtected;
1079 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1080 if (CXXC->isExplicit())
1081 Flags |= llvm::DIDescriptor::FlagExplicit;
1082 } else if (const CXXConversionDecl *CXXC =
1083 dyn_cast<CXXConversionDecl>(Method)) {
1084 if (CXXC->isExplicit())
1085 Flags |= llvm::DIDescriptor::FlagExplicit;
1087 if (Method->hasPrototype())
1088 Flags |= llvm::DIDescriptor::FlagPrototyped;
1090 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1091 llvm::DISubprogram SP =
1092 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1093 MethodDefUnit, MethodLine,
1094 MethodTy, /*isLocalToUnit=*/false,
1095 /* isDefinition=*/ false,
1096 Virtuality, VIndex, ContainingType,
1097 Flags, CGM.getLangOpts().Optimize, NULL,
1100 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1105 /// CollectCXXMemberFunctions - A helper function to collect debug info for
1106 /// C++ member functions. This is used while creating debug info entry for
1109 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1110 SmallVectorImpl<llvm::Value *> &EltTys,
1111 llvm::DIType RecordTy) {
1113 // Since we want more than just the individual member decls if we
1114 // have templated functions iterate over every declaration to gather
1116 for(DeclContext::decl_iterator I = RD->decls_begin(),
1117 E = RD->decls_end(); I != E; ++I) {
1118 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
1119 // Reuse the existing member function declaration if it exists.
1120 // It may be associated with the declaration of the type & should be
1121 // reused as we're building the definition.
1123 // This situation can arise in the vtable-based debug info reduction where
1124 // implicit members are emitted in a non-vtable TU.
1125 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1126 SPCache.find(Method->getCanonicalDecl());
1127 if (MI == SPCache.end()) {
1128 // If the member is implicit, lazily create it when we see the
1129 // definition, not before. (an ODR-used implicit default ctor that's
1130 // never actually code generated should not produce debug info)
1131 if (!Method->isImplicit())
1132 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1134 EltTys.push_back(MI->second);
1135 } else if (const FunctionTemplateDecl *FTD =
1136 dyn_cast<FunctionTemplateDecl>(*I)) {
1137 // Add any template specializations that have already been seen. Like
1138 // implicit member functions, these may have been added to a declaration
1139 // in the case of vtable-based debug info reduction.
1140 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1141 SE = FTD->spec_end();
1143 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1144 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1145 if (MI != SPCache.end())
1146 EltTys.push_back(MI->second);
1152 /// CollectCXXBases - A helper function to collect debug info for
1153 /// C++ base classes. This is used while creating debug info entry for
1156 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1157 SmallVectorImpl<llvm::Value *> &EltTys,
1158 llvm::DIType RecordTy) {
1160 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1161 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1162 BE = RD->bases_end(); BI != BE; ++BI) {
1163 unsigned BFlags = 0;
1164 uint64_t BaseOffset;
1166 const CXXRecordDecl *Base =
1167 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1169 if (BI->isVirtual()) {
1170 // virtual base offset offset is -ve. The code generator emits dwarf
1171 // expression where it expects +ve number.
1173 0 - CGM.getItaniumVTableContext()
1174 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1175 BFlags = llvm::DIDescriptor::FlagVirtual;
1177 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1178 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1179 // BI->isVirtual() and bits when not.
1181 AccessSpecifier Access = BI->getAccessSpecifier();
1182 if (Access == clang::AS_private)
1183 BFlags |= llvm::DIDescriptor::FlagPrivate;
1184 else if (Access == clang::AS_protected)
1185 BFlags |= llvm::DIDescriptor::FlagProtected;
1188 DBuilder.createInheritance(RecordTy,
1189 getOrCreateType(BI->getType(), Unit),
1190 BaseOffset, BFlags);
1191 EltTys.push_back(DTy);
1195 /// CollectTemplateParams - A helper function to collect template parameters.
1196 llvm::DIArray CGDebugInfo::
1197 CollectTemplateParams(const TemplateParameterList *TPList,
1198 ArrayRef<TemplateArgument> TAList,
1199 llvm::DIFile Unit) {
1200 SmallVector<llvm::Value *, 16> TemplateParams;
1201 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1202 const TemplateArgument &TA = TAList[i];
1205 Name = TPList->getParam(i)->getName();
1206 switch (TA.getKind()) {
1207 case TemplateArgument::Type: {
1208 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1209 llvm::DITemplateTypeParameter TTP =
1210 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
1211 TemplateParams.push_back(TTP);
1213 case TemplateArgument::Integral: {
1214 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1215 llvm::DITemplateValueParameter TVP =
1216 DBuilder.createTemplateValueParameter(
1218 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1219 TemplateParams.push_back(TVP);
1221 case TemplateArgument::Declaration: {
1222 const ValueDecl *D = TA.getAsDecl();
1223 bool InstanceMember = D->isCXXInstanceMember();
1224 QualType T = InstanceMember
1225 ? CGM.getContext().getMemberPointerType(
1226 D->getType(), cast<RecordDecl>(D->getDeclContext())
1228 : CGM.getContext().getPointerType(D->getType());
1229 llvm::DIType TTy = getOrCreateType(T, Unit);
1231 // Variable pointer template parameters have a value that is the address
1233 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1234 V = CGM.GetAddrOfGlobalVar(VD);
1235 // Member function pointers have special support for building them, though
1236 // this is currently unsupported in LLVM CodeGen.
1237 if (InstanceMember) {
1238 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1239 V = CGM.getCXXABI().EmitMemberPointer(method);
1240 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1241 V = CGM.GetAddrOfFunction(FD);
1242 // Member data pointers have special handling too to compute the fixed
1243 // offset within the object.
1244 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
1245 // These five lines (& possibly the above member function pointer
1246 // handling) might be able to be refactored to use similar code in
1247 // CodeGenModule::getMemberPointerConstant
1248 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1250 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1251 V = CGM.getCXXABI().EmitMemberDataPointer(
1252 cast<MemberPointerType>(T.getTypePtr()), chars);
1254 llvm::DITemplateValueParameter TVP =
1255 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1256 V->stripPointerCasts());
1257 TemplateParams.push_back(TVP);
1259 case TemplateArgument::NullPtr: {
1260 QualType T = TA.getNullPtrType();
1261 llvm::DIType TTy = getOrCreateType(T, Unit);
1263 // Special case member data pointer null values since they're actually -1
1265 if (const MemberPointerType *MPT =
1266 dyn_cast<MemberPointerType>(T.getTypePtr()))
1267 // But treat member function pointers as simple zero integers because
1268 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1269 // CodeGen grows handling for values of non-null member function
1270 // pointers then perhaps we could remove this special case and rely on
1271 // EmitNullMemberPointer for member function pointers.
1272 if (MPT->isMemberDataPointer())
1273 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1275 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1276 llvm::DITemplateValueParameter TVP =
1277 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
1278 TemplateParams.push_back(TVP);
1280 case TemplateArgument::Template: {
1281 llvm::DITemplateValueParameter TVP =
1282 DBuilder.createTemplateTemplateParameter(
1283 TheCU, Name, llvm::DIType(),
1284 TA.getAsTemplate().getAsTemplateDecl()
1285 ->getQualifiedNameAsString());
1286 TemplateParams.push_back(TVP);
1288 case TemplateArgument::Pack: {
1289 llvm::DITemplateValueParameter TVP =
1290 DBuilder.createTemplateParameterPack(
1291 TheCU, Name, llvm::DIType(),
1292 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1293 TemplateParams.push_back(TVP);
1295 case TemplateArgument::Expression: {
1296 const Expr *E = TA.getAsExpr();
1297 QualType T = E->getType();
1298 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1299 assert(V && "Expression in template argument isn't constant");
1300 llvm::DIType TTy = getOrCreateType(T, Unit);
1301 llvm::DITemplateValueParameter TVP =
1302 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1303 V->stripPointerCasts());
1304 TemplateParams.push_back(TVP);
1306 // And the following should never occur:
1307 case TemplateArgument::TemplateExpansion:
1308 case TemplateArgument::Null:
1310 "These argument types shouldn't exist in concrete types");
1313 return DBuilder.getOrCreateArray(TemplateParams);
1316 /// CollectFunctionTemplateParams - A helper function to collect debug
1317 /// info for function template parameters.
1318 llvm::DIArray CGDebugInfo::
1319 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1320 if (FD->getTemplatedKind() ==
1321 FunctionDecl::TK_FunctionTemplateSpecialization) {
1322 const TemplateParameterList *TList =
1323 FD->getTemplateSpecializationInfo()->getTemplate()
1324 ->getTemplateParameters();
1325 return CollectTemplateParams(
1326 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
1328 return llvm::DIArray();
1331 /// CollectCXXTemplateParams - A helper function to collect debug info for
1332 /// template parameters.
1333 llvm::DIArray CGDebugInfo::
1334 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1335 llvm::DIFile Unit) {
1336 llvm::PointerUnion<ClassTemplateDecl *,
1337 ClassTemplatePartialSpecializationDecl *>
1338 PU = TSpecial->getSpecializedTemplateOrPartial();
1340 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1341 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1342 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1343 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1344 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
1347 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1348 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1349 if (VTablePtrType.isValid())
1350 return VTablePtrType;
1352 ASTContext &Context = CGM.getContext();
1355 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1356 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1357 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1358 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1359 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1361 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1362 return VTablePtrType;
1365 /// getVTableName - Get vtable name for the given Class.
1366 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1367 // Copy the gdb compatible name on the side and use its reference.
1368 return internString("_vptr$", RD->getNameAsString());
1372 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1373 /// debug info entry in EltTys vector.
1375 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1376 SmallVectorImpl<llvm::Value *> &EltTys) {
1377 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1379 // If there is a primary base then it will hold vtable info.
1380 if (RL.getPrimaryBase())
1383 // If this class is not dynamic then there is not any vtable info to collect.
1384 if (!RD->isDynamicClass())
1387 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1389 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1391 llvm::DIDescriptor::FlagArtificial,
1392 getOrCreateVTablePtrType(Unit));
1393 EltTys.push_back(VPTR);
1396 /// getOrCreateRecordType - Emit record type's standalone debug info.
1397 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1398 SourceLocation Loc) {
1399 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1400 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1404 /// getOrCreateInterfaceType - Emit an objective c interface type standalone
1406 llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1407 SourceLocation Loc) {
1408 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
1409 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1410 RetainedTypes.push_back(D.getAsOpaquePtr());
1414 void CGDebugInfo::completeType(const RecordDecl *RD) {
1415 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1416 !CGM.getLangOpts().CPlusPlus)
1417 completeRequiredType(RD);
1420 void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
1421 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1422 if (CXXDecl->isDynamicClass())
1425 QualType Ty = CGM.getContext().getRecordType(RD);
1426 llvm::DIType T = getTypeOrNull(Ty);
1427 if (T && T.isForwardDecl())
1428 completeClassData(RD);
1431 void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1432 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
1434 QualType Ty = CGM.getContext().getRecordType(RD);
1435 void* TyPtr = Ty.getAsOpaquePtr();
1436 if (CompletedTypeCache.count(TyPtr))
1438 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1439 assert(!Res.isForwardDecl());
1440 CompletedTypeCache[TyPtr] = Res;
1441 TypeCache[TyPtr] = Res;
1444 /// CreateType - get structure or union type.
1445 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1446 RecordDecl *RD = Ty->getDecl();
1447 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1448 // Always emit declarations for types that aren't required to be complete when
1449 // in limit-debug-info mode. If the type is later found to be required to be
1450 // complete this declaration will be upgraded to a definition by
1451 // `completeRequiredType`.
1452 // If the type is dynamic, only emit the definition in TUs that require class
1453 // data. This is handled by `completeClassData`.
1454 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1455 // If we've already emitted the type, just use that, even if it's only a
1456 // declaration. The completeType, completeRequiredType, and completeClassData
1457 // callbacks will handle promoting the declaration to a definition.
1459 // Under -flimit-debug-info:
1460 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1461 // Emit only a forward declaration unless the type is required.
1462 ((!RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1463 // If the class is dynamic, only emit a declaration. A definition will be
1464 // emitted whenever the vtable is emitted.
1465 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())))) {
1466 llvm::DIDescriptor FDContext =
1467 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1469 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1473 return CreateTypeDefinition(Ty);
1476 llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1477 RecordDecl *RD = Ty->getDecl();
1479 // Get overall information about the record type for the debug info.
1480 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1482 // Records and classes and unions can all be recursive. To handle them, we
1483 // first generate a debug descriptor for the struct as a forward declaration.
1484 // Then (if it is a definition) we go through and get debug info for all of
1485 // its members. Finally, we create a descriptor for the complete type (which
1486 // may refer to the forward decl if the struct is recursive) and replace all
1487 // uses of the forward declaration with the final definition.
1489 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
1490 assert(FwdDecl.isCompositeType() &&
1491 "The debug type of a RecordType should be a llvm::DICompositeType");
1493 if (FwdDecl.isForwardDecl())
1496 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1497 CollectContainingType(CXXDecl, FwdDecl);
1499 // Push the struct on region stack.
1500 LexicalBlockStack.push_back(&*FwdDecl);
1501 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1503 // Add this to the completed-type cache while we're completing it recursively.
1504 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1506 // Convert all the elements.
1507 SmallVector<llvm::Value *, 16> EltTys;
1508 // what about nested types?
1510 // Note: The split of CXXDecl information here is intentional, the
1511 // gdb tests will depend on a certain ordering at printout. The debug
1512 // information offsets are still correct if we merge them all together
1514 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1516 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1517 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1520 // Collect data fields (including static variables and any initializers).
1521 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1523 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1525 LexicalBlockStack.pop_back();
1526 RegionMap.erase(Ty->getDecl());
1528 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1529 FwdDecl.setTypeArray(Elements);
1531 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1535 /// CreateType - get objective-c object type.
1536 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1537 llvm::DIFile Unit) {
1538 // Ignore protocols.
1539 return getOrCreateType(Ty->getBaseType(), Unit);
1543 /// \return true if Getter has the default name for the property PD.
1544 static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1545 const ObjCMethodDecl *Getter) {
1550 assert(Getter->getDeclName().isObjCZeroArgSelector());
1551 return PD->getName() ==
1552 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1555 /// \return true if Setter has the default name for the property PD.
1556 static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1557 const ObjCMethodDecl *Setter) {
1562 assert(Setter->getDeclName().isObjCOneArgSelector());
1563 return SelectorTable::constructSetterName(PD->getName()) ==
1564 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1567 /// CreateType - get objective-c interface type.
1568 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1569 llvm::DIFile Unit) {
1570 ObjCInterfaceDecl *ID = Ty->getDecl();
1572 return llvm::DIType();
1574 // Get overall information about the record type for the debug info.
1575 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1576 unsigned Line = getLineNumber(ID->getLocation());
1577 unsigned RuntimeLang = TheCU.getLanguage();
1579 // If this is just a forward declaration return a special forward-declaration
1580 // debug type since we won't be able to lay out the entire type.
1581 ObjCInterfaceDecl *Def = ID->getDefinition();
1583 llvm::DIType FwdDecl =
1584 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1585 ID->getName(), TheCU, DefUnit, Line,
1592 // Bit size, align and offset of the type.
1593 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1594 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1597 if (ID->getImplementation())
1598 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1600 llvm::DICompositeType RealDecl =
1601 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1602 Line, Size, Align, Flags,
1603 llvm::DIType(), llvm::DIArray(), RuntimeLang);
1605 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1606 // will find it and we're emitting the complete type.
1607 QualType QualTy = QualType(Ty, 0);
1608 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
1610 // Push the struct on region stack.
1611 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
1612 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1614 // Convert all the elements.
1615 SmallVector<llvm::Value *, 16> EltTys;
1617 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1619 llvm::DIType SClassTy =
1620 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1621 if (!SClassTy.isValid())
1622 return llvm::DIType();
1624 llvm::DIType InhTag =
1625 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1626 EltTys.push_back(InhTag);
1629 // Create entries for all of the properties.
1630 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1631 E = ID->prop_end(); I != E; ++I) {
1632 const ObjCPropertyDecl *PD = *I;
1633 SourceLocation Loc = PD->getLocation();
1634 llvm::DIFile PUnit = getOrCreateFile(Loc);
1635 unsigned PLine = getLineNumber(Loc);
1636 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1637 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1638 llvm::MDNode *PropertyNode =
1639 DBuilder.createObjCProperty(PD->getName(),
1641 hasDefaultGetterName(PD, Getter) ? "" :
1642 getSelectorName(PD->getGetterName()),
1643 hasDefaultSetterName(PD, Setter) ? "" :
1644 getSelectorName(PD->getSetterName()),
1645 PD->getPropertyAttributes(),
1646 getOrCreateType(PD->getType(), PUnit));
1647 EltTys.push_back(PropertyNode);
1650 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1651 unsigned FieldNo = 0;
1652 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1653 Field = Field->getNextIvar(), ++FieldNo) {
1654 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1655 if (!FieldTy.isValid())
1656 return llvm::DIType();
1658 StringRef FieldName = Field->getName();
1660 // Ignore unnamed fields.
1661 if (FieldName.empty())
1664 // Get the location for the field.
1665 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1666 unsigned FieldLine = getLineNumber(Field->getLocation());
1667 QualType FType = Field->getType();
1668 uint64_t FieldSize = 0;
1669 unsigned FieldAlign = 0;
1671 if (!FType->isIncompleteArrayType()) {
1673 // Bit size, align and offset of the type.
1674 FieldSize = Field->isBitField()
1675 ? Field->getBitWidthValue(CGM.getContext())
1676 : CGM.getContext().getTypeSize(FType);
1677 FieldAlign = CGM.getContext().getTypeAlign(FType);
1680 uint64_t FieldOffset;
1681 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1682 // We don't know the runtime offset of an ivar if we're using the
1683 // non-fragile ABI. For bitfields, use the bit offset into the first
1684 // byte of storage of the bitfield. For other fields, use zero.
1685 if (Field->isBitField()) {
1686 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1688 FieldOffset %= CGM.getContext().getCharWidth();
1693 FieldOffset = RL.getFieldOffset(FieldNo);
1697 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1698 Flags = llvm::DIDescriptor::FlagProtected;
1699 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1700 Flags = llvm::DIDescriptor::FlagPrivate;
1702 llvm::MDNode *PropertyNode = NULL;
1703 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1704 if (ObjCPropertyImplDecl *PImpD =
1705 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1706 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1707 SourceLocation Loc = PD->getLocation();
1708 llvm::DIFile PUnit = getOrCreateFile(Loc);
1709 unsigned PLine = getLineNumber(Loc);
1710 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1711 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1713 DBuilder.createObjCProperty(PD->getName(),
1715 hasDefaultGetterName(PD, Getter) ? "" :
1716 getSelectorName(PD->getGetterName()),
1717 hasDefaultSetterName(PD, Setter) ? "" :
1718 getSelectorName(PD->getSetterName()),
1719 PD->getPropertyAttributes(),
1720 getOrCreateType(PD->getType(), PUnit));
1724 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1725 FieldLine, FieldSize, FieldAlign,
1726 FieldOffset, Flags, FieldTy,
1728 EltTys.push_back(FieldTy);
1731 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1732 RealDecl.setTypeArray(Elements);
1734 // If the implementation is not yet set, we do not want to mark it
1735 // as complete. An implementation may declare additional
1736 // private ivars that we would miss otherwise.
1737 if (ID->getImplementation() == 0)
1738 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
1740 LexicalBlockStack.pop_back();
1744 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1745 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1746 int64_t Count = Ty->getNumElements();
1748 // If number of elements are not known then this is an unbounded array.
1749 // Use Count == -1 to express such arrays.
1752 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1753 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1755 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1756 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1758 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1761 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1762 llvm::DIFile Unit) {
1766 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1767 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1770 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1771 } else if (Ty->isIncompleteArrayType()) {
1773 if (Ty->getElementType()->isIncompleteType())
1776 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1777 } else if (Ty->isIncompleteType()) {
1781 // Size and align of the whole array, not the element type.
1782 Size = CGM.getContext().getTypeSize(Ty);
1783 Align = CGM.getContext().getTypeAlign(Ty);
1786 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1787 // interior arrays, do we care? Why aren't nested arrays represented the
1788 // obvious/recursive way?
1789 SmallVector<llvm::Value *, 8> Subscripts;
1790 QualType EltTy(Ty, 0);
1791 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1792 // If the number of elements is known, then count is that number. Otherwise,
1793 // it's -1. This allows us to represent a subrange with an array of 0
1794 // elements, like this:
1799 int64_t Count = -1; // Count == -1 is an unbounded array.
1800 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1801 Count = CAT->getSize().getZExtValue();
1803 // FIXME: Verify this is right for VLAs.
1804 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1805 EltTy = Ty->getElementType();
1808 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1810 llvm::DIType DbgTy =
1811 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1816 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1817 llvm::DIFile Unit) {
1818 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1819 Ty, Ty->getPointeeType(), Unit);
1822 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1823 llvm::DIFile Unit) {
1824 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1825 Ty, Ty->getPointeeType(), Unit);
1828 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1830 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1831 if (!Ty->getPointeeType()->isFunctionType())
1832 return DBuilder.createMemberPointerType(
1833 getOrCreateType(Ty->getPointeeType(), U), ClassType);
1834 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1835 CGM.getContext().getPointerType(
1836 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1837 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1841 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1843 // Ignore the atomic wrapping
1844 // FIXME: What is the correct representation?
1845 return getOrCreateType(Ty->getValueType(), U);
1848 /// CreateEnumType - get enumeration type.
1849 llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
1850 const EnumDecl *ED = Ty->getDecl();
1853 if (!ED->getTypeForDecl()->isIncompleteType()) {
1854 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1855 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1858 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1860 // If this is just a forward declaration, construct an appropriately
1861 // marked node and just return it.
1862 if (!ED->getDefinition()) {
1863 llvm::DIDescriptor EDContext;
1864 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1865 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1866 unsigned Line = getLineNumber(ED->getLocation());
1867 StringRef EDName = ED->getName();
1868 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1869 EDName, EDContext, DefUnit, Line, 0,
1870 Size, Align, FullName);
1873 // Create DIEnumerator elements for each enumerator.
1874 SmallVector<llvm::Value *, 16> Enumerators;
1875 ED = ED->getDefinition();
1876 for (EnumDecl::enumerator_iterator
1877 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1878 Enum != EnumEnd; ++Enum) {
1879 Enumerators.push_back(
1880 DBuilder.createEnumerator(Enum->getName(),
1881 Enum->getInitVal().getSExtValue()));
1884 // Return a CompositeType for the enum itself.
1885 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1887 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1888 unsigned Line = getLineNumber(ED->getLocation());
1889 llvm::DIDescriptor EnumContext =
1890 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1891 llvm::DIType ClassTy = ED->isFixed() ?
1892 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1893 llvm::DIType DbgTy =
1894 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1895 Size, Align, EltArray,
1900 static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1903 Qualifiers InnerQuals = T.getLocalQualifiers();
1904 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1905 // that is already there.
1906 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1907 Quals += InnerQuals;
1909 switch (T->getTypeClass()) {
1911 return C.getQualifiedType(T.getTypePtr(), Quals);
1912 case Type::TemplateSpecialization:
1913 T = cast<TemplateSpecializationType>(T)->desugar();
1915 case Type::TypeOfExpr:
1916 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1919 T = cast<TypeOfType>(T)->getUnderlyingType();
1921 case Type::Decltype:
1922 T = cast<DecltypeType>(T)->getUnderlyingType();
1924 case Type::UnaryTransform:
1925 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1927 case Type::Attributed:
1928 T = cast<AttributedType>(T)->getEquivalentType();
1930 case Type::Elaborated:
1931 T = cast<ElaboratedType>(T)->getNamedType();
1934 T = cast<ParenType>(T)->getInnerType();
1936 case Type::SubstTemplateTypeParm:
1937 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1940 QualType DT = cast<AutoType>(T)->getDeducedType();
1947 assert(T != LastT && "Type unwrapping failed to unwrap!");
1952 /// getType - Get the type from the cache or return null type if it doesn't
1954 llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1956 // Unwrap the type as needed for debug information.
1957 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1959 // Check for existing entry.
1960 if (Ty->getTypeClass() == Type::ObjCInterface) {
1961 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1963 return llvm::DIType(cast<llvm::MDNode>(V));
1964 else return llvm::DIType();
1967 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1968 TypeCache.find(Ty.getAsOpaquePtr());
1969 if (it != TypeCache.end()) {
1970 // Verify that the debug info still exists.
1971 if (llvm::Value *V = it->second)
1972 return llvm::DIType(cast<llvm::MDNode>(V));
1975 return llvm::DIType();
1978 /// getCompletedTypeOrNull - Get the type from the cache or return null if it
1980 llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1982 // Unwrap the type as needed for debug information.
1983 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
1985 // Check for existing entry.
1987 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1988 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1989 if (it != CompletedTypeCache.end())
1992 V = getCachedInterfaceTypeOrNull(Ty);
1995 // Verify that any cached debug info still exists.
1996 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
1999 /// getCachedInterfaceTypeOrNull - Get the type from the interface
2000 /// cache, unless it needs to regenerated. Otherwise return null.
2001 llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2002 // Is there a cached interface that hasn't changed?
2003 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2004 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2006 if (it1 != ObjCInterfaceCache.end())
2007 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2008 if (Checksum(Decl) == it1->second.second)
2009 // Return cached forward declaration.
2010 return it1->second.first;
2015 /// getOrCreateType - Get the type from the cache or create a new
2016 /// one if necessary.
2017 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
2019 return llvm::DIType();
2021 // Unwrap the type as needed for debug information.
2022 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
2024 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
2027 // Otherwise create the type.
2028 llvm::DIType Res = CreateTypeNode(Ty, Unit);
2029 void* TyPtr = Ty.getAsOpaquePtr();
2031 // And update the type cache.
2032 TypeCache[TyPtr] = Res;
2034 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2035 // into the cache - but getTypeOrNull has a special case for cached interface
2036 // types. We should probably just pull that out as a special case for the
2037 // "else" block below & skip the otherwise needless lookup.
2038 llvm::DIType TC = getTypeOrNull(Ty);
2039 if (TC && TC.isForwardDecl())
2040 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2041 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2042 // Interface types may have elements added to them by a
2043 // subsequent implementation or extension, so we keep them in
2044 // the ObjCInterfaceCache together with a checksum. Instead of
2045 // the (possibly) incomplete interface type, we return a forward
2046 // declaration that gets RAUW'd in CGDebugInfo::finalize().
2047 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2049 return llvm::DIType(cast<llvm::MDNode>(V.first));
2050 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2051 Decl->getName(), TheCU, Unit,
2052 getLineNumber(Decl->getLocation()),
2053 TheCU.getLanguage());
2054 // Store the forward declaration in the cache.
2056 V.second = Checksum(Decl);
2058 // Register the type for replacement in finalize().
2059 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2064 if (!Res.isForwardDecl())
2065 CompletedTypeCache[TyPtr] = Res;
2070 /// Currently the checksum of an interface includes the number of
2071 /// ivars and property accessors.
2072 unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
2073 // The assumption is that the number of ivars can only increase
2074 // monotonically, so it is safe to just use their current number as
2077 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2078 Ivar != 0; Ivar = Ivar->getNextIvar())
2084 ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2085 switch (Ty->getTypeClass()) {
2086 case Type::ObjCObjectPointer:
2087 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2088 ->getPointeeType());
2089 case Type::ObjCInterface:
2090 return cast<ObjCInterfaceType>(Ty)->getDecl();
2096 /// CreateTypeNode - Create a new debug type node.
2097 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
2098 // Handle qualifiers, which recursively handles what they refer to.
2099 if (Ty.hasLocalQualifiers())
2100 return CreateQualifiedType(Ty, Unit);
2102 const char *Diag = 0;
2104 // Work out details of type.
2105 switch (Ty->getTypeClass()) {
2106 #define TYPE(Class, Base)
2107 #define ABSTRACT_TYPE(Class, Base)
2108 #define NON_CANONICAL_TYPE(Class, Base)
2109 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2110 #include "clang/AST/TypeNodes.def"
2111 llvm_unreachable("Dependent types cannot show up in debug information");
2113 case Type::ExtVector:
2115 return CreateType(cast<VectorType>(Ty), Unit);
2116 case Type::ObjCObjectPointer:
2117 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2118 case Type::ObjCObject:
2119 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2120 case Type::ObjCInterface:
2121 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2123 return CreateType(cast<BuiltinType>(Ty));
2125 return CreateType(cast<ComplexType>(Ty));
2127 return CreateType(cast<PointerType>(Ty), Unit);
2129 // Decayed types are just pointers in LLVM and DWARF.
2131 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
2132 case Type::BlockPointer:
2133 return CreateType(cast<BlockPointerType>(Ty), Unit);
2135 return CreateType(cast<TypedefType>(Ty), Unit);
2137 return CreateType(cast<RecordType>(Ty));
2139 return CreateEnumType(cast<EnumType>(Ty));
2140 case Type::FunctionProto:
2141 case Type::FunctionNoProto:
2142 return CreateType(cast<FunctionType>(Ty), Unit);
2143 case Type::ConstantArray:
2144 case Type::VariableArray:
2145 case Type::IncompleteArray:
2146 return CreateType(cast<ArrayType>(Ty), Unit);
2148 case Type::LValueReference:
2149 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2150 case Type::RValueReference:
2151 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2153 case Type::MemberPointer:
2154 return CreateType(cast<MemberPointerType>(Ty), Unit);
2157 return CreateType(cast<AtomicType>(Ty), Unit);
2159 case Type::Attributed:
2160 case Type::TemplateSpecialization:
2161 case Type::Elaborated:
2163 case Type::SubstTemplateTypeParm:
2164 case Type::TypeOfExpr:
2166 case Type::Decltype:
2167 case Type::UnaryTransform:
2168 case Type::PackExpansion:
2169 llvm_unreachable("type should have been unwrapped!");
2175 assert(Diag && "Fall through without a diagnostic?");
2176 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2177 "debug information for %0 is not yet supported");
2178 CGM.getDiags().Report(DiagID)
2180 return llvm::DIType();
2183 /// getOrCreateLimitedType - Get the type from the cache or create a new
2184 /// limited type if necessary.
2185 llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
2186 llvm::DIFile Unit) {
2187 QualType QTy(Ty, 0);
2189 llvm::DICompositeType T(getTypeOrNull(QTy));
2191 // We may have cached a forward decl when we could have created
2192 // a non-forward decl. Go ahead and create a non-forward decl
2194 if (T && !T.isForwardDecl()) return T;
2196 // Otherwise create the type.
2197 llvm::DICompositeType Res = CreateLimitedType(Ty);
2199 // Propagate members from the declaration to the definition
2200 // CreateType(const RecordType*) will overwrite this with the members in the
2201 // correct order if the full type is needed.
2202 Res.setTypeArray(T.getTypeArray());
2204 if (T && T.isForwardDecl())
2205 ReplaceMap.push_back(
2206 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
2208 // And update the type cache.
2209 TypeCache[QTy.getAsOpaquePtr()] = Res;
2213 // TODO: Currently used for context chains when limiting debug info.
2214 llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2215 RecordDecl *RD = Ty->getDecl();
2217 // Get overall information about the record type for the debug info.
2218 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2219 unsigned Line = getLineNumber(RD->getLocation());
2220 StringRef RDName = getClassName(RD);
2222 llvm::DIDescriptor RDContext =
2223 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2225 // If we ended up creating the type during the context chain construction,
2226 // just return that.
2227 // FIXME: this could be dealt with better if the type was recorded as
2228 // completed before we started this (see the CompletedTypeCache usage in
2229 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2230 // be pushed to before context creation, but after it was known to be
2231 // destined for completion (might still have an issue if this caller only
2232 // required a declaration but the context construction ended up creating a
2234 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2235 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
2238 // If this is just a forward or incomplete declaration, construct an
2239 // appropriately marked node and just return it.
2240 const RecordDecl *D = RD->getDefinition();
2241 if (!D || !D->isCompleteDefinition())
2242 return getOrCreateRecordFwdDecl(Ty, RDContext);
2244 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2245 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2246 llvm::DICompositeType RealDecl;
2248 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2251 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
2252 Size, Align, 0, llvm::DIArray(), 0,
2254 else if (RD->isClass()) {
2255 // FIXME: This could be a struct type giving a default visibility different
2256 // than C++ class type, but needs llvm metadata changes first.
2257 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
2258 Size, Align, 0, 0, llvm::DIType(),
2259 llvm::DIArray(), llvm::DIType(),
2260 llvm::DIArray(), FullName);
2262 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
2263 Size, Align, 0, llvm::DIType(),
2264 llvm::DIArray(), 0, llvm::DIType(),
2267 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
2268 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
2270 if (const ClassTemplateSpecializationDecl *TSpecial =
2271 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2272 RealDecl.setTypeArray(llvm::DIArray(),
2273 CollectCXXTemplateParams(TSpecial, DefUnit));
2277 void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2278 llvm::DICompositeType RealDecl) {
2279 // A class's primary base or the class itself contains the vtable.
2280 llvm::DICompositeType ContainingType;
2281 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2282 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2283 // Seek non virtual primary base root.
2285 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2286 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2287 if (PBT && !BRL.isPrimaryBaseVirtual())
2292 ContainingType = llvm::DICompositeType(
2293 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2294 getOrCreateFile(RD->getLocation())));
2295 } else if (RD->isDynamicClass())
2296 ContainingType = RealDecl;
2298 RealDecl.setContainingType(ContainingType);
2301 /// CreateMemberType - Create new member and increase Offset by FType's size.
2302 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2305 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2306 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2307 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2308 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2309 FieldSize, FieldAlign,
2310 *Offset, 0, FieldTy);
2311 *Offset += FieldSize;
2315 llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2316 // We only need a declaration (not a definition) of the type - so use whatever
2317 // we would otherwise do to get a type for a pointee. (forward declarations in
2318 // limited debug info, full definitions (if the type definition is available)
2319 // in unlimited debug info)
2320 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2321 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
2322 getOrCreateFile(TD->getLocation()));
2323 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2324 // This doesn't handle providing declarations (for functions or variables) for
2325 // entities without definitions in this TU, nor when the definition proceeds
2326 // the call to this function.
2327 // FIXME: This should be split out into more specific maps with support for
2328 // emitting forward declarations and merging definitions with declarations,
2329 // the same way as we do for types.
2330 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2331 DeclCache.find(D->getCanonicalDecl());
2332 if (I == DeclCache.end())
2333 return llvm::DIDescriptor();
2334 llvm::Value *V = I->second;
2335 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2338 /// getFunctionDeclaration - Return debug info descriptor to describe method
2339 /// declaration for the given method definition.
2340 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2341 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2342 return llvm::DISubprogram();
2344 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2345 if (!FD) return llvm::DISubprogram();
2348 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
2350 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2351 MI = SPCache.find(FD->getCanonicalDecl());
2352 if (MI == SPCache.end()) {
2353 if (const CXXMethodDecl *MD =
2354 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
2355 llvm::DICompositeType T(S);
2356 llvm::DISubprogram SP =
2357 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2362 if (MI != SPCache.end()) {
2363 llvm::Value *V = MI->second;
2364 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2365 if (SP.isSubprogram() && !SP.isDefinition())
2369 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2370 E = FD->redecls_end(); I != E; ++I) {
2371 const FunctionDecl *NextFD = *I;
2372 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2373 MI = SPCache.find(NextFD->getCanonicalDecl());
2374 if (MI != SPCache.end()) {
2375 llvm::Value *V = MI->second;
2376 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2377 if (SP.isSubprogram() && !SP.isDefinition())
2381 return llvm::DISubprogram();
2384 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2385 // implicit parameter "this".
2386 llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2389 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2390 // Create fake but valid subroutine type. Otherwise
2391 // llvm::DISubprogram::Verify() would return false, and
2392 // subprogram DIE will miss DW_AT_decl_file and
2393 // DW_AT_decl_line fields.
2394 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
2396 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2397 return getOrCreateMethodType(Method, F);
2398 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2399 // Add "self" and "_cmd"
2400 SmallVector<llvm::Value *, 16> Elts;
2402 // First element is always return type. For 'void' functions it is NULL.
2403 QualType ResultTy = OMethod->getResultType();
2405 // Replace the instancetype keyword with the actual type.
2406 if (ResultTy == CGM.getContext().getObjCInstanceType())
2407 ResultTy = CGM.getContext().getPointerType(
2408 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2410 Elts.push_back(getOrCreateType(ResultTy, F));
2411 // "self" pointer is always first argument.
2412 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2413 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2414 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
2415 // "_cmd" pointer is always second argument.
2416 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2417 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2418 // Get rest of the arguments.
2419 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2420 PE = OMethod->param_end(); PI != PE; ++PI)
2421 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2423 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2424 return DBuilder.createSubroutineType(F, EltTypeArray);
2427 // Variadic function.
2428 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2429 if (FD->isVariadic()) {
2430 SmallVector<llvm::Value *, 16> EltTys;
2431 EltTys.push_back(getOrCreateType(FD->getResultType(), F));
2432 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FnType))
2433 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
2434 EltTys.push_back(getOrCreateType(FPT->getArgType(i), F));
2435 EltTys.push_back(DBuilder.createUnspecifiedParameter());
2436 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
2437 return DBuilder.createSubroutineType(F, EltTypeArray);
2440 return llvm::DICompositeType(getOrCreateType(FnType, F));
2443 /// EmitFunctionStart - Constructs the debug code for entering a function.
2444 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2446 CGBuilderTy &Builder) {
2449 StringRef LinkageName;
2451 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2453 const Decl *D = GD.getDecl();
2454 // Function may lack declaration in source code if it is created by Clang
2455 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2456 bool HasDecl = (D != 0);
2457 // Use the location of the declaration.
2460 Loc = D->getLocation();
2463 llvm::DIFile Unit = getOrCreateFile(Loc);
2464 llvm::DIDescriptor FDContext(Unit);
2465 llvm::DIArray TParamsArray;
2467 // Use llvm function name.
2468 LinkageName = Fn->getName();
2469 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2470 // If there is a DISubprogram for this function available then use it.
2471 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2472 FI = SPCache.find(FD->getCanonicalDecl());
2473 if (FI != SPCache.end()) {
2474 llvm::Value *V = FI->second;
2475 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2476 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2477 llvm::MDNode *SPN = SP;
2478 LexicalBlockStack.push_back(SPN);
2479 RegionMap[D] = llvm::WeakVH(SP);
2483 Name = getFunctionName(FD);
2484 // Use mangled name as linkage name for C/C++ functions.
2485 if (FD->hasPrototype()) {
2486 LinkageName = CGM.getMangledName(GD);
2487 Flags |= llvm::DIDescriptor::FlagPrototyped;
2489 // No need to replicate the linkage name if it isn't different from the
2490 // subprogram name, no need to have it at all unless coverage is enabled or
2491 // debug is set to more than just line tables.
2492 if (LinkageName == Name ||
2493 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2494 !CGM.getCodeGenOpts().EmitGcovNotes &&
2495 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
2496 LinkageName = StringRef();
2498 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
2499 if (const NamespaceDecl *NSDecl =
2500 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2501 FDContext = getOrCreateNameSpace(NSDecl);
2502 else if (const RecordDecl *RDecl =
2503 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2504 FDContext = getContextDescriptor(cast<Decl>(RDecl));
2506 // Collect template parameters.
2507 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2509 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2510 Name = getObjCMethodName(OMD);
2511 Flags |= llvm::DIDescriptor::FlagPrototyped;
2513 // Use llvm function name.
2514 Name = Fn->getName();
2515 Flags |= llvm::DIDescriptor::FlagPrototyped;
2517 if (!Name.empty() && Name[0] == '\01')
2518 Name = Name.substr(1);
2520 unsigned LineNo = getLineNumber(Loc);
2521 if (!HasDecl || D->isImplicit())
2522 Flags |= llvm::DIDescriptor::FlagArtificial;
2524 llvm::DISubprogram SP =
2525 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2526 getOrCreateFunctionType(D, FnType, Unit),
2527 Fn->hasInternalLinkage(), true /*definition*/,
2528 getLineNumber(CurLoc), Flags,
2529 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2530 getFunctionDeclaration(D));
2532 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
2534 // Push function on region stack.
2535 llvm::MDNode *SPN = SP;
2536 LexicalBlockStack.push_back(SPN);
2538 RegionMap[D] = llvm::WeakVH(SP);
2541 /// EmitLocation - Emit metadata to indicate a change in line/column
2542 /// information in the source file. If the location is invalid, the
2543 /// previous location will be reused.
2544 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2545 bool ForceColumnInfo) {
2546 // Update our current location
2549 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2551 // Don't bother if things are the same as last time.
2552 SourceManager &SM = CGM.getContext().getSourceManager();
2553 if (CurLoc == PrevLoc ||
2554 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2555 // New Builder may not be in sync with CGDebugInfo.
2556 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2557 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2558 LexicalBlockStack.back())
2561 // Update last state.
2564 llvm::MDNode *Scope = LexicalBlockStack.back();
2565 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2566 (getLineNumber(CurLoc),
2567 getColumnNumber(CurLoc, ForceColumnInfo),
2571 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2573 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2574 llvm::DIDescriptor D =
2575 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2576 llvm::DIDescriptor() :
2577 llvm::DIDescriptor(LexicalBlockStack.back()),
2578 getOrCreateFile(CurLoc),
2579 getLineNumber(CurLoc),
2580 getColumnNumber(CurLoc));
2581 llvm::MDNode *DN = D;
2582 LexicalBlockStack.push_back(DN);
2585 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2586 /// region - beginning of a DW_TAG_lexical_block.
2587 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2588 SourceLocation Loc) {
2589 // Set our current location.
2592 // Create a new lexical block and push it on the stack.
2593 CreateLexicalBlock(Loc);
2595 // Emit a line table change for the current location inside the new scope.
2596 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2597 getColumnNumber(Loc),
2598 LexicalBlockStack.back()));
2601 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2602 /// region - end of a DW_TAG_lexical_block.
2603 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2604 SourceLocation Loc) {
2605 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2607 // Provide an entry in the line table for the end of the block.
2608 EmitLocation(Builder, Loc);
2610 LexicalBlockStack.pop_back();
2613 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
2614 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2615 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2616 unsigned RCount = FnBeginRegionCount.back();
2617 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2619 // Pop all regions for this function.
2620 while (LexicalBlockStack.size() != RCount)
2621 EmitLexicalBlockEnd(Builder, CurLoc);
2622 FnBeginRegionCount.pop_back();
2625 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2626 // See BuildByRefType.
2627 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2628 uint64_t *XOffset) {
2630 SmallVector<llvm::Value *, 5> EltTys;
2632 uint64_t FieldSize, FieldOffset;
2633 unsigned FieldAlign;
2635 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2636 QualType Type = VD->getType();
2639 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2640 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2641 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2642 FType = CGM.getContext().IntTy;
2643 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2644 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2646 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2647 if (HasCopyAndDispose) {
2648 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2649 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2651 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2654 bool HasByrefExtendedLayout;
2655 Qualifiers::ObjCLifetime Lifetime;
2656 if (CGM.getContext().getByrefLifetime(Type,
2657 Lifetime, HasByrefExtendedLayout)
2658 && HasByrefExtendedLayout) {
2659 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2660 EltTys.push_back(CreateMemberType(Unit, FType,
2661 "__byref_variable_layout",
2665 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2666 if (Align > CGM.getContext().toCharUnitsFromBits(
2667 CGM.getTarget().getPointerAlign(0))) {
2668 CharUnits FieldOffsetInBytes
2669 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2670 CharUnits AlignedOffsetInBytes
2671 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2672 CharUnits NumPaddingBytes
2673 = AlignedOffsetInBytes - FieldOffsetInBytes;
2675 if (NumPaddingBytes.isPositive()) {
2676 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2677 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2678 pad, ArrayType::Normal, 0);
2679 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2684 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2685 FieldSize = CGM.getContext().getTypeSize(FType);
2686 FieldAlign = CGM.getContext().toBits(Align);
2688 *XOffset = FieldOffset;
2689 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2690 0, FieldSize, FieldAlign,
2691 FieldOffset, 0, FieldTy);
2692 EltTys.push_back(FieldTy);
2693 FieldOffset += FieldSize;
2695 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2697 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2699 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2700 llvm::DIType(), Elements);
2703 /// EmitDeclare - Emit local variable declaration debug info.
2704 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2705 llvm::Value *Storage,
2706 unsigned ArgNo, CGBuilderTy &Builder) {
2707 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2708 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2711 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2712 cast<Decl>(VD->getDeclContext())->isImplicit());
2715 Unit = getOrCreateFile(VD->getLocation());
2717 uint64_t XOffset = 0;
2718 if (VD->hasAttr<BlocksAttr>())
2719 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2721 Ty = getOrCreateType(VD->getType(), Unit);
2723 // If there is no debug info for this type then do not emit debug info
2724 // for this variable.
2728 // Get location information.
2730 unsigned Column = 0;
2732 Line = getLineNumber(VD->getLocation());
2733 Column = getColumnNumber(VD->getLocation());
2736 if (VD->isImplicit())
2737 Flags |= llvm::DIDescriptor::FlagArtificial;
2738 // If this is the first argument and it is implicit then
2739 // give it an object pointer flag.
2740 // FIXME: There has to be a better way to do this, but for static
2741 // functions there won't be an implicit param at arg1 and
2742 // otherwise it is 'self' or 'this'.
2743 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2744 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2745 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
2746 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2747 !VD->getType()->isPointerType())
2748 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2750 llvm::MDNode *Scope = LexicalBlockStack.back();
2752 StringRef Name = VD->getName();
2753 if (!Name.empty()) {
2754 if (VD->hasAttr<BlocksAttr>()) {
2755 CharUnits offset = CharUnits::fromQuantity(32);
2756 SmallVector<llvm::Value *, 9> addr;
2757 llvm::Type *Int64Ty = CGM.Int64Ty;
2758 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2759 // offset of __forwarding field
2760 offset = CGM.getContext().toCharUnitsFromBits(
2761 CGM.getTarget().getPointerWidth(0));
2762 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2764 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2765 // offset of x field
2766 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2767 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2769 // Create the descriptor for the variable.
2770 llvm::DIVariable D =
2771 DBuilder.createComplexVariable(Tag,
2772 llvm::DIDescriptor(Scope),
2773 VD->getName(), Unit, Line, Ty,
2776 // Insert an llvm.dbg.declare into the current block.
2777 llvm::Instruction *Call =
2778 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2779 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2781 } else if (isa<VariableArrayType>(VD->getType()))
2782 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
2783 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2784 // If VD is an anonymous union then Storage represents value for
2785 // all union fields.
2786 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2787 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
2788 for (RecordDecl::field_iterator I = RD->field_begin(),
2789 E = RD->field_end();
2791 FieldDecl *Field = *I;
2792 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2793 StringRef FieldName = Field->getName();
2795 // Ignore unnamed fields. Do not ignore unnamed records.
2796 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2799 // Use VarDecl's Tag, Scope and Line number.
2800 llvm::DIVariable D =
2801 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2802 FieldName, Unit, Line, FieldTy,
2803 CGM.getLangOpts().Optimize, Flags,
2806 // Insert an llvm.dbg.declare into the current block.
2807 llvm::Instruction *Call =
2808 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2809 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2815 // Create the descriptor for the variable.
2816 llvm::DIVariable D =
2817 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2818 Name, Unit, Line, Ty,
2819 CGM.getLangOpts().Optimize, Flags, ArgNo);
2821 // Insert an llvm.dbg.declare into the current block.
2822 llvm::Instruction *Call =
2823 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2824 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2827 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2828 llvm::Value *Storage,
2829 CGBuilderTy &Builder) {
2830 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2831 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2834 /// Look up the completed type for a self pointer in the TypeCache and
2835 /// create a copy of it with the ObjectPointer and Artificial flags
2836 /// set. If the type is not cached, a new one is created. This should
2837 /// never happen though, since creating a type for the implicit self
2838 /// argument implies that we already parsed the interface definition
2839 /// and the ivar declarations in the implementation.
2840 llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2842 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2843 if (CachedTy) Ty = CachedTy;
2844 else DEBUG(llvm::dbgs() << "No cached type for self.");
2845 return DBuilder.createObjectPointerType(Ty);
2848 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2849 llvm::Value *Storage,
2850 CGBuilderTy &Builder,
2851 const CGBlockInfo &blockInfo) {
2852 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2853 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2855 if (Builder.GetInsertBlock() == 0)
2858 bool isByRef = VD->hasAttr<BlocksAttr>();
2860 uint64_t XOffset = 0;
2861 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2864 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2866 Ty = getOrCreateType(VD->getType(), Unit);
2868 // Self is passed along as an implicit non-arg variable in a
2869 // block. Mark it as the object pointer.
2870 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2871 Ty = CreateSelfType(VD->getType(), Ty);
2873 // Get location information.
2874 unsigned Line = getLineNumber(VD->getLocation());
2875 unsigned Column = getColumnNumber(VD->getLocation());
2877 const llvm::DataLayout &target = CGM.getDataLayout();
2879 CharUnits offset = CharUnits::fromQuantity(
2880 target.getStructLayout(blockInfo.StructureType)
2881 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2883 SmallVector<llvm::Value *, 9> addr;
2884 llvm::Type *Int64Ty = CGM.Int64Ty;
2885 if (isa<llvm::AllocaInst>(Storage))
2886 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2887 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2888 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2890 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2892 // offset of __forwarding field
2893 offset = CGM.getContext()
2894 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2895 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2896 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2897 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2898 // offset of x field
2899 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2900 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2903 // Create the descriptor for the variable.
2904 llvm::DIVariable D =
2905 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2906 llvm::DIDescriptor(LexicalBlockStack.back()),
2907 VD->getName(), Unit, Line, Ty, addr);
2909 // Insert an llvm.dbg.declare into the current block.
2910 llvm::Instruction *Call =
2911 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2912 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2913 LexicalBlockStack.back()));
2916 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2917 /// variable declaration.
2918 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2920 CGBuilderTy &Builder) {
2921 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2922 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2926 struct BlockLayoutChunk {
2927 uint64_t OffsetInBits;
2928 const BlockDecl::Capture *Capture;
2930 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2931 return l.OffsetInBits < r.OffsetInBits;
2935 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2937 llvm::Value *LocalAddr,
2938 CGBuilderTy &Builder) {
2939 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
2940 ASTContext &C = CGM.getContext();
2941 const BlockDecl *blockDecl = block.getBlockDecl();
2943 // Collect some general information about the block's location.
2944 SourceLocation loc = blockDecl->getCaretLocation();
2945 llvm::DIFile tunit = getOrCreateFile(loc);
2946 unsigned line = getLineNumber(loc);
2947 unsigned column = getColumnNumber(loc);
2949 // Build the debug-info type for the block literal.
2950 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2952 const llvm::StructLayout *blockLayout =
2953 CGM.getDataLayout().getStructLayout(block.StructureType);
2955 SmallVector<llvm::Value*, 16> fields;
2956 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2957 blockLayout->getElementOffsetInBits(0),
2959 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2960 blockLayout->getElementOffsetInBits(1),
2962 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2963 blockLayout->getElementOffsetInBits(2),
2965 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2966 blockLayout->getElementOffsetInBits(3),
2968 fields.push_back(createFieldType("__descriptor",
2969 C.getPointerType(block.NeedsCopyDispose ?
2970 C.getBlockDescriptorExtendedType() :
2971 C.getBlockDescriptorType()),
2973 blockLayout->getElementOffsetInBits(4),
2976 // We want to sort the captures by offset, not because DWARF
2977 // requires this, but because we're paranoid about debuggers.
2978 SmallVector<BlockLayoutChunk, 8> chunks;
2981 if (blockDecl->capturesCXXThis()) {
2982 BlockLayoutChunk chunk;
2983 chunk.OffsetInBits =
2984 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2986 chunks.push_back(chunk);
2989 // Variable captures.
2990 for (BlockDecl::capture_const_iterator
2991 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2993 const BlockDecl::Capture &capture = *i;
2994 const VarDecl *variable = capture.getVariable();
2995 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2997 // Ignore constant captures.
2998 if (captureInfo.isConstant())
3001 BlockLayoutChunk chunk;
3002 chunk.OffsetInBits =
3003 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3004 chunk.Capture = &capture;
3005 chunks.push_back(chunk);
3009 llvm::array_pod_sort(chunks.begin(), chunks.end());
3011 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3012 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3013 uint64_t offsetInBits = i->OffsetInBits;
3014 const BlockDecl::Capture *capture = i->Capture;
3016 // If we have a null capture, this must be the C++ 'this' capture.
3018 const CXXMethodDecl *method =
3019 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3020 QualType type = method->getThisType(C);
3022 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3023 offsetInBits, tunit, tunit));
3027 const VarDecl *variable = capture->getVariable();
3028 StringRef name = variable->getName();
3030 llvm::DIType fieldType;
3031 if (capture->isByRef()) {
3032 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3034 // FIXME: this creates a second copy of this type!
3036 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3037 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3038 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3039 ptrInfo.first, ptrInfo.second,
3040 offsetInBits, 0, fieldType);
3042 fieldType = createFieldType(name, variable->getType(), 0,
3043 loc, AS_public, offsetInBits, tunit, tunit);
3045 fields.push_back(fieldType);
3048 SmallString<36> typeName;
3049 llvm::raw_svector_ostream(typeName)
3050 << "__block_literal_" << CGM.getUniqueBlockCount();
3052 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3055 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3056 CGM.getContext().toBits(block.BlockSize),
3057 CGM.getContext().toBits(block.BlockAlign),
3058 0, llvm::DIType(), fieldsArray);
3059 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3061 // Get overall information about the block.
3062 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3063 llvm::MDNode *scope = LexicalBlockStack.back();
3065 // Create the descriptor for the parameter.
3066 llvm::DIVariable debugVar =
3067 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
3068 llvm::DIDescriptor(scope),
3069 Arg->getName(), tunit, line, type,
3070 CGM.getLangOpts().Optimize, flags,
3071 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3074 // Insert an llvm.dbg.value into the current block.
3075 llvm::Instruction *DbgVal =
3076 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
3077 Builder.GetInsertBlock());
3078 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3081 // Insert an llvm.dbg.declare into the current block.
3082 llvm::Instruction *DbgDecl =
3083 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3084 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3087 /// If D is an out-of-class definition of a static data member of a class, find
3088 /// its corresponding in-class declaration.
3090 CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3091 if (!D->isStaticDataMember())
3092 return llvm::DIDerivedType();
3093 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3094 StaticDataMemberCache.find(D->getCanonicalDecl());
3095 if (MI != StaticDataMemberCache.end()) {
3096 assert(MI->second && "Static data member declaration should still exist");
3097 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
3100 // If the member wasn't found in the cache, lazily construct and add it to the
3101 // type (used when a limited form of the type is emitted).
3102 llvm::DICompositeType Ctxt(
3103 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3104 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
3109 /// EmitGlobalVariable - Emit information about a global variable.
3110 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3112 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3113 // Create global variable debug descriptor.
3114 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3115 unsigned LineNo = getLineNumber(D->getLocation());
3117 setLocation(D->getLocation());
3119 QualType T = D->getType();
3120 if (T->isIncompleteArrayType()) {
3122 // CodeGen turns int[] into int[1] so we'll do the same here.
3123 llvm::APInt ConstVal(32, 1);
3124 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3126 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3127 ArrayType::Normal, 0);
3129 StringRef DeclName = D->getName();
3130 StringRef LinkageName;
3131 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3132 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3133 LinkageName = Var->getName();
3134 if (LinkageName == DeclName)
3135 LinkageName = StringRef();
3136 llvm::DIDescriptor DContext =
3137 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
3138 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3139 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
3140 Var->hasInternalLinkage(), Var,
3141 getOrCreateStaticDataMemberDeclarationOrNull(D));
3142 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
3145 /// EmitGlobalVariable - Emit information about an objective-c interface.
3146 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3147 ObjCInterfaceDecl *ID) {
3148 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3149 // Create global variable debug descriptor.
3150 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3151 unsigned LineNo = getLineNumber(ID->getLocation());
3153 StringRef Name = ID->getName();
3155 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3156 if (T->isIncompleteArrayType()) {
3158 // CodeGen turns int[] into int[1] so we'll do the same here.
3159 llvm::APInt ConstVal(32, 1);
3160 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3162 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3163 ArrayType::Normal, 0);
3166 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3167 getOrCreateType(T, Unit),
3168 Var->hasInternalLinkage(), Var);
3171 /// EmitGlobalVariable - Emit global variable's debug info.
3172 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3173 llvm::Constant *Init) {
3174 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
3175 // Create the descriptor for the variable.
3176 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3177 StringRef Name = VD->getName();
3178 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3179 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3180 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3181 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3182 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3184 // Do not use DIGlobalVariable for enums.
3185 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3187 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3188 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3189 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3190 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3193 llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3194 if (!LexicalBlockStack.empty())
3195 return llvm::DIScope(LexicalBlockStack.back());
3196 return getContextDescriptor(D);
3199 void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3200 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3202 DBuilder.createImportedModule(
3203 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3204 getOrCreateNameSpace(UD.getNominatedNamespace()),
3205 getLineNumber(UD.getLocation()));
3208 void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3209 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3211 assert(UD.shadow_size() &&
3212 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3213 // Emitting one decl is sufficient - debuggers can detect that this is an
3214 // overloaded name & provide lookup for all the overloads.
3215 const UsingShadowDecl &USD = **UD.shadow_begin();
3216 if (llvm::DIDescriptor Target =
3217 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3218 DBuilder.createImportedDeclaration(
3219 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3220 getLineNumber(USD.getLocation()));
3223 llvm::DIImportedEntity
3224 CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3225 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3226 return llvm::DIImportedEntity(0);
3227 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3229 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3230 llvm::DIImportedEntity R(0);
3231 if (const NamespaceAliasDecl *Underlying =
3232 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3233 // This could cache & dedup here rather than relying on metadata deduping.
3234 R = DBuilder.createImportedModule(
3235 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3236 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3239 R = DBuilder.createImportedModule(
3240 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3241 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3242 getLineNumber(NA.getLocation()), NA.getName());
3247 /// getOrCreateNamesSpace - Return namespace descriptor for the given
3250 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3251 NSDecl = NSDecl->getCanonicalDecl();
3252 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3253 NameSpaceCache.find(NSDecl);
3254 if (I != NameSpaceCache.end())
3255 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3257 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3258 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3259 llvm::DIDescriptor Context =
3260 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3261 llvm::DINameSpace NS =
3262 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3263 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3267 void CGDebugInfo::finalize() {
3268 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3269 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3270 llvm::DIType Ty, RepTy;
3271 // Verify that the debug info still exists.
3272 if (llvm::Value *V = VI->second)
3273 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3275 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3276 TypeCache.find(VI->first);
3277 if (it != TypeCache.end()) {
3278 // Verify that the debug info still exists.
3279 if (llvm::Value *V = it->second)
3280 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3283 if (Ty && Ty.isForwardDecl() && RepTy)
3284 Ty.replaceAllUsesWith(RepTy);
3287 // We keep our own list of retained types, because we need to look
3288 // up the final type in the type cache.
3289 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3290 RE = RetainedTypes.end(); RI != RE; ++RI)
3291 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3293 DBuilder.finalize();