1 //===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the debug information generation while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CGDebugInfo.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/FileManager.h"
26 #include "clang/Basic/Version.h"
27 #include "clang/Frontend/CodeGenOptions.h"
28 #include "llvm/Constants.h"
29 #include "llvm/DerivedTypes.h"
30 #include "llvm/Instructions.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Module.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/SmallVector.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Target/TargetMachine.h"
39 using namespace clang;
40 using namespace clang::CodeGen;
42 CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43 : CGM(CGM), DBuilder(CGM.getModule()),
44 BlockLiteralGenericSet(false) {
48 CGDebugInfo::~CGDebugInfo() {
49 assert(LexicalBlockStack.empty() &&
50 "Region stack mismatch, stack not empty!");
53 void CGDebugInfo::setLocation(SourceLocation Loc) {
54 // If the new location isn't valid return.
55 if (!Loc.isValid()) return;
57 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
59 // If we've changed files in the middle of a lexical scope go ahead
60 // and create a new lexical scope with file node if it's different
61 // from the one in the scope.
62 if (LexicalBlockStack.empty()) return;
64 SourceManager &SM = CGM.getContext().getSourceManager();
65 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
68 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
72 llvm::MDNode *LB = LexicalBlockStack.back();
73 llvm::DIScope Scope = llvm::DIScope(LB);
74 if (Scope.isLexicalBlockFile()) {
75 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
77 = DBuilder.createLexicalBlockFile(LBF.getScope(),
78 getOrCreateFile(CurLoc));
80 LexicalBlockStack.pop_back();
81 LexicalBlockStack.push_back(N);
82 } else if (Scope.isLexicalBlock()) {
84 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
86 LexicalBlockStack.pop_back();
87 LexicalBlockStack.push_back(N);
91 /// getContextDescriptor - Get context info for the decl.
92 llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
96 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97 I = RegionMap.find(Context);
98 if (I != RegionMap.end())
99 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(&*I->second));
102 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
103 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
105 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
106 if (!RDecl->isDependentType()) {
107 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
108 getOrCreateMainFile());
109 return llvm::DIDescriptor(Ty);
115 /// getFunctionName - Get function name for the given FunctionDecl. If the
116 /// name is constructred on demand (e.g. C++ destructor) then the name
117 /// is stored on the side.
118 StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
119 assert (FD && "Invalid FunctionDecl!");
120 IdentifierInfo *FII = FD->getIdentifier();
122 return FII->getName();
124 // Otherwise construct human readable name for debug info.
125 std::string NS = FD->getNameAsString();
127 // Copy this name on the side and use its reference.
128 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
129 memcpy(StrPtr, NS.data(), NS.length());
130 return StringRef(StrPtr, NS.length());
133 StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
134 llvm::SmallString<256> MethodName;
135 llvm::raw_svector_ostream OS(MethodName);
136 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
137 const DeclContext *DC = OMD->getDeclContext();
138 if (const ObjCImplementationDecl *OID =
139 dyn_cast<const ObjCImplementationDecl>(DC)) {
140 OS << OID->getName();
141 } else if (const ObjCInterfaceDecl *OID =
142 dyn_cast<const ObjCInterfaceDecl>(DC)) {
143 OS << OID->getName();
144 } else if (const ObjCCategoryImplDecl *OCD =
145 dyn_cast<const ObjCCategoryImplDecl>(DC)){
146 OS << ((NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
147 OCD->getIdentifier()->getNameStart() << ')';
149 OS << ' ' << OMD->getSelector().getAsString() << ']';
151 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
152 memcpy(StrPtr, MethodName.begin(), OS.tell());
153 return StringRef(StrPtr, OS.tell());
156 /// getSelectorName - Return selector name. This is used for debugging
158 StringRef CGDebugInfo::getSelectorName(Selector S) {
159 const std::string &SName = S.getAsString();
160 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
161 memcpy(StrPtr, SName.data(), SName.size());
162 return StringRef(StrPtr, SName.size());
165 /// getClassName - Get class name including template argument list.
167 CGDebugInfo::getClassName(RecordDecl *RD) {
168 ClassTemplateSpecializationDecl *Spec
169 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
171 return RD->getName();
173 const TemplateArgument *Args;
176 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
177 const TemplateSpecializationType *TST =
178 cast<TemplateSpecializationType>(TAW->getType());
179 Args = TST->getArgs();
180 NumArgs = TST->getNumArgs();
182 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
183 Args = TemplateArgs.data();
184 NumArgs = TemplateArgs.size();
186 Buffer = RD->getIdentifier()->getNameStart();
187 PrintingPolicy Policy(CGM.getLangOptions());
188 Buffer += TemplateSpecializationType::PrintTemplateArgumentList(Args,
192 // Copy this name on the side and use its reference.
193 char *StrPtr = DebugInfoNames.Allocate<char>(Buffer.length());
194 memcpy(StrPtr, Buffer.data(), Buffer.length());
195 return StringRef(StrPtr, Buffer.length());
198 /// getOrCreateFile - Get the file debug info descriptor for the input location.
199 llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
201 // If Location is not valid then use main input file.
202 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
204 SourceManager &SM = CGM.getContext().getSourceManager();
205 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
207 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
208 // If the location is not valid then use main input file.
209 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
211 // Cache the results.
212 const char *fname = PLoc.getFilename();
213 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
214 DIFileCache.find(fname);
216 if (it != DIFileCache.end()) {
217 // Verify that the information still exists.
219 return llvm::DIFile(cast<llvm::MDNode>(it->second));
222 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
224 DIFileCache[fname] = F;
229 /// getOrCreateMainFile - Get the file info for main compile unit.
230 llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
231 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
234 /// getLineNumber - Get line number for the location. If location is invalid
235 /// then use current location.
236 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
237 assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!");
238 SourceManager &SM = CGM.getContext().getSourceManager();
239 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
240 return PLoc.isValid()? PLoc.getLine() : 0;
243 /// getColumnNumber - Get column number for the location. If location is
244 /// invalid then use current location.
245 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
246 assert((Loc.isValid() || CurLoc.isValid()) && "Invalid current location!");
247 SourceManager &SM = CGM.getContext().getSourceManager();
248 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
249 return PLoc.isValid()? PLoc.getColumn() : 0;
252 StringRef CGDebugInfo::getCurrentDirname() {
253 if (!CWDName.empty())
255 llvm::SmallString<256> CWD;
256 llvm::sys::fs::current_path(CWD);
257 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
258 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
259 return CWDName = StringRef(CompDirnamePtr, CWD.size());
262 /// CreateCompileUnit - Create new compile unit.
263 void CGDebugInfo::CreateCompileUnit() {
265 // Get absolute path name.
266 SourceManager &SM = CGM.getContext().getSourceManager();
267 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
268 if (MainFileName.empty())
269 MainFileName = "<unknown>";
271 // The main file name provided via the "-main-file-name" option contains just
272 // the file name itself with no path information. This file name may have had
273 // a relative path, so we look into the actual file entry for the main
274 // file to determine the real absolute path for the file.
275 std::string MainFileDir;
276 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
277 MainFileDir = MainFile->getDir()->getName();
278 if (MainFileDir != ".")
279 MainFileName = MainFileDir + "/" + MainFileName;
282 // Save filename string.
283 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
284 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
285 StringRef Filename(FilenamePtr, MainFileName.length());
288 const LangOptions &LO = CGM.getLangOptions();
291 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
293 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
294 } else if (LO.ObjC1) {
295 LangTag = llvm::dwarf::DW_LANG_ObjC;
297 LangTag = llvm::dwarf::DW_LANG_C99;
299 LangTag = llvm::dwarf::DW_LANG_C89;
302 std::string Producer = getClangFullVersion();
304 // Figure out which version of the ObjC runtime we have.
305 unsigned RuntimeVers = 0;
307 RuntimeVers = LO.ObjCNonFragileABI ? 2 : 1;
309 // Create new compile unit.
310 DBuilder.createCompileUnit(
311 LangTag, Filename, getCurrentDirname(),
313 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
314 // FIXME - Eliminate TheCU.
315 TheCU = llvm::DICompileUnit(DBuilder.getCU());
318 /// CreateType - Get the Basic type from the cache or create a new
319 /// one if necessary.
320 llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
321 unsigned Encoding = 0;
322 const char *BTName = NULL;
323 switch (BT->getKind()) {
324 case BuiltinType::Dependent:
325 llvm_unreachable("Unexpected builtin type Dependent");
326 case BuiltinType::Overload:
327 llvm_unreachable("Unexpected builtin type Overload");
328 case BuiltinType::BoundMember:
329 llvm_unreachable("Unexpected builtin type BoundMember");
330 case BuiltinType::UnknownAny:
331 llvm_unreachable("Unexpected builtin type UnknownAny");
332 case BuiltinType::NullPtr:
334 createNullPtrType(BT->getName(CGM.getContext().getLangOptions()));
335 case BuiltinType::Void:
336 return llvm::DIType();
337 case BuiltinType::ObjCClass:
338 return DBuilder.createStructType(TheCU, "objc_class",
339 getOrCreateMainFile(), 0, 0, 0,
340 llvm::DIDescriptor::FlagFwdDecl,
342 case BuiltinType::ObjCId: {
343 // typedef struct objc_class *Class;
344 // typedef struct objc_object {
349 DBuilder.createStructType(TheCU, "objc_class",
350 getOrCreateMainFile(), 0, 0, 0,
351 llvm::DIDescriptor::FlagFwdDecl,
353 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
355 llvm::DIType ISATy = DBuilder.createPointerType(OCTy, Size);
357 SmallVector<llvm::Value *, 16> EltTys;
358 llvm::DIType FieldTy =
359 DBuilder.createMemberType(getOrCreateMainFile(), "isa",
360 getOrCreateMainFile(), 0, Size,
362 EltTys.push_back(FieldTy);
363 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
365 return DBuilder.createStructType(TheCU, "objc_object",
366 getOrCreateMainFile(),
367 0, 0, 0, 0, Elements);
369 case BuiltinType::ObjCSel: {
370 return DBuilder.createStructType(TheCU, "objc_selector",
371 getOrCreateMainFile(), 0, 0, 0,
372 llvm::DIDescriptor::FlagFwdDecl,
375 case BuiltinType::UChar:
376 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
377 case BuiltinType::Char_S:
378 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
379 case BuiltinType::Char16:
380 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
381 case BuiltinType::UShort:
382 case BuiltinType::UInt:
383 case BuiltinType::UInt128:
384 case BuiltinType::ULong:
385 case BuiltinType::WChar_U:
386 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
387 case BuiltinType::Short:
388 case BuiltinType::Int:
389 case BuiltinType::Int128:
390 case BuiltinType::Long:
391 case BuiltinType::WChar_S:
392 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
393 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
394 case BuiltinType::Half:
395 case BuiltinType::Float:
396 case BuiltinType::LongDouble:
397 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
400 switch (BT->getKind()) {
401 case BuiltinType::Long: BTName = "long int"; break;
402 case BuiltinType::LongLong: BTName = "long long int"; break;
403 case BuiltinType::ULong: BTName = "long unsigned int"; break;
404 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
406 BTName = BT->getName(CGM.getContext().getLangOptions());
409 // Bit size, align and offset of the type.
410 uint64_t Size = CGM.getContext().getTypeSize(BT);
411 uint64_t Align = CGM.getContext().getTypeAlign(BT);
413 DBuilder.createBasicType(BTName, Size, Align, Encoding);
417 llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
418 // Bit size, align and offset of the type.
419 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
420 if (Ty->isComplexIntegerType())
421 Encoding = llvm::dwarf::DW_ATE_lo_user;
423 uint64_t Size = CGM.getContext().getTypeSize(Ty);
424 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
426 DBuilder.createBasicType("complex", Size, Align, Encoding);
431 /// CreateCVRType - Get the qualified type from the cache or create
432 /// a new one if necessary.
433 llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
434 QualifierCollector Qc;
435 const Type *T = Qc.strip(Ty);
437 // Ignore these qualifiers for now.
438 Qc.removeObjCGCAttr();
439 Qc.removeAddressSpace();
440 Qc.removeObjCLifetime();
442 // We will create one Derived type for one qualifier and recurse to handle any
446 Tag = llvm::dwarf::DW_TAG_const_type;
448 } else if (Qc.hasVolatile()) {
449 Tag = llvm::dwarf::DW_TAG_volatile_type;
451 } else if (Qc.hasRestrict()) {
452 Tag = llvm::dwarf::DW_TAG_restrict_type;
455 assert(Qc.empty() && "Unknown type qualifier for debug info");
456 return getOrCreateType(QualType(T, 0), Unit);
459 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
461 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
462 // CVR derived types.
463 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
468 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
471 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
472 Ty->getPointeeType(), Unit);
476 llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
478 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
479 Ty->getPointeeType(), Unit);
482 /// CreatePointeeType - Create Pointee type. If Pointee is a record
483 /// then emit record's fwd if debug info size reduction is enabled.
484 llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
486 if (!CGM.getCodeGenOpts().LimitDebugInfo)
487 return getOrCreateType(PointeeTy, Unit);
489 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
490 RecordDecl *RD = RTy->getDecl();
491 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
492 unsigned Line = getLineNumber(RD->getLocation());
493 llvm::DIDescriptor FDContext =
494 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
497 return DBuilder.createStructType(FDContext, RD->getName(), DefUnit,
498 Line, 0, 0, llvm::DIType::FlagFwdDecl,
500 else if (RD->isUnion())
501 return DBuilder.createUnionType(FDContext, RD->getName(), DefUnit,
502 Line, 0, 0, llvm::DIType::FlagFwdDecl,
505 assert(RD->isClass() && "Unknown RecordType!");
506 return DBuilder.createClassType(FDContext, RD->getName(), DefUnit,
507 Line, 0, 0, 0, llvm::DIType::FlagFwdDecl,
508 llvm::DIType(), llvm::DIArray());
511 return getOrCreateType(PointeeTy, Unit);
515 llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
520 if (Tag == llvm::dwarf::DW_TAG_reference_type)
521 return DBuilder.createReferenceType(CreatePointeeType(PointeeTy, Unit));
523 // Bit size, align and offset of the type.
524 // Size is always the size of a pointer. We can't use getTypeSize here
525 // because that does not return the correct value for references.
526 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
527 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
528 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
531 DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit), Size, Align);
534 llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
536 if (BlockLiteralGenericSet)
537 return BlockLiteralGeneric;
539 SmallVector<llvm::Value *, 8> EltTys;
540 llvm::DIType FieldTy;
542 uint64_t FieldSize, FieldOffset;
544 llvm::DIArray Elements;
545 llvm::DIType EltTy, DescTy;
548 FType = CGM.getContext().UnsignedLongTy;
549 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
550 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
552 Elements = DBuilder.getOrCreateArray(EltTys);
555 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
556 unsigned LineNo = getLineNumber(CurLoc);
558 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
559 Unit, LineNo, FieldOffset, 0,
562 // Bit size, align and offset of the type.
563 uint64_t Size = CGM.getContext().getTypeSize(Ty);
565 DescTy = DBuilder.createPointerType(EltTy, Size);
568 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
569 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
570 FType = CGM.getContext().IntTy;
571 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
572 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
573 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
574 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
576 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
578 FieldSize = CGM.getContext().getTypeSize(Ty);
579 FieldAlign = CGM.getContext().getTypeAlign(Ty);
580 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
581 LineNo, FieldSize, FieldAlign,
582 FieldOffset, 0, FieldTy);
583 EltTys.push_back(FieldTy);
585 FieldOffset += FieldSize;
586 Elements = DBuilder.getOrCreateArray(EltTys);
588 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
589 Unit, LineNo, FieldOffset, 0,
592 BlockLiteralGenericSet = true;
593 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
594 return BlockLiteralGeneric;
597 llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty,
599 // Typedefs are derived from some other type. If we have a typedef of a
600 // typedef, make sure to emit the whole chain.
601 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
603 return llvm::DIType();
604 // We don't set size information, but do specify where the typedef was
606 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
607 const TypedefNameDecl *TyDecl = Ty->getDecl();
608 llvm::DIDescriptor TydefContext =
609 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
612 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TydefContext);
615 llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
617 SmallVector<llvm::Value *, 16> EltTys;
619 // Add the result type at least.
620 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
622 // Set up remainder of arguments if there is a prototype.
623 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
624 if (isa<FunctionNoProtoType>(Ty))
625 EltTys.push_back(DBuilder.createUnspecifiedParameter());
626 else if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(Ty)) {
627 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
628 EltTys.push_back(getOrCreateType(FTP->getArgType(i), Unit));
631 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
633 llvm::DIType DbgTy = DBuilder.createSubroutineType(Unit, EltTypeArray);
637 llvm::DIType CGDebugInfo::createFieldType(StringRef name,
639 uint64_t sizeInBitsOverride,
642 uint64_t offsetInBits,
644 llvm::DIDescriptor scope) {
645 llvm::DIType debugType = getOrCreateType(type, tunit);
647 // Get the location for the field.
648 llvm::DIFile file = getOrCreateFile(loc);
649 unsigned line = getLineNumber(loc);
651 uint64_t sizeInBits = 0;
652 unsigned alignInBits = 0;
653 if (!type->isIncompleteArrayType()) {
654 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
656 if (sizeInBitsOverride)
657 sizeInBits = sizeInBitsOverride;
661 if (AS == clang::AS_private)
662 flags |= llvm::DIDescriptor::FlagPrivate;
663 else if (AS == clang::AS_protected)
664 flags |= llvm::DIDescriptor::FlagProtected;
666 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
667 alignInBits, offsetInBits, flags, debugType);
670 /// CollectRecordFields - A helper function to collect debug info for
671 /// record fields. This is used while creating debug info entry for a Record.
673 CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
674 SmallVectorImpl<llvm::Value *> &elements,
675 llvm::DIType RecordTy) {
676 unsigned fieldNo = 0;
677 const FieldDecl *LastFD = 0;
678 bool IsMsStruct = record->hasAttr<MsStructAttr>();
680 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
681 for (RecordDecl::field_iterator I = record->field_begin(),
682 E = record->field_end();
683 I != E; ++I, ++fieldNo) {
684 FieldDecl *field = *I;
686 // Zero-length bitfields following non-bitfield members are ignored
687 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD)) {
694 StringRef name = field->getName();
695 QualType type = field->getType();
697 // Ignore unnamed fields unless they're anonymous structs/unions.
698 if (name.empty() && !type->isRecordType()) {
703 uint64_t SizeInBitsOverride = 0;
704 if (field->isBitField()) {
705 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
706 assert(SizeInBitsOverride && "found named 0-width bitfield");
709 llvm::DIType fieldType
710 = createFieldType(name, type, SizeInBitsOverride,
711 field->getLocation(), field->getAccess(),
712 layout.getFieldOffset(fieldNo), tunit, RecordTy);
714 elements.push_back(fieldType);
718 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
719 /// function type is not updated to include implicit "this" pointer. Use this
720 /// routine to get a method type which includes "this" pointer.
722 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
725 = getOrCreateType(QualType(Method->getType()->getAs<FunctionProtoType>(),
729 // Add "this" pointer.
730 llvm::DIArray Args = llvm::DICompositeType(FnTy).getTypeArray();
731 assert (Args.getNumElements() && "Invalid number of arguments!");
733 SmallVector<llvm::Value *, 16> Elts;
735 // First element is always return type. For 'void' functions it is NULL.
736 Elts.push_back(Args.getElement(0));
738 if (!Method->isStatic()) {
739 // "this" pointer is always first argument.
740 QualType ThisPtr = Method->getThisType(CGM.getContext());
741 llvm::DIType ThisPtrType =
742 DBuilder.createArtificialType(getOrCreateType(ThisPtr, Unit));
744 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
745 Elts.push_back(ThisPtrType);
748 // Copy rest of the arguments.
749 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
750 Elts.push_back(Args.getElement(i));
752 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
754 return DBuilder.createSubroutineType(Unit, EltTypeArray);
757 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
758 /// inside a function.
759 static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
760 if (const CXXRecordDecl *NRD =
761 dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
762 return isFunctionLocalClass(NRD);
763 else if (isa<FunctionDecl>(RD->getDeclContext()))
768 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
769 /// a single member function GlobalDecl.
771 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
773 llvm::DIType RecordTy) {
775 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
777 StringRef MethodName = getFunctionName(Method);
778 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
780 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
781 // make sense to give a single ctor/dtor a linkage name.
782 StringRef MethodLinkageName;
783 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
784 MethodLinkageName = CGM.getMangledName(Method);
786 // Get the location for the method.
787 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
788 unsigned MethodLine = getLineNumber(Method->getLocation());
790 // Collect virtual method info.
791 llvm::DIType ContainingType;
792 unsigned Virtuality = 0;
795 if (Method->isVirtual()) {
796 if (Method->isPure())
797 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
799 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
801 // It doesn't make sense to give a virtual destructor a vtable index,
802 // since a single destructor has two entries in the vtable.
803 if (!isa<CXXDestructorDecl>(Method))
804 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
805 ContainingType = RecordTy;
809 if (Method->isImplicit())
810 Flags |= llvm::DIDescriptor::FlagArtificial;
811 AccessSpecifier Access = Method->getAccess();
812 if (Access == clang::AS_private)
813 Flags |= llvm::DIDescriptor::FlagPrivate;
814 else if (Access == clang::AS_protected)
815 Flags |= llvm::DIDescriptor::FlagProtected;
816 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
817 if (CXXC->isExplicit())
818 Flags |= llvm::DIDescriptor::FlagExplicit;
819 } else if (const CXXConversionDecl *CXXC =
820 dyn_cast<CXXConversionDecl>(Method)) {
821 if (CXXC->isExplicit())
822 Flags |= llvm::DIDescriptor::FlagExplicit;
824 if (Method->hasPrototype())
825 Flags |= llvm::DIDescriptor::FlagPrototyped;
827 llvm::DISubprogram SP =
828 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
829 MethodDefUnit, MethodLine,
830 MethodTy, /*isLocalToUnit=*/false,
831 /* isDefinition=*/ false,
832 Virtuality, VIndex, ContainingType,
833 Flags, CGM.getLangOptions().Optimize);
835 SPCache[Method] = llvm::WeakVH(SP);
840 /// CollectCXXMemberFunctions - A helper function to collect debug info for
841 /// C++ member functions.This is used while creating debug info entry for
844 CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
845 SmallVectorImpl<llvm::Value *> &EltTys,
846 llvm::DIType RecordTy) {
847 for(CXXRecordDecl::method_iterator I = RD->method_begin(),
848 E = RD->method_end(); I != E; ++I) {
849 const CXXMethodDecl *Method = *I;
851 if (Method->isImplicit() && !Method->isUsed())
854 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
858 /// CollectCXXFriends - A helper function to collect debug info for
859 /// C++ base classes. This is used while creating debug info entry for
862 CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
863 SmallVectorImpl<llvm::Value *> &EltTys,
864 llvm::DIType RecordTy) {
865 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
866 BE = RD->friend_end(); BI != BE; ++BI) {
867 if ((*BI)->isUnsupportedFriend())
869 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
870 EltTys.push_back(DBuilder.createFriend(RecordTy,
871 getOrCreateType(TInfo->getType(),
876 /// CollectCXXBases - A helper function to collect debug info for
877 /// C++ base classes. This is used while creating debug info entry for
880 CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
881 SmallVectorImpl<llvm::Value *> &EltTys,
882 llvm::DIType RecordTy) {
884 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
885 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
886 BE = RD->bases_end(); BI != BE; ++BI) {
890 const CXXRecordDecl *Base =
891 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
893 if (BI->isVirtual()) {
894 // virtual base offset offset is -ve. The code generator emits dwarf
895 // expression where it expects +ve number.
897 0 - CGM.getVTableContext()
898 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
899 BFlags = llvm::DIDescriptor::FlagVirtual;
901 BaseOffset = RL.getBaseClassOffsetInBits(Base);
902 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
903 // BI->isVirtual() and bits when not.
905 AccessSpecifier Access = BI->getAccessSpecifier();
906 if (Access == clang::AS_private)
907 BFlags |= llvm::DIDescriptor::FlagPrivate;
908 else if (Access == clang::AS_protected)
909 BFlags |= llvm::DIDescriptor::FlagProtected;
912 DBuilder.createInheritance(RecordTy,
913 getOrCreateType(BI->getType(), Unit),
915 EltTys.push_back(DTy);
919 /// CollectTemplateParams - A helper function to collect template parameters.
920 llvm::DIArray CGDebugInfo::
921 CollectTemplateParams(const TemplateParameterList *TPList,
922 const TemplateArgumentList &TAList,
924 SmallVector<llvm::Value *, 16> TemplateParams;
925 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
926 const TemplateArgument &TA = TAList[i];
927 const NamedDecl *ND = TPList->getParam(i);
928 if (TA.getKind() == TemplateArgument::Type) {
929 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
930 llvm::DITemplateTypeParameter TTP =
931 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
932 TemplateParams.push_back(TTP);
933 } else if (TA.getKind() == TemplateArgument::Integral) {
934 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
935 llvm::DITemplateValueParameter TVP =
936 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
937 TA.getAsIntegral()->getZExtValue());
938 TemplateParams.push_back(TVP);
941 return DBuilder.getOrCreateArray(TemplateParams);
944 /// CollectFunctionTemplateParams - A helper function to collect debug
945 /// info for function template parameters.
946 llvm::DIArray CGDebugInfo::
947 CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
948 if (FD->getTemplatedKind() ==
949 FunctionDecl::TK_FunctionTemplateSpecialization) {
950 const TemplateParameterList *TList =
951 FD->getTemplateSpecializationInfo()->getTemplate()
952 ->getTemplateParameters();
954 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
956 return llvm::DIArray();
959 /// CollectCXXTemplateParams - A helper function to collect debug info for
960 /// template parameters.
961 llvm::DIArray CGDebugInfo::
962 CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
964 llvm::PointerUnion<ClassTemplateDecl *,
965 ClassTemplatePartialSpecializationDecl *>
966 PU = TSpecial->getSpecializedTemplateOrPartial();
968 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
969 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
970 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
971 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
972 return CollectTemplateParams(TPList, TAList, Unit);
975 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
976 llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
977 if (VTablePtrType.isValid())
978 return VTablePtrType;
980 ASTContext &Context = CGM.getContext();
983 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
984 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
985 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
986 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
987 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
989 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
990 return VTablePtrType;
993 /// getVTableName - Get vtable name for the given Class.
994 StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
995 // Otherwise construct gdb compatible name name.
996 std::string Name = "_vptr$" + RD->getNameAsString();
998 // Copy this name on the side and use its reference.
999 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1000 memcpy(StrPtr, Name.data(), Name.length());
1001 return StringRef(StrPtr, Name.length());
1005 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1006 /// debug info entry in EltTys vector.
1008 CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1009 SmallVectorImpl<llvm::Value *> &EltTys) {
1010 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1012 // If there is a primary base then it will hold vtable info.
1013 if (RL.getPrimaryBase())
1016 // If this class is not dynamic then there is not any vtable info to collect.
1017 if (!RD->isDynamicClass())
1020 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1022 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1024 getOrCreateVTablePtrType(Unit));
1025 EltTys.push_back(VPTR);
1028 /// getOrCreateRecordType - Emit record type's standalone debug info.
1029 llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1030 SourceLocation Loc) {
1031 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1032 DBuilder.retainType(T);
1036 /// CreateType - get structure or union type.
1037 llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1038 RecordDecl *RD = Ty->getDecl();
1039 llvm::DIFile Unit = getOrCreateFile(RD->getLocation());
1041 // Get overall information about the record type for the debug info.
1042 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1043 unsigned Line = getLineNumber(RD->getLocation());
1045 // Records and classes and unions can all be recursive. To handle them, we
1046 // first generate a debug descriptor for the struct as a forward declaration.
1047 // Then (if it is a definition) we go through and get debug info for all of
1048 // its members. Finally, we create a descriptor for the complete type (which
1049 // may refer to the forward decl if the struct is recursive) and replace all
1050 // uses of the forward declaration with the final definition.
1051 llvm::DIDescriptor FDContext =
1052 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1054 // If this is just a forward declaration, construct an appropriately
1055 // marked node and just return it.
1056 if (!RD->getDefinition()) {
1057 llvm::DIType FwdDecl =
1058 DBuilder.createStructType(FDContext, RD->getName(),
1059 DefUnit, Line, 0, 0,
1060 llvm::DIDescriptor::FlagFwdDecl,
1066 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1068 llvm::MDNode *MN = FwdDecl;
1069 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1070 // Otherwise, insert it into the TypeCache so that recursive uses will find
1072 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1073 // Push the struct on region stack.
1074 LexicalBlockStack.push_back(FwdDeclNode);
1075 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1077 // Convert all the elements.
1078 SmallVector<llvm::Value *, 16> EltTys;
1080 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1082 CollectCXXBases(CXXDecl, Unit, EltTys, FwdDecl);
1083 CollectVTableInfo(CXXDecl, Unit, EltTys);
1086 // Collect static variables with initializers.
1087 for (RecordDecl::decl_iterator I = RD->decls_begin(), E = RD->decls_end();
1089 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
1090 if (const Expr *Init = V->getInit()) {
1091 Expr::EvalResult Result;
1092 if (Init->Evaluate(Result, CGM.getContext()) && Result.Val.isInt()) {
1093 llvm::ConstantInt *CI
1094 = llvm::ConstantInt::get(CGM.getLLVMContext(), Result.Val.getInt());
1096 // Create the descriptor for static variable.
1097 llvm::DIFile VUnit = getOrCreateFile(V->getLocation());
1098 StringRef VName = V->getName();
1099 llvm::DIType VTy = getOrCreateType(V->getType(), VUnit);
1100 // Do not use DIGlobalVariable for enums.
1101 if (VTy.getTag() != llvm::dwarf::DW_TAG_enumeration_type) {
1102 DBuilder.createStaticVariable(FwdDecl, VName, VName, VUnit,
1103 getLineNumber(V->getLocation()),
1110 CollectRecordFields(RD, Unit, EltTys, FwdDecl);
1111 llvm::DIArray TParamsArray;
1113 CollectCXXMemberFunctions(CXXDecl, Unit, EltTys, FwdDecl);
1114 CollectCXXFriends(CXXDecl, Unit, EltTys, FwdDecl);
1115 if (const ClassTemplateSpecializationDecl *TSpecial
1116 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1117 TParamsArray = CollectCXXTemplateParams(TSpecial, Unit);
1120 LexicalBlockStack.pop_back();
1121 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1122 RegionMap.find(Ty->getDecl());
1123 if (RI != RegionMap.end())
1124 RegionMap.erase(RI);
1126 llvm::DIDescriptor RDContext =
1127 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1128 StringRef RDName = RD->getName();
1129 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1130 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1131 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1132 llvm::MDNode *RealDecl = NULL;
1135 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1136 Size, Align, 0, Elements);
1138 RDName = getClassName(RD);
1139 // A class's primary base or the class itself contains the vtable.
1140 llvm::MDNode *ContainingType = NULL;
1141 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1142 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1143 // Seek non virtual primary base root.
1145 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1146 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1147 if (PBT && !BRL.isPrimaryBaseVirtual())
1153 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), Unit);
1155 else if (CXXDecl->isDynamicClass())
1156 ContainingType = FwdDecl;
1158 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1159 Size, Align, 0, 0, llvm::DIType(),
1160 Elements, ContainingType,
1163 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1164 Size, Align, 0, Elements);
1166 // Now that we have a real decl for the struct, replace anything using the
1167 // old decl with the new one. This will recursively update the debug info.
1168 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1169 RegionMap[RD] = llvm::WeakVH(RealDecl);
1170 return llvm::DIType(RealDecl);
1173 /// CreateType - get objective-c object type.
1174 llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1175 llvm::DIFile Unit) {
1176 // Ignore protocols.
1177 return getOrCreateType(Ty->getBaseType(), Unit);
1180 /// CreateType - get objective-c interface type.
1181 llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1182 llvm::DIFile Unit) {
1183 ObjCInterfaceDecl *ID = Ty->getDecl();
1185 return llvm::DIType();
1187 // Get overall information about the record type for the debug info.
1188 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1189 unsigned Line = getLineNumber(ID->getLocation());
1190 unsigned RuntimeLang = TheCU.getLanguage();
1192 // If this is just a forward declaration return a special forward-declaration
1193 // debug type since we won't be able to lay out the entire type.
1194 if (ID->isForwardDecl()) {
1195 llvm::DIType FwdDecl =
1196 DBuilder.createStructType(Unit, ID->getName(),
1197 DefUnit, Line, 0, 0, 0,
1198 llvm::DIArray(), RuntimeLang);
1202 // To handle a recursive interface, we first generate a debug descriptor
1203 // for the struct as a forward declaration. Then (if it is a definition)
1204 // we go through and get debug info for all of its members. Finally, we
1205 // create a descriptor for the complete type (which may refer to the
1206 // forward decl if the struct is recursive) and replace all uses of the
1207 // forward declaration with the final definition.
1208 llvm::DIType FwdDecl = DBuilder.createTemporaryType(DefUnit);
1210 llvm::MDNode *MN = FwdDecl;
1211 llvm::TrackingVH<llvm::MDNode> FwdDeclNode = MN;
1212 // Otherwise, insert it into the TypeCache so that recursive uses will find
1214 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1215 // Push the struct on region stack.
1216 LexicalBlockStack.push_back(FwdDeclNode);
1217 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1219 // Convert all the elements.
1220 SmallVector<llvm::Value *, 16> EltTys;
1222 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1224 llvm::DIType SClassTy =
1225 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1226 if (!SClassTy.isValid())
1227 return llvm::DIType();
1229 llvm::DIType InhTag =
1230 DBuilder.createInheritance(FwdDecl, SClassTy, 0, 0);
1231 EltTys.push_back(InhTag);
1234 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1235 ObjCImplementationDecl *ImpD = ID->getImplementation();
1236 unsigned FieldNo = 0;
1237 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1238 Field = Field->getNextIvar(), ++FieldNo) {
1239 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1240 if (!FieldTy.isValid())
1241 return llvm::DIType();
1243 StringRef FieldName = Field->getName();
1245 // Ignore unnamed fields.
1246 if (FieldName.empty())
1249 // Get the location for the field.
1250 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1251 unsigned FieldLine = getLineNumber(Field->getLocation());
1252 QualType FType = Field->getType();
1253 uint64_t FieldSize = 0;
1254 unsigned FieldAlign = 0;
1256 if (!FType->isIncompleteArrayType()) {
1258 // Bit size, align and offset of the type.
1259 FieldSize = Field->isBitField()
1260 ? Field->getBitWidthValue(CGM.getContext())
1261 : CGM.getContext().getTypeSize(FType);
1262 FieldAlign = CGM.getContext().getTypeAlign(FType);
1265 // We can't know the offset of our ivar in the structure if we're using
1266 // the non-fragile abi and the debugger should ignore the value anyways.
1267 // Call it the FieldNo+1 due to how debuggers use the information,
1268 // e.g. negating the value when it needs a lookup in the dynamic table.
1269 uint64_t FieldOffset = CGM.getLangOptions().ObjCNonFragileABI ? FieldNo+1
1270 : RL.getFieldOffset(FieldNo);
1273 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1274 Flags = llvm::DIDescriptor::FlagProtected;
1275 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1276 Flags = llvm::DIDescriptor::FlagPrivate;
1278 StringRef PropertyName;
1279 StringRef PropertyGetter;
1280 StringRef PropertySetter;
1281 unsigned PropertyAttributes = 0;
1282 ObjCPropertyDecl *PD = NULL;
1284 if (ObjCPropertyImplDecl *PImpD =
1285 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier()))
1286 PD = PImpD->getPropertyDecl();
1288 PropertyName = PD->getName();
1289 PropertyGetter = getSelectorName(PD->getGetterName());
1290 PropertySetter = getSelectorName(PD->getSetterName());
1291 PropertyAttributes = PD->getPropertyAttributes();
1293 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1294 FieldLine, FieldSize, FieldAlign,
1295 FieldOffset, Flags, FieldTy,
1296 PropertyName, PropertyGetter,
1297 PropertySetter, PropertyAttributes);
1298 EltTys.push_back(FieldTy);
1301 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1303 LexicalBlockStack.pop_back();
1304 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator RI =
1305 RegionMap.find(Ty->getDecl());
1306 if (RI != RegionMap.end())
1307 RegionMap.erase(RI);
1309 // Bit size, align and offset of the type.
1310 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1311 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1314 if (ID->getImplementation())
1315 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1317 llvm::DIType RealDecl =
1318 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1319 Line, Size, Align, Flags,
1320 Elements, RuntimeLang);
1322 // Now that we have a real decl for the struct, replace anything using the
1323 // old decl with the new one. This will recursively update the debug info.
1324 llvm::DIType(FwdDeclNode).replaceAllUsesWith(RealDecl);
1325 RegionMap[ID] = llvm::WeakVH(RealDecl);
1330 llvm::DIType CGDebugInfo::CreateType(const TagType *Ty) {
1331 if (const RecordType *RT = dyn_cast<RecordType>(Ty))
1332 return CreateType(RT);
1333 else if (const EnumType *ET = dyn_cast<EnumType>(Ty))
1334 return CreateEnumType(ET->getDecl());
1336 return llvm::DIType();
1339 llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty,
1340 llvm::DIFile Unit) {
1341 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1342 int64_t NumElems = Ty->getNumElements();
1343 int64_t LowerBound = 0;
1345 // If number of elements are not known then this is an unbounded array.
1346 // Use Low = 1, Hi = 0 to express such arrays.
1351 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(LowerBound, NumElems);
1352 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1354 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1355 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1358 DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1361 llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1362 llvm::DIFile Unit) {
1367 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1368 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1371 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1372 } else if (Ty->isIncompleteArrayType()) {
1374 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1375 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1379 // Size and align of the whole array, not the element type.
1380 Size = CGM.getContext().getTypeSize(Ty);
1381 Align = CGM.getContext().getTypeAlign(Ty);
1384 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1385 // interior arrays, do we care? Why aren't nested arrays represented the
1386 // obvious/recursive way?
1387 SmallVector<llvm::Value *, 8> Subscripts;
1388 QualType EltTy(Ty, 0);
1389 if (Ty->isIncompleteArrayType())
1390 EltTy = Ty->getElementType();
1392 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1393 int64_t UpperBound = 0;
1394 int64_t LowerBound = 0;
1395 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty)) {
1396 if (CAT->getSize().getZExtValue())
1397 UpperBound = CAT->getSize().getZExtValue() - 1;
1399 // This is an unbounded array. Use Low = 1, Hi = 0 to express such
1403 // FIXME: Verify this is right for VLAs.
1404 Subscripts.push_back(DBuilder.getOrCreateSubrange(LowerBound,
1406 EltTy = Ty->getElementType();
1410 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1412 llvm::DIType DbgTy =
1413 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1418 llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1419 llvm::DIFile Unit) {
1420 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1421 Ty, Ty->getPointeeType(), Unit);
1424 llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1425 llvm::DIFile Unit) {
1426 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1427 Ty, Ty->getPointeeType(), Unit);
1430 llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1432 QualType PointerDiffTy = CGM.getContext().getPointerDiffType();
1433 llvm::DIType PointerDiffDITy = getOrCreateType(PointerDiffTy, U);
1435 if (!Ty->getPointeeType()->isFunctionType()) {
1436 // We have a data member pointer type.
1437 return PointerDiffDITy;
1440 // We have a member function pointer type. Treat it as a struct with two
1441 // ptrdiff_t members.
1442 std::pair<uint64_t, unsigned> Info = CGM.getContext().getTypeInfo(Ty);
1444 uint64_t FieldOffset = 0;
1445 llvm::Value *ElementTypes[2];
1447 // FIXME: This should probably be a function type instead.
1449 DBuilder.createMemberType(U, "ptr", U, 0,
1450 Info.first, Info.second, FieldOffset, 0,
1452 FieldOffset += Info.first;
1455 DBuilder.createMemberType(U, "ptr", U, 0,
1456 Info.first, Info.second, FieldOffset, 0,
1459 llvm::DIArray Elements = DBuilder.getOrCreateArray(ElementTypes);
1461 return DBuilder.createStructType(U, StringRef("test"),
1466 llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1468 // Ignore the atomic wrapping
1469 // FIXME: What is the correct representation?
1470 return getOrCreateType(Ty->getValueType(), U);
1473 /// CreateEnumType - get enumeration type.
1474 llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1475 llvm::DIFile Unit = getOrCreateFile(ED->getLocation());
1476 SmallVector<llvm::Value *, 16> Enumerators;
1478 // Create DIEnumerator elements for each enumerator.
1479 for (EnumDecl::enumerator_iterator
1480 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1481 Enum != EnumEnd; ++Enum) {
1482 Enumerators.push_back(
1483 DBuilder.createEnumerator(Enum->getName(),
1484 Enum->getInitVal().getZExtValue()));
1487 // Return a CompositeType for the enum itself.
1488 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1490 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1491 unsigned Line = getLineNumber(ED->getLocation());
1494 if (!ED->getTypeForDecl()->isIncompleteType()) {
1495 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1496 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1498 llvm::DIDescriptor EnumContext =
1499 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1500 llvm::DIType DbgTy =
1501 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1502 Size, Align, EltArray);
1506 static QualType UnwrapTypeForDebugInfo(QualType T) {
1509 switch (T->getTypeClass()) {
1512 case Type::TemplateSpecialization:
1513 T = cast<TemplateSpecializationType>(T)->desugar();
1515 case Type::TypeOfExpr:
1516 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1519 T = cast<TypeOfType>(T)->getUnderlyingType();
1521 case Type::Decltype:
1522 T = cast<DecltypeType>(T)->getUnderlyingType();
1524 case Type::UnaryTransform:
1525 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1527 case Type::Attributed:
1528 T = cast<AttributedType>(T)->getEquivalentType();
1530 case Type::Elaborated:
1531 T = cast<ElaboratedType>(T)->getNamedType();
1534 T = cast<ParenType>(T)->getInnerType();
1536 case Type::SubstTemplateTypeParm:
1537 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
1540 T = cast<AutoType>(T)->getDeducedType();
1544 assert(T != LastT && "Type unwrapping failed to unwrap!");
1552 /// getOrCreateType - Get the type from the cache or create a new
1553 /// one if necessary.
1554 llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty,
1555 llvm::DIFile Unit) {
1557 return llvm::DIType();
1559 // Unwrap the type as needed for debug information.
1560 Ty = UnwrapTypeForDebugInfo(Ty);
1562 // Check for existing entry.
1563 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1564 TypeCache.find(Ty.getAsOpaquePtr());
1565 if (it != TypeCache.end()) {
1566 // Verify that the debug info still exists.
1568 return llvm::DIType(cast<llvm::MDNode>(it->second));
1571 // Otherwise create the type.
1572 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1574 // And update the type cache.
1575 TypeCache[Ty.getAsOpaquePtr()] = Res;
1579 /// CreateTypeNode - Create a new debug type node.
1580 llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty,
1581 llvm::DIFile Unit) {
1582 // Handle qualifiers, which recursively handles what they refer to.
1583 if (Ty.hasLocalQualifiers())
1584 return CreateQualifiedType(Ty, Unit);
1586 const char *Diag = 0;
1588 // Work out details of type.
1589 switch (Ty->getTypeClass()) {
1590 #define TYPE(Class, Base)
1591 #define ABSTRACT_TYPE(Class, Base)
1592 #define NON_CANONICAL_TYPE(Class, Base)
1593 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1594 #include "clang/AST/TypeNodes.def"
1595 llvm_unreachable("Dependent types cannot show up in debug information");
1597 case Type::ExtVector:
1599 return CreateType(cast<VectorType>(Ty), Unit);
1600 case Type::ObjCObjectPointer:
1601 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1602 case Type::ObjCObject:
1603 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1604 case Type::ObjCInterface:
1605 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1606 case Type::Builtin: return CreateType(cast<BuiltinType>(Ty));
1607 case Type::Complex: return CreateType(cast<ComplexType>(Ty));
1608 case Type::Pointer: return CreateType(cast<PointerType>(Ty), Unit);
1609 case Type::BlockPointer:
1610 return CreateType(cast<BlockPointerType>(Ty), Unit);
1611 case Type::Typedef: return CreateType(cast<TypedefType>(Ty), Unit);
1614 return CreateType(cast<TagType>(Ty));
1615 case Type::FunctionProto:
1616 case Type::FunctionNoProto:
1617 return CreateType(cast<FunctionType>(Ty), Unit);
1618 case Type::ConstantArray:
1619 case Type::VariableArray:
1620 case Type::IncompleteArray:
1621 return CreateType(cast<ArrayType>(Ty), Unit);
1623 case Type::LValueReference:
1624 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1625 case Type::RValueReference:
1626 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1628 case Type::MemberPointer:
1629 return CreateType(cast<MemberPointerType>(Ty), Unit);
1632 return CreateType(cast<AtomicType>(Ty), Unit);
1634 case Type::Attributed:
1635 case Type::TemplateSpecialization:
1636 case Type::Elaborated:
1638 case Type::SubstTemplateTypeParm:
1639 case Type::TypeOfExpr:
1641 case Type::Decltype:
1642 case Type::UnaryTransform:
1644 llvm_unreachable("type should have been unwrapped!");
1645 return llvm::DIType();
1648 assert(Diag && "Fall through without a diagnostic?");
1649 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1650 "debug information for %0 is not yet supported");
1651 CGM.getDiags().Report(DiagID)
1653 return llvm::DIType();
1656 /// CreateMemberType - Create new member and increase Offset by FType's size.
1657 llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
1660 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1661 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
1662 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
1663 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
1664 FieldSize, FieldAlign,
1665 *Offset, 0, FieldTy);
1666 *Offset += FieldSize;
1670 /// getFunctionDeclaration - Return debug info descriptor to describe method
1671 /// declaration for the given method definition.
1672 llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
1673 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
1674 if (!FD) return llvm::DISubprogram();
1677 getContextDescriptor(cast<Decl>(D->getDeclContext()));
1679 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1680 MI = SPCache.find(FD);
1681 if (MI != SPCache.end()) {
1682 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1683 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1687 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
1688 E = FD->redecls_end(); I != E; ++I) {
1689 const FunctionDecl *NextFD = *I;
1690 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1691 MI = SPCache.find(NextFD);
1692 if (MI != SPCache.end()) {
1693 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(&*MI->second));
1694 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
1698 return llvm::DISubprogram();
1701 // getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
1702 // implicit parameter "this".
1703 llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl * D,
1706 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1707 return getOrCreateMethodType(Method, F);
1708 else if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
1709 // Add "self" and "_cmd"
1710 SmallVector<llvm::Value *, 16> Elts;
1712 // First element is always return type. For 'void' functions it is NULL.
1713 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
1714 // "self" pointer is always first argument.
1715 Elts.push_back(getOrCreateType(OMethod->getSelfDecl()->getType(), F));
1716 // "cmd" pointer is always second argument.
1717 Elts.push_back(getOrCreateType(OMethod->getCmdDecl()->getType(), F));
1718 // Get rest of the arguments.
1719 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
1720 PE = OMethod->param_end(); PI != PE; ++PI)
1721 Elts.push_back(getOrCreateType((*PI)->getType(), F));
1723 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1724 return DBuilder.createSubroutineType(F, EltTypeArray);
1726 return getOrCreateType(FnType, F);
1729 /// EmitFunctionStart - Constructs the debug code for entering a function -
1730 /// "llvm.dbg.func.start.".
1731 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
1733 CGBuilderTy &Builder) {
1736 StringRef LinkageName;
1738 FnBeginRegionCount.push_back(LexicalBlockStack.size());
1740 const Decl *D = GD.getDecl();
1743 llvm::DIFile Unit = getOrCreateFile(CurLoc);
1744 llvm::DIDescriptor FDContext(Unit);
1745 llvm::DIArray TParamsArray;
1746 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747 // If there is a DISubprogram for this function available then use it.
1748 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
1749 FI = SPCache.find(FD);
1750 if (FI != SPCache.end()) {
1751 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(&*FI->second));
1752 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
1753 llvm::MDNode *SPN = SP;
1754 LexicalBlockStack.push_back(SPN);
1755 RegionMap[D] = llvm::WeakVH(SP);
1759 Name = getFunctionName(FD);
1760 // Use mangled name as linkage name for c/c++ functions.
1761 if (!Fn->hasInternalLinkage())
1762 LinkageName = CGM.getMangledName(GD);
1763 if (LinkageName == Name)
1764 LinkageName = StringRef();
1765 if (FD->hasPrototype())
1766 Flags |= llvm::DIDescriptor::FlagPrototyped;
1767 if (const NamespaceDecl *NSDecl =
1768 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
1769 FDContext = getOrCreateNameSpace(NSDecl);
1770 else if (const RecordDecl *RDecl =
1771 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
1772 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
1774 // Collect template parameters.
1775 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
1776 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
1777 Name = getObjCMethodName(OMD);
1778 Flags |= llvm::DIDescriptor::FlagPrototyped;
1780 // Use llvm function name.
1781 Name = Fn->getName();
1782 Flags |= llvm::DIDescriptor::FlagPrototyped;
1784 if (!Name.empty() && Name[0] == '\01')
1785 Name = Name.substr(1);
1787 // It is expected that CurLoc is set before using EmitFunctionStart.
1788 // Usually, CurLoc points to the left bracket location of compound
1789 // statement representing function body.
1790 unsigned LineNo = getLineNumber(CurLoc);
1791 if (D->isImplicit())
1792 Flags |= llvm::DIDescriptor::FlagArtificial;
1793 llvm::DISubprogram SPDecl = getFunctionDeclaration(D);
1794 llvm::DISubprogram SP =
1795 DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
1796 LineNo, getOrCreateFunctionType(D, FnType, Unit),
1797 Fn->hasInternalLinkage(), true/*definition*/,
1798 Flags, CGM.getLangOptions().Optimize, Fn,
1799 TParamsArray, SPDecl);
1801 // Push function on region stack.
1802 llvm::MDNode *SPN = SP;
1803 LexicalBlockStack.push_back(SPN);
1804 RegionMap[D] = llvm::WeakVH(SP);
1807 /// EmitLocation - Emit metadata to indicate a change in line/column
1808 /// information in the source file.
1809 void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
1811 // Update our current location
1814 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
1816 // Don't bother if things are the same as last time.
1817 SourceManager &SM = CGM.getContext().getSourceManager();
1818 if (CurLoc == PrevLoc ||
1819 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
1820 // New Builder may not be in sync with CGDebugInfo.
1821 if (!Builder.getCurrentDebugLocation().isUnknown())
1824 // Update last state.
1827 llvm::MDNode *Scope = LexicalBlockStack.back();
1828 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
1829 getColumnNumber(CurLoc),
1833 /// CreateLexicalBlock - Creates a new lexical block node and pushes it on
1835 void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
1836 llvm::DIDescriptor D =
1837 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
1838 llvm::DIDescriptor() :
1839 llvm::DIDescriptor(LexicalBlockStack.back()),
1840 getOrCreateFile(CurLoc),
1841 getLineNumber(CurLoc),
1842 getColumnNumber(CurLoc));
1843 llvm::MDNode *DN = D;
1844 LexicalBlockStack.push_back(DN);
1847 /// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
1848 /// region - beginning of a DW_TAG_lexical_block.
1849 void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
1850 // Set our current location.
1853 // Create a new lexical block and push it on the stack.
1854 CreateLexicalBlock(Loc);
1856 // Emit a line table change for the current location inside the new scope.
1857 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
1858 getColumnNumber(Loc),
1859 LexicalBlockStack.back()));
1862 /// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
1863 /// region - end of a DW_TAG_lexical_block.
1864 void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
1865 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1867 // Provide an entry in the line table for the end of the block.
1868 EmitLocation(Builder, Loc);
1870 LexicalBlockStack.pop_back();
1873 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1874 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
1875 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1876 unsigned RCount = FnBeginRegionCount.back();
1877 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
1879 // Pop all regions for this function.
1880 while (LexicalBlockStack.size() != RCount)
1881 EmitLexicalBlockEnd(Builder, CurLoc);
1882 FnBeginRegionCount.pop_back();
1885 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1886 // See BuildByRefType.
1887 llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl *VD,
1888 uint64_t *XOffset) {
1890 SmallVector<llvm::Value *, 5> EltTys;
1892 uint64_t FieldSize, FieldOffset;
1893 unsigned FieldAlign;
1895 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1896 QualType Type = VD->getType();
1899 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1900 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
1901 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
1902 FType = CGM.getContext().IntTy;
1903 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
1904 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
1906 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type);
1907 if (HasCopyAndDispose) {
1908 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
1909 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
1911 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
1915 CharUnits Align = CGM.getContext().getDeclAlign(VD);
1916 if (Align > CGM.getContext().toCharUnitsFromBits(
1917 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
1918 CharUnits FieldOffsetInBytes
1919 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
1920 CharUnits AlignedOffsetInBytes
1921 = FieldOffsetInBytes.RoundUpToAlignment(Align);
1922 CharUnits NumPaddingBytes
1923 = AlignedOffsetInBytes - FieldOffsetInBytes;
1925 if (NumPaddingBytes.isPositive()) {
1926 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
1927 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
1928 pad, ArrayType::Normal, 0);
1929 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
1934 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
1935 FieldSize = CGM.getContext().getTypeSize(FType);
1936 FieldAlign = CGM.getContext().toBits(Align);
1938 *XOffset = FieldOffset;
1939 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
1940 0, FieldSize, FieldAlign,
1941 FieldOffset, 0, FieldTy);
1942 EltTys.push_back(FieldTy);
1943 FieldOffset += FieldSize;
1945 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1947 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
1949 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
1953 /// EmitDeclare - Emit local variable declaration debug info.
1954 void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
1955 llvm::Value *Storage,
1956 unsigned ArgNo, CGBuilderTy &Builder) {
1957 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
1959 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
1961 uint64_t XOffset = 0;
1962 if (VD->hasAttr<BlocksAttr>())
1963 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
1965 Ty = getOrCreateType(VD->getType(), Unit);
1967 // If there is not any debug info for type then do not emit debug info
1968 // for this variable.
1972 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
1973 // If Storage is an aggregate returned as 'sret' then let debugger know
1975 if (Arg->hasStructRetAttr())
1976 Ty = DBuilder.createReferenceType(Ty);
1977 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
1978 // If an aggregate variable has non trivial destructor or non trivial copy
1979 // constructor than it is pass indirectly. Let debug info know about this
1980 // by using reference of the aggregate type as a argument type.
1981 if (!Record->hasTrivialCopyConstructor() ||
1982 !Record->hasTrivialDestructor())
1983 Ty = DBuilder.createReferenceType(Ty);
1987 // Get location information.
1988 unsigned Line = getLineNumber(VD->getLocation());
1989 unsigned Column = getColumnNumber(VD->getLocation());
1991 if (VD->isImplicit())
1992 Flags |= llvm::DIDescriptor::FlagArtificial;
1993 llvm::MDNode *Scope = LexicalBlockStack.back();
1995 StringRef Name = VD->getName();
1996 if (!Name.empty()) {
1997 if (VD->hasAttr<BlocksAttr>()) {
1998 CharUnits offset = CharUnits::fromQuantity(32);
1999 SmallVector<llvm::Value *, 9> addr;
2000 llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2001 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2002 // offset of __forwarding field
2003 offset = CGM.getContext().toCharUnitsFromBits(
2004 CGM.getContext().getTargetInfo().getPointerWidth(0));
2005 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2006 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2007 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2008 // offset of x field
2009 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2010 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2012 // Create the descriptor for the variable.
2013 llvm::DIVariable D =
2014 DBuilder.createComplexVariable(Tag,
2015 llvm::DIDescriptor(Scope),
2016 VD->getName(), Unit, Line, Ty,
2019 // Insert an llvm.dbg.declare into the current block.
2020 // Insert an llvm.dbg.declare into the current block.
2021 llvm::Instruction *Call =
2022 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2023 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2026 // Create the descriptor for the variable.
2027 llvm::DIVariable D =
2028 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2029 Name, Unit, Line, Ty,
2030 CGM.getLangOptions().Optimize, Flags, ArgNo);
2032 // Insert an llvm.dbg.declare into the current block.
2033 llvm::Instruction *Call =
2034 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2035 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2039 // If VD is an anonymous union then Storage represents value for
2040 // all union fields.
2041 if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2042 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
2043 if (RD->isUnion()) {
2044 for (RecordDecl::field_iterator I = RD->field_begin(),
2045 E = RD->field_end();
2047 FieldDecl *Field = *I;
2048 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2049 StringRef FieldName = Field->getName();
2051 // Ignore unnamed fields. Do not ignore unnamed records.
2052 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2055 // Use VarDecl's Tag, Scope and Line number.
2056 llvm::DIVariable D =
2057 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2058 FieldName, Unit, Line, FieldTy,
2059 CGM.getLangOptions().Optimize, Flags,
2062 // Insert an llvm.dbg.declare into the current block.
2063 llvm::Instruction *Call =
2064 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2065 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2071 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2072 llvm::Value *Storage,
2073 CGBuilderTy &Builder) {
2074 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2077 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
2078 const VarDecl *VD, llvm::Value *Storage, CGBuilderTy &Builder,
2079 const CGBlockInfo &blockInfo) {
2080 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2082 if (Builder.GetInsertBlock() == 0)
2085 bool isByRef = VD->hasAttr<BlocksAttr>();
2087 uint64_t XOffset = 0;
2088 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2091 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2093 Ty = getOrCreateType(VD->getType(), Unit);
2095 // Get location information.
2096 unsigned Line = getLineNumber(VD->getLocation());
2097 unsigned Column = getColumnNumber(VD->getLocation());
2099 const llvm::TargetData &target = CGM.getTargetData();
2101 CharUnits offset = CharUnits::fromQuantity(
2102 target.getStructLayout(blockInfo.StructureType)
2103 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2105 SmallVector<llvm::Value *, 9> addr;
2106 llvm::Type *Int64Ty = llvm::Type::getInt64Ty(CGM.getLLVMContext());
2107 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2108 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2110 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2111 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2112 // offset of __forwarding field
2113 offset = CGM.getContext()
2114 .toCharUnitsFromBits(target.getPointerSizeInBits());
2115 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2116 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2117 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2118 // offset of x field
2119 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2120 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2123 // Create the descriptor for the variable.
2124 llvm::DIVariable D =
2125 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2126 llvm::DIDescriptor(LexicalBlockStack.back()),
2127 VD->getName(), Unit, Line, Ty, addr);
2128 // Insert an llvm.dbg.declare into the current block.
2129 llvm::Instruction *Call =
2130 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2131 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2132 LexicalBlockStack.back()));
2135 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2136 /// variable declaration.
2137 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2139 CGBuilderTy &Builder) {
2140 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2144 struct BlockLayoutChunk {
2145 uint64_t OffsetInBits;
2146 const BlockDecl::Capture *Capture;
2148 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2149 return l.OffsetInBits < r.OffsetInBits;
2153 void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2155 CGBuilderTy &Builder) {
2156 ASTContext &C = CGM.getContext();
2157 const BlockDecl *blockDecl = block.getBlockDecl();
2159 // Collect some general information about the block's location.
2160 SourceLocation loc = blockDecl->getCaretLocation();
2161 llvm::DIFile tunit = getOrCreateFile(loc);
2162 unsigned line = getLineNumber(loc);
2163 unsigned column = getColumnNumber(loc);
2165 // Build the debug-info type for the block literal.
2166 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2168 const llvm::StructLayout *blockLayout =
2169 CGM.getTargetData().getStructLayout(block.StructureType);
2171 SmallVector<llvm::Value*, 16> fields;
2172 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2173 blockLayout->getElementOffsetInBits(0),
2175 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2176 blockLayout->getElementOffsetInBits(1),
2178 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2179 blockLayout->getElementOffsetInBits(2),
2181 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2182 blockLayout->getElementOffsetInBits(3),
2184 fields.push_back(createFieldType("__descriptor",
2185 C.getPointerType(block.NeedsCopyDispose ?
2186 C.getBlockDescriptorExtendedType() :
2187 C.getBlockDescriptorType()),
2189 blockLayout->getElementOffsetInBits(4),
2192 // We want to sort the captures by offset, not because DWARF
2193 // requires this, but because we're paranoid about debuggers.
2194 SmallVector<BlockLayoutChunk, 8> chunks;
2197 if (blockDecl->capturesCXXThis()) {
2198 BlockLayoutChunk chunk;
2199 chunk.OffsetInBits =
2200 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2202 chunks.push_back(chunk);
2205 // Variable captures.
2206 for (BlockDecl::capture_const_iterator
2207 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2209 const BlockDecl::Capture &capture = *i;
2210 const VarDecl *variable = capture.getVariable();
2211 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2213 // Ignore constant captures.
2214 if (captureInfo.isConstant())
2217 BlockLayoutChunk chunk;
2218 chunk.OffsetInBits =
2219 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2220 chunk.Capture = &capture;
2221 chunks.push_back(chunk);
2225 llvm::array_pod_sort(chunks.begin(), chunks.end());
2227 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2228 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2229 uint64_t offsetInBits = i->OffsetInBits;
2230 const BlockDecl::Capture *capture = i->Capture;
2232 // If we have a null capture, this must be the C++ 'this' capture.
2234 const CXXMethodDecl *method =
2235 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2236 QualType type = method->getThisType(C);
2238 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2239 offsetInBits, tunit, tunit));
2243 const VarDecl *variable = capture->getVariable();
2244 StringRef name = variable->getName();
2246 llvm::DIType fieldType;
2247 if (capture->isByRef()) {
2248 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2250 // FIXME: this creates a second copy of this type!
2252 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2253 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2254 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2255 ptrInfo.first, ptrInfo.second,
2256 offsetInBits, 0, fieldType);
2258 fieldType = createFieldType(name, variable->getType(), 0,
2259 loc, AS_public, offsetInBits, tunit, tunit);
2261 fields.push_back(fieldType);
2264 llvm::SmallString<36> typeName;
2265 llvm::raw_svector_ostream(typeName)
2266 << "__block_literal_" << CGM.getUniqueBlockCount();
2268 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2271 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2272 CGM.getContext().toBits(block.BlockSize),
2273 CGM.getContext().toBits(block.BlockAlign),
2275 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2277 // Get overall information about the block.
2278 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2279 llvm::MDNode *scope = LexicalBlockStack.back();
2280 StringRef name = ".block_descriptor";
2282 // Create the descriptor for the parameter.
2283 llvm::DIVariable debugVar =
2284 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2285 llvm::DIDescriptor(scope),
2286 name, tunit, line, type,
2287 CGM.getLangOptions().Optimize, flags,
2288 cast<llvm::Argument>(addr)->getArgNo() + 1);
2290 // Insert an llvm.dbg.value into the current block.
2291 llvm::Instruction *declare =
2292 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2293 Builder.GetInsertBlock());
2294 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2297 /// EmitGlobalVariable - Emit information about a global variable.
2298 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2301 // Create global variable debug descriptor.
2302 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2303 unsigned LineNo = getLineNumber(D->getLocation());
2305 setLocation(D->getLocation());
2307 QualType T = D->getType();
2308 if (T->isIncompleteArrayType()) {
2310 // CodeGen turns int[] into int[1] so we'll do the same here.
2311 llvm::APSInt ConstVal(32);
2314 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2316 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2317 ArrayType::Normal, 0);
2319 StringRef DeclName = D->getName();
2320 StringRef LinkageName;
2321 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2322 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2323 LinkageName = Var->getName();
2324 if (LinkageName == DeclName)
2325 LinkageName = StringRef();
2326 llvm::DIDescriptor DContext =
2327 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2328 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2329 Unit, LineNo, getOrCreateType(T, Unit),
2330 Var->hasInternalLinkage(), Var);
2333 /// EmitGlobalVariable - Emit information about an objective-c interface.
2334 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2335 ObjCInterfaceDecl *ID) {
2336 // Create global variable debug descriptor.
2337 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2338 unsigned LineNo = getLineNumber(ID->getLocation());
2340 StringRef Name = ID->getName();
2342 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2343 if (T->isIncompleteArrayType()) {
2345 // CodeGen turns int[] into int[1] so we'll do the same here.
2346 llvm::APSInt ConstVal(32);
2349 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2351 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2352 ArrayType::Normal, 0);
2355 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2356 getOrCreateType(T, Unit),
2357 Var->hasInternalLinkage(), Var);
2360 /// EmitGlobalVariable - Emit global variable's debug info.
2361 void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2362 llvm::Constant *Init) {
2363 // Create the descriptor for the variable.
2364 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2365 StringRef Name = VD->getName();
2366 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2367 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2368 if (const EnumDecl *ED = dyn_cast<EnumDecl>(ECD->getDeclContext()))
2369 Ty = CreateEnumType(ED);
2371 // Do not use DIGlobalVariable for enums.
2372 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2374 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2375 getLineNumber(VD->getLocation()),
2379 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2382 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2383 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2384 NameSpaceCache.find(NSDecl);
2385 if (I != NameSpaceCache.end())
2386 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2388 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2389 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2390 llvm::DIDescriptor Context =
2391 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2392 llvm::DINameSpace NS =
2393 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2394 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2398 /// UpdateCompletedType - Update type cache because the type is now
2400 void CGDebugInfo::UpdateCompletedType(const TagDecl *TD) {
2401 QualType Ty = CGM.getContext().getTagDeclType(TD);
2403 // If the type exist in type cache then remove it from the cache.
2404 // There is no need to prepare debug info for the completed type
2405 // right now. It will be generated on demand lazily.
2406 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2407 TypeCache.find(Ty.getAsOpaquePtr());
2408 if (it != TypeCache.end())
2409 TypeCache.erase(it);