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