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