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/Path.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(RegionStack
.empty() && "Region stack mismatch, stack not empty!");
52 void CGDebugInfo::setLocation(SourceLocation Loc
) {
54 CurLoc
= CGM
.getContext().getSourceManager().getInstantiationLoc(Loc
);
57 /// getContextDescriptor - Get context info for the decl.
58 llvm::DIDescriptor
CGDebugInfo::getContextDescriptor(const Decl
*Context
) {
62 llvm::DenseMap
<const Decl
*, llvm::WeakVH
>::iterator
63 I
= RegionMap
.find(Context
);
64 if (I
!= RegionMap
.end())
65 return llvm::DIDescriptor(dyn_cast_or_null
<llvm::MDNode
>(&*I
->second
));
68 if (const NamespaceDecl
*NSDecl
= dyn_cast
<NamespaceDecl
>(Context
))
69 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl
));
71 if (const RecordDecl
*RDecl
= dyn_cast
<RecordDecl
>(Context
)) {
72 if (!RDecl
->isDependentType()) {
73 llvm::DIType Ty
= getOrCreateType(CGM
.getContext().getTypeDeclType(RDecl
),
74 getOrCreateMainFile());
75 return llvm::DIDescriptor(Ty
);
81 /// getFunctionName - Get function name for the given FunctionDecl. If the
82 /// name is constructred on demand (e.g. C++ destructor) then the name
83 /// is stored on the side.
84 llvm::StringRef
CGDebugInfo::getFunctionName(const FunctionDecl
*FD
) {
85 assert (FD
&& "Invalid FunctionDecl!");
86 IdentifierInfo
*FII
= FD
->getIdentifier();
88 return FII
->getName();
90 // Otherwise construct human readable name for debug info.
91 std::string NS
= FD
->getNameAsString();
93 // Copy this name on the side and use its reference.
94 char *StrPtr
= DebugInfoNames
.Allocate
<char>(NS
.length());
95 memcpy(StrPtr
, NS
.data(), NS
.length());
96 return llvm::StringRef(StrPtr
, NS
.length());
99 llvm::StringRef
CGDebugInfo::getObjCMethodName(const ObjCMethodDecl
*OMD
) {
100 llvm::SmallString
<256> MethodName
;
101 llvm::raw_svector_ostream
OS(MethodName
);
102 OS
<< (OMD
->isInstanceMethod() ? '-' : '+') << '[';
103 const DeclContext
*DC
= OMD
->getDeclContext();
104 if (const ObjCImplementationDecl
*OID
=
105 dyn_cast
<const ObjCImplementationDecl
>(DC
)) {
106 OS
<< OID
->getName();
107 } else if (const ObjCInterfaceDecl
*OID
=
108 dyn_cast
<const ObjCInterfaceDecl
>(DC
)) {
109 OS
<< OID
->getName();
110 } else if (const ObjCCategoryImplDecl
*OCD
=
111 dyn_cast
<const ObjCCategoryImplDecl
>(DC
)){
112 OS
<< ((NamedDecl
*)OCD
)->getIdentifier()->getNameStart() << '(' <<
113 OCD
->getIdentifier()->getNameStart() << ')';
115 OS
<< ' ' << OMD
->getSelector().getAsString() << ']';
117 char *StrPtr
= DebugInfoNames
.Allocate
<char>(OS
.tell());
118 memcpy(StrPtr
, MethodName
.begin(), OS
.tell());
119 return llvm::StringRef(StrPtr
, OS
.tell());
122 /// getClassName - Get class name including template argument list.
124 CGDebugInfo::getClassName(RecordDecl
*RD
) {
125 ClassTemplateSpecializationDecl
*Spec
126 = dyn_cast
<ClassTemplateSpecializationDecl
>(RD
);
128 return RD
->getName();
130 const TemplateArgument
*Args
;
133 if (TypeSourceInfo
*TAW
= Spec
->getTypeAsWritten()) {
134 const TemplateSpecializationType
*TST
=
135 cast
<TemplateSpecializationType
>(TAW
->getType());
136 Args
= TST
->getArgs();
137 NumArgs
= TST
->getNumArgs();
139 const TemplateArgumentList
&TemplateArgs
= Spec
->getTemplateArgs();
140 Args
= TemplateArgs
.data();
141 NumArgs
= TemplateArgs
.size();
143 Buffer
= RD
->getIdentifier()->getNameStart();
144 PrintingPolicy
Policy(CGM
.getLangOptions());
145 Buffer
+= TemplateSpecializationType::PrintTemplateArgumentList(Args
,
149 // Copy this name on the side and use its reference.
150 char *StrPtr
= DebugInfoNames
.Allocate
<char>(Buffer
.length());
151 memcpy(StrPtr
, Buffer
.data(), Buffer
.length());
152 return llvm::StringRef(StrPtr
, Buffer
.length());
155 /// getOrCreateFile - Get the file debug info descriptor for the input location.
156 llvm::DIFile
CGDebugInfo::getOrCreateFile(SourceLocation Loc
) {
158 // If Location is not valid then use main input file.
159 return DBuilder
.CreateFile(TheCU
.getFilename(), TheCU
.getDirectory());
161 SourceManager
&SM
= CGM
.getContext().getSourceManager();
162 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
);
164 if (PLoc
.isInvalid() || llvm::StringRef(PLoc
.getFilename()).empty())
165 // If the location is not valid then use main input file.
166 return DBuilder
.CreateFile(TheCU
.getFilename(), TheCU
.getDirectory());
168 // Cache the results.
169 const char *fname
= PLoc
.getFilename();
170 llvm::DenseMap
<const char *, llvm::WeakVH
>::iterator it
=
171 DIFileCache
.find(fname
);
173 if (it
!= DIFileCache
.end()) {
174 // Verify that the information still exists.
176 return llvm::DIFile(cast
<llvm::MDNode
>(it
->second
));
179 llvm::DIFile F
= DBuilder
.CreateFile(PLoc
.getFilename(), getCurrentDirname());
181 DIFileCache
[fname
] = F
;
186 /// getOrCreateMainFile - Get the file info for main compile unit.
187 llvm::DIFile
CGDebugInfo::getOrCreateMainFile() {
188 return DBuilder
.CreateFile(TheCU
.getFilename(), TheCU
.getDirectory());
191 /// getLineNumber - Get line number for the location. If location is invalid
192 /// then use current location.
193 unsigned CGDebugInfo::getLineNumber(SourceLocation Loc
) {
194 assert (CurLoc
.isValid() && "Invalid current location!");
195 SourceManager
&SM
= CGM
.getContext().getSourceManager();
196 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
.isValid() ? Loc
: CurLoc
);
197 return PLoc
.isValid()? PLoc
.getLine() : 0;
200 /// getColumnNumber - Get column number for the location. If location is
201 /// invalid then use current location.
202 unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc
) {
203 assert (CurLoc
.isValid() && "Invalid current location!");
204 SourceManager
&SM
= CGM
.getContext().getSourceManager();
205 PresumedLoc PLoc
= SM
.getPresumedLoc(Loc
.isValid() ? Loc
: CurLoc
);
206 return PLoc
.isValid()? PLoc
.getColumn() : 0;
209 llvm::StringRef
CGDebugInfo::getCurrentDirname() {
210 if (!CWDName
.empty())
212 char *CompDirnamePtr
= NULL
;
213 llvm::sys::Path CWD
= llvm::sys::Path::GetCurrentDirectory();
214 CompDirnamePtr
= DebugInfoNames
.Allocate
<char>(CWD
.size());
215 memcpy(CompDirnamePtr
, CWD
.c_str(), CWD
.size());
216 return CWDName
= llvm::StringRef(CompDirnamePtr
, CWD
.size());
219 /// CreateCompileUnit - Create new compile unit.
220 void CGDebugInfo::CreateCompileUnit() {
222 // Get absolute path name.
223 SourceManager
&SM
= CGM
.getContext().getSourceManager();
224 std::string MainFileName
= CGM
.getCodeGenOpts().MainFileName
;
225 if (MainFileName
.empty())
226 MainFileName
= "<unknown>";
228 // The main file name provided via the "-main-file-name" option contains just
229 // the file name itself with no path information. This file name may have had
230 // a relative path, so we look into the actual file entry for the main
231 // file to determine the real absolute path for the file.
232 std::string MainFileDir
;
233 if (const FileEntry
*MainFile
= SM
.getFileEntryForID(SM
.getMainFileID())) {
234 MainFileDir
= MainFile
->getDir()->getName();
235 if (MainFileDir
!= ".")
236 MainFileName
= MainFileDir
+ "/" + MainFileName
;
239 // Save filename string.
240 char *FilenamePtr
= DebugInfoNames
.Allocate
<char>(MainFileName
.length());
241 memcpy(FilenamePtr
, MainFileName
.c_str(), MainFileName
.length());
242 llvm::StringRef
Filename(FilenamePtr
, MainFileName
.length());
245 const LangOptions
&LO
= CGM
.getLangOptions();
248 LangTag
= llvm::dwarf::DW_LANG_ObjC_plus_plus
;
250 LangTag
= llvm::dwarf::DW_LANG_C_plus_plus
;
251 } else if (LO
.ObjC1
) {
252 LangTag
= llvm::dwarf::DW_LANG_ObjC
;
254 LangTag
= llvm::dwarf::DW_LANG_C99
;
256 LangTag
= llvm::dwarf::DW_LANG_C89
;
259 std::string Producer
= getClangFullVersion();
261 // Figure out which version of the ObjC runtime we have.
262 unsigned RuntimeVers
= 0;
264 RuntimeVers
= LO
.ObjCNonFragileABI
? 2 : 1;
266 // Create new compile unit.
267 DBuilder
.CreateCompileUnit(
268 LangTag
, Filename
, getCurrentDirname(),
270 LO
.Optimize
, CGM
.getCodeGenOpts().DwarfDebugFlags
, RuntimeVers
);
271 // FIXME - Eliminate TheCU.
272 TheCU
= llvm::DICompileUnit(DBuilder
.getCU());
275 /// CreateType - Get the Basic type from the cache or create a new
276 /// one if necessary.
277 llvm::DIType
CGDebugInfo::CreateType(const BuiltinType
*BT
) {
278 unsigned Encoding
= 0;
279 const char *BTName
= NULL
;
280 switch (BT
->getKind()) {
282 case BuiltinType::Void
:
283 return llvm::DIType();
284 case BuiltinType::ObjCClass
:
285 return DBuilder
.CreateStructType(TheCU
, "objc_class",
286 getOrCreateMainFile(), 0, 0, 0,
287 llvm::DIDescriptor::FlagFwdDecl
,
289 case BuiltinType::ObjCId
: {
290 // typedef struct objc_class *Class;
291 // typedef struct objc_object {
296 DBuilder
.CreateStructType(TheCU
, "objc_class",
297 getOrCreateMainFile(), 0, 0, 0,
298 llvm::DIDescriptor::FlagFwdDecl
,
300 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
302 llvm::DIType ISATy
= DBuilder
.CreatePointerType(OCTy
, Size
);
304 llvm::SmallVector
<llvm::Value
*, 16> EltTys
;
305 llvm::DIType FieldTy
=
306 DBuilder
.CreateMemberType("isa", getOrCreateMainFile(),
307 0,Size
, 0, 0, 0, ISATy
);
308 EltTys
.push_back(FieldTy
);
309 llvm::DIArray Elements
=
310 DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
312 return DBuilder
.CreateStructType(TheCU
, "objc_object",
313 getOrCreateMainFile(),
314 0, 0, 0, 0, Elements
);
316 case BuiltinType::ObjCSel
: {
317 return DBuilder
.CreateStructType(TheCU
, "objc_selector",
318 getOrCreateMainFile(), 0, 0, 0,
319 llvm::DIDescriptor::FlagFwdDecl
,
322 case BuiltinType::UChar
:
323 case BuiltinType::Char_U
: Encoding
= llvm::dwarf::DW_ATE_unsigned_char
; break;
324 case BuiltinType::Char_S
:
325 case BuiltinType::SChar
: Encoding
= llvm::dwarf::DW_ATE_signed_char
; break;
326 case BuiltinType::UShort
:
327 case BuiltinType::UInt
:
328 case BuiltinType::ULong
:
329 case BuiltinType::ULongLong
: Encoding
= llvm::dwarf::DW_ATE_unsigned
; break;
330 case BuiltinType::Short
:
331 case BuiltinType::Int
:
332 case BuiltinType::Long
:
333 case BuiltinType::LongLong
: Encoding
= llvm::dwarf::DW_ATE_signed
; break;
334 case BuiltinType::Bool
: Encoding
= llvm::dwarf::DW_ATE_boolean
; break;
335 case BuiltinType::Float
:
336 case BuiltinType::LongDouble
:
337 case BuiltinType::Double
: Encoding
= llvm::dwarf::DW_ATE_float
; break;
340 switch (BT
->getKind()) {
341 case BuiltinType::Long
: BTName
= "long int"; break;
342 case BuiltinType::LongLong
: BTName
= "long long int"; break;
343 case BuiltinType::ULong
: BTName
= "long unsigned int"; break;
344 case BuiltinType::ULongLong
: BTName
= "long long unsigned int"; break;
346 BTName
= BT
->getName(CGM
.getContext().getLangOptions());
349 // Bit size, align and offset of the type.
350 uint64_t Size
= CGM
.getContext().getTypeSize(BT
);
351 uint64_t Align
= CGM
.getContext().getTypeAlign(BT
);
353 DBuilder
.CreateBasicType(BTName
, Size
, Align
, Encoding
);
357 llvm::DIType
CGDebugInfo::CreateType(const ComplexType
*Ty
) {
358 // Bit size, align and offset of the type.
359 unsigned Encoding
= llvm::dwarf::DW_ATE_complex_float
;
360 if (Ty
->isComplexIntegerType())
361 Encoding
= llvm::dwarf::DW_ATE_lo_user
;
363 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
364 uint64_t Align
= CGM
.getContext().getTypeAlign(Ty
);
366 DBuilder
.CreateBasicType("complex", Size
, Align
, Encoding
);
371 /// CreateCVRType - Get the qualified type from the cache or create
372 /// a new one if necessary.
373 llvm::DIType
CGDebugInfo::CreateQualifiedType(QualType Ty
, llvm::DIFile Unit
) {
374 QualifierCollector Qc
;
375 const Type
*T
= Qc
.strip(Ty
);
377 // Ignore these qualifiers for now.
378 Qc
.removeObjCGCAttr();
379 Qc
.removeAddressSpace();
381 // We will create one Derived type for one qualifier and recurse to handle any
385 Tag
= llvm::dwarf::DW_TAG_const_type
;
387 } else if (Qc
.hasVolatile()) {
388 Tag
= llvm::dwarf::DW_TAG_volatile_type
;
390 } else if (Qc
.hasRestrict()) {
391 Tag
= llvm::dwarf::DW_TAG_restrict_type
;
394 assert(Qc
.empty() && "Unknown type qualifier for debug info");
395 return getOrCreateType(QualType(T
, 0), Unit
);
398 llvm::DIType FromTy
= getOrCreateType(Qc
.apply(CGM
.getContext(), T
), Unit
);
400 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
401 // CVR derived types.
402 llvm::DIType DbgTy
= DBuilder
.CreateQualifiedType(Tag
, FromTy
);
407 llvm::DIType
CGDebugInfo::CreateType(const ObjCObjectPointerType
*Ty
,
410 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
411 Ty
->getPointeeType(), Unit
);
415 llvm::DIType
CGDebugInfo::CreateType(const PointerType
*Ty
,
417 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type
, Ty
,
418 Ty
->getPointeeType(), Unit
);
421 /// CreatePointeeType - Create PointTee type. If Pointee is a record
422 /// then emit record's fwd if debug info size reduction is enabled.
423 llvm::DIType
CGDebugInfo::CreatePointeeType(QualType PointeeTy
,
425 if (!CGM
.getCodeGenOpts().LimitDebugInfo
)
426 return getOrCreateType(PointeeTy
, Unit
);
428 if (const RecordType
*RTy
= dyn_cast
<RecordType
>(PointeeTy
)) {
429 RecordDecl
*RD
= RTy
->getDecl();
430 llvm::DIFile DefUnit
= getOrCreateFile(RD
->getLocation());
431 unsigned Line
= getLineNumber(RD
->getLocation());
432 llvm::DIDescriptor FDContext
=
433 getContextDescriptor(dyn_cast
<Decl
>(RD
->getDeclContext()));
436 return DBuilder
.CreateStructType(FDContext
, RD
->getName(), DefUnit
,
437 Line
, 0, 0, llvm::DIType::FlagFwdDecl
,
439 else if (RD
->isUnion())
440 return DBuilder
.CreateUnionType(FDContext
, RD
->getName(), DefUnit
,
441 Line
, 0, 0, llvm::DIType::FlagFwdDecl
,
444 assert(RD
->isClass() && "Unknown RecordType!");
445 return DBuilder
.CreateClassType(FDContext
, RD
->getName(), DefUnit
,
446 Line
, 0, 0, 0, llvm::DIType::FlagFwdDecl
,
447 llvm::DIType(), llvm::DIArray());
450 return getOrCreateType(PointeeTy
, Unit
);
454 llvm::DIType
CGDebugInfo::CreatePointerLikeType(unsigned Tag
,
459 if (Tag
== llvm::dwarf::DW_TAG_reference_type
)
460 return DBuilder
.CreateReferenceType(CreatePointeeType(PointeeTy
, Unit
));
462 // Bit size, align and offset of the type.
463 // Size is always the size of a pointer. We can't use getTypeSize here
464 // because that does not return the correct value for references.
466 CGM
.getContext().Target
.getPointerWidth(PointeeTy
.getAddressSpace());
467 uint64_t Align
= CGM
.getContext().getTypeAlign(Ty
);
470 DBuilder
.CreatePointerType(CreatePointeeType(PointeeTy
, Unit
), Size
, Align
);
473 llvm::DIType
CGDebugInfo::CreateType(const BlockPointerType
*Ty
,
475 if (BlockLiteralGenericSet
)
476 return BlockLiteralGeneric
;
478 llvm::SmallVector
<llvm::Value
*, 8> EltTys
;
479 llvm::DIType FieldTy
;
481 uint64_t FieldSize
, FieldOffset
;
483 llvm::DIArray Elements
;
484 llvm::DIType EltTy
, DescTy
;
487 FType
= CGM
.getContext().UnsignedLongTy
;
488 EltTys
.push_back(CreateMemberType(Unit
, FType
, "reserved", &FieldOffset
));
489 EltTys
.push_back(CreateMemberType(Unit
, FType
, "Size", &FieldOffset
));
491 Elements
= DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
494 unsigned Flags
= llvm::DIDescriptor::FlagAppleBlock
;
495 unsigned LineNo
= getLineNumber(CurLoc
);
497 EltTy
= DBuilder
.CreateStructType(Unit
, "__block_descriptor",
498 Unit
, LineNo
, FieldOffset
, 0,
501 // Bit size, align and offset of the type.
502 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
504 DescTy
= DBuilder
.CreatePointerType(EltTy
, Size
);
507 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
508 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
509 FType
= CGM
.getContext().IntTy
;
510 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
511 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__reserved", &FieldOffset
));
512 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
513 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__FuncPtr", &FieldOffset
));
515 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
517 FieldSize
= CGM
.getContext().getTypeSize(Ty
);
518 FieldAlign
= CGM
.getContext().getTypeAlign(Ty
);
519 FieldTy
= DBuilder
.CreateMemberType("__descriptor", Unit
,
520 LineNo
, FieldSize
, FieldAlign
,
521 FieldOffset
, 0, FieldTy
);
522 EltTys
.push_back(FieldTy
);
524 FieldOffset
+= FieldSize
;
525 Elements
= DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
527 EltTy
= DBuilder
.CreateStructType(Unit
, "__block_literal_generic",
528 Unit
, LineNo
, FieldOffset
, 0,
531 BlockLiteralGenericSet
= true;
532 BlockLiteralGeneric
= DBuilder
.CreatePointerType(EltTy
, Size
);
533 return BlockLiteralGeneric
;
536 llvm::DIType
CGDebugInfo::CreateType(const TypedefType
*Ty
,
538 // Typedefs are derived from some other type. If we have a typedef of a
539 // typedef, make sure to emit the whole chain.
540 llvm::DIType Src
= getOrCreateType(Ty
->getDecl()->getUnderlyingType(), Unit
);
542 return llvm::DIType();
543 // We don't set size information, but do specify where the typedef was
545 unsigned Line
= getLineNumber(Ty
->getDecl()->getLocation());
546 llvm::DIType DbgTy
= DBuilder
.CreateTypedef(Src
, Ty
->getDecl()->getName(),
551 llvm::DIType
CGDebugInfo::CreateType(const FunctionType
*Ty
,
553 llvm::SmallVector
<llvm::Value
*, 16> EltTys
;
555 // Add the result type at least.
556 EltTys
.push_back(getOrCreateType(Ty
->getResultType(), Unit
));
558 // Set up remainder of arguments if there is a prototype.
559 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
560 if (isa
<FunctionNoProtoType
>(Ty
))
561 EltTys
.push_back(DBuilder
.CreateUnspecifiedParameter());
562 else if (const FunctionProtoType
*FTP
= dyn_cast
<FunctionProtoType
>(Ty
)) {
563 for (unsigned i
= 0, e
= FTP
->getNumArgs(); i
!= e
; ++i
)
564 EltTys
.push_back(getOrCreateType(FTP
->getArgType(i
), Unit
));
567 llvm::DIArray EltTypeArray
=
568 DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
570 llvm::DIType DbgTy
= DBuilder
.CreateSubroutineType(Unit
, EltTypeArray
);
574 /// CollectRecordFields - A helper function to collect debug info for
575 /// record fields. This is used while creating debug info entry for a Record.
577 CollectRecordFields(const RecordDecl
*RD
, llvm::DIFile Unit
,
578 llvm::SmallVectorImpl
<llvm::Value
*> &EltTys
) {
579 unsigned FieldNo
= 0;
580 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
581 for (RecordDecl::field_iterator I
= RD
->field_begin(),
583 I
!= E
; ++I
, ++FieldNo
) {
584 FieldDecl
*Field
= *I
;
585 llvm::DIType FieldTy
= getOrCreateType(Field
->getType(), Unit
);
586 llvm::StringRef FieldName
= Field
->getName();
588 // Ignore unnamed fields. Do not ignore unnamed records.
589 if (FieldName
.empty() && !isa
<RecordType
>(Field
->getType()))
592 // Get the location for the field.
593 llvm::DIFile FieldDefUnit
= getOrCreateFile(Field
->getLocation());
594 unsigned FieldLine
= getLineNumber(Field
->getLocation());
595 QualType FType
= Field
->getType();
596 uint64_t FieldSize
= 0;
597 unsigned FieldAlign
= 0;
598 if (!FType
->isIncompleteArrayType()) {
600 // Bit size, align and offset of the type.
601 FieldSize
= CGM
.getContext().getTypeSize(FType
);
602 Expr
*BitWidth
= Field
->getBitWidth();
604 FieldSize
= BitWidth
->EvaluateAsInt(CGM
.getContext()).getZExtValue();
605 FieldAlign
= CGM
.getContext().getTypeAlign(FType
);
608 uint64_t FieldOffset
= RL
.getFieldOffset(FieldNo
);
611 AccessSpecifier Access
= I
->getAccess();
612 if (Access
== clang::AS_private
)
613 Flags
|= llvm::DIDescriptor::FlagPrivate
;
614 else if (Access
== clang::AS_protected
)
615 Flags
|= llvm::DIDescriptor::FlagProtected
;
617 FieldTy
= DBuilder
.CreateMemberType(FieldName
, FieldDefUnit
,
618 FieldLine
, FieldSize
, FieldAlign
,
619 FieldOffset
, Flags
, FieldTy
);
620 EltTys
.push_back(FieldTy
);
624 /// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
625 /// function type is not updated to include implicit "this" pointer. Use this
626 /// routine to get a method type which includes "this" pointer.
628 CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl
*Method
,
631 = getOrCreateType(QualType(Method
->getType()->getAs
<FunctionProtoType
>(),
635 // Add "this" pointer.
637 llvm::DIArray Args
= llvm::DICompositeType(FnTy
).getTypeArray();
638 assert (Args
.getNumElements() && "Invalid number of arguments!");
640 llvm::SmallVector
<llvm::Value
*, 16> Elts
;
642 // First element is always return type. For 'void' functions it is NULL.
643 Elts
.push_back(Args
.getElement(0));
645 if (!Method
->isStatic())
647 // "this" pointer is always first argument.
648 ASTContext
&Context
= CGM
.getContext();
650 Context
.getPointerType(Context
.getTagDeclType(Method
->getParent()));
651 llvm::DIType ThisPtrType
=
652 DBuilder
.CreateArtificialType(getOrCreateType(ThisPtr
, Unit
));
654 TypeCache
[ThisPtr
.getAsOpaquePtr()] = ThisPtrType
;
655 Elts
.push_back(ThisPtrType
);
658 // Copy rest of the arguments.
659 for (unsigned i
= 1, e
= Args
.getNumElements(); i
!= e
; ++i
)
660 Elts
.push_back(Args
.getElement(i
));
662 llvm::DIArray EltTypeArray
=
663 DBuilder
.GetOrCreateArray(Elts
.data(), Elts
.size());
665 return DBuilder
.CreateSubroutineType(Unit
, EltTypeArray
);
668 /// isFunctionLocalClass - Return true if CXXRecordDecl is defined
669 /// inside a function.
670 static bool isFunctionLocalClass(const CXXRecordDecl
*RD
) {
671 if (const CXXRecordDecl
*NRD
=
672 dyn_cast
<CXXRecordDecl
>(RD
->getDeclContext()))
673 return isFunctionLocalClass(NRD
);
674 else if (isa
<FunctionDecl
>(RD
->getDeclContext()))
679 /// CreateCXXMemberFunction - A helper function to create a DISubprogram for
680 /// a single member function GlobalDecl.
682 CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl
*Method
,
684 llvm::DIType RecordTy
) {
686 isa
<CXXConstructorDecl
>(Method
) || isa
<CXXDestructorDecl
>(Method
);
688 llvm::StringRef MethodName
= getFunctionName(Method
);
689 llvm::DIType MethodTy
= getOrCreateMethodType(Method
, Unit
);
691 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
692 // make sense to give a single ctor/dtor a linkage name.
693 llvm::StringRef MethodLinkageName
;
694 if (!IsCtorOrDtor
&& !isFunctionLocalClass(Method
->getParent()))
695 MethodLinkageName
= CGM
.getMangledName(Method
);
697 // Get the location for the method.
698 llvm::DIFile MethodDefUnit
= getOrCreateFile(Method
->getLocation());
699 unsigned MethodLine
= getLineNumber(Method
->getLocation());
701 // Collect virtual method info.
702 llvm::DIType ContainingType
;
703 unsigned Virtuality
= 0;
706 if (Method
->isVirtual()) {
707 if (Method
->isPure())
708 Virtuality
= llvm::dwarf::DW_VIRTUALITY_pure_virtual
;
710 Virtuality
= llvm::dwarf::DW_VIRTUALITY_virtual
;
712 // It doesn't make sense to give a virtual destructor a vtable index,
713 // since a single destructor has two entries in the vtable.
714 if (!isa
<CXXDestructorDecl
>(Method
))
715 VIndex
= CGM
.getVTables().getMethodVTableIndex(Method
);
716 ContainingType
= RecordTy
;
720 if (Method
->isImplicit())
721 Flags
|= llvm::DIDescriptor::FlagArtificial
;
722 AccessSpecifier Access
= Method
->getAccess();
723 if (Access
== clang::AS_private
)
724 Flags
|= llvm::DIDescriptor::FlagPrivate
;
725 else if (Access
== clang::AS_protected
)
726 Flags
|= llvm::DIDescriptor::FlagProtected
;
727 if (const CXXConstructorDecl
*CXXC
= dyn_cast
<CXXConstructorDecl
>(Method
)) {
728 if (CXXC
->isExplicit())
729 Flags
|= llvm::DIDescriptor::FlagExplicit
;
730 } else if (const CXXConversionDecl
*CXXC
=
731 dyn_cast
<CXXConversionDecl
>(Method
)) {
732 if (CXXC
->isExplicit())
733 Flags
|= llvm::DIDescriptor::FlagExplicit
;
735 if (Method
->hasPrototype())
736 Flags
|= llvm::DIDescriptor::FlagPrototyped
;
738 llvm::DISubprogram SP
=
739 DBuilder
.CreateMethod(RecordTy
, MethodName
, MethodLinkageName
,
740 MethodDefUnit
, MethodLine
,
741 MethodTy
, /*isLocalToUnit=*/false,
742 /* isDefinition=*/ false,
743 Virtuality
, VIndex
, ContainingType
,
744 Flags
, CGM
.getLangOptions().Optimize
);
746 // Don't cache ctors or dtors since we have to emit multiple functions for
747 // a single ctor or dtor.
748 if (!IsCtorOrDtor
&& Method
->isThisDeclarationADefinition())
749 SPCache
[Method
] = llvm::WeakVH(SP
);
754 /// CollectCXXMemberFunctions - A helper function to collect debug info for
755 /// C++ member functions.This is used while creating debug info entry for
758 CollectCXXMemberFunctions(const CXXRecordDecl
*RD
, llvm::DIFile Unit
,
759 llvm::SmallVectorImpl
<llvm::Value
*> &EltTys
,
760 llvm::DIType RecordTy
) {
761 for(CXXRecordDecl::method_iterator I
= RD
->method_begin(),
762 E
= RD
->method_end(); I
!= E
; ++I
) {
763 const CXXMethodDecl
*Method
= *I
;
765 if (Method
->isImplicit() && !Method
->isUsed())
768 EltTys
.push_back(CreateCXXMemberFunction(Method
, Unit
, RecordTy
));
772 /// CollectCXXFriends - A helper function to collect debug info for
773 /// C++ base classes. This is used while creating debug info entry for
776 CollectCXXFriends(const CXXRecordDecl
*RD
, llvm::DIFile Unit
,
777 llvm::SmallVectorImpl
<llvm::Value
*> &EltTys
,
778 llvm::DIType RecordTy
) {
780 for (CXXRecordDecl::friend_iterator BI
= RD
->friend_begin(),
781 BE
= RD
->friend_end(); BI
!= BE
; ++BI
) {
782 if (TypeSourceInfo
*TInfo
= (*BI
)->getFriendType())
783 EltTys
.push_back(DBuilder
.CreateFriend(RecordTy
,
784 getOrCreateType(TInfo
->getType(),
789 /// CollectCXXBases - A helper function to collect debug info for
790 /// C++ base classes. This is used while creating debug info entry for
793 CollectCXXBases(const CXXRecordDecl
*RD
, llvm::DIFile Unit
,
794 llvm::SmallVectorImpl
<llvm::Value
*> &EltTys
,
795 llvm::DIType RecordTy
) {
797 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
798 for (CXXRecordDecl::base_class_const_iterator BI
= RD
->bases_begin(),
799 BE
= RD
->bases_end(); BI
!= BE
; ++BI
) {
803 const CXXRecordDecl
*Base
=
804 cast
<CXXRecordDecl
>(BI
->getType()->getAs
<RecordType
>()->getDecl());
806 if (BI
->isVirtual()) {
807 // virtual base offset offset is -ve. The code generator emits dwarf
808 // expression where it expects +ve number.
809 BaseOffset
= 0 - CGM
.getVTables().getVirtualBaseOffsetOffset(RD
, Base
);
810 BFlags
= llvm::DIDescriptor::FlagVirtual
;
812 BaseOffset
= RL
.getBaseClassOffsetInBits(Base
);
814 AccessSpecifier Access
= BI
->getAccessSpecifier();
815 if (Access
== clang::AS_private
)
816 BFlags
|= llvm::DIDescriptor::FlagPrivate
;
817 else if (Access
== clang::AS_protected
)
818 BFlags
|= llvm::DIDescriptor::FlagProtected
;
821 DBuilder
.CreateInheritance(RecordTy
,
822 getOrCreateType(BI
->getType(), Unit
),
824 EltTys
.push_back(DTy
);
828 /// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
829 llvm::DIType
CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit
) {
830 if (VTablePtrType
.isValid())
831 return VTablePtrType
;
833 ASTContext
&Context
= CGM
.getContext();
836 llvm::Value
*STy
= getOrCreateType(Context
.IntTy
, Unit
);
837 llvm::DIArray SElements
= DBuilder
.GetOrCreateArray(&STy
, 1);
838 llvm::DIType SubTy
= DBuilder
.CreateSubroutineType(Unit
, SElements
);
839 unsigned Size
= Context
.getTypeSize(Context
.VoidPtrTy
);
840 llvm::DIType vtbl_ptr_type
= DBuilder
.CreatePointerType(SubTy
, Size
, 0,
842 VTablePtrType
= DBuilder
.CreatePointerType(vtbl_ptr_type
, Size
);
843 return VTablePtrType
;
846 /// getVTableName - Get vtable name for the given Class.
847 llvm::StringRef
CGDebugInfo::getVTableName(const CXXRecordDecl
*RD
) {
848 // Otherwise construct gdb compatible name name.
849 std::string Name
= "_vptr$" + RD
->getNameAsString();
851 // Copy this name on the side and use its reference.
852 char *StrPtr
= DebugInfoNames
.Allocate
<char>(Name
.length());
853 memcpy(StrPtr
, Name
.data(), Name
.length());
854 return llvm::StringRef(StrPtr
, Name
.length());
858 /// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
859 /// debug info entry in EltTys vector.
861 CollectVTableInfo(const CXXRecordDecl
*RD
, llvm::DIFile Unit
,
862 llvm::SmallVectorImpl
<llvm::Value
*> &EltTys
) {
863 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
865 // If there is a primary base then it will hold vtable info.
866 if (RL
.getPrimaryBase())
869 // If this class is not dynamic then there is not any vtable info to collect.
870 if (!RD
->isDynamicClass())
873 unsigned Size
= CGM
.getContext().getTypeSize(CGM
.getContext().VoidPtrTy
);
875 = DBuilder
.CreateMemberType(getVTableName(RD
), Unit
,
877 getOrCreateVTablePtrType(Unit
));
878 EltTys
.push_back(VPTR
);
881 /// getOrCreateRecordType - Emit record type's standalone debug info.
882 llvm::DIType
CGDebugInfo::getOrCreateRecordType(QualType RTy
,
883 SourceLocation Loc
) {
884 llvm::DIType T
= getOrCreateType(RTy
, getOrCreateFile(Loc
));
885 DBuilder
.RetainType(T
);
889 /// CreateType - get structure or union type.
890 llvm::DIType
CGDebugInfo::CreateType(const RecordType
*Ty
) {
891 RecordDecl
*RD
= Ty
->getDecl();
892 llvm::DIFile Unit
= getOrCreateFile(RD
->getLocation());
894 // Get overall information about the record type for the debug info.
895 llvm::DIFile DefUnit
= getOrCreateFile(RD
->getLocation());
896 unsigned Line
= getLineNumber(RD
->getLocation());
898 // Records and classes and unions can all be recursive. To handle them, we
899 // first generate a debug descriptor for the struct as a forward declaration.
900 // Then (if it is a definition) we go through and get debug info for all of
901 // its members. Finally, we create a descriptor for the complete type (which
902 // may refer to the forward decl if the struct is recursive) and replace all
903 // uses of the forward declaration with the final definition.
904 llvm::DIDescriptor FDContext
=
905 getContextDescriptor(dyn_cast
<Decl
>(RD
->getDeclContext()));
907 // If this is just a forward declaration, construct an appropriately
908 // marked node and just return it.
909 if (!RD
->getDefinition()) {
910 llvm::DIType FwdDecl
=
911 DBuilder
.CreateStructType(FDContext
, RD
->getName(),
913 llvm::DIDescriptor::FlagFwdDecl
,
919 llvm::DIType FwdDecl
= DBuilder
.CreateTemporaryType(DefUnit
);
921 llvm::MDNode
*MN
= FwdDecl
;
922 llvm::TrackingVH
<llvm::MDNode
> FwdDeclNode
= MN
;
923 // Otherwise, insert it into the TypeCache so that recursive uses will find
925 TypeCache
[QualType(Ty
, 0).getAsOpaquePtr()] = FwdDecl
;
926 // Push the struct on region stack.
927 RegionStack
.push_back(FwdDeclNode
);
928 RegionMap
[Ty
->getDecl()] = llvm::WeakVH(FwdDecl
);
930 // Convert all the elements.
931 llvm::SmallVector
<llvm::Value
*, 16> EltTys
;
933 const CXXRecordDecl
*CXXDecl
= dyn_cast
<CXXRecordDecl
>(RD
);
935 CollectCXXBases(CXXDecl
, Unit
, EltTys
, FwdDecl
);
936 CollectVTableInfo(CXXDecl
, Unit
, EltTys
);
939 // Collect static variables with initializers.
940 for (RecordDecl::decl_iterator I
= RD
->decls_begin(), E
= RD
->decls_end();
942 if (const VarDecl
*V
= dyn_cast
<VarDecl
>(*I
)) {
943 if (const Expr
*Init
= V
->getInit()) {
944 Expr::EvalResult Result
;
945 if (Init
->Evaluate(Result
, CGM
.getContext()) && Result
.Val
.isInt()) {
946 llvm::ConstantInt
*CI
947 = llvm::ConstantInt::get(CGM
.getLLVMContext(), Result
.Val
.getInt());
949 // Create the descriptor for static variable.
950 llvm::DIFile VUnit
= getOrCreateFile(V
->getLocation());
951 llvm::StringRef VName
= V
->getName();
952 llvm::DIType VTy
= getOrCreateType(V
->getType(), VUnit
);
953 // Do not use DIGlobalVariable for enums.
954 if (VTy
.getTag() != llvm::dwarf::DW_TAG_enumeration_type
) {
955 DBuilder
.CreateStaticVariable(FwdDecl
, VName
, VName
, VUnit
,
956 getLineNumber(V
->getLocation()),
963 CollectRecordFields(RD
, Unit
, EltTys
);
964 llvm::SmallVector
<llvm::Value
*, 16> TemplateParams
;
966 CollectCXXMemberFunctions(CXXDecl
, Unit
, EltTys
, FwdDecl
);
967 CollectCXXFriends(CXXDecl
, Unit
, EltTys
, FwdDecl
);
968 if (ClassTemplateSpecializationDecl
*TSpecial
969 = dyn_cast
<ClassTemplateSpecializationDecl
>(RD
)) {
970 const TemplateArgumentList
&TAL
= TSpecial
->getTemplateArgs();
971 for (unsigned i
= 0, e
= TAL
.size(); i
!= e
; ++i
) {
972 const TemplateArgument
&TA
= TAL
[i
];
973 if (TA
.getKind() == TemplateArgument::Type
) {
974 llvm::DIType TTy
= getOrCreateType(TA
.getAsType(), Unit
);
975 llvm::DITemplateTypeParameter TTP
=
976 DBuilder
.CreateTemplateTypeParameter(TheCU
, TTy
.getName(), TTy
);
977 TemplateParams
.push_back(TTP
);
978 } else if (TA
.getKind() == TemplateArgument::Integral
) {
979 llvm::DIType TTy
= getOrCreateType(TA
.getIntegralType(), Unit
);
980 // FIXME: Get parameter name, instead of parameter type name.
981 llvm::DITemplateValueParameter TVP
=
982 DBuilder
.CreateTemplateValueParameter(TheCU
, TTy
.getName(), TTy
,
983 TA
.getAsIntegral()->getZExtValue());
984 TemplateParams
.push_back(TVP
);
990 RegionStack
.pop_back();
991 llvm::DenseMap
<const Decl
*, llvm::WeakVH
>::iterator RI
=
992 RegionMap
.find(Ty
->getDecl());
993 if (RI
!= RegionMap
.end())
996 llvm::DIDescriptor RDContext
=
997 getContextDescriptor(dyn_cast
<Decl
>(RD
->getDeclContext()));
998 llvm::StringRef RDName
= RD
->getName();
999 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1000 uint64_t Align
= CGM
.getContext().getTypeAlign(Ty
);
1001 llvm::DIArray Elements
=
1002 DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
1003 llvm::MDNode
*RealDecl
= NULL
;
1006 RealDecl
= DBuilder
.CreateStructType(RDContext
, RDName
, DefUnit
, Line
,
1007 Size
, Align
, 0, Elements
);
1008 else if (RD
->isUnion())
1009 RealDecl
= DBuilder
.CreateUnionType(RDContext
, RDName
, DefUnit
, Line
,
1010 Size
, Align
, 0, Elements
);
1012 assert(RD
->isClass() && "Unknown RecordType!");
1013 RDName
= getClassName(RD
);
1014 // A class's primary base or the class itself contains the vtable.
1015 llvm::MDNode
*ContainingType
= NULL
;
1016 const ASTRecordLayout
&RL
= CGM
.getContext().getASTRecordLayout(RD
);
1017 if (const CXXRecordDecl
*PBase
= RL
.getPrimaryBase()) {
1018 // Seek non virtual primary base root.
1020 const ASTRecordLayout
&BRL
= CGM
.getContext().getASTRecordLayout(PBase
);
1021 const CXXRecordDecl
*PBT
= BRL
.getPrimaryBase();
1022 if (PBT
&& !BRL
.isPrimaryBaseVirtual())
1028 getOrCreateType(QualType(PBase
->getTypeForDecl(), 0), Unit
);
1030 else if (CXXDecl
->isDynamicClass())
1031 ContainingType
= FwdDecl
;
1032 llvm::DIArray TParamsArray
=
1033 DBuilder
.GetOrCreateArray(TemplateParams
.data(), TemplateParams
.size());
1034 RealDecl
= DBuilder
.CreateClassType(RDContext
, RDName
, DefUnit
, Line
,
1035 Size
, Align
, 0, 0, llvm::DIType(),
1036 Elements
, ContainingType
,
1040 // Now that we have a real decl for the struct, replace anything using the
1041 // old decl with the new one. This will recursively update the debug info.
1042 llvm::DIType(FwdDeclNode
).replaceAllUsesWith(RealDecl
);
1043 RegionMap
[RD
] = llvm::WeakVH(RealDecl
);
1044 return llvm::DIType(RealDecl
);
1047 /// CreateType - get objective-c object type.
1048 llvm::DIType
CGDebugInfo::CreateType(const ObjCObjectType
*Ty
,
1049 llvm::DIFile Unit
) {
1050 // Ignore protocols.
1051 return getOrCreateType(Ty
->getBaseType(), Unit
);
1054 /// CreateType - get objective-c interface type.
1055 llvm::DIType
CGDebugInfo::CreateType(const ObjCInterfaceType
*Ty
,
1056 llvm::DIFile Unit
) {
1057 ObjCInterfaceDecl
*ID
= Ty
->getDecl();
1059 return llvm::DIType();
1061 // Get overall information about the record type for the debug info.
1062 llvm::DIFile DefUnit
= getOrCreateFile(ID
->getLocation());
1063 unsigned Line
= getLineNumber(ID
->getLocation());
1064 unsigned RuntimeLang
= TheCU
.getLanguage();
1066 // If this is just a forward declaration, return a special forward-declaration
1068 if (ID
->isForwardDecl()) {
1069 llvm::DIType FwdDecl
=
1070 DBuilder
.CreateStructType(Unit
, ID
->getName(),
1071 DefUnit
, Line
, 0, 0, 0,
1072 llvm::DIArray(), RuntimeLang
);
1076 // To handle recursive interface, we
1077 // first generate a debug descriptor for the struct as a forward declaration.
1078 // Then (if it is a definition) we go through and get debug info for all of
1079 // its members. Finally, we create a descriptor for the complete type (which
1080 // may refer to the forward decl if the struct is recursive) and replace all
1081 // uses of the forward declaration with the final definition.
1082 llvm::DIType FwdDecl
= DBuilder
.CreateTemporaryType(DefUnit
);
1084 llvm::MDNode
*MN
= FwdDecl
;
1085 llvm::TrackingVH
<llvm::MDNode
> FwdDeclNode
= MN
;
1086 // Otherwise, insert it into the TypeCache so that recursive uses will find
1088 TypeCache
[QualType(Ty
, 0).getAsOpaquePtr()] = FwdDecl
;
1089 // Push the struct on region stack.
1090 RegionStack
.push_back(FwdDeclNode
);
1091 RegionMap
[Ty
->getDecl()] = llvm::WeakVH(FwdDecl
);
1093 // Convert all the elements.
1094 llvm::SmallVector
<llvm::Value
*, 16> EltTys
;
1096 ObjCInterfaceDecl
*SClass
= ID
->getSuperClass();
1098 llvm::DIType SClassTy
=
1099 getOrCreateType(CGM
.getContext().getObjCInterfaceType(SClass
), Unit
);
1100 if (!SClassTy
.isValid())
1101 return llvm::DIType();
1103 llvm::DIType InhTag
=
1104 DBuilder
.CreateInheritance(FwdDecl
, SClassTy
, 0, 0);
1105 EltTys
.push_back(InhTag
);
1108 const ASTRecordLayout
&RL
= CGM
.getContext().getASTObjCInterfaceLayout(ID
);
1110 unsigned FieldNo
= 0;
1111 for (ObjCIvarDecl
*Field
= ID
->all_declared_ivar_begin(); Field
;
1112 Field
= Field
->getNextIvar(), ++FieldNo
) {
1113 llvm::DIType FieldTy
= getOrCreateType(Field
->getType(), Unit
);
1114 if (!FieldTy
.isValid())
1115 return llvm::DIType();
1117 llvm::StringRef FieldName
= Field
->getName();
1119 // Ignore unnamed fields.
1120 if (FieldName
.empty())
1123 // Get the location for the field.
1124 llvm::DIFile FieldDefUnit
= getOrCreateFile(Field
->getLocation());
1125 unsigned FieldLine
= getLineNumber(Field
->getLocation());
1126 QualType FType
= Field
->getType();
1127 uint64_t FieldSize
= 0;
1128 unsigned FieldAlign
= 0;
1130 if (!FType
->isIncompleteArrayType()) {
1132 // Bit size, align and offset of the type.
1133 FieldSize
= CGM
.getContext().getTypeSize(FType
);
1134 Expr
*BitWidth
= Field
->getBitWidth();
1136 FieldSize
= BitWidth
->EvaluateAsInt(CGM
.getContext()).getZExtValue();
1138 FieldAlign
= CGM
.getContext().getTypeAlign(FType
);
1141 uint64_t FieldOffset
= RL
.getFieldOffset(FieldNo
);
1144 if (Field
->getAccessControl() == ObjCIvarDecl::Protected
)
1145 Flags
= llvm::DIDescriptor::FlagProtected
;
1146 else if (Field
->getAccessControl() == ObjCIvarDecl::Private
)
1147 Flags
= llvm::DIDescriptor::FlagPrivate
;
1149 FieldTy
= DBuilder
.CreateMemberType(FieldName
, FieldDefUnit
,
1150 FieldLine
, FieldSize
, FieldAlign
,
1151 FieldOffset
, Flags
, FieldTy
);
1152 EltTys
.push_back(FieldTy
);
1155 llvm::DIArray Elements
=
1156 DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
1158 RegionStack
.pop_back();
1159 llvm::DenseMap
<const Decl
*, llvm::WeakVH
>::iterator RI
=
1160 RegionMap
.find(Ty
->getDecl());
1161 if (RI
!= RegionMap
.end())
1162 RegionMap
.erase(RI
);
1164 // Bit size, align and offset of the type.
1165 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1166 uint64_t Align
= CGM
.getContext().getTypeAlign(Ty
);
1168 llvm::DIType RealDecl
=
1169 DBuilder
.CreateStructType(Unit
, ID
->getName(), DefUnit
,
1170 Line
, Size
, Align
, 0,
1171 Elements
, RuntimeLang
);
1173 // Now that we have a real decl for the struct, replace anything using the
1174 // old decl with the new one. This will recursively update the debug info.
1175 llvm::DIType(FwdDeclNode
).replaceAllUsesWith(RealDecl
);
1176 RegionMap
[ID
] = llvm::WeakVH(RealDecl
);
1181 llvm::DIType
CGDebugInfo::CreateType(const TagType
*Ty
) {
1182 if (const RecordType
*RT
= dyn_cast
<RecordType
>(Ty
))
1183 return CreateType(RT
);
1184 else if (const EnumType
*ET
= dyn_cast
<EnumType
>(Ty
))
1185 return CreateEnumType(ET
->getDecl());
1187 return llvm::DIType();
1190 llvm::DIType
CGDebugInfo::CreateType(const VectorType
*Ty
,
1191 llvm::DIFile Unit
) {
1192 llvm::DIType ElementTy
= getOrCreateType(Ty
->getElementType(), Unit
);
1193 uint64_t NumElems
= Ty
->getNumElements();
1197 llvm::Value
*Subscript
= DBuilder
.GetOrCreateSubrange(0, NumElems
);
1198 llvm::DIArray SubscriptArray
= DBuilder
.GetOrCreateArray(&Subscript
, 1);
1200 uint64_t Size
= CGM
.getContext().getTypeSize(Ty
);
1201 uint64_t Align
= CGM
.getContext().getTypeAlign(Ty
);
1204 DBuilder
.CreateVectorType(Size
, Align
, ElementTy
, SubscriptArray
);
1207 llvm::DIType
CGDebugInfo::CreateType(const ArrayType
*Ty
,
1208 llvm::DIFile Unit
) {
1213 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1214 if (const VariableArrayType
*VAT
= dyn_cast
<VariableArrayType
>(Ty
)) {
1217 CGM
.getContext().getTypeAlign(CGM
.getContext().getBaseElementType(VAT
));
1218 } else if (Ty
->isIncompleteArrayType()) {
1220 Align
= CGM
.getContext().getTypeAlign(Ty
->getElementType());
1222 // Size and align of the whole array, not the element type.
1223 Size
= CGM
.getContext().getTypeSize(Ty
);
1224 Align
= CGM
.getContext().getTypeAlign(Ty
);
1227 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1228 // interior arrays, do we care? Why aren't nested arrays represented the
1229 // obvious/recursive way?
1230 llvm::SmallVector
<llvm::Value
*, 8> Subscripts
;
1231 QualType
EltTy(Ty
, 0);
1232 if (Ty
->isIncompleteArrayType())
1233 EltTy
= Ty
->getElementType();
1235 while ((Ty
= dyn_cast
<ArrayType
>(EltTy
))) {
1237 if (const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(Ty
))
1238 if (CAT
->getSize().getZExtValue())
1239 Upper
= CAT
->getSize().getZExtValue() - 1;
1240 // FIXME: Verify this is right for VLAs.
1241 Subscripts
.push_back(DBuilder
.GetOrCreateSubrange(0, Upper
));
1242 EltTy
= Ty
->getElementType();
1246 llvm::DIArray SubscriptArray
=
1247 DBuilder
.GetOrCreateArray(Subscripts
.data(), Subscripts
.size());
1249 llvm::DIType DbgTy
=
1250 DBuilder
.CreateArrayType(Size
, Align
, getOrCreateType(EltTy
, Unit
),
1255 llvm::DIType
CGDebugInfo::CreateType(const LValueReferenceType
*Ty
,
1256 llvm::DIFile Unit
) {
1257 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type
,
1258 Ty
, Ty
->getPointeeType(), Unit
);
1261 llvm::DIType
CGDebugInfo::CreateType(const RValueReferenceType
*Ty
,
1262 llvm::DIFile Unit
) {
1263 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type
,
1264 Ty
, Ty
->getPointeeType(), Unit
);
1267 llvm::DIType
CGDebugInfo::CreateType(const MemberPointerType
*Ty
,
1269 QualType PointerDiffTy
= CGM
.getContext().getPointerDiffType();
1270 llvm::DIType PointerDiffDITy
= getOrCreateType(PointerDiffTy
, U
);
1272 if (!Ty
->getPointeeType()->isFunctionType()) {
1273 // We have a data member pointer type.
1274 return PointerDiffDITy
;
1277 // We have a member function pointer type. Treat it as a struct with two
1278 // ptrdiff_t members.
1279 std::pair
<uint64_t, unsigned> Info
= CGM
.getContext().getTypeInfo(Ty
);
1281 uint64_t FieldOffset
= 0;
1282 llvm::Value
*ElementTypes
[2];
1284 // FIXME: This should probably be a function type instead.
1286 DBuilder
.CreateMemberType("ptr", U
, 0,
1287 Info
.first
, Info
.second
, FieldOffset
, 0,
1289 FieldOffset
+= Info
.first
;
1292 DBuilder
.CreateMemberType("ptr", U
, 0,
1293 Info
.first
, Info
.second
, FieldOffset
, 0,
1296 llvm::DIArray Elements
=
1297 DBuilder
.GetOrCreateArray(&ElementTypes
[0],
1298 llvm::array_lengthof(ElementTypes
));
1300 return DBuilder
.CreateStructType(U
, llvm::StringRef("test"),
1305 /// CreateEnumType - get enumeration type.
1306 llvm::DIType
CGDebugInfo::CreateEnumType(const EnumDecl
*ED
) {
1307 llvm::DIFile Unit
= getOrCreateFile(ED
->getLocation());
1308 llvm::SmallVector
<llvm::Value
*, 16> Enumerators
;
1310 // Create DIEnumerator elements for each enumerator.
1311 for (EnumDecl::enumerator_iterator
1312 Enum
= ED
->enumerator_begin(), EnumEnd
= ED
->enumerator_end();
1313 Enum
!= EnumEnd
; ++Enum
) {
1314 Enumerators
.push_back(
1315 DBuilder
.CreateEnumerator(Enum
->getName(),
1316 Enum
->getInitVal().getZExtValue()));
1319 // Return a CompositeType for the enum itself.
1320 llvm::DIArray EltArray
=
1321 DBuilder
.GetOrCreateArray(Enumerators
.data(), Enumerators
.size());
1323 llvm::DIFile DefUnit
= getOrCreateFile(ED
->getLocation());
1324 unsigned Line
= getLineNumber(ED
->getLocation());
1327 if (!ED
->getTypeForDecl()->isIncompleteType()) {
1328 Size
= CGM
.getContext().getTypeSize(ED
->getTypeForDecl());
1329 Align
= CGM
.getContext().getTypeAlign(ED
->getTypeForDecl());
1331 llvm::DIDescriptor EnumContext
=
1332 getContextDescriptor(dyn_cast
<Decl
>(ED
->getDeclContext()));
1333 llvm::DIType DbgTy
=
1334 DBuilder
.CreateEnumerationType(EnumContext
, ED
->getName(), DefUnit
, Line
,
1335 Size
, Align
, EltArray
);
1339 static QualType
UnwrapTypeForDebugInfo(QualType T
) {
1342 switch (T
->getTypeClass()) {
1345 case Type::TemplateSpecialization
:
1346 T
= cast
<TemplateSpecializationType
>(T
)->desugar();
1348 case Type::TypeOfExpr
:
1349 T
= cast
<TypeOfExprType
>(T
)->getUnderlyingExpr()->getType();
1352 T
= cast
<TypeOfType
>(T
)->getUnderlyingType();
1354 case Type::Decltype
:
1355 T
= cast
<DecltypeType
>(T
)->getUnderlyingType();
1357 case Type::Attributed
:
1358 T
= cast
<AttributedType
>(T
)->getEquivalentType();
1359 case Type::Elaborated
:
1360 T
= cast
<ElaboratedType
>(T
)->getNamedType();
1363 T
= cast
<ParenType
>(T
)->getInnerType();
1365 case Type::SubstTemplateTypeParm
:
1366 T
= cast
<SubstTemplateTypeParmType
>(T
)->getReplacementType();
1370 assert(T
!= LastT
&& "Type unwrapping failed to unwrap!");
1378 /// getOrCreateType - Get the type from the cache or create a new
1379 /// one if necessary.
1380 llvm::DIType
CGDebugInfo::getOrCreateType(QualType Ty
,
1381 llvm::DIFile Unit
) {
1383 return llvm::DIType();
1385 // Unwrap the type as needed for debug information.
1386 Ty
= UnwrapTypeForDebugInfo(Ty
);
1388 // Check for existing entry.
1389 llvm::DenseMap
<void *, llvm::WeakVH
>::iterator it
=
1390 TypeCache
.find(Ty
.getAsOpaquePtr());
1391 if (it
!= TypeCache
.end()) {
1392 // Verify that the debug info still exists.
1394 return llvm::DIType(cast
<llvm::MDNode
>(it
->second
));
1397 // Otherwise create the type.
1398 llvm::DIType Res
= CreateTypeNode(Ty
, Unit
);
1400 // And update the type cache.
1401 TypeCache
[Ty
.getAsOpaquePtr()] = Res
;
1405 /// CreateTypeNode - Create a new debug type node.
1406 llvm::DIType
CGDebugInfo::CreateTypeNode(QualType Ty
,
1407 llvm::DIFile Unit
) {
1408 // Handle qualifiers, which recursively handles what they refer to.
1409 if (Ty
.hasLocalQualifiers())
1410 return CreateQualifiedType(Ty
, Unit
);
1412 const char *Diag
= 0;
1414 // Work out details of type.
1415 switch (Ty
->getTypeClass()) {
1416 #define TYPE(Class, Base)
1417 #define ABSTRACT_TYPE(Class, Base)
1418 #define NON_CANONICAL_TYPE(Class, Base)
1419 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1420 #include "clang/AST/TypeNodes.def"
1421 assert(false && "Dependent types cannot show up in debug information");
1423 // FIXME: Handle these.
1424 case Type::ExtVector
:
1425 return llvm::DIType();
1428 return CreateType(cast
<VectorType
>(Ty
), Unit
);
1429 case Type::ObjCObjectPointer
:
1430 return CreateType(cast
<ObjCObjectPointerType
>(Ty
), Unit
);
1431 case Type::ObjCObject
:
1432 return CreateType(cast
<ObjCObjectType
>(Ty
), Unit
);
1433 case Type::ObjCInterface
:
1434 return CreateType(cast
<ObjCInterfaceType
>(Ty
), Unit
);
1435 case Type::Builtin
: return CreateType(cast
<BuiltinType
>(Ty
));
1436 case Type::Complex
: return CreateType(cast
<ComplexType
>(Ty
));
1437 case Type::Pointer
: return CreateType(cast
<PointerType
>(Ty
), Unit
);
1438 case Type::BlockPointer
:
1439 return CreateType(cast
<BlockPointerType
>(Ty
), Unit
);
1440 case Type::Typedef
: return CreateType(cast
<TypedefType
>(Ty
), Unit
);
1443 return CreateType(cast
<TagType
>(Ty
));
1444 case Type::FunctionProto
:
1445 case Type::FunctionNoProto
:
1446 return CreateType(cast
<FunctionType
>(Ty
), Unit
);
1447 case Type::ConstantArray
:
1448 case Type::VariableArray
:
1449 case Type::IncompleteArray
:
1450 return CreateType(cast
<ArrayType
>(Ty
), Unit
);
1452 case Type::LValueReference
:
1453 return CreateType(cast
<LValueReferenceType
>(Ty
), Unit
);
1454 case Type::RValueReference
:
1455 return CreateType(cast
<RValueReferenceType
>(Ty
), Unit
);
1457 case Type::MemberPointer
:
1458 return CreateType(cast
<MemberPointerType
>(Ty
), Unit
);
1460 case Type::Attributed
:
1461 case Type::TemplateSpecialization
:
1462 case Type::Elaborated
:
1464 case Type::SubstTemplateTypeParm
:
1465 case Type::TypeOfExpr
:
1467 case Type::Decltype
:
1468 llvm_unreachable("type should have been unwrapped!");
1469 return llvm::DIType();
1472 assert(Diag
&& "Fall through without a diagnostic?");
1473 unsigned DiagID
= CGM
.getDiags().getCustomDiagID(Diagnostic::Error
,
1474 "debug information for %0 is not yet supported");
1475 CGM
.getDiags().Report(DiagID
)
1477 return llvm::DIType();
1480 /// CreateMemberType - Create new member and increase Offset by FType's size.
1481 llvm::DIType
CGDebugInfo::CreateMemberType(llvm::DIFile Unit
, QualType FType
,
1482 llvm::StringRef Name
,
1484 llvm::DIType FieldTy
= CGDebugInfo::getOrCreateType(FType
, Unit
);
1485 uint64_t FieldSize
= CGM
.getContext().getTypeSize(FType
);
1486 unsigned FieldAlign
= CGM
.getContext().getTypeAlign(FType
);
1487 llvm::DIType Ty
= DBuilder
.CreateMemberType(Name
, Unit
, 0,
1488 FieldSize
, FieldAlign
,
1489 *Offset
, 0, FieldTy
);
1490 *Offset
+= FieldSize
;
1494 /// EmitFunctionStart - Constructs the debug code for entering a function -
1495 /// "llvm.dbg.func.start.".
1496 void CGDebugInfo::EmitFunctionStart(GlobalDecl GD
, QualType FnType
,
1498 CGBuilderTy
&Builder
) {
1500 llvm::StringRef Name
;
1501 llvm::StringRef LinkageName
;
1503 FnBeginRegionCount
.push_back(RegionStack
.size());
1505 const Decl
*D
= GD
.getDecl();
1507 llvm::DIFile Unit
= getOrCreateFile(CurLoc
);
1508 llvm::DIDescriptor
FDContext(Unit
);
1509 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
1510 // If there is a DISubprogram for this function available then use it.
1511 llvm::DenseMap
<const FunctionDecl
*, llvm::WeakVH
>::iterator
1512 FI
= SPCache
.find(FD
);
1513 if (FI
!= SPCache
.end()) {
1514 llvm::DIDescriptor
SP(dyn_cast_or_null
<llvm::MDNode
>(&*FI
->second
));
1515 if (SP
.isSubprogram() && llvm::DISubprogram(SP
).isDefinition()) {
1516 llvm::MDNode
*SPN
= SP
;
1517 RegionStack
.push_back(SPN
);
1518 RegionMap
[D
] = llvm::WeakVH(SP
);
1522 Name
= getFunctionName(FD
);
1523 // Use mangled name as linkage name for c/c++ functions.
1524 LinkageName
= CGM
.getMangledName(GD
);
1525 if (LinkageName
== Name
)
1526 LinkageName
= llvm::StringRef();
1527 if (FD
->hasPrototype())
1528 Flags
|= llvm::DIDescriptor::FlagPrototyped
;
1529 if (const NamespaceDecl
*NSDecl
=
1530 dyn_cast_or_null
<NamespaceDecl
>(FD
->getDeclContext()))
1531 FDContext
= getOrCreateNameSpace(NSDecl
);
1532 } else if (const ObjCMethodDecl
*OMD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
1533 Name
= getObjCMethodName(OMD
);
1534 Flags
|= llvm::DIDescriptor::FlagPrototyped
;
1536 // Use llvm function name.
1537 Name
= Fn
->getName();
1538 Flags
|= llvm::DIDescriptor::FlagPrototyped
;
1540 if (!Name
.empty() && Name
[0] == '\01')
1541 Name
= Name
.substr(1);
1543 // It is expected that CurLoc is set before using EmitFunctionStart.
1544 // Usually, CurLoc points to the left bracket location of compound
1545 // statement representing function body.
1546 unsigned LineNo
= getLineNumber(CurLoc
);
1547 if (D
->isImplicit())
1548 Flags
|= llvm::DIDescriptor::FlagArtificial
;
1549 llvm::DISubprogram SP
=
1550 DBuilder
.CreateFunction(FDContext
, Name
, LinkageName
, Unit
,
1551 LineNo
, getOrCreateType(FnType
, Unit
),
1552 Fn
->hasInternalLinkage(), true/*definition*/,
1553 Flags
, CGM
.getLangOptions().Optimize
, Fn
);
1555 // Push function on region stack.
1556 llvm::MDNode
*SPN
= SP
;
1557 RegionStack
.push_back(SPN
);
1558 RegionMap
[D
] = llvm::WeakVH(SP
);
1560 // Clear stack used to keep track of #line directives.
1561 LineDirectiveFiles
.clear();
1565 void CGDebugInfo::EmitStopPoint(CGBuilderTy
&Builder
) {
1566 if (CurLoc
.isInvalid() || CurLoc
.isMacroID()) return;
1568 // Don't bother if things are the same as last time.
1569 SourceManager
&SM
= CGM
.getContext().getSourceManager();
1570 if (CurLoc
== PrevLoc
1571 || (SM
.getInstantiationLineNumber(CurLoc
) ==
1572 SM
.getInstantiationLineNumber(PrevLoc
)
1573 && SM
.isFromSameFile(CurLoc
, PrevLoc
)))
1574 // New Builder may not be in sync with CGDebugInfo.
1575 if (!Builder
.getCurrentDebugLocation().isUnknown())
1578 // Update last state.
1581 llvm::MDNode
*Scope
= RegionStack
.back();
1582 Builder
.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc
),
1583 getColumnNumber(CurLoc
),
1587 /// UpdateLineDirectiveRegion - Update region stack only if #line directive
1588 /// has introduced scope change.
1589 void CGDebugInfo::UpdateLineDirectiveRegion(CGBuilderTy
&Builder
) {
1590 if (CurLoc
.isInvalid() || CurLoc
.isMacroID() ||
1591 PrevLoc
.isInvalid() || PrevLoc
.isMacroID())
1593 SourceManager
&SM
= CGM
.getContext().getSourceManager();
1594 PresumedLoc PCLoc
= SM
.getPresumedLoc(CurLoc
);
1595 PresumedLoc PPLoc
= SM
.getPresumedLoc(PrevLoc
);
1597 if (PCLoc
.isInvalid() || PPLoc
.isInvalid() ||
1598 !strcmp(PPLoc
.getFilename(), PCLoc
.getFilename()))
1601 // If #line directive stack is empty then we are entering a new scope.
1602 if (LineDirectiveFiles
.empty()) {
1603 EmitRegionStart(Builder
);
1604 LineDirectiveFiles
.push_back(PCLoc
.getFilename());
1608 assert (RegionStack
.size() >= LineDirectiveFiles
.size()
1609 && "error handling #line regions!");
1611 bool SeenThisFile
= false;
1612 // Chek if current file is already seen earlier.
1613 for(std::vector
<const char *>::iterator I
= LineDirectiveFiles
.begin(),
1614 E
= LineDirectiveFiles
.end(); I
!= E
; ++I
)
1615 if (!strcmp(PCLoc
.getFilename(), *I
)) {
1616 SeenThisFile
= true;
1620 // If #line for this file is seen earlier then pop out #line regions.
1622 while (!LineDirectiveFiles
.empty()) {
1623 const char *LastFile
= LineDirectiveFiles
.back();
1624 RegionStack
.pop_back();
1625 LineDirectiveFiles
.pop_back();
1626 if (!strcmp(PPLoc
.getFilename(), LastFile
))
1632 // .. otherwise insert new #line region.
1633 EmitRegionStart(Builder
);
1634 LineDirectiveFiles
.push_back(PCLoc
.getFilename());
1638 /// EmitRegionStart- Constructs the debug code for entering a declarative
1639 /// region - "llvm.dbg.region.start.".
1640 void CGDebugInfo::EmitRegionStart(CGBuilderTy
&Builder
) {
1641 llvm::DIDescriptor D
=
1642 DBuilder
.CreateLexicalBlock(RegionStack
.empty() ?
1643 llvm::DIDescriptor() :
1644 llvm::DIDescriptor(RegionStack
.back()),
1645 getOrCreateFile(CurLoc
),
1646 getLineNumber(CurLoc
),
1647 getColumnNumber(CurLoc
));
1648 llvm::MDNode
*DN
= D
;
1649 RegionStack
.push_back(DN
);
1652 /// EmitRegionEnd - Constructs the debug code for exiting a declarative
1653 /// region - "llvm.dbg.region.end."
1654 void CGDebugInfo::EmitRegionEnd(CGBuilderTy
&Builder
) {
1655 assert(!RegionStack
.empty() && "Region stack mismatch, stack empty!");
1657 // Provide an region stop point.
1658 EmitStopPoint(Builder
);
1660 RegionStack
.pop_back();
1663 /// EmitFunctionEnd - Constructs the debug code for exiting a function.
1664 void CGDebugInfo::EmitFunctionEnd(CGBuilderTy
&Builder
) {
1665 assert(!RegionStack
.empty() && "Region stack mismatch, stack empty!");
1666 unsigned RCount
= FnBeginRegionCount
.back();
1667 assert(RCount
<= RegionStack
.size() && "Region stack mismatch");
1669 // Pop all regions for this function.
1670 while (RegionStack
.size() != RCount
)
1671 EmitRegionEnd(Builder
);
1672 FnBeginRegionCount
.pop_back();
1675 // EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
1676 // See BuildByRefType.
1677 llvm::DIType
CGDebugInfo::EmitTypeForVarWithBlocksAttr(const ValueDecl
*VD
,
1678 uint64_t *XOffset
) {
1680 llvm::SmallVector
<llvm::Value
*, 5> EltTys
;
1682 uint64_t FieldSize
, FieldOffset
;
1683 unsigned FieldAlign
;
1685 llvm::DIFile Unit
= getOrCreateFile(VD
->getLocation());
1686 QualType Type
= VD
->getType();
1689 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1690 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__isa", &FieldOffset
));
1691 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__forwarding", &FieldOffset
));
1692 FType
= CGM
.getContext().IntTy
;
1693 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__flags", &FieldOffset
));
1694 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__size", &FieldOffset
));
1696 bool HasCopyAndDispose
= CGM
.getContext().BlockRequiresCopying(Type
);
1697 if (HasCopyAndDispose
) {
1698 FType
= CGM
.getContext().getPointerType(CGM
.getContext().VoidTy
);
1699 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__copy_helper",
1701 EltTys
.push_back(CreateMemberType(Unit
, FType
, "__destroy_helper",
1705 CharUnits Align
= CGM
.getContext().getDeclAlign(VD
);
1706 if (Align
> CharUnits::fromQuantity(
1707 CGM
.getContext().Target
.getPointerAlign(0) / 8)) {
1708 unsigned AlignedOffsetInBytes
1709 = llvm::RoundUpToAlignment(FieldOffset
/8, Align
.getQuantity());
1710 unsigned NumPaddingBytes
1711 = AlignedOffsetInBytes
- FieldOffset
/8;
1713 if (NumPaddingBytes
> 0) {
1714 llvm::APInt
pad(32, NumPaddingBytes
);
1715 FType
= CGM
.getContext().getConstantArrayType(CGM
.getContext().CharTy
,
1716 pad
, ArrayType::Normal
, 0);
1717 EltTys
.push_back(CreateMemberType(Unit
, FType
, "", &FieldOffset
));
1722 llvm::DIType FieldTy
= CGDebugInfo::getOrCreateType(FType
, Unit
);
1723 FieldSize
= CGM
.getContext().getTypeSize(FType
);
1724 FieldAlign
= Align
.getQuantity()*8;
1726 *XOffset
= FieldOffset
;
1727 FieldTy
= DBuilder
.CreateMemberType(VD
->getName(), Unit
,
1728 0, FieldSize
, FieldAlign
,
1729 FieldOffset
, 0, FieldTy
);
1730 EltTys
.push_back(FieldTy
);
1731 FieldOffset
+= FieldSize
;
1733 llvm::DIArray Elements
=
1734 DBuilder
.GetOrCreateArray(EltTys
.data(), EltTys
.size());
1736 unsigned Flags
= llvm::DIDescriptor::FlagBlockByrefStruct
;
1738 return DBuilder
.CreateStructType(Unit
, "", Unit
, 0, FieldOffset
, 0, Flags
,
1742 /// EmitDeclare - Emit local variable declaration debug info.
1743 void CGDebugInfo::EmitDeclare(const VarDecl
*VD
, unsigned Tag
,
1744 llvm::Value
*Storage
, CGBuilderTy
&Builder
) {
1745 assert(!RegionStack
.empty() && "Region stack mismatch, stack empty!");
1747 llvm::DIFile Unit
= getOrCreateFile(VD
->getLocation());
1749 uint64_t XOffset
= 0;
1750 if (VD
->hasAttr
<BlocksAttr
>())
1751 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
);
1753 Ty
= getOrCreateType(VD
->getType(), Unit
);
1755 // If there is not any debug info for type then do not emit debug info
1756 // for this variable.
1760 if (llvm::Argument
*Arg
= dyn_cast
<llvm::Argument
>(Storage
)) {
1761 // If Storage is an aggregate returned as 'sret' then let debugger know
1763 if (Arg
->hasStructRetAttr())
1764 Ty
= DBuilder
.CreateReferenceType(Ty
);
1765 else if (CXXRecordDecl
*Record
= VD
->getType()->getAsCXXRecordDecl()) {
1766 // If an aggregate variable has non trivial destructor or non trivial copy
1767 // constructor than it is pass indirectly. Let debug info know about this
1768 // by using reference of the aggregate type as a argument type.
1769 if (!Record
->hasTrivialCopyConstructor() || !Record
->hasTrivialDestructor())
1770 Ty
= DBuilder
.CreateReferenceType(Ty
);
1774 // Get location information.
1775 unsigned Line
= getLineNumber(VD
->getLocation());
1776 unsigned Column
= getColumnNumber(VD
->getLocation());
1778 if (VD
->isImplicit())
1779 Flags
|= llvm::DIDescriptor::FlagArtificial
;
1780 llvm::MDNode
*Scope
= RegionStack
.back();
1782 llvm::StringRef Name
= VD
->getName();
1783 if (!Name
.empty()) {
1784 if (VD
->hasAttr
<BlocksAttr
>()) {
1785 CharUnits offset
= CharUnits::fromQuantity(32);
1786 llvm::SmallVector
<llvm::Value
*, 9> addr
;
1787 const llvm::Type
*Int64Ty
= llvm::Type::getInt64Ty(CGM
.getLLVMContext());
1788 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpPlus
));
1789 // offset of __forwarding field
1791 CharUnits::fromQuantity(CGM
.getContext().Target
.getPointerWidth(0)/8);
1792 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, offset
.getQuantity()));
1793 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpDeref
));
1794 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpPlus
));
1795 // offset of x field
1796 offset
= CharUnits::fromQuantity(XOffset
/8);
1797 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, offset
.getQuantity()));
1799 // Create the descriptor for the variable.
1800 llvm::DIVariable D
=
1801 DBuilder
.CreateComplexVariable(Tag
,
1802 llvm::DIDescriptor(RegionStack
.back()),
1803 VD
->getName(), Unit
, Line
, Ty
,
1804 addr
.data(), addr
.size());
1806 // Insert an llvm.dbg.declare into the current block.
1807 llvm::Instruction
*Call
=
1808 DBuilder
.InsertDeclare(Storage
, D
, Builder
.GetInsertBlock());
1810 Call
->setDebugLoc(llvm::DebugLoc::get(Line
, Column
, Scope
));
1813 // Create the descriptor for the variable.
1814 llvm::DIVariable D
=
1815 DBuilder
.CreateLocalVariable(Tag
, llvm::DIDescriptor(Scope
),
1816 Name
, Unit
, Line
, Ty
,
1817 CGM
.getLangOptions().Optimize
, Flags
);
1819 // Insert an llvm.dbg.declare into the current block.
1820 llvm::Instruction
*Call
=
1821 DBuilder
.InsertDeclare(Storage
, D
, Builder
.GetInsertBlock());
1823 Call
->setDebugLoc(llvm::DebugLoc::get(Line
, Column
, Scope
));
1827 // If VD is an anonymous union then Storage represents value for
1828 // all union fields.
1829 if (const RecordType
*RT
= dyn_cast
<RecordType
>(VD
->getType()))
1830 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(RT
->getDecl()))
1831 if (RD
->isUnion()) {
1832 for (RecordDecl::field_iterator I
= RD
->field_begin(),
1833 E
= RD
->field_end();
1835 FieldDecl
*Field
= *I
;
1836 llvm::DIType FieldTy
= getOrCreateType(Field
->getType(), Unit
);
1837 llvm::StringRef FieldName
= Field
->getName();
1839 // Ignore unnamed fields. Do not ignore unnamed records.
1840 if (FieldName
.empty() && !isa
<RecordType
>(Field
->getType()))
1843 // Use VarDecl's Tag, Scope and Line number.
1844 llvm::DIVariable D
=
1845 DBuilder
.CreateLocalVariable(Tag
, llvm::DIDescriptor(Scope
),
1846 FieldName
, Unit
, Line
, FieldTy
,
1847 CGM
.getLangOptions().Optimize
, Flags
);
1849 // Insert an llvm.dbg.declare into the current block.
1850 llvm::Instruction
*Call
=
1851 DBuilder
.InsertDeclare(Storage
, D
, Builder
.GetInsertBlock());
1853 Call
->setDebugLoc(llvm::DebugLoc::get(Line
, Column
, Scope
));
1858 /// EmitDeclare - Emit local variable declaration debug info.
1859 void CGDebugInfo::EmitDeclare(const VarDecl
*VD
, unsigned Tag
,
1860 llvm::Value
*Storage
, CGBuilderTy
&Builder
,
1861 const CGBlockInfo
&blockInfo
) {
1862 assert(!RegionStack
.empty() && "Region stack mismatch, stack empty!");
1864 if (Builder
.GetInsertBlock() == 0)
1867 bool isByRef
= VD
->hasAttr
<BlocksAttr
>();
1869 uint64_t XOffset
= 0;
1870 llvm::DIFile Unit
= getOrCreateFile(VD
->getLocation());
1873 Ty
= EmitTypeForVarWithBlocksAttr(VD
, &XOffset
);
1875 Ty
= getOrCreateType(VD
->getType(), Unit
);
1877 // Get location information.
1878 unsigned Line
= getLineNumber(VD
->getLocation());
1879 unsigned Column
= getColumnNumber(VD
->getLocation());
1881 const llvm::TargetData
&target
= CGM
.getTargetData();
1883 CharUnits offset
= CharUnits::fromQuantity(
1884 target
.getStructLayout(blockInfo
.StructureType
)
1885 ->getElementOffset(blockInfo
.getCapture(VD
).getIndex()));
1887 llvm::SmallVector
<llvm::Value
*, 9> addr
;
1888 const llvm::Type
*Int64Ty
= llvm::Type::getInt64Ty(CGM
.getLLVMContext());
1889 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpDeref
));
1890 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpPlus
));
1891 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, offset
.getQuantity()));
1893 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpDeref
));
1894 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpPlus
));
1895 // offset of __forwarding field
1896 offset
= CharUnits::fromQuantity(target
.getPointerSize()/8);
1897 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, offset
.getQuantity()));
1898 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpDeref
));
1899 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, llvm::DIFactory::OpPlus
));
1900 // offset of x field
1901 offset
= CharUnits::fromQuantity(XOffset
/8);
1902 addr
.push_back(llvm::ConstantInt::get(Int64Ty
, offset
.getQuantity()));
1905 // Create the descriptor for the variable.
1906 llvm::DIVariable D
=
1907 DBuilder
.CreateComplexVariable(Tag
, llvm::DIDescriptor(RegionStack
.back()),
1908 VD
->getName(), Unit
, Line
, Ty
,
1909 addr
.data(), addr
.size());
1910 // Insert an llvm.dbg.declare into the current block.
1911 llvm::Instruction
*Call
=
1912 DBuilder
.InsertDeclare(Storage
, D
, Builder
.GetInsertBlock());
1914 llvm::MDNode
*Scope
= RegionStack
.back();
1915 Call
->setDebugLoc(llvm::DebugLoc::get(Line
, Column
, Scope
));
1918 void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl
*VD
,
1919 llvm::Value
*Storage
,
1920 CGBuilderTy
&Builder
) {
1921 EmitDeclare(VD
, llvm::dwarf::DW_TAG_auto_variable
, Storage
, Builder
);
1924 void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(
1925 const VarDecl
*variable
, llvm::Value
*Storage
, CGBuilderTy
&Builder
,
1926 const CGBlockInfo
&blockInfo
) {
1927 EmitDeclare(variable
, llvm::dwarf::DW_TAG_auto_variable
, Storage
, Builder
,
1931 /// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
1932 /// variable declaration.
1933 void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl
*VD
, llvm::Value
*AI
,
1934 CGBuilderTy
&Builder
) {
1935 EmitDeclare(VD
, llvm::dwarf::DW_TAG_arg_variable
, AI
, Builder
);
1940 /// EmitGlobalVariable - Emit information about a global variable.
1941 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable
*Var
,
1944 // Create global variable debug descriptor.
1945 llvm::DIFile Unit
= getOrCreateFile(D
->getLocation());
1946 unsigned LineNo
= getLineNumber(D
->getLocation());
1948 QualType T
= D
->getType();
1949 if (T
->isIncompleteArrayType()) {
1951 // CodeGen turns int[] into int[1] so we'll do the same here.
1952 llvm::APSInt
ConstVal(32);
1955 QualType ET
= CGM
.getContext().getAsArrayType(T
)->getElementType();
1957 T
= CGM
.getContext().getConstantArrayType(ET
, ConstVal
,
1958 ArrayType::Normal
, 0);
1960 llvm::StringRef DeclName
= D
->getName();
1961 llvm::StringRef LinkageName
;
1962 if (D
->getDeclContext() && !isa
<FunctionDecl
>(D
->getDeclContext())
1963 && !isa
<ObjCMethodDecl
>(D
->getDeclContext()))
1964 LinkageName
= Var
->getName();
1965 if (LinkageName
== DeclName
)
1966 LinkageName
= llvm::StringRef();
1967 llvm::DIDescriptor DContext
=
1968 getContextDescriptor(dyn_cast
<Decl
>(D
->getDeclContext()));
1969 DBuilder
.CreateStaticVariable(DContext
, DeclName
, LinkageName
,
1970 Unit
, LineNo
, getOrCreateType(T
, Unit
),
1971 Var
->hasInternalLinkage(), Var
);
1974 /// EmitGlobalVariable - Emit information about an objective-c interface.
1975 void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable
*Var
,
1976 ObjCInterfaceDecl
*ID
) {
1977 // Create global variable debug descriptor.
1978 llvm::DIFile Unit
= getOrCreateFile(ID
->getLocation());
1979 unsigned LineNo
= getLineNumber(ID
->getLocation());
1981 llvm::StringRef Name
= ID
->getName();
1983 QualType T
= CGM
.getContext().getObjCInterfaceType(ID
);
1984 if (T
->isIncompleteArrayType()) {
1986 // CodeGen turns int[] into int[1] so we'll do the same here.
1987 llvm::APSInt
ConstVal(32);
1990 QualType ET
= CGM
.getContext().getAsArrayType(T
)->getElementType();
1992 T
= CGM
.getContext().getConstantArrayType(ET
, ConstVal
,
1993 ArrayType::Normal
, 0);
1996 DBuilder
.CreateGlobalVariable(Name
, Unit
, LineNo
,
1997 getOrCreateType(T
, Unit
),
1998 Var
->hasInternalLinkage(), Var
);
2001 /// EmitGlobalVariable - Emit global variable's debug info.
2002 void CGDebugInfo::EmitGlobalVariable(const ValueDecl
*VD
,
2003 llvm::Constant
*Init
) {
2004 // Create the descriptor for the variable.
2005 llvm::DIFile Unit
= getOrCreateFile(VD
->getLocation());
2006 llvm::StringRef Name
= VD
->getName();
2007 llvm::DIType Ty
= getOrCreateType(VD
->getType(), Unit
);
2008 if (const EnumConstantDecl
*ECD
= dyn_cast
<EnumConstantDecl
>(VD
)) {
2009 if (const EnumDecl
*ED
= dyn_cast
<EnumDecl
>(ECD
->getDeclContext()))
2010 Ty
= CreateEnumType(ED
);
2012 // Do not use DIGlobalVariable for enums.
2013 if (Ty
.getTag() == llvm::dwarf::DW_TAG_enumeration_type
)
2015 DBuilder
.CreateStaticVariable(Unit
, Name
, Name
, Unit
,
2016 getLineNumber(VD
->getLocation()),
2020 /// getOrCreateNamesSpace - Return namespace descriptor for the given
2023 CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl
*NSDecl
) {
2024 llvm::DenseMap
<const NamespaceDecl
*, llvm::WeakVH
>::iterator I
=
2025 NameSpaceCache
.find(NSDecl
);
2026 if (I
!= NameSpaceCache
.end())
2027 return llvm::DINameSpace(cast
<llvm::MDNode
>(I
->second
));
2029 unsigned LineNo
= getLineNumber(NSDecl
->getLocation());
2030 llvm::DIFile FileD
= getOrCreateFile(NSDecl
->getLocation());
2031 llvm::DIDescriptor Context
=
2032 getContextDescriptor(dyn_cast
<Decl
>(NSDecl
->getDeclContext()));
2033 llvm::DINameSpace NS
=
2034 DBuilder
.CreateNameSpace(Context
, NSDecl
->getName(), FileD
, LineNo
);
2035 NameSpaceCache
[NSDecl
] = llvm::WeakVH(NS
);