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