blob: 13b681edc9e6958751f8e09a0f909c5a424efcb1 [file] [log] [blame]
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie9dfd2432013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei7f92f2d2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
44 : CGM(CGM), DBuilder(CGM.getModule()),
45 BlockLiteralGenericSet(false) {
46 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
54void CGDebugInfo::setLocation(SourceLocation Loc) {
55 // If the new location isn't valid return.
56 if (!Loc.isValid()) return;
57
58 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
59
60 // If we've changed files in the middle of a lexical scope go ahead
61 // and create a new lexical scope with file node if it's different
62 // from the one in the scope.
63 if (LexicalBlockStack.empty()) return;
64
65 SourceManager &SM = CGM.getContext().getSourceManager();
66 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
67 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
68
69 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
70 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
71 return;
72
73 llvm::MDNode *LB = LexicalBlockStack.back();
74 llvm::DIScope Scope = llvm::DIScope(LB);
75 if (Scope.isLexicalBlockFile()) {
76 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
77 llvm::DIDescriptor D
78 = DBuilder.createLexicalBlockFile(LBF.getScope(),
79 getOrCreateFile(CurLoc));
80 llvm::MDNode *N = D;
81 LexicalBlockStack.pop_back();
82 LexicalBlockStack.push_back(N);
David Blaikiea6504852013-01-26 22:16:26 +000083 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000084 llvm::DIDescriptor D
85 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
86 llvm::MDNode *N = D;
87 LexicalBlockStack.pop_back();
88 LexicalBlockStack.push_back(N);
89 }
90}
91
92/// getContextDescriptor - Get context info for the decl.
David Blaikiebb000792013-04-19 06:56:38 +000093llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +000094 if (!Context)
95 return TheCU;
96
97 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
98 I = RegionMap.find(Context);
99 if (I != RegionMap.end()) {
100 llvm::Value *V = I->second;
David Blaikiebb000792013-04-19 06:56:38 +0000101 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000102 }
103
104 // Check namespace.
105 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebb000792013-04-19 06:56:38 +0000106 return getOrCreateNameSpace(NSDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000107
David Blaikiebb000792013-04-19 06:56:38 +0000108 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
109 if (!RDecl->isDependentType())
110 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000111 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000112 return TheCU;
113}
114
115/// getFunctionName - Get function name for the given FunctionDecl. If the
116/// name is constructred on demand (e.g. C++ destructor) then the name
117/// is stored on the side.
118StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
119 assert (FD && "Invalid FunctionDecl!");
120 IdentifierInfo *FII = FD->getIdentifier();
121 FunctionTemplateSpecializationInfo *Info
122 = FD->getTemplateSpecializationInfo();
123 if (!Info && FII)
124 return FII->getName();
125
126 // Otherwise construct human readable name for debug info.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000127 SmallString<128> NS;
128 llvm::raw_svector_ostream OS(NS);
129 FD->printName(OS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000130
131 // Add any template specialization args.
132 if (Info) {
133 const TemplateArgumentList *TArgs = Info->TemplateArguments;
134 const TemplateArgument *Args = TArgs->data();
135 unsigned NumArgs = TArgs->size();
136 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000137 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
138 Policy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000139 }
140
141 // Copy this name on the side and use its reference.
Benjamin Kramer5eada842013-02-22 15:46:01 +0000142 OS.flush();
143 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
144 memcpy(StrPtr, NS.data(), NS.size());
145 return StringRef(StrPtr, NS.size());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000146}
147
148StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
149 SmallString<256> MethodName;
150 llvm::raw_svector_ostream OS(MethodName);
151 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
152 const DeclContext *DC = OMD->getDeclContext();
153 if (const ObjCImplementationDecl *OID =
154 dyn_cast<const ObjCImplementationDecl>(DC)) {
155 OS << OID->getName();
156 } else if (const ObjCInterfaceDecl *OID =
157 dyn_cast<const ObjCInterfaceDecl>(DC)) {
158 OS << OID->getName();
159 } else if (const ObjCCategoryImplDecl *OCD =
160 dyn_cast<const ObjCCategoryImplDecl>(DC)){
161 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
162 OCD->getIdentifier()->getNameStart() << ')';
163 }
164 OS << ' ' << OMD->getSelector().getAsString() << ']';
165
166 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
167 memcpy(StrPtr, MethodName.begin(), OS.tell());
168 return StringRef(StrPtr, OS.tell());
169}
170
171/// getSelectorName - Return selector name. This is used for debugging
172/// info.
173StringRef CGDebugInfo::getSelectorName(Selector S) {
174 const std::string &SName = S.getAsString();
175 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
176 memcpy(StrPtr, SName.data(), SName.size());
177 return StringRef(StrPtr, SName.size());
178}
179
180/// getClassName - Get class name including template argument list.
181StringRef
182CGDebugInfo::getClassName(const RecordDecl *RD) {
183 const ClassTemplateSpecializationDecl *Spec
184 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
185 if (!Spec)
186 return RD->getName();
187
188 const TemplateArgument *Args;
189 unsigned NumArgs;
190 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
191 const TemplateSpecializationType *TST =
192 cast<TemplateSpecializationType>(TAW->getType());
193 Args = TST->getArgs();
194 NumArgs = TST->getNumArgs();
195 } else {
196 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
197 Args = TemplateArgs.data();
198 NumArgs = TemplateArgs.size();
199 }
200 StringRef Name = RD->getIdentifier()->getName();
201 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer5eada842013-02-22 15:46:01 +0000202 SmallString<128> TemplateArgList;
203 {
204 llvm::raw_svector_ostream OS(TemplateArgList);
205 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
206 Policy);
207 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000208
209 // Copy this name on the side and use its reference.
210 size_t Length = Name.size() + TemplateArgList.size();
211 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
212 memcpy(StrPtr, Name.data(), Name.size());
213 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
214 return StringRef(StrPtr, Length);
215}
216
217/// getOrCreateFile - Get the file debug info descriptor for the input location.
218llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
219 if (!Loc.isValid())
220 // If Location is not valid then use main input file.
221 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
222
223 SourceManager &SM = CGM.getContext().getSourceManager();
224 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
225
226 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
227 // If the location is not valid then use main input file.
228 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
229
230 // Cache the results.
231 const char *fname = PLoc.getFilename();
232 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
233 DIFileCache.find(fname);
234
235 if (it != DIFileCache.end()) {
236 // Verify that the information still exists.
237 if (llvm::Value *V = it->second)
238 return llvm::DIFile(cast<llvm::MDNode>(V));
239 }
240
241 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
242
243 DIFileCache[fname] = F;
244 return F;
245}
246
247/// getOrCreateMainFile - Get the file info for main compile unit.
248llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
249 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
250}
251
252/// getLineNumber - Get line number for the location. If location is invalid
253/// then use current location.
254unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
255 if (Loc.isInvalid() && CurLoc.isInvalid())
256 return 0;
257 SourceManager &SM = CGM.getContext().getSourceManager();
258 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
259 return PLoc.isValid()? PLoc.getLine() : 0;
260}
261
262/// getColumnNumber - Get column number for the location.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000263unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000264 // We may not want column information at all.
Adrian Prantl00df5ea2013-03-12 20:43:25 +0000265 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000266 return 0;
267
268 // If the location is invalid then use the current column.
269 if (Loc.isInvalid() && CurLoc.isInvalid())
270 return 0;
271 SourceManager &SM = CGM.getContext().getSourceManager();
272 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
273 return PLoc.isValid()? PLoc.getColumn() : 0;
274}
275
276StringRef CGDebugInfo::getCurrentDirname() {
277 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
278 return CGM.getCodeGenOpts().DebugCompilationDir;
279
280 if (!CWDName.empty())
281 return CWDName;
282 SmallString<256> CWD;
283 llvm::sys::fs::current_path(CWD);
284 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
285 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
286 return CWDName = StringRef(CompDirnamePtr, CWD.size());
287}
288
289/// CreateCompileUnit - Create new compile unit.
290void CGDebugInfo::CreateCompileUnit() {
291
292 // Get absolute path name.
293 SourceManager &SM = CGM.getContext().getSourceManager();
294 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
295 if (MainFileName.empty())
296 MainFileName = "<unknown>";
297
298 // The main file name provided via the "-main-file-name" option contains just
299 // the file name itself with no path information. This file name may have had
300 // a relative path, so we look into the actual file entry for the main
301 // file to determine the real absolute path for the file.
302 std::string MainFileDir;
303 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
304 MainFileDir = MainFile->getDir()->getName();
305 if (MainFileDir != ".")
306 MainFileName = MainFileDir + "/" + MainFileName;
307 }
308
309 // Save filename string.
310 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
311 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
312 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherff971d72013-02-22 23:50:16 +0000313
314 // Save split dwarf file string.
315 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
316 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
317 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
318 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000319
320 unsigned LangTag;
321 const LangOptions &LO = CGM.getLangOpts();
322 if (LO.CPlusPlus) {
323 if (LO.ObjC1)
324 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
325 else
326 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
327 } else if (LO.ObjC1) {
328 LangTag = llvm::dwarf::DW_LANG_ObjC;
329 } else if (LO.C99) {
330 LangTag = llvm::dwarf::DW_LANG_C99;
331 } else {
332 LangTag = llvm::dwarf::DW_LANG_C89;
333 }
334
335 std::string Producer = getClangFullVersion();
336
337 // Figure out which version of the ObjC runtime we have.
338 unsigned RuntimeVers = 0;
339 if (LO.ObjC1)
340 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
341
342 // Create new compile unit.
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000343 DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
344 Producer, LO.Optimize,
Eric Christopherff971d72013-02-22 23:50:16 +0000345 CGM.getCodeGenOpts().DwarfDebugFlags,
346 RuntimeVers, SplitDwarfFilename);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000347 // FIXME - Eliminate TheCU.
348 TheCU = llvm::DICompileUnit(DBuilder.getCU());
349}
350
351/// CreateType - Get the Basic type from the cache or create a new
352/// one if necessary.
353llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
354 unsigned Encoding = 0;
355 StringRef BTName;
356 switch (BT->getKind()) {
357#define BUILTIN_TYPE(Id, SingletonId)
358#define PLACEHOLDER_TYPE(Id, SingletonId) \
359 case BuiltinType::Id:
360#include "clang/AST/BuiltinTypes.def"
361 case BuiltinType::Dependent:
362 llvm_unreachable("Unexpected builtin type");
363 case BuiltinType::NullPtr:
364 return DBuilder.
365 createNullPtrType(BT->getName(CGM.getLangOpts()));
366 case BuiltinType::Void:
367 return llvm::DIType();
368 case BuiltinType::ObjCClass:
369 if (ClassTy.Verify())
370 return ClassTy;
371 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
372 "objc_class", TheCU,
373 getOrCreateMainFile(), 0);
374 return ClassTy;
375 case BuiltinType::ObjCId: {
376 // typedef struct objc_class *Class;
377 // typedef struct objc_object {
378 // Class isa;
379 // } *id;
380
381 if (ObjTy.Verify())
382 return ObjTy;
383
384 if (!ClassTy.Verify())
385 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
386 "objc_class", TheCU,
387 getOrCreateMainFile(), 0);
388
389 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
390
391 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
392
Eric Christopherf068c922013-04-02 22:59:11 +0000393 ObjTy =
David Blaikiec1d0af12013-02-25 01:07:08 +0000394 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
395 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000396
Eric Christopherf068c922013-04-02 22:59:11 +0000397 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
398 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 return ObjTy;
400 }
401 case BuiltinType::ObjCSel: {
402 if (SelTy.Verify())
403 return SelTy;
404 SelTy =
405 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
406 "objc_selector", TheCU, getOrCreateMainFile(),
407 0);
408 return SelTy;
409 }
Guy Benyeib13621d2012-12-18 14:38:23 +0000410
411 case BuiltinType::OCLImage1d:
412 return getOrCreateStructPtrType("opencl_image1d_t",
413 OCLImage1dDITy);
414 case BuiltinType::OCLImage1dArray:
415 return getOrCreateStructPtrType("opencl_image1d_array_t",
416 OCLImage1dArrayDITy);
417 case BuiltinType::OCLImage1dBuffer:
418 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
419 OCLImage1dBufferDITy);
420 case BuiltinType::OCLImage2d:
421 return getOrCreateStructPtrType("opencl_image2d_t",
422 OCLImage2dDITy);
423 case BuiltinType::OCLImage2dArray:
424 return getOrCreateStructPtrType("opencl_image2d_array_t",
425 OCLImage2dArrayDITy);
426 case BuiltinType::OCLImage3d:
427 return getOrCreateStructPtrType("opencl_image3d_t",
428 OCLImage3dDITy);
Guy Benyei21f18c42013-02-07 10:55:47 +0000429 case BuiltinType::OCLSampler:
430 return DBuilder.createBasicType("opencl_sampler_t",
431 CGM.getContext().getTypeSize(BT),
432 CGM.getContext().getTypeAlign(BT),
433 llvm::dwarf::DW_ATE_unsigned);
Guy Benyeie6b9d802013-01-20 12:31:11 +0000434 case BuiltinType::OCLEvent:
435 return getOrCreateStructPtrType("opencl_event_t",
436 OCLEventDITy);
Guy Benyeib13621d2012-12-18 14:38:23 +0000437
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000438 case BuiltinType::UChar:
439 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
440 case BuiltinType::Char_S:
441 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
442 case BuiltinType::Char16:
443 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
444 case BuiltinType::UShort:
445 case BuiltinType::UInt:
446 case BuiltinType::UInt128:
447 case BuiltinType::ULong:
448 case BuiltinType::WChar_U:
449 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
450 case BuiltinType::Short:
451 case BuiltinType::Int:
452 case BuiltinType::Int128:
453 case BuiltinType::Long:
454 case BuiltinType::WChar_S:
455 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
456 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
457 case BuiltinType::Half:
458 case BuiltinType::Float:
459 case BuiltinType::LongDouble:
460 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
461 }
462
463 switch (BT->getKind()) {
464 case BuiltinType::Long: BTName = "long int"; break;
465 case BuiltinType::LongLong: BTName = "long long int"; break;
466 case BuiltinType::ULong: BTName = "long unsigned int"; break;
467 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
468 default:
469 BTName = BT->getName(CGM.getLangOpts());
470 break;
471 }
472 // Bit size, align and offset of the type.
473 uint64_t Size = CGM.getContext().getTypeSize(BT);
474 uint64_t Align = CGM.getContext().getTypeAlign(BT);
475 llvm::DIType DbgTy =
476 DBuilder.createBasicType(BTName, Size, Align, Encoding);
477 return DbgTy;
478}
479
480llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
481 // Bit size, align and offset of the type.
482 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
483 if (Ty->isComplexIntegerType())
484 Encoding = llvm::dwarf::DW_ATE_lo_user;
485
486 uint64_t Size = CGM.getContext().getTypeSize(Ty);
487 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
488 llvm::DIType DbgTy =
489 DBuilder.createBasicType("complex", Size, Align, Encoding);
490
491 return DbgTy;
492}
493
494/// CreateCVRType - Get the qualified type from the cache or create
495/// a new one if necessary.
496llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
497 QualifierCollector Qc;
498 const Type *T = Qc.strip(Ty);
499
500 // Ignore these qualifiers for now.
501 Qc.removeObjCGCAttr();
502 Qc.removeAddressSpace();
503 Qc.removeObjCLifetime();
504
505 // We will create one Derived type for one qualifier and recurse to handle any
506 // additional ones.
507 unsigned Tag;
508 if (Qc.hasConst()) {
509 Tag = llvm::dwarf::DW_TAG_const_type;
510 Qc.removeConst();
511 } else if (Qc.hasVolatile()) {
512 Tag = llvm::dwarf::DW_TAG_volatile_type;
513 Qc.removeVolatile();
514 } else if (Qc.hasRestrict()) {
515 Tag = llvm::dwarf::DW_TAG_restrict_type;
516 Qc.removeRestrict();
517 } else {
518 assert(Qc.empty() && "Unknown type qualifier for debug info");
519 return getOrCreateType(QualType(T, 0), Unit);
520 }
521
522 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
523
524 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
525 // CVR derived types.
526 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
527
528 return DbgTy;
529}
530
531llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
532 llvm::DIFile Unit) {
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000533
534 // The frontend treats 'id' as a typedef to an ObjCObjectType,
535 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
536 // debug info, we want to emit 'id' in both cases.
537 if (Ty->isObjCQualifiedIdType())
538 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
539
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000540 llvm::DIType DbgTy =
541 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
542 Ty->getPointeeType(), Unit);
543 return DbgTy;
544}
545
546llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
547 llvm::DIFile Unit) {
548 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
549 Ty->getPointeeType(), Unit);
550}
551
552// Creates a forward declaration for a RecordDecl in the given context.
553llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
554 llvm::DIDescriptor Ctx) {
555 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
556 unsigned Line = getLineNumber(RD->getLocation());
557 StringRef RDName = getClassName(RD);
558
559 unsigned Tag = 0;
560 if (RD->isStruct() || RD->isInterface())
561 Tag = llvm::dwarf::DW_TAG_structure_type;
562 else if (RD->isUnion())
563 Tag = llvm::dwarf::DW_TAG_union_type;
564 else {
565 assert(RD->isClass());
566 Tag = llvm::dwarf::DW_TAG_class_type;
567 }
568
569 // Create the type.
570 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
571}
572
573// Walk up the context chain and create forward decls for record decls,
574// and normal descriptors for namespaces.
575llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
576 if (!Context)
577 return TheCU;
578
579 // See if we already have the parent.
580 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
581 I = RegionMap.find(Context);
582 if (I != RegionMap.end()) {
583 llvm::Value *V = I->second;
584 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
585 }
586
587 // Check namespace.
588 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
589 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
590
591 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
592 if (!RD->isDependentType()) {
593 llvm::DIType Ty = getOrCreateLimitedType(CGM.getContext().getTypeDeclType(RD),
Eric Christopherbe5f1be2013-02-21 22:35:08 +0000594 getOrCreateMainFile());
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000595 return llvm::DIDescriptor(Ty);
596 }
597 }
598 return TheCU;
599}
600
601/// CreatePointeeType - Create Pointee type. If Pointee is a record
602/// then emit record's fwd if debug info size reduction is enabled.
603llvm::DIType CGDebugInfo::CreatePointeeType(QualType PointeeTy,
604 llvm::DIFile Unit) {
605 if (CGM.getCodeGenOpts().getDebugInfo() != CodeGenOptions::LimitedDebugInfo)
606 return getOrCreateType(PointeeTy, Unit);
607
608 // Limit debug info for the pointee type.
609
610 // If we have an existing type, use that, it's still smaller than creating
611 // a new type.
612 llvm::DIType Ty = getTypeOrNull(PointeeTy);
613 if (Ty.Verify()) return Ty;
614
615 // Handle qualifiers.
616 if (PointeeTy.hasLocalQualifiers())
617 return CreateQualifiedType(PointeeTy, Unit);
618
619 if (const RecordType *RTy = dyn_cast<RecordType>(PointeeTy)) {
620 RecordDecl *RD = RTy->getDecl();
621 llvm::DIDescriptor FDContext =
622 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
623 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
624 TypeCache[QualType(RTy, 0).getAsOpaquePtr()] = RetTy;
625 return RetTy;
626 }
627 return getOrCreateType(PointeeTy, Unit);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000628}
629
630llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
631 const Type *Ty,
632 QualType PointeeTy,
633 llvm::DIFile Unit) {
634 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
635 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
636 return DBuilder.createReferenceType(Tag,
637 CreatePointeeType(PointeeTy, Unit));
Fariborz Jahanian05f8ff12013-02-21 20:42:11 +0000638
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000639 // Bit size, align and offset of the type.
640 // Size is always the size of a pointer. We can't use getTypeSize here
641 // because that does not return the correct value for references.
642 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000643 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000644 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
645
646 return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
647 Size, Align);
648}
649
Guy Benyeib13621d2012-12-18 14:38:23 +0000650llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name, llvm::DIType &Cache) {
651 if (Cache.Verify())
652 return Cache;
653 Cache =
654 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
655 Name, TheCU, getOrCreateMainFile(),
656 0);
657 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
658 Cache = DBuilder.createPointerType(Cache, Size);
659 return Cache;
660}
661
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000662llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
663 llvm::DIFile Unit) {
664 if (BlockLiteralGenericSet)
665 return BlockLiteralGeneric;
666
667 SmallVector<llvm::Value *, 8> EltTys;
668 llvm::DIType FieldTy;
669 QualType FType;
670 uint64_t FieldSize, FieldOffset;
671 unsigned FieldAlign;
672 llvm::DIArray Elements;
673 llvm::DIType EltTy, DescTy;
674
675 FieldOffset = 0;
676 FType = CGM.getContext().UnsignedLongTy;
677 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
678 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
679
680 Elements = DBuilder.getOrCreateArray(EltTys);
681 EltTys.clear();
682
683 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
684 unsigned LineNo = getLineNumber(CurLoc);
685
686 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
687 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000688 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000689
690 // Bit size, align and offset of the type.
691 uint64_t Size = CGM.getContext().getTypeSize(Ty);
692
693 DescTy = DBuilder.createPointerType(EltTy, Size);
694
695 FieldOffset = 0;
696 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
697 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
698 FType = CGM.getContext().IntTy;
699 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
700 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
701 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
702 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
703
704 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
705 FieldTy = DescTy;
706 FieldSize = CGM.getContext().getTypeSize(Ty);
707 FieldAlign = CGM.getContext().getTypeAlign(Ty);
708 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
709 LineNo, FieldSize, FieldAlign,
710 FieldOffset, 0, FieldTy);
711 EltTys.push_back(FieldTy);
712
713 FieldOffset += FieldSize;
714 Elements = DBuilder.getOrCreateArray(EltTys);
715
716 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
717 Unit, LineNo, FieldOffset, 0,
David Blaikiec1d0af12013-02-25 01:07:08 +0000718 Flags, llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000719
720 BlockLiteralGenericSet = true;
721 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
722 return BlockLiteralGeneric;
723}
724
725llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
726 // Typedefs are derived from some other type. If we have a typedef of a
727 // typedef, make sure to emit the whole chain.
728 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
729 if (!Src.Verify())
730 return llvm::DIType();
731 // We don't set size information, but do specify where the typedef was
732 // declared.
733 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
734 const TypedefNameDecl *TyDecl = Ty->getDecl();
735
736 llvm::DIDescriptor TypedefContext =
737 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
738
739 return
740 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
741}
742
743llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
744 llvm::DIFile Unit) {
745 SmallVector<llvm::Value *, 16> EltTys;
746
747 // Add the result type at least.
748 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
749
750 // Set up remainder of arguments if there is a prototype.
751 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
752 if (isa<FunctionNoProtoType>(Ty))
753 EltTys.push_back(DBuilder.createUnspecifiedParameter());
754 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
755 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
756 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
757 }
758
759 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
760 return DBuilder.createSubroutineType(Unit, EltTypeArray);
761}
762
763
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000764llvm::DIType CGDebugInfo::createFieldType(StringRef name,
765 QualType type,
766 uint64_t sizeInBitsOverride,
767 SourceLocation loc,
768 AccessSpecifier AS,
769 uint64_t offsetInBits,
770 llvm::DIFile tunit,
771 llvm::DIDescriptor scope) {
772 llvm::DIType debugType = getOrCreateType(type, tunit);
773
774 // Get the location for the field.
775 llvm::DIFile file = getOrCreateFile(loc);
776 unsigned line = getLineNumber(loc);
777
778 uint64_t sizeInBits = 0;
779 unsigned alignInBits = 0;
780 if (!type->isIncompleteArrayType()) {
781 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
782
783 if (sizeInBitsOverride)
784 sizeInBits = sizeInBitsOverride;
785 }
786
787 unsigned flags = 0;
788 if (AS == clang::AS_private)
789 flags |= llvm::DIDescriptor::FlagPrivate;
790 else if (AS == clang::AS_protected)
791 flags |= llvm::DIDescriptor::FlagProtected;
792
793 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
794 alignInBits, offsetInBits, flags, debugType);
795}
796
Eric Christopher0395de32013-01-16 01:22:32 +0000797/// CollectRecordLambdaFields - Helper for CollectRecordFields.
798void CGDebugInfo::
799CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
800 SmallVectorImpl<llvm::Value *> &elements,
801 llvm::DIType RecordTy) {
802 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
803 // has the name and the location of the variable so we should iterate over
804 // both concurrently.
805 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
806 RecordDecl::field_iterator Field = CXXDecl->field_begin();
807 unsigned fieldno = 0;
808 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
809 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
810 const LambdaExpr::Capture C = *I;
811 if (C.capturesVariable()) {
812 VarDecl *V = C.getCapturedVar();
813 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
814 StringRef VName = V->getName();
815 uint64_t SizeInBitsOverride = 0;
816 if (Field->isBitField()) {
817 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
818 assert(SizeInBitsOverride && "found named 0-width bitfield");
819 }
820 llvm::DIType fieldType
821 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
822 C.getLocation(), Field->getAccess(),
823 layout.getFieldOffset(fieldno), VUnit, RecordTy);
824 elements.push_back(fieldType);
825 } else {
826 // TODO: Need to handle 'this' in some way by probably renaming the
827 // this of the lambda class and having a field member of 'this' or
828 // by using AT_object_pointer for the function and having that be
829 // used as 'this' for semantic references.
830 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
831 FieldDecl *f = *Field;
832 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
833 QualType type = f->getType();
834 llvm::DIType fieldType
835 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
836 layout.getFieldOffset(fieldno), VUnit, RecordTy);
837
838 elements.push_back(fieldType);
839 }
840 }
841}
842
843/// CollectRecordStaticField - Helper for CollectRecordFields.
844void CGDebugInfo::
845CollectRecordStaticField(const VarDecl *Var,
846 SmallVectorImpl<llvm::Value *> &elements,
847 llvm::DIType RecordTy) {
848 // Create the descriptor for the static variable, with or without
849 // constant initializers.
850 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
851 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
852
853 // Do not describe enums as static members.
854 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
855 return;
856
857 unsigned LineNumber = getLineNumber(Var->getLocation());
858 StringRef VName = Var->getName();
David Blaikiea89701b2013-01-20 01:19:17 +0000859 llvm::Constant *C = NULL;
Eric Christopher0395de32013-01-16 01:22:32 +0000860 if (Var->getInit()) {
861 const APValue *Value = Var->evaluateValue();
David Blaikiea89701b2013-01-20 01:19:17 +0000862 if (Value) {
863 if (Value->isInt())
864 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
865 if (Value->isFloat())
866 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
867 }
Eric Christopher0395de32013-01-16 01:22:32 +0000868 }
869
870 unsigned Flags = 0;
871 AccessSpecifier Access = Var->getAccess();
872 if (Access == clang::AS_private)
873 Flags |= llvm::DIDescriptor::FlagPrivate;
874 else if (Access == clang::AS_protected)
875 Flags |= llvm::DIDescriptor::FlagProtected;
876
877 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikiea89701b2013-01-20 01:19:17 +0000878 LineNumber, VTy, Flags, C);
Eric Christopher0395de32013-01-16 01:22:32 +0000879 elements.push_back(GV);
880 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
881}
882
883/// CollectRecordNormalField - Helper for CollectRecordFields.
884void CGDebugInfo::
885CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
886 llvm::DIFile tunit,
887 SmallVectorImpl<llvm::Value *> &elements,
888 llvm::DIType RecordTy) {
889 StringRef name = field->getName();
890 QualType type = field->getType();
891
892 // Ignore unnamed fields unless they're anonymous structs/unions.
893 if (name.empty() && !type->isRecordType())
894 return;
895
896 uint64_t SizeInBitsOverride = 0;
897 if (field->isBitField()) {
898 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
899 assert(SizeInBitsOverride && "found named 0-width bitfield");
900 }
901
902 llvm::DIType fieldType
903 = createFieldType(name, type, SizeInBitsOverride,
904 field->getLocation(), field->getAccess(),
905 OffsetInBits, tunit, RecordTy);
906
907 elements.push_back(fieldType);
908}
909
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000910/// CollectRecordFields - A helper function to collect debug info for
911/// record fields. This is used while creating debug info entry for a Record.
912void CGDebugInfo::
913CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
914 SmallVectorImpl<llvm::Value *> &elements,
915 llvm::DIType RecordTy) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000916 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
917
Eric Christopher0395de32013-01-16 01:22:32 +0000918 if (CXXDecl && CXXDecl->isLambda())
919 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
920 else {
921 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000922
Eric Christopher0395de32013-01-16 01:22:32 +0000923 // Field number for non-static fields.
Eric Christopherfd5ac0d2013-01-04 17:59:07 +0000924 unsigned fieldNo = 0;
Eric Christopher0395de32013-01-16 01:22:32 +0000925
926 // Bookkeeping for an ms struct, which ignores certain fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000927 bool IsMsStruct = record->isMsStruct(CGM.getContext());
928 const FieldDecl *LastFD = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000929
Eric Christopher0395de32013-01-16 01:22:32 +0000930 // Static and non-static members should appear in the same order as
931 // the corresponding declarations in the source program.
932 for (RecordDecl::decl_iterator I = record->decls_begin(),
933 E = record->decls_end(); I != E; ++I)
934 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
935 CollectRecordStaticField(V, elements, RecordTy);
936 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
937 if (IsMsStruct) {
938 // Zero-length bitfields following non-bitfield members are
939 // completely ignored; we don't even count them.
940 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((field), LastFD))
941 continue;
942 LastFD = field;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000943 }
Eric Christopher0395de32013-01-16 01:22:32 +0000944 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
945 tunit, elements, RecordTy);
946
947 // Bump field number for next field.
948 ++fieldNo;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000949 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000950 }
951}
952
953/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
954/// function type is not updated to include implicit "this" pointer. Use this
955/// routine to get a method type which includes "this" pointer.
956llvm::DIType
957CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
958 llvm::DIFile Unit) {
David Blaikie9c78f9b2013-01-07 23:06:35 +0000959 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000960 if (Method->isStatic())
David Blaikie9c78f9b2013-01-07 23:06:35 +0000961 return getOrCreateType(QualType(Func, 0), Unit);
962 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
963 Func, Unit);
964}
David Blaikie67f8b5e2013-01-07 22:24:59 +0000965
David Blaikie9c78f9b2013-01-07 23:06:35 +0000966llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
967 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000968 // Add "this" pointer.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000969 llvm::DIArray Args = llvm::DICompositeType(
970 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000971 assert (Args.getNumElements() && "Invalid number of arguments!");
972
973 SmallVector<llvm::Value *, 16> Elts;
974
975 // First element is always return type. For 'void' functions it is NULL.
976 Elts.push_back(Args.getElement(0));
977
David Blaikie67f8b5e2013-01-07 22:24:59 +0000978 // "this" pointer is always first argument.
David Blaikie9c78f9b2013-01-07 23:06:35 +0000979 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie67f8b5e2013-01-07 22:24:59 +0000980 if (isa<ClassTemplateSpecializationDecl>(RD)) {
981 // Create pointer type directly in this case.
982 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
983 QualType PointeeTy = ThisPtrTy->getPointeeType();
984 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCall64aa4b32013-04-16 22:48:15 +0000985 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie67f8b5e2013-01-07 22:24:59 +0000986 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
987 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
988 llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
989 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
990 // TODO: This and the artificial type below are misleading, the
991 // types aren't artificial the argument is, but the current
992 // metadata doesn't represent that.
993 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
994 Elts.push_back(ThisPtrType);
995 } else {
996 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
997 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001000 }
1001
1002 // Copy rest of the arguments.
1003 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1004 Elts.push_back(Args.getElement(i));
1005
1006 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1007
1008 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1009}
1010
1011/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
1012/// inside a function.
1013static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1014 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1015 return isFunctionLocalClass(NRD);
1016 if (isa<FunctionDecl>(RD->getDeclContext()))
1017 return true;
1018 return false;
1019}
1020
1021/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1022/// a single member function GlobalDecl.
1023llvm::DISubprogram
1024CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1025 llvm::DIFile Unit,
1026 llvm::DIType RecordTy) {
1027 bool IsCtorOrDtor =
1028 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
1029
1030 StringRef MethodName = getFunctionName(Method);
1031 llvm::DIType MethodTy = getOrCreateMethodType(Method, Unit);
1032
1033 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1034 // make sense to give a single ctor/dtor a linkage name.
1035 StringRef MethodLinkageName;
1036 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1037 MethodLinkageName = CGM.getMangledName(Method);
1038
1039 // Get the location for the method.
1040 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1041 unsigned MethodLine = getLineNumber(Method->getLocation());
1042
1043 // Collect virtual method info.
1044 llvm::DIType ContainingType;
1045 unsigned Virtuality = 0;
1046 unsigned VIndex = 0;
1047
1048 if (Method->isVirtual()) {
1049 if (Method->isPure())
1050 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1051 else
1052 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
1053
1054 // It doesn't make sense to give a virtual destructor a vtable index,
1055 // since a single destructor has two entries in the vtable.
1056 if (!isa<CXXDestructorDecl>(Method))
1057 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1058 ContainingType = RecordTy;
1059 }
1060
1061 unsigned Flags = 0;
1062 if (Method->isImplicit())
1063 Flags |= llvm::DIDescriptor::FlagArtificial;
1064 AccessSpecifier Access = Method->getAccess();
1065 if (Access == clang::AS_private)
1066 Flags |= llvm::DIDescriptor::FlagPrivate;
1067 else if (Access == clang::AS_protected)
1068 Flags |= llvm::DIDescriptor::FlagProtected;
1069 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1070 if (CXXC->isExplicit())
1071 Flags |= llvm::DIDescriptor::FlagExplicit;
1072 } else if (const CXXConversionDecl *CXXC =
1073 dyn_cast<CXXConversionDecl>(Method)) {
1074 if (CXXC->isExplicit())
1075 Flags |= llvm::DIDescriptor::FlagExplicit;
1076 }
1077 if (Method->hasPrototype())
1078 Flags |= llvm::DIDescriptor::FlagPrototyped;
1079
1080 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1081 llvm::DISubprogram SP =
1082 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
1083 MethodDefUnit, MethodLine,
1084 MethodTy, /*isLocalToUnit=*/false,
1085 /* isDefinition=*/ false,
1086 Virtuality, VIndex, ContainingType,
1087 Flags, CGM.getLangOpts().Optimize, NULL,
1088 TParamsArray);
1089
1090 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1091
1092 return SP;
1093}
1094
1095/// CollectCXXMemberFunctions - A helper function to collect debug info for
1096/// C++ member functions. This is used while creating debug info entry for
1097/// a Record.
1098void CGDebugInfo::
1099CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1100 SmallVectorImpl<llvm::Value *> &EltTys,
1101 llvm::DIType RecordTy) {
1102
1103 // Since we want more than just the individual member decls if we
1104 // have templated functions iterate over every declaration to gather
1105 // the functions.
1106 for(DeclContext::decl_iterator I = RD->decls_begin(),
1107 E = RD->decls_end(); I != E; ++I) {
1108 Decl *D = *I;
1109 if (D->isImplicit() && !D->isUsed())
1110 continue;
1111
1112 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1113 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1114 else if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
1115 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1116 SE = FTD->spec_end(); SI != SE; ++SI)
1117 EltTys.push_back(CreateCXXMemberFunction(cast<CXXMethodDecl>(*SI), Unit,
1118 RecordTy));
1119 }
1120}
1121
1122/// CollectCXXFriends - A helper function to collect debug info for
1123/// C++ base classes. This is used while creating debug info entry for
1124/// a Record.
1125void CGDebugInfo::
1126CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1127 SmallVectorImpl<llvm::Value *> &EltTys,
1128 llvm::DIType RecordTy) {
1129 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1130 BE = RD->friend_end(); BI != BE; ++BI) {
1131 if ((*BI)->isUnsupportedFriend())
1132 continue;
1133 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
1134 EltTys.push_back(DBuilder.createFriend(RecordTy,
1135 getOrCreateType(TInfo->getType(),
1136 Unit)));
1137 }
1138}
1139
1140/// CollectCXXBases - A helper function to collect debug info for
1141/// C++ base classes. This is used while creating debug info entry for
1142/// a Record.
1143void CGDebugInfo::
1144CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1145 SmallVectorImpl<llvm::Value *> &EltTys,
1146 llvm::DIType RecordTy) {
1147
1148 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1149 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1150 BE = RD->bases_end(); BI != BE; ++BI) {
1151 unsigned BFlags = 0;
1152 uint64_t BaseOffset;
1153
1154 const CXXRecordDecl *Base =
1155 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
1156
1157 if (BI->isVirtual()) {
1158 // virtual base offset offset is -ve. The code generator emits dwarf
1159 // expression where it expects +ve number.
1160 BaseOffset =
1161 0 - CGM.getVTableContext()
1162 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1163 BFlags = llvm::DIDescriptor::FlagVirtual;
1164 } else
1165 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1166 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1167 // BI->isVirtual() and bits when not.
1168
1169 AccessSpecifier Access = BI->getAccessSpecifier();
1170 if (Access == clang::AS_private)
1171 BFlags |= llvm::DIDescriptor::FlagPrivate;
1172 else if (Access == clang::AS_protected)
1173 BFlags |= llvm::DIDescriptor::FlagProtected;
1174
1175 llvm::DIType DTy =
1176 DBuilder.createInheritance(RecordTy,
1177 getOrCreateType(BI->getType(), Unit),
1178 BaseOffset, BFlags);
1179 EltTys.push_back(DTy);
1180 }
1181}
1182
1183/// CollectTemplateParams - A helper function to collect template parameters.
1184llvm::DIArray CGDebugInfo::
1185CollectTemplateParams(const TemplateParameterList *TPList,
1186 const TemplateArgumentList &TAList,
1187 llvm::DIFile Unit) {
1188 SmallVector<llvm::Value *, 16> TemplateParams;
1189 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1190 const TemplateArgument &TA = TAList[i];
1191 const NamedDecl *ND = TPList->getParam(i);
David Blaikie9dfd2432013-05-10 21:53:14 +00001192 switch (TA.getKind()) {
1193 case TemplateArgument::Type: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001194 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1195 llvm::DITemplateTypeParameter TTP =
1196 DBuilder.createTemplateTypeParameter(TheCU, ND->getName(), TTy);
1197 TemplateParams.push_back(TTP);
David Blaikie9dfd2432013-05-10 21:53:14 +00001198 } break;
1199 case TemplateArgument::Integral: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001200 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1201 llvm::DITemplateValueParameter TVP =
David Blaikie9dfd2432013-05-10 21:53:14 +00001202 DBuilder.createTemplateValueParameter(
1203 TheCU, ND->getName(), TTy,
1204 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1205 TemplateParams.push_back(TVP);
1206 } break;
1207 case TemplateArgument::Declaration: {
1208 const ValueDecl *D = TA.getAsDecl();
1209 bool InstanceMember = D->isCXXInstanceMember();
1210 QualType T = InstanceMember
1211 ? CGM.getContext().getMemberPointerType(
1212 D->getType(), cast<RecordDecl>(D->getDeclContext())
1213 ->getTypeForDecl())
1214 : CGM.getContext().getPointerType(D->getType());
1215 llvm::DIType TTy = getOrCreateType(T, Unit);
1216 llvm::Value *V = 0;
1217 // Variable pointer template parameters have a value that is the address
1218 // of the variable.
1219 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1220 V = CGM.GetAddrOfGlobalVar(VD);
1221 // Member function pointers have special support for building them, though
1222 // this is currently unsupported in LLVM CodeGen.
1223 if (InstanceMember)
1224 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1225 V = CGM.getCXXABI().EmitMemberPointer(method);
1226 // Member data pointers have special handling too to compute the fixed
1227 // offset within the object.
1228 if (isa<FieldDecl>(D)) {
1229 // These five lines (& possibly the above member function pointer
1230 // handling) might be able to be refactored to use similar code in
1231 // CodeGenModule::getMemberPointerConstant
1232 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1233 CharUnits chars =
1234 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1235 V = CGM.getCXXABI().EmitMemberDataPointer(
1236 cast<MemberPointerType>(T.getTypePtr()), chars);
1237 }
1238 llvm::DITemplateValueParameter TVP =
1239 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1240 TemplateParams.push_back(TVP);
1241 } break;
1242 case TemplateArgument::NullPtr: {
1243 QualType T = TA.getNullPtrType();
1244 llvm::DIType TTy = getOrCreateType(T, Unit);
1245 llvm::Value *V = 0;
1246 // Special case member data pointer null values since they're actually -1
1247 // instead of zero.
1248 if (const MemberPointerType *MPT =
1249 dyn_cast<MemberPointerType>(T.getTypePtr()))
1250 // But treat member function pointers as simple zero integers because
1251 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1252 // CodeGen grows handling for values of non-null member function
1253 // pointers then perhaps we could remove this special case and rely on
1254 // EmitNullMemberPointer for member function pointers.
1255 if (MPT->isMemberDataPointer())
1256 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1257 if (!V)
1258 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1259 llvm::DITemplateValueParameter TVP =
1260 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1261 TemplateParams.push_back(TVP);
1262 } break;
1263 case TemplateArgument::Template:
1264 // We could support this with the GCC extension
1265 // DW_TAG_GNU_template_template_param
1266 break;
David Blaikie776a3642013-05-10 22:53:25 +00001267 case TemplateArgument::Pack:
1268 // And this with DW_TAG_GNU_template_parameter_pack
1269 break;
David Blaikiee8065122013-05-10 23:36:06 +00001270 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001271 case TemplateArgument::Expression:
1272 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 case TemplateArgument::Null:
1274 llvm_unreachable(
1275 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001276 }
1277 }
1278 return DBuilder.getOrCreateArray(TemplateParams);
1279}
1280
1281/// CollectFunctionTemplateParams - A helper function to collect debug
1282/// info for function template parameters.
1283llvm::DIArray CGDebugInfo::
1284CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1285 if (FD->getTemplatedKind() ==
1286 FunctionDecl::TK_FunctionTemplateSpecialization) {
1287 const TemplateParameterList *TList =
1288 FD->getTemplateSpecializationInfo()->getTemplate()
1289 ->getTemplateParameters();
1290 return
1291 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1292 }
1293 return llvm::DIArray();
1294}
1295
1296/// CollectCXXTemplateParams - A helper function to collect debug info for
1297/// template parameters.
1298llvm::DIArray CGDebugInfo::
1299CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1300 llvm::DIFile Unit) {
1301 llvm::PointerUnion<ClassTemplateDecl *,
1302 ClassTemplatePartialSpecializationDecl *>
1303 PU = TSpecial->getSpecializedTemplateOrPartial();
1304
1305 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1306 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1307 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1308 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1309 return CollectTemplateParams(TPList, TAList, Unit);
1310}
1311
1312/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1313llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1314 if (VTablePtrType.isValid())
1315 return VTablePtrType;
1316
1317 ASTContext &Context = CGM.getContext();
1318
1319 /* Function type */
1320 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1321 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1322 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1323 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1324 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1325 "__vtbl_ptr_type");
1326 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1327 return VTablePtrType;
1328}
1329
1330/// getVTableName - Get vtable name for the given Class.
1331StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1332 // Construct gdb compatible name name.
1333 std::string Name = "_vptr$" + RD->getNameAsString();
1334
1335 // Copy this name on the side and use its reference.
1336 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1337 memcpy(StrPtr, Name.data(), Name.length());
1338 return StringRef(StrPtr, Name.length());
1339}
1340
1341
1342/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1343/// debug info entry in EltTys vector.
1344void CGDebugInfo::
1345CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1346 SmallVectorImpl<llvm::Value *> &EltTys) {
1347 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1348
1349 // If there is a primary base then it will hold vtable info.
1350 if (RL.getPrimaryBase())
1351 return;
1352
1353 // If this class is not dynamic then there is not any vtable info to collect.
1354 if (!RD->isDynamicClass())
1355 return;
1356
1357 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1358 llvm::DIType VPTR
1359 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1360 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1361 getOrCreateVTablePtrType(Unit));
1362 EltTys.push_back(VPTR);
1363}
1364
1365/// getOrCreateRecordType - Emit record type's standalone debug info.
1366llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1367 SourceLocation Loc) {
1368 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1369 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1370 return T;
1371}
1372
1373/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1374/// debug info.
1375llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001376 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001377 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1378 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001379 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001380 return T;
1381}
1382
1383/// CreateType - get structure or union type.
1384llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1385 RecordDecl *RD = Ty->getDecl();
1386
1387 // Get overall information about the record type for the debug info.
1388 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1389
1390 // Records and classes and unions can all be recursive. To handle them, we
1391 // first generate a debug descriptor for the struct as a forward declaration.
1392 // Then (if it is a definition) we go through and get debug info for all of
1393 // its members. Finally, we create a descriptor for the complete type (which
1394 // may refer to the forward decl if the struct is recursive) and replace all
1395 // uses of the forward declaration with the final definition.
1396
Eric Christopherf068c922013-04-02 22:59:11 +00001397 llvm::DICompositeType FwdDecl(
1398 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1399 assert(FwdDecl.Verify() &&
1400 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001401
1402 if (FwdDecl.isForwardDecl())
1403 return FwdDecl;
1404
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001406 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1408
Adrian Prantl4919de62013-03-06 22:03:30 +00001409 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001410 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1411
1412 // Convert all the elements.
1413 SmallVector<llvm::Value *, 16> EltTys;
1414
1415 // Note: The split of CXXDecl information here is intentional, the
1416 // gdb tests will depend on a certain ordering at printout. The debug
1417 // information offsets are still correct if we merge them all together
1418 // though.
1419 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1420 if (CXXDecl) {
1421 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1422 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1423 }
1424
Eric Christopher0395de32013-01-16 01:22:32 +00001425 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001426 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1427 llvm::DIArray TParamsArray;
1428 if (CXXDecl) {
1429 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1430 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1431 if (const ClassTemplateSpecializationDecl *TSpecial
1432 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1433 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1434 }
1435
1436 LexicalBlockStack.pop_back();
1437 RegionMap.erase(Ty->getDecl());
1438
1439 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001440 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001441
Eric Christopherf068c922013-04-02 22:59:11 +00001442 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1443 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001444}
1445
1446/// CreateType - get objective-c object type.
1447llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1448 llvm::DIFile Unit) {
1449 // Ignore protocols.
1450 return getOrCreateType(Ty->getBaseType(), Unit);
1451}
1452
1453/// CreateType - get objective-c interface type.
1454llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1455 llvm::DIFile Unit) {
1456 ObjCInterfaceDecl *ID = Ty->getDecl();
1457 if (!ID)
1458 return llvm::DIType();
1459
1460 // Get overall information about the record type for the debug info.
1461 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1462 unsigned Line = getLineNumber(ID->getLocation());
1463 unsigned RuntimeLang = TheCU.getLanguage();
1464
1465 // If this is just a forward declaration return a special forward-declaration
1466 // debug type since we won't be able to lay out the entire type.
1467 ObjCInterfaceDecl *Def = ID->getDefinition();
1468 if (!Def) {
1469 llvm::DIType FwdDecl =
1470 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001471 ID->getName(), TheCU, DefUnit, Line,
1472 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001473 return FwdDecl;
1474 }
1475
1476 ID = Def;
1477
1478 // Bit size, align and offset of the type.
1479 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1480 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1481
1482 unsigned Flags = 0;
1483 if (ID->getImplementation())
1484 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1485
Eric Christopherf068c922013-04-02 22:59:11 +00001486 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001487 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1488 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001489 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001490
1491 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1492 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001493 QualType QualTy = QualType(Ty, 0);
1494 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001495 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001496
Eric Christopherf068c922013-04-02 22:59:11 +00001497 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001498 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1499
1500 // Convert all the elements.
1501 SmallVector<llvm::Value *, 16> EltTys;
1502
1503 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1504 if (SClass) {
1505 llvm::DIType SClassTy =
1506 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1507 if (!SClassTy.isValid())
1508 return llvm::DIType();
1509
1510 llvm::DIType InhTag =
1511 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1512 EltTys.push_back(InhTag);
1513 }
1514
1515 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1516 E = ID->prop_end(); I != E; ++I) {
1517 const ObjCPropertyDecl *PD = *I;
1518 SourceLocation Loc = PD->getLocation();
1519 llvm::DIFile PUnit = getOrCreateFile(Loc);
1520 unsigned PLine = getLineNumber(Loc);
1521 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1522 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1523 llvm::MDNode *PropertyNode =
1524 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001525 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001526 (Getter && Getter->isImplicit()) ? "" :
1527 getSelectorName(PD->getGetterName()),
1528 (Setter && Setter->isImplicit()) ? "" :
1529 getSelectorName(PD->getSetterName()),
1530 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001531 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001532 EltTys.push_back(PropertyNode);
1533 }
1534
1535 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1536 unsigned FieldNo = 0;
1537 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1538 Field = Field->getNextIvar(), ++FieldNo) {
1539 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1540 if (!FieldTy.isValid())
1541 return llvm::DIType();
1542
1543 StringRef FieldName = Field->getName();
1544
1545 // Ignore unnamed fields.
1546 if (FieldName.empty())
1547 continue;
1548
1549 // Get the location for the field.
1550 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1551 unsigned FieldLine = getLineNumber(Field->getLocation());
1552 QualType FType = Field->getType();
1553 uint64_t FieldSize = 0;
1554 unsigned FieldAlign = 0;
1555
1556 if (!FType->isIncompleteArrayType()) {
1557
1558 // Bit size, align and offset of the type.
1559 FieldSize = Field->isBitField()
1560 ? Field->getBitWidthValue(CGM.getContext())
1561 : CGM.getContext().getTypeSize(FType);
1562 FieldAlign = CGM.getContext().getTypeAlign(FType);
1563 }
1564
1565 uint64_t FieldOffset;
1566 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1567 // We don't know the runtime offset of an ivar if we're using the
1568 // non-fragile ABI. For bitfields, use the bit offset into the first
1569 // byte of storage of the bitfield. For other fields, use zero.
1570 if (Field->isBitField()) {
1571 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1572 CGM, ID, Field);
1573 FieldOffset %= CGM.getContext().getCharWidth();
1574 } else {
1575 FieldOffset = 0;
1576 }
1577 } else {
1578 FieldOffset = RL.getFieldOffset(FieldNo);
1579 }
1580
1581 unsigned Flags = 0;
1582 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1583 Flags = llvm::DIDescriptor::FlagProtected;
1584 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1585 Flags = llvm::DIDescriptor::FlagPrivate;
1586
1587 llvm::MDNode *PropertyNode = NULL;
1588 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1589 if (ObjCPropertyImplDecl *PImpD =
1590 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1591 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001592 SourceLocation Loc = PD->getLocation();
1593 llvm::DIFile PUnit = getOrCreateFile(Loc);
1594 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001595 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1596 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1597 PropertyNode =
1598 DBuilder.createObjCProperty(PD->getName(),
1599 PUnit, PLine,
1600 (Getter && Getter->isImplicit()) ? "" :
1601 getSelectorName(PD->getGetterName()),
1602 (Setter && Setter->isImplicit()) ? "" :
1603 getSelectorName(PD->getSetterName()),
1604 PD->getPropertyAttributes(),
1605 getOrCreateType(PD->getType(), PUnit));
1606 }
1607 }
1608 }
1609 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1610 FieldLine, FieldSize, FieldAlign,
1611 FieldOffset, Flags, FieldTy,
1612 PropertyNode);
1613 EltTys.push_back(FieldTy);
1614 }
1615
1616 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001617 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001618
1619 // If the implementation is not yet set, we do not want to mark it
1620 // as complete. An implementation may declare additional
1621 // private ivars that we would miss otherwise.
1622 if (ID->getImplementation() == 0)
1623 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001624
1625 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001626 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001627}
1628
1629llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1630 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1631 int64_t Count = Ty->getNumElements();
1632 if (Count == 0)
1633 // If number of elements are not known then this is an unbounded array.
1634 // Use Count == -1 to express such arrays.
1635 Count = -1;
1636
1637 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1638 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1639
1640 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1641 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1642
1643 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1644}
1645
1646llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1647 llvm::DIFile Unit) {
1648 uint64_t Size;
1649 uint64_t Align;
1650
1651 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1652 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1653 Size = 0;
1654 Align =
1655 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1656 } else if (Ty->isIncompleteArrayType()) {
1657 Size = 0;
1658 if (Ty->getElementType()->isIncompleteType())
1659 Align = 0;
1660 else
1661 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001662 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001663 Size = 0;
1664 Align = 0;
1665 } else {
1666 // Size and align of the whole array, not the element type.
1667 Size = CGM.getContext().getTypeSize(Ty);
1668 Align = CGM.getContext().getTypeAlign(Ty);
1669 }
1670
1671 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1672 // interior arrays, do we care? Why aren't nested arrays represented the
1673 // obvious/recursive way?
1674 SmallVector<llvm::Value *, 8> Subscripts;
1675 QualType EltTy(Ty, 0);
1676 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1677 // If the number of elements is known, then count is that number. Otherwise,
1678 // it's -1. This allows us to represent a subrange with an array of 0
1679 // elements, like this:
1680 //
1681 // struct foo {
1682 // int x[0];
1683 // };
1684 int64_t Count = -1; // Count == -1 is an unbounded array.
1685 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1686 Count = CAT->getSize().getZExtValue();
1687
1688 // FIXME: Verify this is right for VLAs.
1689 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1690 EltTy = Ty->getElementType();
1691 }
1692
1693 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1694
1695 llvm::DIType DbgTy =
1696 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1697 SubscriptArray);
1698 return DbgTy;
1699}
1700
1701llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1702 llvm::DIFile Unit) {
1703 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1704 Ty, Ty->getPointeeType(), Unit);
1705}
1706
1707llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1708 llvm::DIFile Unit) {
1709 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1710 Ty, Ty->getPointeeType(), Unit);
1711}
1712
1713llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1714 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001715 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1716 if (!Ty->getPointeeType()->isFunctionType())
1717 return DBuilder.createMemberPointerType(
1718 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1719 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1720 CGM.getContext().getPointerType(
1721 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1722 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1723 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001724}
1725
1726llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1727 llvm::DIFile U) {
1728 // Ignore the atomic wrapping
1729 // FIXME: What is the correct representation?
1730 return getOrCreateType(Ty->getValueType(), U);
1731}
1732
1733/// CreateEnumType - get enumeration type.
1734llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1735 uint64_t Size = 0;
1736 uint64_t Align = 0;
1737 if (!ED->getTypeForDecl()->isIncompleteType()) {
1738 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1739 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1740 }
1741
1742 // If this is just a forward declaration, construct an appropriately
1743 // marked node and just return it.
1744 if (!ED->getDefinition()) {
1745 llvm::DIDescriptor EDContext;
1746 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1747 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1748 unsigned Line = getLineNumber(ED->getLocation());
1749 StringRef EDName = ED->getName();
1750 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1751 EDName, EDContext, DefUnit, Line, 0,
1752 Size, Align);
1753 }
1754
1755 // Create DIEnumerator elements for each enumerator.
1756 SmallVector<llvm::Value *, 16> Enumerators;
1757 ED = ED->getDefinition();
1758 for (EnumDecl::enumerator_iterator
1759 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1760 Enum != EnumEnd; ++Enum) {
1761 Enumerators.push_back(
1762 DBuilder.createEnumerator(Enum->getName(),
1763 Enum->getInitVal().getZExtValue()));
1764 }
1765
1766 // Return a CompositeType for the enum itself.
1767 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1768
1769 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1770 unsigned Line = getLineNumber(ED->getLocation());
1771 llvm::DIDescriptor EnumContext =
1772 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001773 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001774 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1775 llvm::DIType DbgTy =
1776 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1777 Size, Align, EltArray,
1778 ClassTy);
1779 return DbgTy;
1780}
1781
David Blaikie4b12be62013-01-21 04:37:12 +00001782static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1783 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001785 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 QualType LastT = T;
1787 switch (T->getTypeClass()) {
1788 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001789 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001790 case Type::TemplateSpecialization:
1791 T = cast<TemplateSpecializationType>(T)->desugar();
1792 break;
1793 case Type::TypeOfExpr:
1794 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1795 break;
1796 case Type::TypeOf:
1797 T = cast<TypeOfType>(T)->getUnderlyingType();
1798 break;
1799 case Type::Decltype:
1800 T = cast<DecltypeType>(T)->getUnderlyingType();
1801 break;
1802 case Type::UnaryTransform:
1803 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1804 break;
1805 case Type::Attributed:
1806 T = cast<AttributedType>(T)->getEquivalentType();
1807 break;
1808 case Type::Elaborated:
1809 T = cast<ElaboratedType>(T)->getNamedType();
1810 break;
1811 case Type::Paren:
1812 T = cast<ParenType>(T)->getInnerType();
1813 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001814 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001815 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001816 break;
1817 case Type::Auto:
1818 T = cast<AutoType>(T)->getDeducedType();
1819 break;
1820 }
1821
1822 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001823 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001824 } while (true);
1825}
1826
1827/// getType - Get the type from the cache or return null type if it doesn't exist.
1828llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1829
1830 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001831 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001832
1833 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001834 if (Ty->getTypeClass() == Type::ObjCInterface) {
1835 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1836 if (V)
1837 return llvm::DIType(cast<llvm::MDNode>(V));
1838 else return llvm::DIType();
1839 }
1840
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001841 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1842 TypeCache.find(Ty.getAsOpaquePtr());
1843 if (it != TypeCache.end()) {
1844 // Verify that the debug info still exists.
1845 if (llvm::Value *V = it->second)
1846 return llvm::DIType(cast<llvm::MDNode>(V));
1847 }
1848
1849 return llvm::DIType();
1850}
1851
1852/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1853/// doesn't exist.
1854llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1855
1856 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001857 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001858
1859 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001860 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001861 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1862 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001863 if (it != CompletedTypeCache.end())
1864 V = it->second;
1865 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001866 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001867 }
1868
Adrian Prantl4919de62013-03-06 22:03:30 +00001869 // Verify that any cached debug info still exists.
1870 if (V != 0)
1871 return llvm::DIType(cast<llvm::MDNode>(V));
1872
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001873 return llvm::DIType();
1874}
1875
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001876/// getCachedInterfaceTypeOrNull - Get the type from the interface
1877/// cache, unless it needs to regenerated. Otherwise return null.
1878llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1879 // Is there a cached interface that hasn't changed?
1880 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1881 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1882
1883 if (it1 != ObjCInterfaceCache.end())
1884 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1885 if (Checksum(Decl) == it1->second.second)
1886 // Return cached forward declaration.
1887 return it1->second.first;
1888
1889 return 0;
1890}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001891
1892/// getOrCreateType - Get the type from the cache or create a new
1893/// one if necessary.
1894llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1895 if (Ty.isNull())
1896 return llvm::DIType();
1897
1898 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001899 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001900
1901 llvm::DIType T = getCompletedTypeOrNull(Ty);
1902
1903 if (T.Verify())
1904 return T;
1905
1906 // Otherwise create the type.
1907 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001908 void* TyPtr = Ty.getAsOpaquePtr();
1909
1910 // And update the type cache.
1911 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001912
1913 llvm::DIType TC = getTypeOrNull(Ty);
1914 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001915 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1916 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1917 // Interface types may have elements added to them by a
1918 // subsequent implementation or extension, so we keep them in
1919 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001920 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001921 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1922 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1923 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1924 if (it != ObjCInterfaceCache.end())
1925 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1926 else
1927 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001928 Decl->getName(), TheCU, Unit,
1929 getLineNumber(Decl->getLocation()),
1930 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001931 // Store the forward declaration in the cache.
1932 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1933
1934 // Register the type for replacement in finalize().
1935 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1936 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001937 }
1938
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001939 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001940 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001941
1942 return Res;
1943}
1944
Adrian Prantl4919de62013-03-06 22:03:30 +00001945/// Currently the checksum merely consists of the number of ivars.
1946unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001947 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001948 unsigned IvarNo = 0;
1949 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1950 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1951 return IvarNo;
1952}
1953
1954ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1955 switch (Ty->getTypeClass()) {
1956 case Type::ObjCObjectPointer:
1957 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1958 case Type::ObjCInterface:
1959 return cast<ObjCInterfaceType>(Ty)->getDecl();
1960 default:
1961 return 0;
1962 }
1963}
1964
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001965/// CreateTypeNode - Create a new debug type node.
1966llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1967 // Handle qualifiers, which recursively handles what they refer to.
1968 if (Ty.hasLocalQualifiers())
1969 return CreateQualifiedType(Ty, Unit);
1970
1971 const char *Diag = 0;
1972
1973 // Work out details of type.
1974 switch (Ty->getTypeClass()) {
1975#define TYPE(Class, Base)
1976#define ABSTRACT_TYPE(Class, Base)
1977#define NON_CANONICAL_TYPE(Class, Base)
1978#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1979#include "clang/AST/TypeNodes.def"
1980 llvm_unreachable("Dependent types cannot show up in debug information");
1981
1982 case Type::ExtVector:
1983 case Type::Vector:
1984 return CreateType(cast<VectorType>(Ty), Unit);
1985 case Type::ObjCObjectPointer:
1986 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1987 case Type::ObjCObject:
1988 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1989 case Type::ObjCInterface:
1990 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1991 case Type::Builtin:
1992 return CreateType(cast<BuiltinType>(Ty));
1993 case Type::Complex:
1994 return CreateType(cast<ComplexType>(Ty));
1995 case Type::Pointer:
1996 return CreateType(cast<PointerType>(Ty), Unit);
1997 case Type::BlockPointer:
1998 return CreateType(cast<BlockPointerType>(Ty), Unit);
1999 case Type::Typedef:
2000 return CreateType(cast<TypedefType>(Ty), Unit);
2001 case Type::Record:
2002 return CreateType(cast<RecordType>(Ty));
2003 case Type::Enum:
2004 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2005 case Type::FunctionProto:
2006 case Type::FunctionNoProto:
2007 return CreateType(cast<FunctionType>(Ty), Unit);
2008 case Type::ConstantArray:
2009 case Type::VariableArray:
2010 case Type::IncompleteArray:
2011 return CreateType(cast<ArrayType>(Ty), Unit);
2012
2013 case Type::LValueReference:
2014 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2015 case Type::RValueReference:
2016 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2017
2018 case Type::MemberPointer:
2019 return CreateType(cast<MemberPointerType>(Ty), Unit);
2020
2021 case Type::Atomic:
2022 return CreateType(cast<AtomicType>(Ty), Unit);
2023
2024 case Type::Attributed:
2025 case Type::TemplateSpecialization:
2026 case Type::Elaborated:
2027 case Type::Paren:
2028 case Type::SubstTemplateTypeParm:
2029 case Type::TypeOfExpr:
2030 case Type::TypeOf:
2031 case Type::Decltype:
2032 case Type::UnaryTransform:
2033 case Type::Auto:
2034 llvm_unreachable("type should have been unwrapped!");
2035 }
2036
2037 assert(Diag && "Fall through without a diagnostic?");
2038 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2039 "debug information for %0 is not yet supported");
2040 CGM.getDiags().Report(DiagID)
2041 << Diag;
2042 return llvm::DIType();
2043}
2044
2045/// getOrCreateLimitedType - Get the type from the cache or create a new
2046/// limited type if necessary.
2047llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002048 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002049 if (Ty.isNull())
2050 return llvm::DIType();
2051
2052 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002053 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002054
2055 llvm::DIType T = getTypeOrNull(Ty);
2056
2057 // We may have cached a forward decl when we could have created
2058 // a non-forward decl. Go ahead and create a non-forward decl
2059 // now.
2060 if (T.Verify() && !T.isForwardDecl()) return T;
2061
2062 // Otherwise create the type.
2063 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2064
2065 if (T.Verify() && T.isForwardDecl())
2066 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2067 static_cast<llvm::Value*>(T)));
2068
2069 // And update the type cache.
2070 TypeCache[Ty.getAsOpaquePtr()] = Res;
2071 return Res;
2072}
2073
2074// TODO: Currently used for context chains when limiting debug info.
2075llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2076 RecordDecl *RD = Ty->getDecl();
2077
2078 // Get overall information about the record type for the debug info.
2079 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2080 unsigned Line = getLineNumber(RD->getLocation());
2081 StringRef RDName = getClassName(RD);
2082
2083 llvm::DIDescriptor RDContext;
2084 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2085 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2086 else
2087 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2088
2089 // If this is just a forward declaration, construct an appropriately
2090 // marked node and just return it.
2091 if (!RD->getDefinition())
2092 return createRecordFwdDecl(RD, RDContext);
2093
2094 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2095 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2096 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002097 llvm::DICompositeType RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002098
2099 if (RD->isUnion())
2100 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002101 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002102 else if (RD->isClass()) {
2103 // FIXME: This could be a struct type giving a default visibility different
2104 // than C++ class type, but needs llvm metadata changes first.
2105 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002106 Size, Align, 0, 0, llvm::DIType(),
2107 llvm::DIArray(), llvm::DIType(),
2108 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002109 } else
2110 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002111 Size, Align, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002112
2113 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002114 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002115
2116 if (CXXDecl) {
2117 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002118 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002119 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2120 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2121 // Seek non virtual primary base root.
2122 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002123 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2124 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2125 if (PBT && !BRL.isPrimaryBaseVirtual())
2126 PBase = PBT;
2127 else
2128 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002129 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002130 ContainingType = llvm::DICompositeType(
2131 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2132 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002133 ContainingType = RealDecl;
2134
David Blaikie2fcadbe2013-03-26 23:47:35 +00002135 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002136 }
2137 return llvm::DIType(RealDecl);
2138}
2139
2140/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2141/// declare composite types that haven't been processed yet.
2142llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2143
2144 // Work out details of type.
2145 switch (Ty->getTypeClass()) {
2146#define TYPE(Class, Base)
2147#define ABSTRACT_TYPE(Class, Base)
2148#define NON_CANONICAL_TYPE(Class, Base)
2149#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2150 #include "clang/AST/TypeNodes.def"
2151 llvm_unreachable("Dependent types cannot show up in debug information");
2152
2153 case Type::Record:
2154 return CreateLimitedType(cast<RecordType>(Ty));
2155 default:
2156 return CreateTypeNode(Ty, Unit);
2157 }
2158}
2159
2160/// CreateMemberType - Create new member and increase Offset by FType's size.
2161llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2162 StringRef Name,
2163 uint64_t *Offset) {
2164 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2165 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2166 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2167 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2168 FieldSize, FieldAlign,
2169 *Offset, 0, FieldTy);
2170 *Offset += FieldSize;
2171 return Ty;
2172}
2173
David Blaikie3923d6a2013-05-08 06:01:46 +00002174llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikie87360f22013-05-12 18:05:52 +00002175 // We only need a declaration (not a definition) of the type - so use whatever
2176 // we would otherwise do to get a type for a pointee. (forward declarations in
2177 // limited debug info, full definitions (if the type definition is available)
2178 // in unlimited debug info)
David Blaikie3923d6a2013-05-08 06:01:46 +00002179 if (const TypeDecl *RD = dyn_cast<TypeDecl>(D))
2180 return CreatePointeeType(QualType(RD->getTypeForDecl(), 0), llvm::DIFile());
David Blaikie87360f22013-05-12 18:05:52 +00002181 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2182 // This doesn't handle providing declarations (for functions or variables) for
2183 // entities without definitions in this TU, nor when the definition proceeds
2184 // the call to this function.
2185 // FIXME: This should be split out into more specific maps with support for
2186 // emitting forward declarations and merging definitions with declarations,
2187 // the same way as we do for types.
David Blaikie3923d6a2013-05-08 06:01:46 +00002188 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2189 DeclCache.find(D->getCanonicalDecl());
2190 if (I == DeclCache.end())
2191 return llvm::DIDescriptor();
2192 llvm::Value *V = I->second;
2193 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2194}
2195
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002196/// getFunctionDeclaration - Return debug info descriptor to describe method
2197/// declaration for the given method definition.
2198llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2199 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2200 if (!FD) return llvm::DISubprogram();
2201
2202 // Setup context.
2203 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2204
2205 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2206 MI = SPCache.find(FD->getCanonicalDecl());
2207 if (MI != SPCache.end()) {
2208 llvm::Value *V = MI->second;
2209 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2210 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2211 return SP;
2212 }
2213
2214 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2215 E = FD->redecls_end(); I != E; ++I) {
2216 const FunctionDecl *NextFD = *I;
2217 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2218 MI = SPCache.find(NextFD->getCanonicalDecl());
2219 if (MI != SPCache.end()) {
2220 llvm::Value *V = MI->second;
2221 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2222 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2223 return SP;
2224 }
2225 }
2226 return llvm::DISubprogram();
2227}
2228
2229// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2230// implicit parameter "this".
2231llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2232 QualType FnType,
2233 llvm::DIFile F) {
2234
2235 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2236 return getOrCreateMethodType(Method, F);
2237 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2238 // Add "self" and "_cmd"
2239 SmallVector<llvm::Value *, 16> Elts;
2240
2241 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002242 QualType ResultTy = OMethod->hasRelatedResultType()
2243 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2244 : OMethod->getResultType();
2245 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002246 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002247 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2248 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2249 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002250 // "_cmd" pointer is always second argument.
2251 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2252 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2253 // Get rest of the arguments.
2254 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2255 PE = OMethod->param_end(); PI != PE; ++PI)
2256 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2257
2258 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2259 return DBuilder.createSubroutineType(F, EltTypeArray);
2260 }
2261 return getOrCreateType(FnType, F);
2262}
2263
2264/// EmitFunctionStart - Constructs the debug code for entering a function.
2265void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2266 llvm::Function *Fn,
2267 CGBuilderTy &Builder) {
2268
2269 StringRef Name;
2270 StringRef LinkageName;
2271
2272 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2273
2274 const Decl *D = GD.getDecl();
2275 // Function may lack declaration in source code if it is created by Clang
2276 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2277 bool HasDecl = (D != 0);
2278 // Use the location of the declaration.
2279 SourceLocation Loc;
2280 if (HasDecl)
2281 Loc = D->getLocation();
2282
2283 unsigned Flags = 0;
2284 llvm::DIFile Unit = getOrCreateFile(Loc);
2285 llvm::DIDescriptor FDContext(Unit);
2286 llvm::DIArray TParamsArray;
2287 if (!HasDecl) {
2288 // Use llvm function name.
2289 Name = Fn->getName();
2290 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2291 // If there is a DISubprogram for this function available then use it.
2292 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2293 FI = SPCache.find(FD->getCanonicalDecl());
2294 if (FI != SPCache.end()) {
2295 llvm::Value *V = FI->second;
2296 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2297 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2298 llvm::MDNode *SPN = SP;
2299 LexicalBlockStack.push_back(SPN);
2300 RegionMap[D] = llvm::WeakVH(SP);
2301 return;
2302 }
2303 }
2304 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002305 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002306 if (FD->hasPrototype()) {
2307 LinkageName = CGM.getMangledName(GD);
2308 Flags |= llvm::DIDescriptor::FlagPrototyped;
2309 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002310 // No need to replicate the linkage name if it isn't different from the
2311 // subprogram name, no need to have it at all unless coverage is enabled or
2312 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002313 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002314 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2315 !CGM.getCodeGenOpts().EmitGcovNotes &&
2316 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317 LinkageName = StringRef();
2318
2319 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2320 if (const NamespaceDecl *NSDecl =
2321 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2322 FDContext = getOrCreateNameSpace(NSDecl);
2323 else if (const RecordDecl *RDecl =
2324 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2325 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2326
2327 // Collect template parameters.
2328 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2329 }
2330 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2331 Name = getObjCMethodName(OMD);
2332 Flags |= llvm::DIDescriptor::FlagPrototyped;
2333 } else {
2334 // Use llvm function name.
2335 Name = Fn->getName();
2336 Flags |= llvm::DIDescriptor::FlagPrototyped;
2337 }
2338 if (!Name.empty() && Name[0] == '\01')
2339 Name = Name.substr(1);
2340
2341 unsigned LineNo = getLineNumber(Loc);
2342 if (!HasDecl || D->isImplicit())
2343 Flags |= llvm::DIDescriptor::FlagArtificial;
2344
2345 llvm::DIType DIFnType;
2346 llvm::DISubprogram SPDecl;
2347 if (HasDecl &&
2348 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2349 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2350 SPDecl = getFunctionDeclaration(D);
2351 } else {
2352 // Create fake but valid subroutine type. Otherwise
2353 // llvm::DISubprogram::Verify() would return false, and
2354 // subprogram DIE will miss DW_AT_decl_file and
2355 // DW_AT_decl_line fields.
2356 SmallVector<llvm::Value*, 16> Elts;
2357 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2358 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2359 }
2360 llvm::DISubprogram SP;
2361 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2362 LineNo, DIFnType,
2363 Fn->hasInternalLinkage(), true/*definition*/,
2364 getLineNumber(CurLoc), Flags,
2365 CGM.getLangOpts().Optimize,
2366 Fn, TParamsArray, SPDecl);
David Blaikie3923d6a2013-05-08 06:01:46 +00002367 if (HasDecl)
2368 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002369
2370 // Push function on region stack.
2371 llvm::MDNode *SPN = SP;
2372 LexicalBlockStack.push_back(SPN);
2373 if (HasDecl)
2374 RegionMap[D] = llvm::WeakVH(SP);
2375}
2376
2377/// EmitLocation - Emit metadata to indicate a change in line/column
2378/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002379void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2380 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002381
2382 // Update our current location
2383 setLocation(Loc);
2384
2385 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2386
2387 // Don't bother if things are the same as last time.
2388 SourceManager &SM = CGM.getContext().getSourceManager();
2389 if (CurLoc == PrevLoc ||
2390 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2391 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002392 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2393 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2394 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002395 return;
2396
2397 // Update last state.
2398 PrevLoc = CurLoc;
2399
2400 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002401 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2402 (getLineNumber(CurLoc),
2403 getColumnNumber(CurLoc, ForceColumnInfo),
2404 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002405}
2406
2407/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2408/// the stack.
2409void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2410 llvm::DIDescriptor D =
2411 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2412 llvm::DIDescriptor() :
2413 llvm::DIDescriptor(LexicalBlockStack.back()),
2414 getOrCreateFile(CurLoc),
2415 getLineNumber(CurLoc),
2416 getColumnNumber(CurLoc));
2417 llvm::MDNode *DN = D;
2418 LexicalBlockStack.push_back(DN);
2419}
2420
2421/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2422/// region - beginning of a DW_TAG_lexical_block.
2423void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2424 // Set our current location.
2425 setLocation(Loc);
2426
2427 // Create a new lexical block and push it on the stack.
2428 CreateLexicalBlock(Loc);
2429
2430 // Emit a line table change for the current location inside the new scope.
2431 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2432 getColumnNumber(Loc),
2433 LexicalBlockStack.back()));
2434}
2435
2436/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2437/// region - end of a DW_TAG_lexical_block.
2438void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2439 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2440
2441 // Provide an entry in the line table for the end of the block.
2442 EmitLocation(Builder, Loc);
2443
2444 LexicalBlockStack.pop_back();
2445}
2446
2447/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2448void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2449 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2450 unsigned RCount = FnBeginRegionCount.back();
2451 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2452
2453 // Pop all regions for this function.
2454 while (LexicalBlockStack.size() != RCount)
2455 EmitLexicalBlockEnd(Builder, CurLoc);
2456 FnBeginRegionCount.pop_back();
2457}
2458
2459// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2460// See BuildByRefType.
2461llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2462 uint64_t *XOffset) {
2463
2464 SmallVector<llvm::Value *, 5> EltTys;
2465 QualType FType;
2466 uint64_t FieldSize, FieldOffset;
2467 unsigned FieldAlign;
2468
2469 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2470 QualType Type = VD->getType();
2471
2472 FieldOffset = 0;
2473 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2474 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2475 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2476 FType = CGM.getContext().IntTy;
2477 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2478 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2479
2480 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2481 if (HasCopyAndDispose) {
2482 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2483 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2484 &FieldOffset));
2485 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2486 &FieldOffset));
2487 }
2488 bool HasByrefExtendedLayout;
2489 Qualifiers::ObjCLifetime Lifetime;
2490 if (CGM.getContext().getByrefLifetime(Type,
2491 Lifetime, HasByrefExtendedLayout)
2492 && HasByrefExtendedLayout)
2493 EltTys.push_back(CreateMemberType(Unit, FType,
2494 "__byref_variable_layout",
2495 &FieldOffset));
2496
2497 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2498 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002499 CGM.getTarget().getPointerAlign(0))) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002500 CharUnits FieldOffsetInBytes
2501 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2502 CharUnits AlignedOffsetInBytes
2503 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2504 CharUnits NumPaddingBytes
2505 = AlignedOffsetInBytes - FieldOffsetInBytes;
2506
2507 if (NumPaddingBytes.isPositive()) {
2508 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2509 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2510 pad, ArrayType::Normal, 0);
2511 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2512 }
2513 }
2514
2515 FType = Type;
2516 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2517 FieldSize = CGM.getContext().getTypeSize(FType);
2518 FieldAlign = CGM.getContext().toBits(Align);
2519
2520 *XOffset = FieldOffset;
2521 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2522 0, FieldSize, FieldAlign,
2523 FieldOffset, 0, FieldTy);
2524 EltTys.push_back(FieldTy);
2525 FieldOffset += FieldSize;
2526
2527 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2528
2529 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2530
2531 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002532 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002533}
2534
2535/// EmitDeclare - Emit local variable declaration debug info.
2536void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2537 llvm::Value *Storage,
2538 unsigned ArgNo, CGBuilderTy &Builder) {
2539 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2540 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2541
2542 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2543 llvm::DIType Ty;
2544 uint64_t XOffset = 0;
2545 if (VD->hasAttr<BlocksAttr>())
2546 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2547 else
2548 Ty = getOrCreateType(VD->getType(), Unit);
2549
2550 // If there is no debug info for this type then do not emit debug info
2551 // for this variable.
2552 if (!Ty)
2553 return;
2554
2555 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2556 // If Storage is an aggregate returned as 'sret' then let debugger know
2557 // about this.
2558 if (Arg->hasStructRetAttr())
2559 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2560 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2561 // If an aggregate variable has non trivial destructor or non trivial copy
2562 // constructor than it is pass indirectly. Let debug info know about this
2563 // by using reference of the aggregate type as a argument type.
2564 if (Record->hasNonTrivialCopyConstructor() ||
2565 !Record->hasTrivialDestructor())
2566 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2567 }
2568 }
2569
2570 // Get location information.
2571 unsigned Line = getLineNumber(VD->getLocation());
2572 unsigned Column = getColumnNumber(VD->getLocation());
2573 unsigned Flags = 0;
2574 if (VD->isImplicit())
2575 Flags |= llvm::DIDescriptor::FlagArtificial;
2576 // If this is the first argument and it is implicit then
2577 // give it an object pointer flag.
2578 // FIXME: There has to be a better way to do this, but for static
2579 // functions there won't be an implicit param at arg1 and
2580 // otherwise it is 'self' or 'this'.
2581 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2582 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2583
2584 llvm::MDNode *Scope = LexicalBlockStack.back();
2585
2586 StringRef Name = VD->getName();
2587 if (!Name.empty()) {
2588 if (VD->hasAttr<BlocksAttr>()) {
2589 CharUnits offset = CharUnits::fromQuantity(32);
2590 SmallVector<llvm::Value *, 9> addr;
2591 llvm::Type *Int64Ty = CGM.Int64Ty;
2592 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2593 // offset of __forwarding field
2594 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002595 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002596 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2597 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2598 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2599 // offset of x field
2600 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2601 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2602
2603 // Create the descriptor for the variable.
2604 llvm::DIVariable D =
2605 DBuilder.createComplexVariable(Tag,
2606 llvm::DIDescriptor(Scope),
2607 VD->getName(), Unit, Line, Ty,
2608 addr, ArgNo);
2609
2610 // Insert an llvm.dbg.declare into the current block.
2611 llvm::Instruction *Call =
2612 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2613 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2614 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002615 } else if (isa<VariableArrayType>(VD->getType())) {
2616 // These are "complex" variables in that they need an op_deref.
2617 // Create the descriptor for the variable.
2618 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2619 llvm::DIBuilder::OpDeref);
2620 llvm::DIVariable D =
2621 DBuilder.createComplexVariable(Tag,
2622 llvm::DIDescriptor(Scope),
2623 Name, Unit, Line, Ty,
2624 Addr, ArgNo);
2625
2626 // Insert an llvm.dbg.declare into the current block.
2627 llvm::Instruction *Call =
2628 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2629 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2630 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002631 }
David Blaikie436653b2013-01-05 05:58:35 +00002632 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2633 // If VD is an anonymous union then Storage represents value for
2634 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002635 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002636 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002637 for (RecordDecl::field_iterator I = RD->field_begin(),
2638 E = RD->field_end();
2639 I != E; ++I) {
2640 FieldDecl *Field = *I;
2641 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2642 StringRef FieldName = Field->getName();
2643
2644 // Ignore unnamed fields. Do not ignore unnamed records.
2645 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2646 continue;
2647
2648 // Use VarDecl's Tag, Scope and Line number.
2649 llvm::DIVariable D =
2650 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2651 FieldName, Unit, Line, FieldTy,
2652 CGM.getLangOpts().Optimize, Flags,
2653 ArgNo);
2654
2655 // Insert an llvm.dbg.declare into the current block.
2656 llvm::Instruction *Call =
2657 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2658 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2659 }
David Blaikied8180cf2013-01-05 20:03:07 +00002660 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002661 }
2662 }
David Blaikie436653b2013-01-05 05:58:35 +00002663
2664 // Create the descriptor for the variable.
2665 llvm::DIVariable D =
2666 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2667 Name, Unit, Line, Ty,
2668 CGM.getLangOpts().Optimize, Flags, ArgNo);
2669
2670 // Insert an llvm.dbg.declare into the current block.
2671 llvm::Instruction *Call =
2672 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2673 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002674}
2675
2676void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2677 llvm::Value *Storage,
2678 CGBuilderTy &Builder) {
2679 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2680 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2681}
2682
Adrian Prantle86fcc42013-03-29 19:20:29 +00002683/// Look up the completed type for a self pointer in the TypeCache and
2684/// create a copy of it with the ObjectPointer and Artificial flags
2685/// set. If the type is not cached, a new one is created. This should
2686/// never happen though, since creating a type for the implicit self
2687/// argument implies that we already parsed the interface definition
2688/// and the ivar declarations in the implementation.
2689llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2690 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2691 if (CachedTy.Verify()) Ty = CachedTy;
2692 else DEBUG(llvm::dbgs() << "No cached type for self.");
2693 return DBuilder.createObjectPointerType(Ty);
2694}
2695
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002696void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2697 llvm::Value *Storage,
2698 CGBuilderTy &Builder,
2699 const CGBlockInfo &blockInfo) {
2700 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2701 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2702
2703 if (Builder.GetInsertBlock() == 0)
2704 return;
2705
2706 bool isByRef = VD->hasAttr<BlocksAttr>();
2707
2708 uint64_t XOffset = 0;
2709 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2710 llvm::DIType Ty;
2711 if (isByRef)
2712 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2713 else
2714 Ty = getOrCreateType(VD->getType(), Unit);
2715
2716 // Self is passed along as an implicit non-arg variable in a
2717 // block. Mark it as the object pointer.
2718 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002719 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002720
2721 // Get location information.
2722 unsigned Line = getLineNumber(VD->getLocation());
2723 unsigned Column = getColumnNumber(VD->getLocation());
2724
2725 const llvm::DataLayout &target = CGM.getDataLayout();
2726
2727 CharUnits offset = CharUnits::fromQuantity(
2728 target.getStructLayout(blockInfo.StructureType)
2729 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2730
2731 SmallVector<llvm::Value *, 9> addr;
2732 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002733 if (isa<llvm::AllocaInst>(Storage))
2734 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002735 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2736 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2737 if (isByRef) {
2738 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2739 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2740 // offset of __forwarding field
2741 offset = CGM.getContext()
2742 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2743 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2744 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2745 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2746 // offset of x field
2747 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2748 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2749 }
2750
2751 // Create the descriptor for the variable.
2752 llvm::DIVariable D =
2753 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2754 llvm::DIDescriptor(LexicalBlockStack.back()),
2755 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002756
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002757 // Insert an llvm.dbg.declare into the current block.
2758 llvm::Instruction *Call =
2759 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2760 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2761 LexicalBlockStack.back()));
2762}
2763
2764/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2765/// variable declaration.
2766void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2767 unsigned ArgNo,
2768 CGBuilderTy &Builder) {
2769 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2770 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2771}
2772
2773namespace {
2774 struct BlockLayoutChunk {
2775 uint64_t OffsetInBits;
2776 const BlockDecl::Capture *Capture;
2777 };
2778 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2779 return l.OffsetInBits < r.OffsetInBits;
2780 }
2781}
2782
2783void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002784 llvm::Value *Arg,
2785 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002786 CGBuilderTy &Builder) {
2787 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2788 ASTContext &C = CGM.getContext();
2789 const BlockDecl *blockDecl = block.getBlockDecl();
2790
2791 // Collect some general information about the block's location.
2792 SourceLocation loc = blockDecl->getCaretLocation();
2793 llvm::DIFile tunit = getOrCreateFile(loc);
2794 unsigned line = getLineNumber(loc);
2795 unsigned column = getColumnNumber(loc);
2796
2797 // Build the debug-info type for the block literal.
2798 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2799
2800 const llvm::StructLayout *blockLayout =
2801 CGM.getDataLayout().getStructLayout(block.StructureType);
2802
2803 SmallVector<llvm::Value*, 16> fields;
2804 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2805 blockLayout->getElementOffsetInBits(0),
2806 tunit, tunit));
2807 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2808 blockLayout->getElementOffsetInBits(1),
2809 tunit, tunit));
2810 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2811 blockLayout->getElementOffsetInBits(2),
2812 tunit, tunit));
2813 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2814 blockLayout->getElementOffsetInBits(3),
2815 tunit, tunit));
2816 fields.push_back(createFieldType("__descriptor",
2817 C.getPointerType(block.NeedsCopyDispose ?
2818 C.getBlockDescriptorExtendedType() :
2819 C.getBlockDescriptorType()),
2820 0, loc, AS_public,
2821 blockLayout->getElementOffsetInBits(4),
2822 tunit, tunit));
2823
2824 // We want to sort the captures by offset, not because DWARF
2825 // requires this, but because we're paranoid about debuggers.
2826 SmallVector<BlockLayoutChunk, 8> chunks;
2827
2828 // 'this' capture.
2829 if (blockDecl->capturesCXXThis()) {
2830 BlockLayoutChunk chunk;
2831 chunk.OffsetInBits =
2832 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2833 chunk.Capture = 0;
2834 chunks.push_back(chunk);
2835 }
2836
2837 // Variable captures.
2838 for (BlockDecl::capture_const_iterator
2839 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2840 i != e; ++i) {
2841 const BlockDecl::Capture &capture = *i;
2842 const VarDecl *variable = capture.getVariable();
2843 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2844
2845 // Ignore constant captures.
2846 if (captureInfo.isConstant())
2847 continue;
2848
2849 BlockLayoutChunk chunk;
2850 chunk.OffsetInBits =
2851 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2852 chunk.Capture = &capture;
2853 chunks.push_back(chunk);
2854 }
2855
2856 // Sort by offset.
2857 llvm::array_pod_sort(chunks.begin(), chunks.end());
2858
2859 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2860 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2861 uint64_t offsetInBits = i->OffsetInBits;
2862 const BlockDecl::Capture *capture = i->Capture;
2863
2864 // If we have a null capture, this must be the C++ 'this' capture.
2865 if (!capture) {
2866 const CXXMethodDecl *method =
2867 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2868 QualType type = method->getThisType(C);
2869
2870 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2871 offsetInBits, tunit, tunit));
2872 continue;
2873 }
2874
2875 const VarDecl *variable = capture->getVariable();
2876 StringRef name = variable->getName();
2877
2878 llvm::DIType fieldType;
2879 if (capture->isByRef()) {
2880 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2881
2882 // FIXME: this creates a second copy of this type!
2883 uint64_t xoffset;
2884 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2885 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2886 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2887 ptrInfo.first, ptrInfo.second,
2888 offsetInBits, 0, fieldType);
2889 } else {
2890 fieldType = createFieldType(name, variable->getType(), 0,
2891 loc, AS_public, offsetInBits, tunit, tunit);
2892 }
2893 fields.push_back(fieldType);
2894 }
2895
2896 SmallString<36> typeName;
2897 llvm::raw_svector_ostream(typeName)
2898 << "__block_literal_" << CGM.getUniqueBlockCount();
2899
2900 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2901
2902 llvm::DIType type =
2903 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2904 CGM.getContext().toBits(block.BlockSize),
2905 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002906 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002907 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2908
2909 // Get overall information about the block.
2910 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2911 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002912
2913 // Create the descriptor for the parameter.
2914 llvm::DIVariable debugVar =
2915 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2916 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002917 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002918 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002919 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2920
Adrian Prantlbea407c2013-03-14 21:52:59 +00002921 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002922 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002923 llvm::Instruction *DbgVal =
2924 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002925 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002926 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2927 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002928
Adrian Prantlbea407c2013-03-14 21:52:59 +00002929 // Insert an llvm.dbg.declare into the current block.
2930 llvm::Instruction *DbgDecl =
2931 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2932 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002933}
2934
Eric Christopher0395de32013-01-16 01:22:32 +00002935/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2936/// a static data member of a class, find its corresponding in-class
2937/// declaration.
2938llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2939 if (cast<VarDecl>(D)->isStaticDataMember()) {
2940 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2941 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2942 if (MI != StaticDataMemberCache.end())
2943 // Verify the info still exists.
2944 if (llvm::Value *V = MI->second)
2945 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2946 }
2947 return llvm::DIDerivedType();
2948}
2949
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002950/// EmitGlobalVariable - Emit information about a global variable.
2951void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2952 const VarDecl *D) {
2953 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2954 // Create global variable debug descriptor.
2955 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2956 unsigned LineNo = getLineNumber(D->getLocation());
2957
2958 setLocation(D->getLocation());
2959
2960 QualType T = D->getType();
2961 if (T->isIncompleteArrayType()) {
2962
2963 // CodeGen turns int[] into int[1] so we'll do the same here.
2964 llvm::APInt ConstVal(32, 1);
2965 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2966
2967 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2968 ArrayType::Normal, 0);
2969 }
2970 StringRef DeclName = D->getName();
2971 StringRef LinkageName;
2972 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2973 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2974 LinkageName = Var->getName();
2975 if (LinkageName == DeclName)
2976 LinkageName = StringRef();
2977 llvm::DIDescriptor DContext =
2978 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie3923d6a2013-05-08 06:01:46 +00002979 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002980 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00002981 Var->hasInternalLinkage(), Var,
2982 getStaticDataMemberDeclaration(D));
David Blaikie3923d6a2013-05-08 06:01:46 +00002983 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002984}
2985
2986/// EmitGlobalVariable - Emit information about an objective-c interface.
2987void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2988 ObjCInterfaceDecl *ID) {
2989 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2990 // Create global variable debug descriptor.
2991 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2992 unsigned LineNo = getLineNumber(ID->getLocation());
2993
2994 StringRef Name = ID->getName();
2995
2996 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2997 if (T->isIncompleteArrayType()) {
2998
2999 // CodeGen turns int[] into int[1] so we'll do the same here.
3000 llvm::APInt ConstVal(32, 1);
3001 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3002
3003 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3004 ArrayType::Normal, 0);
3005 }
3006
3007 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3008 getOrCreateType(T, Unit),
3009 Var->hasInternalLinkage(), Var);
3010}
3011
3012/// EmitGlobalVariable - Emit global variable's debug info.
3013void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3014 llvm::Constant *Init) {
3015 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
3016 // Create the descriptor for the variable.
3017 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3018 StringRef Name = VD->getName();
3019 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3020 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3021 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3022 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3023 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3024 }
3025 // Do not use DIGlobalVariable for enums.
3026 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3027 return;
David Blaikie3923d6a2013-05-08 06:01:46 +00003028 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003029 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003030 Ty, true, Init,
3031 getStaticDataMemberDeclaration(VD));
David Blaikie3923d6a2013-05-08 06:01:46 +00003032 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3033}
3034
3035llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3036 if (!LexicalBlockStack.empty())
3037 return llvm::DIScope(LexicalBlockStack.back());
3038 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003039}
3040
David Blaikie957dac52013-04-22 06:13:21 +00003041void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3042 DBuilder.createImportedModule(
David Blaikie3923d6a2013-05-08 06:01:46 +00003043 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3044 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003045 getLineNumber(UD.getLocation()));
3046}
3047
David Blaikie3923d6a2013-05-08 06:01:46 +00003048void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3049 assert(UD.shadow_size() &&
3050 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3051 // Emitting one decl is sufficient - debuggers can detect that this is an
3052 // overloaded name & provide lookup for all the overloads.
3053 const UsingShadowDecl &USD = **UD.shadow_begin();
3054 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3055 DBuilder.createImportedDeclaration(
3056 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3057 getLineNumber(USD.getLocation()));
3058}
3059
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003060/// getOrCreateNamesSpace - Return namespace descriptor for the given
3061/// namespace decl.
3062llvm::DINameSpace
3063CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3064 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3065 NameSpaceCache.find(NSDecl);
3066 if (I != NameSpaceCache.end())
3067 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3068
3069 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3070 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3071 llvm::DIDescriptor Context =
3072 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3073 llvm::DINameSpace NS =
3074 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3075 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3076 return NS;
3077}
3078
3079void CGDebugInfo::finalize() {
3080 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3081 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3082 llvm::DIType Ty, RepTy;
3083 // Verify that the debug info still exists.
3084 if (llvm::Value *V = VI->second)
3085 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3086
3087 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3088 TypeCache.find(VI->first);
3089 if (it != TypeCache.end()) {
3090 // Verify that the debug info still exists.
3091 if (llvm::Value *V = it->second)
3092 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3093 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003094
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003095 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003096 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003097 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003098
3099 // We keep our own list of retained types, because we need to look
3100 // up the final type in the type cache.
3101 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3102 RE = RetainedTypes.end(); RI != RE; ++RI)
3103 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3104
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003105 DBuilder.finalize();
3106}