blob: a4153d3712ec099fb632166410f53a237de448ab [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
16#include "CGObjCRuntime.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclFriend.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/SourceManager.h"
27#include "clang/Basic/Version.h"
28#include "clang/Frontend/CodeGenOptions.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000037#include "llvm/Support/Dwarf.h"
38#include "llvm/Support/FileSystem.h"
39using namespace clang;
40using namespace clang::CodeGen;
41
42CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
43 : CGM(CGM), DBuilder(CGM.getModule()),
44 BlockLiteralGenericSet(false) {
45 CreateCompileUnit();
46}
47
48CGDebugInfo::~CGDebugInfo() {
49 assert(LexicalBlockStack.empty() &&
50 "Region stack mismatch, stack not empty!");
51}
52
53void CGDebugInfo::setLocation(SourceLocation Loc) {
54 // If the new location isn't valid return.
55 if (!Loc.isValid()) return;
56
57 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
58
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;
63
64 SourceManager &SM = CGM.getContext().getSourceManager();
65 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
66 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
67
68 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
69 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
70 return;
71
72 llvm::MDNode *LB = LexicalBlockStack.back();
73 llvm::DIScope Scope = llvm::DIScope(LB);
74 if (Scope.isLexicalBlockFile()) {
75 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
76 llvm::DIDescriptor D
77 = DBuilder.createLexicalBlockFile(LBF.getScope(),
78 getOrCreateFile(CurLoc));
79 llvm::MDNode *N = D;
80 LexicalBlockStack.pop_back();
81 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +000082 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000083 llvm::DIDescriptor D
84 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
85 llvm::MDNode *N = D;
86 LexicalBlockStack.pop_back();
87 LexicalBlockStack.push_back(N);
88 }
89}
90
91/// getContextDescriptor - Get context info for the decl.
92llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
93 if (!Context)
94 return TheCU;
95
96 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
97 I = RegionMap.find(Context);
98 if (I != RegionMap.end()) {
99 llvm::Value *V = I->second;
100 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
101 }
102
103 // Check namespace.
104 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
105 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
106
107 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
108 if (!RDecl->isDependentType()) {
109 llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
110 getOrCreateMainFile());
111 return llvm::DIDescriptor(Ty);
112 }
113 }
114 return TheCU;
115}
116
117/// getFunctionName - Get function name for the given FunctionDecl. If the
118/// name is constructred on demand (e.g. C++ destructor) then the name
119/// is stored on the side.
120StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
121 assert (FD && "Invalid FunctionDecl!");
122 IdentifierInfo *FII = FD->getIdentifier();
123 FunctionTemplateSpecializationInfo *Info
124 = FD->getTemplateSpecializationInfo();
125 if (!Info && FII)
126 return FII->getName();
127
128 // Otherwise construct human readable name for debug info.
129 std::string NS = FD->getNameAsString();
130
131 // Add any template specialization args.
132 if (Info) {
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
137 NS += TemplateSpecializationType::PrintTemplateArgumentList(Args,
138 NumArgs,
139 Policy);
140 }
141
142 // Copy this name on the side and use its reference.
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.length());
144 memcpy(StrPtr, NS.data(), NS.length());
145 return StringRef(StrPtr, NS.length());
146}
147
148StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
153 if (const ObjCImplementationDecl *OID =
154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
156 } else if (const ObjCInterfaceDecl *OID =
157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
159 } else if (const ObjCCategoryImplDecl *OCD =
160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
163 }
164 OS << ' ' << OMD->getSelector().getAsString() << ']';
165
166 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
167 memcpy(StrPtr, MethodName.begin(), OS.tell());
168 return StringRef(StrPtr, OS.tell());
169}
170
171/// getSelectorName - Return selector name. This is used for debugging
172/// info.
173StringRef CGDebugInfo::getSelectorName(Selector S) {
174 const std::string &SName = S.getAsString();
175 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
176 memcpy(StrPtr, SName.data(), SName.size());
177 return StringRef(StrPtr, SName.size());
178}
179
180/// getClassName - Get class name including template argument list.
181StringRef
182CGDebugInfo::getClassName(const RecordDecl *RD) {
183 const ClassTemplateSpecializationDecl *Spec
184 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 if (!Spec)
186 return RD->getName();
187
188 const TemplateArgument *Args;
189 unsigned NumArgs;
190 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
191 const TemplateSpecializationType *TST =
192 cast<TemplateSpecializationType>(TAW->getType());
193 Args = TST->getArgs();
194 NumArgs = TST->getNumArgs();
195 } else {
196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
197 Args = TemplateArgs.data();
198 NumArgs = TemplateArgs.size();
199 }
200 StringRef Name = RD->getIdentifier()->getName();
201 PrintingPolicy Policy(CGM.getLangOpts());
202 std::string TemplateArgList =
203 TemplateSpecializationType::PrintTemplateArgumentList(Args, NumArgs, Policy);
204
205 // Copy this name on the side and use its reference.
206 size_t Length = Name.size() + TemplateArgList.size();
207 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
208 memcpy(StrPtr, Name.data(), Name.size());
209 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
210 return StringRef(StrPtr, Length);
211}
212
213/// getOrCreateFile - Get the file debug info descriptor for the input location.
214llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
215 if (!Loc.isValid())
216 // If Location is not valid then use main input file.
217 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
218
219 SourceManager &SM = CGM.getContext().getSourceManager();
220 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
221
222 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
223 // If the location is not valid then use main input file.
224 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
225
226 // Cache the results.
227 const char *fname = PLoc.getFilename();
228 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
229 DIFileCache.find(fname);
230
231 if (it != DIFileCache.end()) {
232 // Verify that the information still exists.
233 if (llvm::Value *V = it->second)
234 return llvm::DIFile(cast<llvm::MDNode>(V));
235 }
236
237 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
238
239 DIFileCache[fname] = F;
240 return F;
241}
242
243/// getOrCreateMainFile - Get the file info for main compile unit.
244llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
245 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
246}
247
248/// getLineNumber - Get line number for the location. If location is invalid
249/// then use current location.
250unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
251 if (Loc.isInvalid() && CurLoc.isInvalid())
252 return 0;
253 SourceManager &SM = CGM.getContext().getSourceManager();
254 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
255 return PLoc.isValid()? PLoc.getLine() : 0;
256}
257
258/// getColumnNumber - Get column number for the location.
259unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc) {
260 // We may not want column information at all.
261 if (!CGM.getCodeGenOpts().DebugColumnInfo)
262 return 0;
263
264 // If the location is invalid then use the current column.
265 if (Loc.isInvalid() && CurLoc.isInvalid())
266 return 0;
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
269 return PLoc.isValid()? PLoc.getColumn() : 0;
270}
271
272StringRef CGDebugInfo::getCurrentDirname() {
273 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
274 return CGM.getCodeGenOpts().DebugCompilationDir;
275
276 if (!CWDName.empty())
277 return CWDName;
278 SmallString<256> CWD;
279 llvm::sys::fs::current_path(CWD);
280 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
281 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
282 return CWDName = StringRef(CompDirnamePtr, CWD.size());
283}
284
285/// CreateCompileUnit - Create new compile unit.
286void CGDebugInfo::CreateCompileUnit() {
287
288 // Get absolute path name.
289 SourceManager &SM = CGM.getContext().getSourceManager();
290 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
291 if (MainFileName.empty())
292 MainFileName = "<unknown>";
293
294 // The main file name provided via the "-main-file-name" option contains just
295 // the file name itself with no path information. This file name may have had
296 // a relative path, so we look into the actual file entry for the main
297 // file to determine the real absolute path for the file.
298 std::string MainFileDir;
299 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
300 MainFileDir = MainFile->getDir()->getName();
301 if (MainFileDir != ".")
302 MainFileName = MainFileDir + "/" + MainFileName;
303 }
304
305 // Save filename string.
306 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
307 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
308 StringRef Filename(FilenamePtr, MainFileName.length());
309
310 unsigned LangTag;
311 const LangOptions &LO = CGM.getLangOpts();
312 if (LO.CPlusPlus) {
313 if (LO.ObjC1)
314 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
315 else
316 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
317 } else if (LO.ObjC1) {
318 LangTag = llvm::dwarf::DW_LANG_ObjC;
319 } else if (LO.C99) {
320 LangTag = llvm::dwarf::DW_LANG_C99;
321 } else {
322 LangTag = llvm::dwarf::DW_LANG_C89;
323 }
324
325 std::string Producer = getClangFullVersion();
326
327 // Figure out which version of the ObjC runtime we have.
328 unsigned RuntimeVers = 0;
329 if (LO.ObjC1)
330 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
331
332 // Create new compile unit.
333 DBuilder.createCompileUnit(
334 LangTag, Filename, getCurrentDirname(),
335 Producer,
336 LO.Optimize, CGM.getCodeGenOpts().DwarfDebugFlags, RuntimeVers);
337 // FIXME - Eliminate TheCU.
338 TheCU = llvm::DICompileUnit(DBuilder.getCU());
339}
340
341/// CreateType - Get the Basic type from the cache or create a new
342/// one if necessary.
343llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
344 unsigned Encoding = 0;
345 StringRef BTName;
346 switch (BT->getKind()) {
347#define BUILTIN_TYPE(Id, SingletonId)
348#define PLACEHOLDER_TYPE(Id, SingletonId) \
349 case BuiltinType::Id:
350#include "clang/AST/BuiltinTypes.def"
351 case BuiltinType::Dependent:
352 llvm_unreachable("Unexpected builtin type");
353 case BuiltinType::NullPtr:
354 return DBuilder.
355 createNullPtrType(BT->getName(CGM.getLangOpts()));
356 case BuiltinType::Void:
357 return llvm::DIType();
358 case BuiltinType::ObjCClass:
359 if (ClassTy.Verify())
360 return ClassTy;
361 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
362 "objc_class", TheCU,
363 getOrCreateMainFile(), 0);
364 return ClassTy;
365 case BuiltinType::ObjCId: {
366 // typedef struct objc_class *Class;
367 // typedef struct objc_object {
368 // Class isa;
369 // } *id;
370
371 if (ObjTy.Verify())
372 return ObjTy;
373
374 if (!ClassTy.Verify())
375 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
376 "objc_class", TheCU,
377 getOrCreateMainFile(), 0);
378
379 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
380
381 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
382
383 llvm::DIType FwdTy = DBuilder.createStructType(TheCU, "objc_object",
384 getOrCreateMainFile(),
385 0, 0, 0, 0,
386 llvm::DIArray());
387
388 llvm::TrackingVH<llvm::MDNode> ObjNode(FwdTy);
389 SmallVector<llvm::Value *, 1> EltTys;
390 llvm::DIType FieldTy =
391 DBuilder.createMemberType(llvm::DIDescriptor(ObjNode), "isa",
392 getOrCreateMainFile(), 0, Size,
393 0, 0, 0, ISATy);
394 EltTys.push_back(FieldTy);
395 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
396
397 ObjNode->replaceOperandWith(10, Elements);
398 ObjTy = llvm::DIType(ObjNode);
399 return ObjTy;
400 }
401 case BuiltinType::ObjCSel: {
402 if (SelTy.Verify())
403 return SelTy;
404 SelTy =
405 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
406 "objc_selector", TheCU, getOrCreateMainFile(),
407 0);
408 return SelTy;
409 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000410
411 case BuiltinType::OCLImage1d:
412 return getOrCreateStructPtrType("opencl_image1d_t",
413 OCLImage1dDITy);
414 case BuiltinType::OCLImage1dArray:
415 return getOrCreateStructPtrType("opencl_image1d_array_t",
416 OCLImage1dArrayDITy);
417 case BuiltinType::OCLImage1dBuffer:
418 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
419 OCLImage1dBufferDITy);
420 case BuiltinType::OCLImage2d:
421 return getOrCreateStructPtrType("opencl_image2d_t",
422 OCLImage2dDITy);
423 case BuiltinType::OCLImage2dArray:
424 return getOrCreateStructPtrType("opencl_image2d_array_t",
425 OCLImage2dArrayDITy);
426 case BuiltinType::OCLImage3d:
427 return getOrCreateStructPtrType("opencl_image3d_t",
428 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000429 case BuiltinType::OCLSampler:
430 return DBuilder.createBasicType("opencl_sampler_t",
431 CGM.getContext().getTypeSize(BT),
432 CGM.getContext().getTypeAlign(BT),
433 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000434 case BuiltinType::OCLEvent:
435 return getOrCreateStructPtrType("opencl_event_t",
436 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000437
Guy Benyei11169dd2012-12-18 14:30:41 +0000438 case BuiltinType::UChar:
439 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
440 case BuiltinType::Char_S:
441 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
442 case BuiltinType::Char16:
443 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
444 case BuiltinType::UShort:
445 case BuiltinType::UInt:
446 case BuiltinType::UInt128:
447 case BuiltinType::ULong:
448 case BuiltinType::WChar_U:
449 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
450 case BuiltinType::Short:
451 case BuiltinType::Int:
452 case BuiltinType::Int128:
453 case BuiltinType::Long:
454 case BuiltinType::WChar_S:
455 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
456 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
457 case BuiltinType::Half:
458 case BuiltinType::Float:
459 case BuiltinType::LongDouble:
460 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
461 }
462
463 switch (BT->getKind()) {
464 case BuiltinType::Long: BTName = "long int"; break;
465 case BuiltinType::LongLong: BTName = "long long int"; break;
466 case BuiltinType::ULong: BTName = "long unsigned int"; break;
467 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
468 default:
469 BTName = BT->getName(CGM.getLangOpts());
470 break;
471 }
472 // Bit size, align and offset of the type.
473 uint64_t Size = CGM.getContext().getTypeSize(BT);
474 uint64_t Align = CGM.getContext().getTypeAlign(BT);
475 llvm::DIType DbgTy =
476 DBuilder.createBasicType(BTName, Size, Align, Encoding);
477 return DbgTy;
478}
479
480llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
481 // Bit size, align and offset of the type.
482 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
483 if (Ty->isComplexIntegerType())
484 Encoding = llvm::dwarf::DW_ATE_lo_user;
485
486 uint64_t Size = CGM.getContext().getTypeSize(Ty);
487 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
488 llvm::DIType DbgTy =
489 DBuilder.createBasicType("complex", Size, Align, Encoding);
490
491 return DbgTy;
492}
493
494/// CreateCVRType - Get the qualified type from the cache or create
495/// a new one if necessary.
496llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
497 QualifierCollector Qc;
498 const Type *T = Qc.strip(Ty);
499
500 // Ignore these qualifiers for now.
501 Qc.removeObjCGCAttr();
502 Qc.removeAddressSpace();
503 Qc.removeObjCLifetime();
504
505 // We will create one Derived type for one qualifier and recurse to handle any
506 // additional ones.
507 unsigned Tag;
508 if (Qc.hasConst()) {
509 Tag = llvm::dwarf::DW_TAG_const_type;
510 Qc.removeConst();
511 } else if (Qc.hasVolatile()) {
512 Tag = llvm::dwarf::DW_TAG_volatile_type;
513 Qc.removeVolatile();
514 } else if (Qc.hasRestrict()) {
515 Tag = llvm::dwarf::DW_TAG_restrict_type;
516 Qc.removeRestrict();
517 } else {
518 assert(Qc.empty() && "Unknown type qualifier for debug info");
519 return getOrCreateType(QualType(T, 0), Unit);
520 }
521
522 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
523
524 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
525 // CVR derived types.
526 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
527
528 return DbgTy;
529}
530
531llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
532 llvm::DIFile Unit) {
533 llvm::DIType DbgTy =
534 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
535 Ty->getPointeeType(), Unit);
536 return DbgTy;
537}
538
539llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
540 llvm::DIFile Unit) {
541 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
542 Ty->getPointeeType(), Unit);
543}
544
545// Creates a forward declaration for a RecordDecl in the given context.
546llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
547 llvm::DIDescriptor Ctx) {
548 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
549 unsigned Line = getLineNumber(RD->getLocation());
550 StringRef RDName = getClassName(RD);
551
552 unsigned Tag = 0;
553 if (RD->isStruct() || RD->isInterface())
554 Tag = llvm::dwarf::DW_TAG_structure_type;
555 else if (RD->isUnion())
556 Tag = llvm::dwarf::DW_TAG_union_type;
557 else {
558 assert(RD->isClass());
559 Tag = llvm::dwarf::DW_TAG_class_type;
560 }
561
562 // Create the type.
563 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
564}
565
566// Walk up the context chain and create forward decls for record decls,
567// and normal descriptors for namespaces.
568llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
569 if (!Context)
570 return TheCU;
571
572 // See if we already have the parent.
573 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
574 I = RegionMap.find(Context);
575 if (I != RegionMap.end()) {
576 llvm::Value *V = I->second;
577 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
578 }
579
580 // Check namespace.
581 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
582 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
583
584 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
585 if (!RD->isDependentType()) {
586 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
587 getOrCreateMainFile());
588 return llvm::DIDescriptor(Ty);
589 }
590 }
591 return TheCU;
592}
593
594/// CreatePointeeType - Create Pointee type. If Pointee is a record
595/// then emit record's fwd if debug info size reduction is enabled.
596llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
597 llvm::DIFile Unit) {
598 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
599 return getOrCreateType(PointeeTy, Unit);
600
601 // Limit debug info for the pointee type.
602
603 // If we have an existing type, use that, it's still smaller than creating
604 // a new type.
605 llvm::DIType Ty = getTypeOrNull(PointeeTy);
606 if (Ty.Verify()) return Ty;
607
608 // Handle qualifiers.
609 if (PointeeTy.hasLocalQualifiers())
610 return CreateQualifiedType(PointeeTy, Unit);
611
612 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
613 RecordDecl *RD = RTy->getDecl();
614 llvm::DIDescriptor FDContext =
615 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
616 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
617 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
618 return RetTy;
619 }
620 return getOrCreateType(PointeeTy, Unit);
621
622}
623
624llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
625 const Type *Ty,
626 QualType PointeeTy,
627 llvm::DIFile Unit) {
628 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
629 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
630 return DBuilder.createReferenceType(Tag,
631 CreatePointeeType(PointeeTy, Unit));
632
633 // Bit size, align and offset of the type.
634 // Size is always the size of a pointer. We can't use getTypeSize here
635 // because that does not return the correct value for references.
636 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
637 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
638 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
639
640 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
641 Size, Align);
642}
643
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000644llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
645 if (Cache.Verify())
646 return Cache;
647 Cache =
648 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
649 Name, TheCU, getOrCreateMainFile(),
650 0);
651 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
652 Cache = DBuilder.createPointerType(Cache, Size);
653 return Cache;
654}
655
Guy Benyei11169dd2012-12-18 14:30:41 +0000656llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
657 llvm::DIFile Unit) {
658 if (BlockLiteralGenericSet)
659 return BlockLiteralGeneric;
660
661 SmallVector<llvm::Value *, 8> EltTys;
662 llvm::DIType FieldTy;
663 QualType FType;
664 uint64_t FieldSize, FieldOffset;
665 unsigned FieldAlign;
666 llvm::DIArray Elements;
667 llvm::DIType EltTy, DescTy;
668
669 FieldOffset = 0;
670 FType = CGM.getContext().UnsignedLongTy;
671 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
672 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
673
674 Elements = DBuilder.getOrCreateArray(EltTys);
675 EltTys.clear();
676
677 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
678 unsigned LineNo = getLineNumber(CurLoc);
679
680 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
681 Unit, LineNo, FieldOffset, 0,
682 Flags, Elements);
683
684 // Bit size, align and offset of the type.
685 uint64_t Size = CGM.getContext().getTypeSize(Ty);
686
687 DescTy = DBuilder.createPointerType(EltTy, Size);
688
689 FieldOffset = 0;
690 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
691 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
692 FType = CGM.getContext().IntTy;
693 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
694 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
695 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
696 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
697
698 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
699 FieldTy = DescTy;
700 FieldSize = CGM.getContext().getTypeSize(Ty);
701 FieldAlign = CGM.getContext().getTypeAlign(Ty);
702 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
703 LineNo, FieldSize, FieldAlign,
704 FieldOffset, 0, FieldTy);
705 EltTys.push_back(FieldTy);
706
707 FieldOffset += FieldSize;
708 Elements = DBuilder.getOrCreateArray(EltTys);
709
710 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
711 Unit, LineNo, FieldOffset, 0,
712 Flags, Elements);
713
714 BlockLiteralGenericSet = true;
715 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
716 return BlockLiteralGeneric;
717}
718
719llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
720 // Typedefs are derived from some other type. If we have a typedef of a
721 // typedef, make sure to emit the whole chain.
722 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
723 if (!Src.Verify())
724 return llvm::DIType();
725 // We don't set size information, but do specify where the typedef was
726 // declared.
727 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
728 const TypedefNameDecl *TyDecl = Ty->getDecl();
729
730 llvm::DIDescriptor TypedefContext =
731 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
732
733 return
734 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
735}
736
737llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
738 llvm::DIFile Unit) {
739 SmallVector<llvm::Value *, 16> EltTys;
740
741 // Add the result type at least.
742 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
743
744 // Set up remainder of arguments if there is a prototype.
745 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
746 if (isa<FunctionNoProtoType>(Ty))
747 EltTys.push_back(DBuilder.createUnspecifiedParameter());
748 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
749 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
750 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
751 }
752
753 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
754 return DBuilder.createSubroutineType(Unit, EltTypeArray);
755}
756
757
Guy Benyei11169dd2012-12-18 14:30:41 +0000758llvm::DIType CGDebugInfo::createFieldType(StringRef name,
759 QualType type,
760 uint64_t sizeInBitsOverride,
761 SourceLocation loc,
762 AccessSpecifier AS,
763 uint64_t offsetInBits,
764 llvm::DIFile tunit,
765 llvm::DIDescriptor scope) {
766 llvm::DIType debugType = getOrCreateType(type, tunit);
767
768 // Get the location for the field.
769 llvm::DIFile file = getOrCreateFile(loc);
770 unsigned line = getLineNumber(loc);
771
772 uint64_t sizeInBits = 0;
773 unsigned alignInBits = 0;
774 if (!type->isIncompleteArrayType()) {
775 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
776
777 if (sizeInBitsOverride)
778 sizeInBits = sizeInBitsOverride;
779 }
780
781 unsigned flags = 0;
782 if (AS == clang::AS_private)
783 flags |= llvm::DIDescriptor::FlagPrivate;
784 else if (AS == clang::AS_protected)
785 flags |= llvm::DIDescriptor::FlagProtected;
786
787 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
788 alignInBits, offsetInBits, flags, debugType);
789}
790
Eric Christopher91a31902013-01-16 01:22:32 +0000791/// CollectRecordLambdaFields - Helper for CollectRecordFields.
792void CGDebugInfo::
793CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
794 SmallVectorImpl<llvm::Value *> &elements,
795 llvm::DIType RecordTy) {
796 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
797 // has the name and the location of the variable so we should iterate over
798 // both concurrently.
799 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
800 RecordDecl::field_iterator Field = CXXDecl->field_begin();
801 unsigned fieldno = 0;
802 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
803 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
804 const LambdaExpr::Capture C = *I;
805 if (C.capturesVariable()) {
806 VarDecl *V = C.getCapturedVar();
807 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
808 StringRef VName = V->getName();
809 uint64_t SizeInBitsOverride = 0;
810 if (Field->isBitField()) {
811 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
812 assert(SizeInBitsOverride && "found named 0-width bitfield");
813 }
814 llvm::DIType fieldType
815 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
816 C.getLocation(), Field->getAccess(),
817 layout.getFieldOffset(fieldno), VUnit, RecordTy);
818 elements.push_back(fieldType);
819 } else {
820 // TODO: Need to handle 'this' in some way by probably renaming the
821 // this of the lambda class and having a field member of 'this' or
822 // by using AT_object_pointer for the function and having that be
823 // used as 'this' for semantic references.
824 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
825 FieldDecl *f = *Field;
826 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
827 QualType type = f->getType();
828 llvm::DIType fieldType
829 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
830 layout.getFieldOffset(fieldno), VUnit, RecordTy);
831
832 elements.push_back(fieldType);
833 }
834 }
835}
836
837/// CollectRecordStaticField - Helper for CollectRecordFields.
838void CGDebugInfo::
839CollectRecordStaticField(const VarDecl *Var,
840 SmallVectorImpl<llvm::Value *> &elements,
841 llvm::DIType RecordTy) {
842 // Create the descriptor for the static variable, with or without
843 // constant initializers.
844 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
845 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
846
847 // Do not describe enums as static members.
848 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
849 return;
850
851 unsigned LineNumber = getLineNumber(Var->getLocation());
852 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000853 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000854 if (Var->getInit()) {
855 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000856 if (Value) {
857 if (Value->isInt())
858 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
859 if (Value->isFloat())
860 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
861 }
Eric Christopher91a31902013-01-16 01:22:32 +0000862 }
863
864 unsigned Flags = 0;
865 AccessSpecifier Access = Var->getAccess();
866 if (Access == clang::AS_private)
867 Flags |= llvm::DIDescriptor::FlagPrivate;
868 else if (Access == clang::AS_protected)
869 Flags |= llvm::DIDescriptor::FlagProtected;
870
871 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000872 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000873 elements.push_back(GV);
874 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
875}
876
877/// CollectRecordNormalField - Helper for CollectRecordFields.
878void CGDebugInfo::
879CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
880 llvm::DIFile tunit,
881 SmallVectorImpl<llvm::Value *> &elements,
882 llvm::DIType RecordTy) {
883 StringRef name = field->getName();
884 QualType type = field->getType();
885
886 // Ignore unnamed fields unless they're anonymous structs/unions.
887 if (name.empty() && !type->isRecordType())
888 return;
889
890 uint64_t SizeInBitsOverride = 0;
891 if (field->isBitField()) {
892 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
893 assert(SizeInBitsOverride && "found named 0-width bitfield");
894 }
895
896 llvm::DIType fieldType
897 = createFieldType(name, type, SizeInBitsOverride,
898 field->getLocation(), field->getAccess(),
899 OffsetInBits, tunit, RecordTy);
900
901 elements.push_back(fieldType);
902}
903
Guy Benyei11169dd2012-12-18 14:30:41 +0000904/// CollectRecordFields - A helper function to collect debug info for
905/// record fields. This is used while creating debug info entry for a Record.
906void CGDebugInfo::
907CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
908 SmallVectorImpl<llvm::Value *> &elements,
909 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000910 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
911
Eric Christopher91a31902013-01-16 01:22:32 +0000912 if (CXXDecl && CXXDecl->isLambda())
913 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
914 else {
915 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000916
Eric Christopher91a31902013-01-16 01:22:32 +0000917 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000918 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000919
920 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei11169dd2012-12-18 14:30:41 +0000921 bool IsMsStruct = record->isMsStruct(CGM.getContext());
922 const FieldDecl *LastFD = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000923
Eric Christopher91a31902013-01-16 01:22:32 +0000924 // Static and non-static members should appear in the same order as
925 // the corresponding declarations in the source program.
926 for (RecordDecl::decl_iterator I = record->decls_begin(),
927 E = record->decls_end(); I != E; ++I)
928 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
929 CollectRecordStaticField(V, elements, RecordTy);
930 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
931 if (IsMsStruct) {
932 // Zero-length bitfields following non-bitfield members are
933 // completely ignored; we don't even count them.
934 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
935 continue;
936 LastFD = field;
Guy Benyei11169dd2012-12-18 14:30:41 +0000937 }
Eric Christopher91a31902013-01-16 01:22:32 +0000938 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
939 tunit, elements, RecordTy);
940
941 // Bump field number for next field.
942 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000944 }
945}
946
947/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
948/// function type is not updated to include implicit "this" pointer. Use this
949/// routine to get a method type which includes "this" pointer.
950llvm::DIType
951CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
952 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000953 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000954 if (Method->isStatic())
David Blaikie7eb06852013-01-07 23:06:35 +0000955 return getOrCreateType(QualType(Func, 0), Unit);
956 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
957 Func, Unit);
958}
David Blaikie2aaf0652013-01-07 22:24:59 +0000959
David Blaikie7eb06852013-01-07 23:06:35 +0000960llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
961 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000963 llvm::DIArray Args = llvm::DICompositeType(
964 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 assert (Args.getNumElements() && "Invalid number of arguments!");
966
967 SmallVector<llvm::Value *, 16> Elts;
968
969 // First element is always return type. For 'void' functions it is NULL.
970 Elts.push_back(Args.getElement(0));
971
David Blaikie2aaf0652013-01-07 22:24:59 +0000972 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000973 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000974 if (isa<ClassTemplateSpecializationDecl>(RD)) {
975 // Create pointer type directly in this case.
976 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
977 QualType PointeeTy = ThisPtrTy->getPointeeType();
978 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
979 uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
980 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
981 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
982 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
983 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
984 // TODO: This and the artificial type below are misleading, the
985 // types aren't artificial the argument is, but the current
986 // metadata doesn't represent that.
987 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
988 Elts.push_back(ThisPtrType);
989 } else {
990 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
991 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
992 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
993 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 }
995
996 // Copy rest of the arguments.
997 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
998 Elts.push_back(Args.getElement(i));
999
1000 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1001
1002 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1003}
1004
1005/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1006/// inside a function.
1007static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1008 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1009 return isFunctionLocalClass(NRD);
1010 if (isa<FunctionDecl>(RD->getDeclContext()))
1011 return true;
1012 return false;
1013}
1014
1015/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1016/// a single member function GlobalDecl.
1017llvm::DISubprogram
1018CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1019 llvm::DIFile Unit,
1020 llvm::DIType RecordTy) {
1021 bool IsCtorOrDtor =
1022 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1023
1024 StringRef MethodName = getFunctionName(Method);
1025 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1026
1027 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1028 // make sense to give a single ctor/dtor a linkage name.
1029 StringRef MethodLinkageName;
1030 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1031 MethodLinkageName = CGM.getMangledName(Method);
1032
1033 // Get the location for the method.
1034 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1035 unsigned MethodLine = getLineNumber(Method->getLocation());
1036
1037 // Collect virtual method info.
1038 llvm::DIType ContainingType;
1039 unsigned Virtuality = 0;
1040 unsigned VIndex = 0;
1041
1042 if (Method->isVirtual()) {
1043 if (Method->isPure())
1044 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1045 else
1046 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1047
1048 // It doesn't make sense to give a virtual destructor a vtable index,
1049 // since a single destructor has two entries in the vtable.
1050 if (!isa<CXXDestructorDecl>(Method))
1051 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1052 ContainingType = RecordTy;
1053 }
1054
1055 unsigned Flags = 0;
1056 if (Method->isImplicit())
1057 Flags |= llvm::DIDescriptor::FlagArtificial;
1058 AccessSpecifier Access = Method->getAccess();
1059 if (Access == clang::AS_private)
1060 Flags |= llvm::DIDescriptor::FlagPrivate;
1061 else if (Access == clang::AS_protected)
1062 Flags |= llvm::DIDescriptor::FlagProtected;
1063 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1064 if (CXXC->isExplicit())
1065 Flags |= llvm::DIDescriptor::FlagExplicit;
1066 } else if (const CXXConversionDecl *CXXC =
1067 dyn_cast<CXXConversionDecl>(Method)) {
1068 if (CXXC->isExplicit())
1069 Flags |= llvm::DIDescriptor::FlagExplicit;
1070 }
1071 if (Method->hasPrototype())
1072 Flags |= llvm::DIDescriptor::FlagPrototyped;
1073
1074 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1075 llvm::DISubprogram SP =
1076 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1077 MethodDefUnit, MethodLine,
1078 MethodTy, /*isLocalToUnit=*/false,
1079 /* isDefinition=*/ false,
1080 Virtuality, VIndex, ContainingType,
1081 Flags, CGM.getLangOpts().Optimize, NULL,
1082 TParamsArray);
1083
1084 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1085
1086 return SP;
1087}
1088
1089/// CollectCXXMemberFunctions - A helper function to collect debug info for
1090/// C++ member functions. This is used while creating debug info entry for
1091/// a Record.
1092void CGDebugInfo::
1093CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1094 SmallVectorImpl<llvm::Value *> &EltTys,
1095 llvm::DIType RecordTy) {
1096
1097 // Since we want more than just the individual member decls if we
1098 // have templated functions iterate over every declaration to gather
1099 // the functions.
1100 for(DeclContext::decl_iterator I = RD->decls_begin(),
1101 E = RD->decls_end(); I != E; ++I) {
1102 Decl *D = *I;
1103 if (D->isImplicit() && !D->isUsed())
1104 continue;
1105
1106 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1107 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1108 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1109 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1110 SE = FTD->spec_end(); SI != SE; ++SI)
1111 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1112 RecordTy));
1113 }
1114}
1115
1116/// CollectCXXFriends - A helper function to collect debug info for
1117/// C++ base classes. This is used while creating debug info entry for
1118/// a Record.
1119void CGDebugInfo::
1120CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1121 SmallVectorImpl<llvm::Value *> &EltTys,
1122 llvm::DIType RecordTy) {
1123 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1124 BE = RD->friend_end(); BI != BE; ++BI) {
1125 if ((*BI)->isUnsupportedFriend())
1126 continue;
1127 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1128 EltTys.push_back(DBuilder.createFriend(RecordTy,
1129 getOrCreateType(TInfo->getType(),
1130 Unit)));
1131 }
1132}
1133
1134/// CollectCXXBases - A helper function to collect debug info for
1135/// C++ base classes. This is used while creating debug info entry for
1136/// a Record.
1137void CGDebugInfo::
1138CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1139 SmallVectorImpl<llvm::Value *> &EltTys,
1140 llvm::DIType RecordTy) {
1141
1142 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1143 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1144 BE = RD->bases_end(); BI != BE; ++BI) {
1145 unsigned BFlags = 0;
1146 uint64_t BaseOffset;
1147
1148 const CXXRecordDecl *Base =
1149 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1150
1151 if (BI->isVirtual()) {
1152 // virtual base offset offset is -ve. The code generator emits dwarf
1153 // expression where it expects +ve number.
1154 BaseOffset =
1155 0 - CGM.getVTableContext()
1156 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1157 BFlags = llvm::DIDescriptor::FlagVirtual;
1158 } else
1159 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1160 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1161 // BI->isVirtual() and bits when not.
1162
1163 AccessSpecifier Access = BI->getAccessSpecifier();
1164 if (Access == clang::AS_private)
1165 BFlags |= llvm::DIDescriptor::FlagPrivate;
1166 else if (Access == clang::AS_protected)
1167 BFlags |= llvm::DIDescriptor::FlagProtected;
1168
1169 llvm::DIType DTy =
1170 DBuilder.createInheritance(RecordTy,
1171 getOrCreateType(BI->getType(), Unit),
1172 BaseOffset, BFlags);
1173 EltTys.push_back(DTy);
1174 }
1175}
1176
1177/// CollectTemplateParams - A helper function to collect template parameters.
1178llvm::DIArray CGDebugInfo::
1179CollectTemplateParams(const TemplateParameterList *TPList,
1180 const TemplateArgumentList &TAList,
1181 llvm::DIFile Unit) {
1182 SmallVector<llvm::Value *, 16> TemplateParams;
1183 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1184 const TemplateArgument &TA = TAList[i];
1185 const NamedDecl *ND = TPList->getParam(i);
1186 if (TA.getKind() == TemplateArgument::Type) {
1187 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1188 llvm::DITemplateTypeParameter TTP =
1189 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1190 TemplateParams.push_back(TTP);
1191 } else if (TA.getKind() == TemplateArgument::Integral) {
1192 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1193 llvm::DITemplateValueParameter TVP =
1194 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy,
1195 TA.getAsIntegral().getZExtValue());
1196 TemplateParams.push_back(TVP);
1197 }
1198 }
1199 return DBuilder.getOrCreateArray(TemplateParams);
1200}
1201
1202/// CollectFunctionTemplateParams - A helper function to collect debug
1203/// info for function template parameters.
1204llvm::DIArray CGDebugInfo::
1205CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1206 if (FD->getTemplatedKind() ==
1207 FunctionDecl::TK_FunctionTemplateSpecialization) {
1208 const TemplateParameterList *TList =
1209 FD->getTemplateSpecializationInfo()->getTemplate()
1210 ->getTemplateParameters();
1211 return
1212 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1213 }
1214 return llvm::DIArray();
1215}
1216
1217/// CollectCXXTemplateParams - A helper function to collect debug info for
1218/// template parameters.
1219llvm::DIArray CGDebugInfo::
1220CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1221 llvm::DIFile Unit) {
1222 llvm::PointerUnion<ClassTemplateDecl *,
1223 ClassTemplatePartialSpecializationDecl *>
1224 PU = TSpecial->getSpecializedTemplateOrPartial();
1225
1226 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1227 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1228 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1229 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1230 return CollectTemplateParams(TPList, TAList, Unit);
1231}
1232
1233/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1234llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1235 if (VTablePtrType.isValid())
1236 return VTablePtrType;
1237
1238 ASTContext &Context = CGM.getContext();
1239
1240 /* Function type */
1241 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1242 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1243 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1244 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1245 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1246 "__vtbl_ptr_type");
1247 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1248 return VTablePtrType;
1249}
1250
1251/// getVTableName - Get vtable name for the given Class.
1252StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1253 // Construct gdb compatible name name.
1254 std::string Name = "_vptr$" + RD->getNameAsString();
1255
1256 // Copy this name on the side and use its reference.
1257 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1258 memcpy(StrPtr, Name.data(), Name.length());
1259 return StringRef(StrPtr, Name.length());
1260}
1261
1262
1263/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1264/// debug info entry in EltTys vector.
1265void CGDebugInfo::
1266CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1267 SmallVectorImpl<llvm::Value *> &EltTys) {
1268 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1269
1270 // If there is a primary base then it will hold vtable info.
1271 if (RL.getPrimaryBase())
1272 return;
1273
1274 // If this class is not dynamic then there is not any vtable info to collect.
1275 if (!RD->isDynamicClass())
1276 return;
1277
1278 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1279 llvm::DIType VPTR
1280 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1281 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1282 getOrCreateVTablePtrType(Unit));
1283 EltTys.push_back(VPTR);
1284}
1285
1286/// getOrCreateRecordType - Emit record type's standalone debug info.
1287llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1288 SourceLocation Loc) {
1289 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1290 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1291 return T;
1292}
1293
1294/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1295/// debug info.
1296llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
1297 SourceLocation Loc) {
1298 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1299 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
1300 DBuilder.retainType(T);
1301 return T;
1302}
1303
1304/// CreateType - get structure or union type.
1305llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1306 RecordDecl *RD = Ty->getDecl();
1307
1308 // Get overall information about the record type for the debug info.
1309 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1310
1311 // Records and classes and unions can all be recursive. To handle them, we
1312 // first generate a debug descriptor for the struct as a forward declaration.
1313 // Then (if it is a definition) we go through and get debug info for all of
1314 // its members. Finally, we create a descriptor for the complete type (which
1315 // may refer to the forward decl if the struct is recursive) and replace all
1316 // uses of the forward declaration with the final definition.
1317
1318 llvm::DIType FwdDecl = getOrCreateLimitedType(QualType(Ty, 0), DefUnit);
1319
1320 if (FwdDecl.isForwardDecl())
1321 return FwdDecl;
1322
1323 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(FwdDecl);
1324
1325 // Push the struct on region stack.
1326 LexicalBlockStack.push_back(FwdDeclNode);
1327 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1328
1329 // Add this to the completed types cache since we're completing it.
1330 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1331
1332 // Convert all the elements.
1333 SmallVector<llvm::Value *, 16> EltTys;
1334
1335 // Note: The split of CXXDecl information here is intentional, the
1336 // gdb tests will depend on a certain ordering at printout. The debug
1337 // information offsets are still correct if we merge them all together
1338 // though.
1339 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1340 if (CXXDecl) {
1341 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1342 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1343 }
1344
Eric Christopher91a31902013-01-16 01:22:32 +00001345 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1347 llvm::DIArray TParamsArray;
1348 if (CXXDecl) {
1349 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1350 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1351 if (const ClassTemplateSpecializationDecl *TSpecial
1352 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1353 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1354 }
1355
1356 LexicalBlockStack.pop_back();
1357 RegionMap.erase(Ty->getDecl());
1358
1359 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1360 // FIXME: Magic numbers ahoy! These should be changed when we
1361 // get some enums in llvm/Analysis/DebugInfo.h to refer to
1362 // them.
1363 if (RD->isUnion())
1364 FwdDeclNode->replaceOperandWith(10, Elements);
1365 else if (CXXDecl) {
1366 FwdDeclNode->replaceOperandWith(10, Elements);
1367 FwdDeclNode->replaceOperandWith(13, TParamsArray);
1368 } else
1369 FwdDeclNode->replaceOperandWith(10, Elements);
1370
1371 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDeclNode);
1372 return llvm::DIType(FwdDeclNode);
1373}
1374
1375/// CreateType - get objective-c object type.
1376llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1377 llvm::DIFile Unit) {
1378 // Ignore protocols.
1379 return getOrCreateType(Ty->getBaseType(), Unit);
1380}
1381
1382/// CreateType - get objective-c interface type.
1383llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1384 llvm::DIFile Unit) {
1385 ObjCInterfaceDecl *ID = Ty->getDecl();
1386 if (!ID)
1387 return llvm::DIType();
1388
1389 // Get overall information about the record type for the debug info.
1390 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1391 unsigned Line = getLineNumber(ID->getLocation());
1392 unsigned RuntimeLang = TheCU.getLanguage();
1393
1394 // If this is just a forward declaration return a special forward-declaration
1395 // debug type since we won't be able to lay out the entire type.
1396 ObjCInterfaceDecl *Def = ID->getDefinition();
1397 if (!Def) {
1398 llvm::DIType FwdDecl =
1399 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
1400 ID->getName(), TheCU, DefUnit, Line,
1401 RuntimeLang);
1402 return FwdDecl;
1403 }
1404
1405 ID = Def;
1406
1407 // Bit size, align and offset of the type.
1408 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1409 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1410
1411 unsigned Flags = 0;
1412 if (ID->getImplementation())
1413 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1414
1415 llvm::DIType RealDecl =
1416 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1417 Line, Size, Align, Flags,
1418 llvm::DIArray(), RuntimeLang);
1419
1420 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1421 // will find it and we're emitting the complete type.
1422 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
1423 // Push the struct on region stack.
1424 llvm::TrackingVH<llvm::MDNode> FwdDeclNode(RealDecl);
1425
1426 LexicalBlockStack.push_back(FwdDeclNode);
1427 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1428
1429 // Convert all the elements.
1430 SmallVector<llvm::Value *, 16> EltTys;
1431
1432 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1433 if (SClass) {
1434 llvm::DIType SClassTy =
1435 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1436 if (!SClassTy.isValid())
1437 return llvm::DIType();
1438
1439 llvm::DIType InhTag =
1440 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1441 EltTys.push_back(InhTag);
1442 }
1443
1444 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1445 E = ID->prop_end(); I != E; ++I) {
1446 const ObjCPropertyDecl *PD = *I;
1447 SourceLocation Loc = PD->getLocation();
1448 llvm::DIFile PUnit = getOrCreateFile(Loc);
1449 unsigned PLine = getLineNumber(Loc);
1450 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1451 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1452 llvm::MDNode *PropertyNode =
1453 DBuilder.createObjCProperty(PD->getName(),
1454 PUnit, PLine,
1455 (Getter && Getter->isImplicit()) ? "" :
1456 getSelectorName(PD->getGetterName()),
1457 (Setter && Setter->isImplicit()) ? "" :
1458 getSelectorName(PD->getSetterName()),
1459 PD->getPropertyAttributes(),
1460 getOrCreateType(PD->getType(), PUnit));
1461 EltTys.push_back(PropertyNode);
1462 }
1463
1464 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1465 unsigned FieldNo = 0;
1466 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1467 Field = Field->getNextIvar(), ++FieldNo) {
1468 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1469 if (!FieldTy.isValid())
1470 return llvm::DIType();
1471
1472 StringRef FieldName = Field->getName();
1473
1474 // Ignore unnamed fields.
1475 if (FieldName.empty())
1476 continue;
1477
1478 // Get the location for the field.
1479 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1480 unsigned FieldLine = getLineNumber(Field->getLocation());
1481 QualType FType = Field->getType();
1482 uint64_t FieldSize = 0;
1483 unsigned FieldAlign = 0;
1484
1485 if (!FType->isIncompleteArrayType()) {
1486
1487 // Bit size, align and offset of the type.
1488 FieldSize = Field->isBitField()
1489 ? Field->getBitWidthValue(CGM.getContext())
1490 : CGM.getContext().getTypeSize(FType);
1491 FieldAlign = CGM.getContext().getTypeAlign(FType);
1492 }
1493
1494 uint64_t FieldOffset;
1495 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1496 // We don't know the runtime offset of an ivar if we're using the
1497 // non-fragile ABI. For bitfields, use the bit offset into the first
1498 // byte of storage of the bitfield. For other fields, use zero.
1499 if (Field->isBitField()) {
1500 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1501 CGM, ID, Field);
1502 FieldOffset %= CGM.getContext().getCharWidth();
1503 } else {
1504 FieldOffset = 0;
1505 }
1506 } else {
1507 FieldOffset = RL.getFieldOffset(FieldNo);
1508 }
1509
1510 unsigned Flags = 0;
1511 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1512 Flags = llvm::DIDescriptor::FlagProtected;
1513 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1514 Flags = llvm::DIDescriptor::FlagPrivate;
1515
1516 llvm::MDNode *PropertyNode = NULL;
1517 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1518 if (ObjCPropertyImplDecl *PImpD =
1519 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1520 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
1521 SourceLocation Loc = PD->getLocation();
1522 llvm::DIFile PUnit = getOrCreateFile(Loc);
1523 unsigned PLine = getLineNumber(Loc);
1524 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1525 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1526 PropertyNode =
1527 DBuilder.createObjCProperty(PD->getName(),
1528 PUnit, PLine,
1529 (Getter && Getter->isImplicit()) ? "" :
1530 getSelectorName(PD->getGetterName()),
1531 (Setter && Setter->isImplicit()) ? "" :
1532 getSelectorName(PD->getSetterName()),
1533 PD->getPropertyAttributes(),
1534 getOrCreateType(PD->getType(), PUnit));
1535 }
1536 }
1537 }
1538 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1539 FieldLine, FieldSize, FieldAlign,
1540 FieldOffset, Flags, FieldTy,
1541 PropertyNode);
1542 EltTys.push_back(FieldTy);
1543 }
1544
1545 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
1546 FwdDeclNode->replaceOperandWith(10, Elements);
1547
1548 LexicalBlockStack.pop_back();
1549 return llvm::DIType(FwdDeclNode);
1550}
1551
1552llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1553 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1554 int64_t Count = Ty->getNumElements();
1555 if (Count == 0)
1556 // If number of elements are not known then this is an unbounded array.
1557 // Use Count == -1 to express such arrays.
1558 Count = -1;
1559
1560 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1561 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1562
1563 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1564 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1565
1566 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1567}
1568
1569llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1570 llvm::DIFile Unit) {
1571 uint64_t Size;
1572 uint64_t Align;
1573
1574 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1575 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1576 Size = 0;
1577 Align =
1578 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1579 } else if (Ty->isIncompleteArrayType()) {
1580 Size = 0;
1581 if (Ty->getElementType()->isIncompleteType())
1582 Align = 0;
1583 else
1584 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
1585 } else if (Ty->isDependentSizedArrayType() || Ty->isIncompleteType()) {
1586 Size = 0;
1587 Align = 0;
1588 } else {
1589 // Size and align of the whole array, not the element type.
1590 Size = CGM.getContext().getTypeSize(Ty);
1591 Align = CGM.getContext().getTypeAlign(Ty);
1592 }
1593
1594 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1595 // interior arrays, do we care? Why aren't nested arrays represented the
1596 // obvious/recursive way?
1597 SmallVector<llvm::Value *, 8> Subscripts;
1598 QualType EltTy(Ty, 0);
1599 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1600 // If the number of elements is known, then count is that number. Otherwise,
1601 // it's -1. This allows us to represent a subrange with an array of 0
1602 // elements, like this:
1603 //
1604 // struct foo {
1605 // int x[0];
1606 // };
1607 int64_t Count = -1; // Count == -1 is an unbounded array.
1608 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1609 Count = CAT->getSize().getZExtValue();
1610
1611 // FIXME: Verify this is right for VLAs.
1612 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1613 EltTy = Ty->getElementType();
1614 }
1615
1616 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1617
1618 llvm::DIType DbgTy =
1619 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1620 SubscriptArray);
1621 return DbgTy;
1622}
1623
1624llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1625 llvm::DIFile Unit) {
1626 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1627 Ty, Ty->getPointeeType(), Unit);
1628}
1629
1630llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1631 llvm::DIFile Unit) {
1632 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1633 Ty, Ty->getPointeeType(), Unit);
1634}
1635
1636llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1637 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001638 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1639 if (!Ty->getPointeeType()->isFunctionType())
1640 return DBuilder.createMemberPointerType(
1641 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1642 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1643 CGM.getContext().getPointerType(
1644 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1645 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1646 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001647}
1648
1649llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1650 llvm::DIFile U) {
1651 // Ignore the atomic wrapping
1652 // FIXME: What is the correct representation?
1653 return getOrCreateType(Ty->getValueType(), U);
1654}
1655
1656/// CreateEnumType - get enumeration type.
1657llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1658 uint64_t Size = 0;
1659 uint64_t Align = 0;
1660 if (!ED->getTypeForDecl()->isIncompleteType()) {
1661 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1662 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1663 }
1664
1665 // If this is just a forward declaration, construct an appropriately
1666 // marked node and just return it.
1667 if (!ED->getDefinition()) {
1668 llvm::DIDescriptor EDContext;
1669 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1670 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1671 unsigned Line = getLineNumber(ED->getLocation());
1672 StringRef EDName = ED->getName();
1673 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1674 EDName, EDContext, DefUnit, Line, 0,
1675 Size, Align);
1676 }
1677
1678 // Create DIEnumerator elements for each enumerator.
1679 SmallVector<llvm::Value *, 16> Enumerators;
1680 ED = ED->getDefinition();
1681 for (EnumDecl::enumerator_iterator
1682 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1683 Enum != EnumEnd; ++Enum) {
1684 Enumerators.push_back(
1685 DBuilder.createEnumerator(Enum->getName(),
1686 Enum->getInitVal().getZExtValue()));
1687 }
1688
1689 // Return a CompositeType for the enum itself.
1690 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1691
1692 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1693 unsigned Line = getLineNumber(ED->getLocation());
1694 llvm::DIDescriptor EnumContext =
1695 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1696 llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
1697 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1698 llvm::DIType DbgTy =
1699 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1700 Size, Align, EltArray,
1701 ClassTy);
1702 return DbgTy;
1703}
1704
David Blaikie05491062013-01-21 04:37:12 +00001705static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1706 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001707 do {
David Blaikie05491062013-01-21 04:37:12 +00001708 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 QualType LastT = T;
1710 switch (T->getTypeClass()) {
1711 default:
David Blaikie05491062013-01-21 04:37:12 +00001712 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001713 case Type::TemplateSpecialization:
1714 T = cast<TemplateSpecializationType>(T)->desugar();
1715 break;
1716 case Type::TypeOfExpr:
1717 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1718 break;
1719 case Type::TypeOf:
1720 T = cast<TypeOfType>(T)->getUnderlyingType();
1721 break;
1722 case Type::Decltype:
1723 T = cast<DecltypeType>(T)->getUnderlyingType();
1724 break;
1725 case Type::UnaryTransform:
1726 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1727 break;
1728 case Type::Attributed:
1729 T = cast<AttributedType>(T)->getEquivalentType();
1730 break;
1731 case Type::Elaborated:
1732 T = cast<ElaboratedType>(T)->getNamedType();
1733 break;
1734 case Type::Paren:
1735 T = cast<ParenType>(T)->getInnerType();
1736 break;
David Blaikie05491062013-01-21 04:37:12 +00001737 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001738 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001739 break;
1740 case Type::Auto:
1741 T = cast<AutoType>(T)->getDeducedType();
1742 break;
1743 }
1744
1745 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001746 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001747 } while (true);
1748}
1749
1750/// getType - Get the type from the cache or return null type if it doesn't exist.
1751llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1752
1753 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001754 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001755
1756 // Check for existing entry.
1757 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1758 TypeCache.find(Ty.getAsOpaquePtr());
1759 if (it != TypeCache.end()) {
1760 // Verify that the debug info still exists.
1761 if (llvm::Value *V = it->second)
1762 return llvm::DIType(cast<llvm::MDNode>(V));
1763 }
1764
1765 return llvm::DIType();
1766}
1767
1768/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1769/// doesn't exist.
1770llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1771
1772 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001773 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001774
1775 // Check for existing entry.
1776 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1777 CompletedTypeCache.find(Ty.getAsOpaquePtr());
1778 if (it != CompletedTypeCache.end()) {
1779 // Verify that the debug info still exists.
1780 if (llvm::Value *V = it->second)
1781 return llvm::DIType(cast<llvm::MDNode>(V));
1782 }
1783
1784 return llvm::DIType();
1785}
1786
1787
1788/// getOrCreateType - Get the type from the cache or create a new
1789/// one if necessary.
1790llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1791 if (Ty.isNull())
1792 return llvm::DIType();
1793
1794 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001795 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001796
1797 llvm::DIType T = getCompletedTypeOrNull(Ty);
1798
1799 if (T.Verify())
1800 return T;
1801
1802 // Otherwise create the type.
1803 llvm::DIType Res = CreateTypeNode(Ty, Unit);
1804
1805 llvm::DIType TC = getTypeOrNull(Ty);
1806 if (TC.Verify() && TC.isForwardDecl())
1807 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1808 static_cast<llvm::Value*>(TC)));
1809
1810 // And update the type cache.
1811 TypeCache[Ty.getAsOpaquePtr()] = Res;
1812
1813 if (!Res.isForwardDecl())
1814 CompletedTypeCache[Ty.getAsOpaquePtr()] = Res;
1815
1816 return Res;
1817}
1818
1819/// CreateTypeNode - Create a new debug type node.
1820llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1821 // Handle qualifiers, which recursively handles what they refer to.
1822 if (Ty.hasLocalQualifiers())
1823 return CreateQualifiedType(Ty, Unit);
1824
1825 const char *Diag = 0;
1826
1827 // Work out details of type.
1828 switch (Ty->getTypeClass()) {
1829#define TYPE(Class, Base)
1830#define ABSTRACT_TYPE(Class, Base)
1831#define NON_CANONICAL_TYPE(Class, Base)
1832#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1833#include "clang/AST/TypeNodes.def"
1834 llvm_unreachable("Dependent types cannot show up in debug information");
1835
1836 case Type::ExtVector:
1837 case Type::Vector:
1838 return CreateType(cast<VectorType>(Ty), Unit);
1839 case Type::ObjCObjectPointer:
1840 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1841 case Type::ObjCObject:
1842 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1843 case Type::ObjCInterface:
1844 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1845 case Type::Builtin:
1846 return CreateType(cast<BuiltinType>(Ty));
1847 case Type::Complex:
1848 return CreateType(cast<ComplexType>(Ty));
1849 case Type::Pointer:
1850 return CreateType(cast<PointerType>(Ty), Unit);
1851 case Type::BlockPointer:
1852 return CreateType(cast<BlockPointerType>(Ty), Unit);
1853 case Type::Typedef:
1854 return CreateType(cast<TypedefType>(Ty), Unit);
1855 case Type::Record:
1856 return CreateType(cast<RecordType>(Ty));
1857 case Type::Enum:
1858 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
1859 case Type::FunctionProto:
1860 case Type::FunctionNoProto:
1861 return CreateType(cast<FunctionType>(Ty), Unit);
1862 case Type::ConstantArray:
1863 case Type::VariableArray:
1864 case Type::IncompleteArray:
1865 return CreateType(cast<ArrayType>(Ty), Unit);
1866
1867 case Type::LValueReference:
1868 return CreateType(cast<LValueReferenceType>(Ty), Unit);
1869 case Type::RValueReference:
1870 return CreateType(cast<RValueReferenceType>(Ty), Unit);
1871
1872 case Type::MemberPointer:
1873 return CreateType(cast<MemberPointerType>(Ty), Unit);
1874
1875 case Type::Atomic:
1876 return CreateType(cast<AtomicType>(Ty), Unit);
1877
1878 case Type::Attributed:
1879 case Type::TemplateSpecialization:
1880 case Type::Elaborated:
1881 case Type::Paren:
1882 case Type::SubstTemplateTypeParm:
1883 case Type::TypeOfExpr:
1884 case Type::TypeOf:
1885 case Type::Decltype:
1886 case Type::UnaryTransform:
1887 case Type::Auto:
1888 llvm_unreachable("type should have been unwrapped!");
1889 }
1890
1891 assert(Diag && "Fall through without a diagnostic?");
1892 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1893 "debug information for %0 is not yet supported");
1894 CGM.getDiags().Report(DiagID)
1895 << Diag;
1896 return llvm::DIType();
1897}
1898
1899/// getOrCreateLimitedType - Get the type from the cache or create a new
1900/// limited type if necessary.
1901llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
1902 llvm::DIFile Unit) {
1903 if (Ty.isNull())
1904 return llvm::DIType();
1905
1906 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001907 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001908
1909 llvm::DIType T = getTypeOrNull(Ty);
1910
1911 // We may have cached a forward decl when we could have created
1912 // a non-forward decl. Go ahead and create a non-forward decl
1913 // now.
1914 if (T.Verify() && !T.isForwardDecl()) return T;
1915
1916 // Otherwise create the type.
1917 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
1918
1919 if (T.Verify() && T.isForwardDecl())
1920 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
1921 static_cast<llvm::Value*>(T)));
1922
1923 // And update the type cache.
1924 TypeCache[Ty.getAsOpaquePtr()] = Res;
1925 return Res;
1926}
1927
1928// TODO: Currently used for context chains when limiting debug info.
1929llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
1930 RecordDecl *RD = Ty->getDecl();
1931
1932 // Get overall information about the record type for the debug info.
1933 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1934 unsigned Line = getLineNumber(RD->getLocation());
1935 StringRef RDName = getClassName(RD);
1936
1937 llvm::DIDescriptor RDContext;
1938 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
1939 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
1940 else
1941 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1942
1943 // If this is just a forward declaration, construct an appropriately
1944 // marked node and just return it.
1945 if (!RD->getDefinition())
1946 return createRecordFwdDecl(RD, RDContext);
1947
1948 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1949 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1950 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1951 llvm::TrackingVH<llvm::MDNode> RealDecl;
1952
1953 if (RD->isUnion())
1954 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
1955 Size, Align, 0, llvm::DIArray());
1956 else if (RD->isClass()) {
1957 // FIXME: This could be a struct type giving a default visibility different
1958 // than C++ class type, but needs llvm metadata changes first.
1959 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
1960 Size, Align, 0, 0, llvm::DIType(),
1961 llvm::DIArray(), llvm::DIType(),
1962 llvm::DIArray());
1963 } else
1964 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
1965 Size, Align, 0, llvm::DIArray());
1966
1967 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1968 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = llvm::DIType(RealDecl);
1969
1970 if (CXXDecl) {
1971 // A class's primary base or the class itself contains the vtable.
1972 llvm::MDNode *ContainingType = NULL;
1973 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1974 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
1975 // Seek non virtual primary base root.
1976 while (1) {
1977 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
1978 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
1979 if (PBT && !BRL.isPrimaryBaseVirtual())
1980 PBase = PBT;
1981 else
1982 break;
1983 }
1984 ContainingType =
1985 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit);
1986 }
1987 else if (CXXDecl->isDynamicClass())
1988 ContainingType = RealDecl;
1989
1990 RealDecl->replaceOperandWith(12, ContainingType);
1991 }
1992 return llvm::DIType(RealDecl);
1993}
1994
1995/// CreateLimitedTypeNode - Create a new debug type node, but only forward
1996/// declare composite types that haven't been processed yet.
1997llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
1998
1999 // Work out details of type.
2000 switch (Ty->getTypeClass()) {
2001#define TYPE(Class, Base)
2002#define ABSTRACT_TYPE(Class, Base)
2003#define NON_CANONICAL_TYPE(Class, Base)
2004#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2005 #include "clang/AST/TypeNodes.def"
2006 llvm_unreachable("Dependent types cannot show up in debug information");
2007
2008 case Type::Record:
2009 return CreateLimitedType(cast<RecordType>(Ty));
2010 default:
2011 return CreateTypeNode(Ty, Unit);
2012 }
2013}
2014
2015/// CreateMemberType - Create new member and increase Offset by FType's size.
2016llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2017 StringRef Name,
2018 uint64_t *Offset) {
2019 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2020 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2021 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2022 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2023 FieldSize, FieldAlign,
2024 *Offset, 0, FieldTy);
2025 *Offset += FieldSize;
2026 return Ty;
2027}
2028
2029/// getFunctionDeclaration - Return debug info descriptor to describe method
2030/// declaration for the given method definition.
2031llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2032 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2033 if (!FD) return llvm::DISubprogram();
2034
2035 // Setup context.
2036 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2037
2038 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2039 MI = SPCache.find(FD->getCanonicalDecl());
2040 if (MI != SPCache.end()) {
2041 llvm::Value *V = MI->second;
2042 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2043 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2044 return SP;
2045 }
2046
2047 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2048 E = FD->redecls_end(); I != E; ++I) {
2049 const FunctionDecl *NextFD = *I;
2050 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2051 MI = SPCache.find(NextFD->getCanonicalDecl());
2052 if (MI != SPCache.end()) {
2053 llvm::Value *V = MI->second;
2054 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2055 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2056 return SP;
2057 }
2058 }
2059 return llvm::DISubprogram();
2060}
2061
2062// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2063// implicit parameter "this".
2064llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2065 QualType FnType,
2066 llvm::DIFile F) {
2067
2068 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2069 return getOrCreateMethodType(Method, F);
2070 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2071 // Add "self" and "_cmd"
2072 SmallVector<llvm::Value *, 16> Elts;
2073
2074 // First element is always return type. For 'void' functions it is NULL.
2075 Elts.push_back(getOrCreateType(OMethod->getResultType(), F));
2076 // "self" pointer is always first argument.
2077 llvm::DIType SelfTy = getOrCreateType(OMethod->getSelfDecl()->getType(), F);
2078 Elts.push_back(DBuilder.createObjectPointerType(SelfTy));
2079 // "_cmd" pointer is always second argument.
2080 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2081 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2082 // Get rest of the arguments.
2083 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2084 PE = OMethod->param_end(); PI != PE; ++PI)
2085 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2086
2087 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2088 return DBuilder.createSubroutineType(F, EltTypeArray);
2089 }
2090 return getOrCreateType(FnType, F);
2091}
2092
2093/// EmitFunctionStart - Constructs the debug code for entering a function.
2094void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2095 llvm::Function *Fn,
2096 CGBuilderTy &Builder) {
2097
2098 StringRef Name;
2099 StringRef LinkageName;
2100
2101 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2102
2103 const Decl *D = GD.getDecl();
2104 // Function may lack declaration in source code if it is created by Clang
2105 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2106 bool HasDecl = (D != 0);
2107 // Use the location of the declaration.
2108 SourceLocation Loc;
2109 if (HasDecl)
2110 Loc = D->getLocation();
2111
2112 unsigned Flags = 0;
2113 llvm::DIFile Unit = getOrCreateFile(Loc);
2114 llvm::DIDescriptor FDContext(Unit);
2115 llvm::DIArray TParamsArray;
2116 if (!HasDecl) {
2117 // Use llvm function name.
2118 Name = Fn->getName();
2119 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2120 // If there is a DISubprogram for this function available then use it.
2121 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2122 FI = SPCache.find(FD->getCanonicalDecl());
2123 if (FI != SPCache.end()) {
2124 llvm::Value *V = FI->second;
2125 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2126 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2127 llvm::MDNode *SPN = SP;
2128 LexicalBlockStack.push_back(SPN);
2129 RegionMap[D] = llvm::WeakVH(SP);
2130 return;
2131 }
2132 }
2133 Name = getFunctionName(FD);
2134 // Use mangled name as linkage name for c/c++ functions.
2135 if (FD->hasPrototype()) {
2136 LinkageName = CGM.getMangledName(GD);
2137 Flags |= llvm::DIDescriptor::FlagPrototyped;
2138 }
2139 if (LinkageName == Name ||
2140 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly)
2141 LinkageName = StringRef();
2142
2143 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2144 if (const NamespaceDecl *NSDecl =
2145 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2146 FDContext = getOrCreateNameSpace(NSDecl);
2147 else if (const RecordDecl *RDecl =
2148 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2149 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2150
2151 // Collect template parameters.
2152 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2153 }
2154 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2155 Name = getObjCMethodName(OMD);
2156 Flags |= llvm::DIDescriptor::FlagPrototyped;
2157 } else {
2158 // Use llvm function name.
2159 Name = Fn->getName();
2160 Flags |= llvm::DIDescriptor::FlagPrototyped;
2161 }
2162 if (!Name.empty() && Name[0] == '\01')
2163 Name = Name.substr(1);
2164
2165 unsigned LineNo = getLineNumber(Loc);
2166 if (!HasDecl || D->isImplicit())
2167 Flags |= llvm::DIDescriptor::FlagArtificial;
2168
2169 llvm::DIType DIFnType;
2170 llvm::DISubprogram SPDecl;
2171 if (HasDecl &&
2172 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2173 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2174 SPDecl = getFunctionDeclaration(D);
2175 } else {
2176 // Create fake but valid subroutine type. Otherwise
2177 // llvm::DISubprogram::Verify() would return false, and
2178 // subprogram DIE will miss DW_AT_decl_file and
2179 // DW_AT_decl_line fields.
2180 SmallVector<llvm::Value*, 16> Elts;
2181 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2182 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2183 }
2184 llvm::DISubprogram SP;
2185 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2186 LineNo, DIFnType,
2187 Fn->hasInternalLinkage(), true/*definition*/,
2188 getLineNumber(CurLoc), Flags,
2189 CGM.getLangOpts().Optimize,
2190 Fn, TParamsArray, SPDecl);
2191
2192 // Push function on region stack.
2193 llvm::MDNode *SPN = SP;
2194 LexicalBlockStack.push_back(SPN);
2195 if (HasDecl)
2196 RegionMap[D] = llvm::WeakVH(SP);
2197}
2198
2199/// EmitLocation - Emit metadata to indicate a change in line/column
2200/// information in the source file.
2201void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc) {
2202
2203 // Update our current location
2204 setLocation(Loc);
2205
2206 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2207
2208 // Don't bother if things are the same as last time.
2209 SourceManager &SM = CGM.getContext().getSourceManager();
2210 if (CurLoc == PrevLoc ||
2211 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2212 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002213 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2214 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2215 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002216 return;
2217
2218 // Update last state.
2219 PrevLoc = CurLoc;
2220
2221 llvm::MDNode *Scope = LexicalBlockStack.back();
2222 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(CurLoc),
2223 getColumnNumber(CurLoc),
2224 Scope));
2225}
2226
2227/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2228/// the stack.
2229void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2230 llvm::DIDescriptor D =
2231 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2232 llvm::DIDescriptor() :
2233 llvm::DIDescriptor(LexicalBlockStack.back()),
2234 getOrCreateFile(CurLoc),
2235 getLineNumber(CurLoc),
2236 getColumnNumber(CurLoc));
2237 llvm::MDNode *DN = D;
2238 LexicalBlockStack.push_back(DN);
2239}
2240
2241/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2242/// region - beginning of a DW_TAG_lexical_block.
2243void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2244 // Set our current location.
2245 setLocation(Loc);
2246
2247 // Create a new lexical block and push it on the stack.
2248 CreateLexicalBlock(Loc);
2249
2250 // Emit a line table change for the current location inside the new scope.
2251 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2252 getColumnNumber(Loc),
2253 LexicalBlockStack.back()));
2254}
2255
2256/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2257/// region - end of a DW_TAG_lexical_block.
2258void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2259 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2260
2261 // Provide an entry in the line table for the end of the block.
2262 EmitLocation(Builder, Loc);
2263
2264 LexicalBlockStack.pop_back();
2265}
2266
2267/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2268void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2269 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2270 unsigned RCount = FnBeginRegionCount.back();
2271 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2272
2273 // Pop all regions for this function.
2274 while (LexicalBlockStack.size() != RCount)
2275 EmitLexicalBlockEnd(Builder, CurLoc);
2276 FnBeginRegionCount.pop_back();
2277}
2278
2279// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2280// See BuildByRefType.
2281llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2282 uint64_t *XOffset) {
2283
2284 SmallVector<llvm::Value *, 5> EltTys;
2285 QualType FType;
2286 uint64_t FieldSize, FieldOffset;
2287 unsigned FieldAlign;
2288
2289 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2290 QualType Type = VD->getType();
2291
2292 FieldOffset = 0;
2293 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2294 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2295 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2296 FType = CGM.getContext().IntTy;
2297 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2298 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2299
2300 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2301 if (HasCopyAndDispose) {
2302 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2303 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2304 &FieldOffset));
2305 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2306 &FieldOffset));
2307 }
2308 bool HasByrefExtendedLayout;
2309 Qualifiers::ObjCLifetime Lifetime;
2310 if (CGM.getContext().getByrefLifetime(Type,
2311 Lifetime, HasByrefExtendedLayout)
2312 && HasByrefExtendedLayout)
2313 EltTys.push_back(CreateMemberType(Unit, FType,
2314 "__byref_variable_layout",
2315 &FieldOffset));
2316
2317 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2318 if (Align > CGM.getContext().toCharUnitsFromBits(
2319 CGM.getContext().getTargetInfo().getPointerAlign(0))) {
2320 CharUnits FieldOffsetInBytes
2321 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2322 CharUnits AlignedOffsetInBytes
2323 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2324 CharUnits NumPaddingBytes
2325 = AlignedOffsetInBytes - FieldOffsetInBytes;
2326
2327 if (NumPaddingBytes.isPositive()) {
2328 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2329 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2330 pad, ArrayType::Normal, 0);
2331 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2332 }
2333 }
2334
2335 FType = Type;
2336 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2337 FieldSize = CGM.getContext().getTypeSize(FType);
2338 FieldAlign = CGM.getContext().toBits(Align);
2339
2340 *XOffset = FieldOffset;
2341 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2342 0, FieldSize, FieldAlign,
2343 FieldOffset, 0, FieldTy);
2344 EltTys.push_back(FieldTy);
2345 FieldOffset += FieldSize;
2346
2347 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2348
2349 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2350
2351 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
2352 Elements);
2353}
2354
2355/// EmitDeclare - Emit local variable declaration debug info.
2356void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2357 llvm::Value *Storage,
2358 unsigned ArgNo, CGBuilderTy &Builder) {
2359 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2360 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2361
2362 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2363 llvm::DIType Ty;
2364 uint64_t XOffset = 0;
2365 if (VD->hasAttr<BlocksAttr>())
2366 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2367 else
2368 Ty = getOrCreateType(VD->getType(), Unit);
2369
2370 // If there is no debug info for this type then do not emit debug info
2371 // for this variable.
2372 if (!Ty)
2373 return;
2374
2375 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2376 // If Storage is an aggregate returned as 'sret' then let debugger know
2377 // about this.
2378 if (Arg->hasStructRetAttr())
2379 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2380 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2381 // If an aggregate variable has non trivial destructor or non trivial copy
2382 // constructor than it is pass indirectly. Let debug info know about this
2383 // by using reference of the aggregate type as a argument type.
2384 if (Record->hasNonTrivialCopyConstructor() ||
2385 !Record->hasTrivialDestructor())
2386 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2387 }
2388 }
2389
2390 // Get location information.
2391 unsigned Line = getLineNumber(VD->getLocation());
2392 unsigned Column = getColumnNumber(VD->getLocation());
2393 unsigned Flags = 0;
2394 if (VD->isImplicit())
2395 Flags |= llvm::DIDescriptor::FlagArtificial;
2396 // If this is the first argument and it is implicit then
2397 // give it an object pointer flag.
2398 // FIXME: There has to be a better way to do this, but for static
2399 // functions there won't be an implicit param at arg1 and
2400 // otherwise it is 'self' or 'this'.
2401 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2402 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2403
2404 llvm::MDNode *Scope = LexicalBlockStack.back();
2405
2406 StringRef Name = VD->getName();
2407 if (!Name.empty()) {
2408 if (VD->hasAttr<BlocksAttr>()) {
2409 CharUnits offset = CharUnits::fromQuantity(32);
2410 SmallVector<llvm::Value *, 9> addr;
2411 llvm::Type *Int64Ty = CGM.Int64Ty;
2412 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2413 // offset of __forwarding field
2414 offset = CGM.getContext().toCharUnitsFromBits(
2415 CGM.getContext().getTargetInfo().getPointerWidth(0));
2416 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2417 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2418 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2419 // offset of x field
2420 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2421 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2422
2423 // Create the descriptor for the variable.
2424 llvm::DIVariable D =
2425 DBuilder.createComplexVariable(Tag,
2426 llvm::DIDescriptor(Scope),
2427 VD->getName(), Unit, Line, Ty,
2428 addr, ArgNo);
2429
2430 // Insert an llvm.dbg.declare into the current block.
2431 llvm::Instruction *Call =
2432 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2433 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2434 return;
2435 } else if (isa<VariableArrayType>(VD->getType())) {
2436 // These are "complex" variables in that they need an op_deref.
2437 // Create the descriptor for the variable.
2438 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2439 llvm::DIBuilder::OpDeref);
2440 llvm::DIVariable D =
2441 DBuilder.createComplexVariable(Tag,
2442 llvm::DIDescriptor(Scope),
2443 Name, Unit, Line, Ty,
2444 Addr, ArgNo);
2445
2446 // Insert an llvm.dbg.declare into the current block.
2447 llvm::Instruction *Call =
2448 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2449 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2450 return;
2451 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002452 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2453 // If VD is an anonymous union then Storage represents value for
2454 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002455 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002456 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002457 for (RecordDecl::field_iterator I = RD->field_begin(),
2458 E = RD->field_end();
2459 I != E; ++I) {
2460 FieldDecl *Field = *I;
2461 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2462 StringRef FieldName = Field->getName();
2463
2464 // Ignore unnamed fields. Do not ignore unnamed records.
2465 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2466 continue;
2467
2468 // Use VarDecl's Tag, Scope and Line number.
2469 llvm::DIVariable D =
2470 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2471 FieldName, Unit, Line, FieldTy,
2472 CGM.getLangOpts().Optimize, Flags,
2473 ArgNo);
2474
2475 // Insert an llvm.dbg.declare into the current block.
2476 llvm::Instruction *Call =
2477 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2478 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2479 }
David Blaikie219c7d92013-01-05 20:03:07 +00002480 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 }
2482 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002483
2484 // Create the descriptor for the variable.
2485 llvm::DIVariable D =
2486 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2487 Name, Unit, Line, Ty,
2488 CGM.getLangOpts().Optimize, Flags, ArgNo);
2489
2490 // Insert an llvm.dbg.declare into the current block.
2491 llvm::Instruction *Call =
2492 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2493 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002494}
2495
2496void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2497 llvm::Value *Storage,
2498 CGBuilderTy &Builder) {
2499 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2500 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2501}
2502
2503void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2504 llvm::Value *Storage,
2505 CGBuilderTy &Builder,
2506 const CGBlockInfo &blockInfo) {
2507 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2508 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2509
2510 if (Builder.GetInsertBlock() == 0)
2511 return;
2512
2513 bool isByRef = VD->hasAttr<BlocksAttr>();
2514
2515 uint64_t XOffset = 0;
2516 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2517 llvm::DIType Ty;
2518 if (isByRef)
2519 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2520 else
2521 Ty = getOrCreateType(VD->getType(), Unit);
2522
2523 // Self is passed along as an implicit non-arg variable in a
2524 // block. Mark it as the object pointer.
2525 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
2526 Ty = DBuilder.createObjectPointerType(Ty);
2527
2528 // Get location information.
2529 unsigned Line = getLineNumber(VD->getLocation());
2530 unsigned Column = getColumnNumber(VD->getLocation());
2531
2532 const llvm::DataLayout &target = CGM.getDataLayout();
2533
2534 CharUnits offset = CharUnits::fromQuantity(
2535 target.getStructLayout(blockInfo.StructureType)
2536 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2537
2538 SmallVector<llvm::Value *, 9> addr;
2539 llvm::Type *Int64Ty = CGM.Int64Ty;
2540 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2541 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2542 if (isByRef) {
2543 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2544 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2545 // offset of __forwarding field
2546 offset = CGM.getContext()
2547 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2548 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2549 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2550 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2551 // offset of x field
2552 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2553 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2554 }
2555
2556 // Create the descriptor for the variable.
2557 llvm::DIVariable D =
2558 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2559 llvm::DIDescriptor(LexicalBlockStack.back()),
2560 VD->getName(), Unit, Line, Ty, addr);
2561 // Insert an llvm.dbg.declare into the current block.
2562 llvm::Instruction *Call =
2563 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2564 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2565 LexicalBlockStack.back()));
2566}
2567
2568/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2569/// variable declaration.
2570void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2571 unsigned ArgNo,
2572 CGBuilderTy &Builder) {
2573 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2574 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2575}
2576
2577namespace {
2578 struct BlockLayoutChunk {
2579 uint64_t OffsetInBits;
2580 const BlockDecl::Capture *Capture;
2581 };
2582 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2583 return l.OffsetInBits < r.OffsetInBits;
2584 }
2585}
2586
2587void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
2588 llvm::Value *addr,
2589 CGBuilderTy &Builder) {
2590 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2591 ASTContext &C = CGM.getContext();
2592 const BlockDecl *blockDecl = block.getBlockDecl();
2593
2594 // Collect some general information about the block's location.
2595 SourceLocation loc = blockDecl->getCaretLocation();
2596 llvm::DIFile tunit = getOrCreateFile(loc);
2597 unsigned line = getLineNumber(loc);
2598 unsigned column = getColumnNumber(loc);
2599
2600 // Build the debug-info type for the block literal.
2601 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2602
2603 const llvm::StructLayout *blockLayout =
2604 CGM.getDataLayout().getStructLayout(block.StructureType);
2605
2606 SmallVector<llvm::Value*, 16> fields;
2607 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2608 blockLayout->getElementOffsetInBits(0),
2609 tunit, tunit));
2610 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2611 blockLayout->getElementOffsetInBits(1),
2612 tunit, tunit));
2613 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2614 blockLayout->getElementOffsetInBits(2),
2615 tunit, tunit));
2616 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2617 blockLayout->getElementOffsetInBits(3),
2618 tunit, tunit));
2619 fields.push_back(createFieldType("__descriptor",
2620 C.getPointerType(block.NeedsCopyDispose ?
2621 C.getBlockDescriptorExtendedType() :
2622 C.getBlockDescriptorType()),
2623 0, loc, AS_public,
2624 blockLayout->getElementOffsetInBits(4),
2625 tunit, tunit));
2626
2627 // We want to sort the captures by offset, not because DWARF
2628 // requires this, but because we're paranoid about debuggers.
2629 SmallVector<BlockLayoutChunk, 8> chunks;
2630
2631 // 'this' capture.
2632 if (blockDecl->capturesCXXThis()) {
2633 BlockLayoutChunk chunk;
2634 chunk.OffsetInBits =
2635 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2636 chunk.Capture = 0;
2637 chunks.push_back(chunk);
2638 }
2639
2640 // Variable captures.
2641 for (BlockDecl::capture_const_iterator
2642 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2643 i != e; ++i) {
2644 const BlockDecl::Capture &capture = *i;
2645 const VarDecl *variable = capture.getVariable();
2646 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2647
2648 // Ignore constant captures.
2649 if (captureInfo.isConstant())
2650 continue;
2651
2652 BlockLayoutChunk chunk;
2653 chunk.OffsetInBits =
2654 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2655 chunk.Capture = &capture;
2656 chunks.push_back(chunk);
2657 }
2658
2659 // Sort by offset.
2660 llvm::array_pod_sort(chunks.begin(), chunks.end());
2661
2662 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2663 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2664 uint64_t offsetInBits = i->OffsetInBits;
2665 const BlockDecl::Capture *capture = i->Capture;
2666
2667 // If we have a null capture, this must be the C++ 'this' capture.
2668 if (!capture) {
2669 const CXXMethodDecl *method =
2670 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2671 QualType type = method->getThisType(C);
2672
2673 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2674 offsetInBits, tunit, tunit));
2675 continue;
2676 }
2677
2678 const VarDecl *variable = capture->getVariable();
2679 StringRef name = variable->getName();
2680
2681 llvm::DIType fieldType;
2682 if (capture->isByRef()) {
2683 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2684
2685 // FIXME: this creates a second copy of this type!
2686 uint64_t xoffset;
2687 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2688 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2689 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2690 ptrInfo.first, ptrInfo.second,
2691 offsetInBits, 0, fieldType);
2692 } else {
2693 fieldType = createFieldType(name, variable->getType(), 0,
2694 loc, AS_public, offsetInBits, tunit, tunit);
2695 }
2696 fields.push_back(fieldType);
2697 }
2698
2699 SmallString<36> typeName;
2700 llvm::raw_svector_ostream(typeName)
2701 << "__block_literal_" << CGM.getUniqueBlockCount();
2702
2703 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2704
2705 llvm::DIType type =
2706 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2707 CGM.getContext().toBits(block.BlockSize),
2708 CGM.getContext().toBits(block.BlockAlign),
2709 0, fieldsArray);
2710 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2711
2712 // Get overall information about the block.
2713 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2714 llvm::MDNode *scope = LexicalBlockStack.back();
2715 StringRef name = ".block_descriptor";
2716
2717 // Create the descriptor for the parameter.
2718 llvm::DIVariable debugVar =
2719 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2720 llvm::DIDescriptor(scope),
2721 name, tunit, line, type,
2722 CGM.getLangOpts().Optimize, flags,
2723 cast<llvm::Argument>(addr)->getArgNo() + 1);
2724
2725 // Insert an llvm.dbg.value into the current block.
2726 llvm::Instruction *declare =
2727 DBuilder.insertDbgValueIntrinsic(addr, 0, debugVar,
2728 Builder.GetInsertBlock());
2729 declare->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2730}
2731
Eric Christopher91a31902013-01-16 01:22:32 +00002732/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2733/// a static data member of a class, find its corresponding in-class
2734/// declaration.
2735llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2736 if (cast<VarDecl>(D)->isStaticDataMember()) {
2737 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2738 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2739 if (MI != StaticDataMemberCache.end())
2740 // Verify the info still exists.
2741 if (llvm::Value *V = MI->second)
2742 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2743 }
2744 return llvm::DIDerivedType();
2745}
2746
Guy Benyei11169dd2012-12-18 14:30:41 +00002747/// EmitGlobalVariable - Emit information about a global variable.
2748void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2749 const VarDecl *D) {
2750 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2751 // Create global variable debug descriptor.
2752 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2753 unsigned LineNo = getLineNumber(D->getLocation());
2754
2755 setLocation(D->getLocation());
2756
2757 QualType T = D->getType();
2758 if (T->isIncompleteArrayType()) {
2759
2760 // CodeGen turns int[] into int[1] so we'll do the same here.
2761 llvm::APInt ConstVal(32, 1);
2762 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2763
2764 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2765 ArrayType::Normal, 0);
2766 }
2767 StringRef DeclName = D->getName();
2768 StringRef LinkageName;
2769 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2770 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2771 LinkageName = Var->getName();
2772 if (LinkageName == DeclName)
2773 LinkageName = StringRef();
2774 llvm::DIDescriptor DContext =
2775 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
2776 DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
2777 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher91a31902013-01-16 01:22:32 +00002778 Var->hasInternalLinkage(), Var,
2779 getStaticDataMemberDeclaration(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00002780}
2781
2782/// EmitGlobalVariable - Emit information about an objective-c interface.
2783void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2784 ObjCInterfaceDecl *ID) {
2785 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2786 // Create global variable debug descriptor.
2787 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2788 unsigned LineNo = getLineNumber(ID->getLocation());
2789
2790 StringRef Name = ID->getName();
2791
2792 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2793 if (T->isIncompleteArrayType()) {
2794
2795 // CodeGen turns int[] into int[1] so we'll do the same here.
2796 llvm::APInt ConstVal(32, 1);
2797 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2798
2799 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2800 ArrayType::Normal, 0);
2801 }
2802
2803 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2804 getOrCreateType(T, Unit),
2805 Var->hasInternalLinkage(), Var);
2806}
2807
2808/// EmitGlobalVariable - Emit global variable's debug info.
2809void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
2810 llvm::Constant *Init) {
2811 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2812 // Create the descriptor for the variable.
2813 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2814 StringRef Name = VD->getName();
2815 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
2816 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
2817 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
2818 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
2819 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
2820 }
2821 // Do not use DIGlobalVariable for enums.
2822 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
2823 return;
2824 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
2825 getLineNumber(VD->getLocation()),
Eric Christopher91a31902013-01-16 01:22:32 +00002826 Ty, true, Init,
2827 getStaticDataMemberDeclaration(VD));
Guy Benyei11169dd2012-12-18 14:30:41 +00002828}
2829
2830/// getOrCreateNamesSpace - Return namespace descriptor for the given
2831/// namespace decl.
2832llvm::DINameSpace
2833CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
2834 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
2835 NameSpaceCache.find(NSDecl);
2836 if (I != NameSpaceCache.end())
2837 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
2838
2839 unsigned LineNo = getLineNumber(NSDecl->getLocation());
2840 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
2841 llvm::DIDescriptor Context =
2842 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
2843 llvm::DINameSpace NS =
2844 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
2845 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
2846 return NS;
2847}
2848
2849void CGDebugInfo::finalize() {
2850 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
2851 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
2852 llvm::DIType Ty, RepTy;
2853 // Verify that the debug info still exists.
2854 if (llvm::Value *V = VI->second)
2855 Ty = llvm::DIType(cast<llvm::MDNode>(V));
2856
2857 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2858 TypeCache.find(VI->first);
2859 if (it != TypeCache.end()) {
2860 // Verify that the debug info still exists.
2861 if (llvm::Value *V = it->second)
2862 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
2863 }
2864
2865 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify()) {
2866 Ty.replaceAllUsesWith(RepTy);
2867 }
2868 }
2869 DBuilder.finalize();
2870}