blob: f236d169bf513bb69a3b6d384c5893b381dc888a [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;
1267 // these next 4 should never occur
1268 case TemplateArgument::Expression:
1269 case TemplateArgument::TemplateExpansion:
1270 case TemplateArgument::Pack:
1271 case TemplateArgument::Null:
1272 llvm_unreachable(
1273 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001274 }
1275 }
1276 return DBuilder.getOrCreateArray(TemplateParams);
1277}
1278
1279/// CollectFunctionTemplateParams - A helper function to collect debug
1280/// info for function template parameters.
1281llvm::DIArray CGDebugInfo::
1282CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1283 if (FD->getTemplatedKind() ==
1284 FunctionDecl::TK_FunctionTemplateSpecialization) {
1285 const TemplateParameterList *TList =
1286 FD->getTemplateSpecializationInfo()->getTemplate()
1287 ->getTemplateParameters();
1288 return
1289 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1290 }
1291 return llvm::DIArray();
1292}
1293
1294/// CollectCXXTemplateParams - A helper function to collect debug info for
1295/// template parameters.
1296llvm::DIArray CGDebugInfo::
1297CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1298 llvm::DIFile Unit) {
1299 llvm::PointerUnion<ClassTemplateDecl *,
1300 ClassTemplatePartialSpecializationDecl *>
1301 PU = TSpecial->getSpecializedTemplateOrPartial();
1302
1303 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1304 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1305 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1306 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1307 return CollectTemplateParams(TPList, TAList, Unit);
1308}
1309
1310/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1311llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1312 if (VTablePtrType.isValid())
1313 return VTablePtrType;
1314
1315 ASTContext &Context = CGM.getContext();
1316
1317 /* Function type */
1318 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1319 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1320 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1321 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1322 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1323 "__vtbl_ptr_type");
1324 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1325 return VTablePtrType;
1326}
1327
1328/// getVTableName - Get vtable name for the given Class.
1329StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1330 // Construct gdb compatible name name.
1331 std::string Name = "_vptr$" + RD->getNameAsString();
1332
1333 // Copy this name on the side and use its reference.
1334 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1335 memcpy(StrPtr, Name.data(), Name.length());
1336 return StringRef(StrPtr, Name.length());
1337}
1338
1339
1340/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1341/// debug info entry in EltTys vector.
1342void CGDebugInfo::
1343CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1344 SmallVectorImpl<llvm::Value *> &EltTys) {
1345 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1346
1347 // If there is a primary base then it will hold vtable info.
1348 if (RL.getPrimaryBase())
1349 return;
1350
1351 // If this class is not dynamic then there is not any vtable info to collect.
1352 if (!RD->isDynamicClass())
1353 return;
1354
1355 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1356 llvm::DIType VPTR
1357 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1358 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1359 getOrCreateVTablePtrType(Unit));
1360 EltTys.push_back(VPTR);
1361}
1362
1363/// getOrCreateRecordType - Emit record type's standalone debug info.
1364llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1365 SourceLocation Loc) {
1366 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1367 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1368 return T;
1369}
1370
1371/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1372/// debug info.
1373llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001374 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001375 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1376 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001377 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001378 return T;
1379}
1380
1381/// CreateType - get structure or union type.
1382llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1383 RecordDecl *RD = Ty->getDecl();
1384
1385 // Get overall information about the record type for the debug info.
1386 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1387
1388 // Records and classes and unions can all be recursive. To handle them, we
1389 // first generate a debug descriptor for the struct as a forward declaration.
1390 // Then (if it is a definition) we go through and get debug info for all of
1391 // its members. Finally, we create a descriptor for the complete type (which
1392 // may refer to the forward decl if the struct is recursive) and replace all
1393 // uses of the forward declaration with the final definition.
1394
Eric Christopherf068c922013-04-02 22:59:11 +00001395 llvm::DICompositeType FwdDecl(
1396 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1397 assert(FwdDecl.Verify() &&
1398 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001399
1400 if (FwdDecl.isForwardDecl())
1401 return FwdDecl;
1402
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001404 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001405 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1406
Adrian Prantl4919de62013-03-06 22:03:30 +00001407 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001408 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1409
1410 // Convert all the elements.
1411 SmallVector<llvm::Value *, 16> EltTys;
1412
1413 // Note: The split of CXXDecl information here is intentional, the
1414 // gdb tests will depend on a certain ordering at printout. The debug
1415 // information offsets are still correct if we merge them all together
1416 // though.
1417 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1418 if (CXXDecl) {
1419 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1420 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1421 }
1422
Eric Christopher0395de32013-01-16 01:22:32 +00001423 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001424 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1425 llvm::DIArray TParamsArray;
1426 if (CXXDecl) {
1427 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1428 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1429 if (const ClassTemplateSpecializationDecl *TSpecial
1430 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1431 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1432 }
1433
1434 LexicalBlockStack.pop_back();
1435 RegionMap.erase(Ty->getDecl());
1436
1437 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001438 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001439
Eric Christopherf068c922013-04-02 22:59:11 +00001440 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1441 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001442}
1443
1444/// CreateType - get objective-c object type.
1445llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1446 llvm::DIFile Unit) {
1447 // Ignore protocols.
1448 return getOrCreateType(Ty->getBaseType(), Unit);
1449}
1450
1451/// CreateType - get objective-c interface type.
1452llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1453 llvm::DIFile Unit) {
1454 ObjCInterfaceDecl *ID = Ty->getDecl();
1455 if (!ID)
1456 return llvm::DIType();
1457
1458 // Get overall information about the record type for the debug info.
1459 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1460 unsigned Line = getLineNumber(ID->getLocation());
1461 unsigned RuntimeLang = TheCU.getLanguage();
1462
1463 // If this is just a forward declaration return a special forward-declaration
1464 // debug type since we won't be able to lay out the entire type.
1465 ObjCInterfaceDecl *Def = ID->getDefinition();
1466 if (!Def) {
1467 llvm::DIType FwdDecl =
1468 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001469 ID->getName(), TheCU, DefUnit, Line,
1470 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001471 return FwdDecl;
1472 }
1473
1474 ID = Def;
1475
1476 // Bit size, align and offset of the type.
1477 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1478 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1479
1480 unsigned Flags = 0;
1481 if (ID->getImplementation())
1482 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1483
Eric Christopherf068c922013-04-02 22:59:11 +00001484 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001485 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1486 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001487 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001488
1489 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1490 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001491 QualType QualTy = QualType(Ty, 0);
1492 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001493 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001494
Eric Christopherf068c922013-04-02 22:59:11 +00001495 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001496 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1497
1498 // Convert all the elements.
1499 SmallVector<llvm::Value *, 16> EltTys;
1500
1501 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1502 if (SClass) {
1503 llvm::DIType SClassTy =
1504 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1505 if (!SClassTy.isValid())
1506 return llvm::DIType();
1507
1508 llvm::DIType InhTag =
1509 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1510 EltTys.push_back(InhTag);
1511 }
1512
1513 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1514 E = ID->prop_end(); I != E; ++I) {
1515 const ObjCPropertyDecl *PD = *I;
1516 SourceLocation Loc = PD->getLocation();
1517 llvm::DIFile PUnit = getOrCreateFile(Loc);
1518 unsigned PLine = getLineNumber(Loc);
1519 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1520 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1521 llvm::MDNode *PropertyNode =
1522 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001523 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001524 (Getter && Getter->isImplicit()) ? "" :
1525 getSelectorName(PD->getGetterName()),
1526 (Setter && Setter->isImplicit()) ? "" :
1527 getSelectorName(PD->getSetterName()),
1528 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001529 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001530 EltTys.push_back(PropertyNode);
1531 }
1532
1533 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1534 unsigned FieldNo = 0;
1535 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1536 Field = Field->getNextIvar(), ++FieldNo) {
1537 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1538 if (!FieldTy.isValid())
1539 return llvm::DIType();
1540
1541 StringRef FieldName = Field->getName();
1542
1543 // Ignore unnamed fields.
1544 if (FieldName.empty())
1545 continue;
1546
1547 // Get the location for the field.
1548 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1549 unsigned FieldLine = getLineNumber(Field->getLocation());
1550 QualType FType = Field->getType();
1551 uint64_t FieldSize = 0;
1552 unsigned FieldAlign = 0;
1553
1554 if (!FType->isIncompleteArrayType()) {
1555
1556 // Bit size, align and offset of the type.
1557 FieldSize = Field->isBitField()
1558 ? Field->getBitWidthValue(CGM.getContext())
1559 : CGM.getContext().getTypeSize(FType);
1560 FieldAlign = CGM.getContext().getTypeAlign(FType);
1561 }
1562
1563 uint64_t FieldOffset;
1564 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1565 // We don't know the runtime offset of an ivar if we're using the
1566 // non-fragile ABI. For bitfields, use the bit offset into the first
1567 // byte of storage of the bitfield. For other fields, use zero.
1568 if (Field->isBitField()) {
1569 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1570 CGM, ID, Field);
1571 FieldOffset %= CGM.getContext().getCharWidth();
1572 } else {
1573 FieldOffset = 0;
1574 }
1575 } else {
1576 FieldOffset = RL.getFieldOffset(FieldNo);
1577 }
1578
1579 unsigned Flags = 0;
1580 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1581 Flags = llvm::DIDescriptor::FlagProtected;
1582 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1583 Flags = llvm::DIDescriptor::FlagPrivate;
1584
1585 llvm::MDNode *PropertyNode = NULL;
1586 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1587 if (ObjCPropertyImplDecl *PImpD =
1588 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1589 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001590 SourceLocation Loc = PD->getLocation();
1591 llvm::DIFile PUnit = getOrCreateFile(Loc);
1592 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001593 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1594 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1595 PropertyNode =
1596 DBuilder.createObjCProperty(PD->getName(),
1597 PUnit, PLine,
1598 (Getter && Getter->isImplicit()) ? "" :
1599 getSelectorName(PD->getGetterName()),
1600 (Setter && Setter->isImplicit()) ? "" :
1601 getSelectorName(PD->getSetterName()),
1602 PD->getPropertyAttributes(),
1603 getOrCreateType(PD->getType(), PUnit));
1604 }
1605 }
1606 }
1607 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1608 FieldLine, FieldSize, FieldAlign,
1609 FieldOffset, Flags, FieldTy,
1610 PropertyNode);
1611 EltTys.push_back(FieldTy);
1612 }
1613
1614 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001615 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001616
1617 // If the implementation is not yet set, we do not want to mark it
1618 // as complete. An implementation may declare additional
1619 // private ivars that we would miss otherwise.
1620 if (ID->getImplementation() == 0)
1621 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001622
1623 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001624 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001625}
1626
1627llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1628 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1629 int64_t Count = Ty->getNumElements();
1630 if (Count == 0)
1631 // If number of elements are not known then this is an unbounded array.
1632 // Use Count == -1 to express such arrays.
1633 Count = -1;
1634
1635 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1636 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1637
1638 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1639 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1640
1641 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1642}
1643
1644llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1645 llvm::DIFile Unit) {
1646 uint64_t Size;
1647 uint64_t Align;
1648
1649 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1650 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1651 Size = 0;
1652 Align =
1653 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1654 } else if (Ty->isIncompleteArrayType()) {
1655 Size = 0;
1656 if (Ty->getElementType()->isIncompleteType())
1657 Align = 0;
1658 else
1659 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001660 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001661 Size = 0;
1662 Align = 0;
1663 } else {
1664 // Size and align of the whole array, not the element type.
1665 Size = CGM.getContext().getTypeSize(Ty);
1666 Align = CGM.getContext().getTypeAlign(Ty);
1667 }
1668
1669 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1670 // interior arrays, do we care? Why aren't nested arrays represented the
1671 // obvious/recursive way?
1672 SmallVector<llvm::Value *, 8> Subscripts;
1673 QualType EltTy(Ty, 0);
1674 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1675 // If the number of elements is known, then count is that number. Otherwise,
1676 // it's -1. This allows us to represent a subrange with an array of 0
1677 // elements, like this:
1678 //
1679 // struct foo {
1680 // int x[0];
1681 // };
1682 int64_t Count = -1; // Count == -1 is an unbounded array.
1683 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1684 Count = CAT->getSize().getZExtValue();
1685
1686 // FIXME: Verify this is right for VLAs.
1687 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1688 EltTy = Ty->getElementType();
1689 }
1690
1691 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1692
1693 llvm::DIType DbgTy =
1694 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1695 SubscriptArray);
1696 return DbgTy;
1697}
1698
1699llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1700 llvm::DIFile Unit) {
1701 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1702 Ty, Ty->getPointeeType(), Unit);
1703}
1704
1705llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1706 llvm::DIFile Unit) {
1707 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1708 Ty, Ty->getPointeeType(), Unit);
1709}
1710
1711llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1712 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001713 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1714 if (!Ty->getPointeeType()->isFunctionType())
1715 return DBuilder.createMemberPointerType(
1716 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1717 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1718 CGM.getContext().getPointerType(
1719 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1720 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1721 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001722}
1723
1724llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1725 llvm::DIFile U) {
1726 // Ignore the atomic wrapping
1727 // FIXME: What is the correct representation?
1728 return getOrCreateType(Ty->getValueType(), U);
1729}
1730
1731/// CreateEnumType - get enumeration type.
1732llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1733 uint64_t Size = 0;
1734 uint64_t Align = 0;
1735 if (!ED->getTypeForDecl()->isIncompleteType()) {
1736 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1737 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1738 }
1739
1740 // If this is just a forward declaration, construct an appropriately
1741 // marked node and just return it.
1742 if (!ED->getDefinition()) {
1743 llvm::DIDescriptor EDContext;
1744 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1745 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1746 unsigned Line = getLineNumber(ED->getLocation());
1747 StringRef EDName = ED->getName();
1748 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1749 EDName, EDContext, DefUnit, Line, 0,
1750 Size, Align);
1751 }
1752
1753 // Create DIEnumerator elements for each enumerator.
1754 SmallVector<llvm::Value *, 16> Enumerators;
1755 ED = ED->getDefinition();
1756 for (EnumDecl::enumerator_iterator
1757 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1758 Enum != EnumEnd; ++Enum) {
1759 Enumerators.push_back(
1760 DBuilder.createEnumerator(Enum->getName(),
1761 Enum->getInitVal().getZExtValue()));
1762 }
1763
1764 // Return a CompositeType for the enum itself.
1765 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1766
1767 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1768 unsigned Line = getLineNumber(ED->getLocation());
1769 llvm::DIDescriptor EnumContext =
1770 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001771 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001772 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1773 llvm::DIType DbgTy =
1774 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1775 Size, Align, EltArray,
1776 ClassTy);
1777 return DbgTy;
1778}
1779
David Blaikie4b12be62013-01-21 04:37:12 +00001780static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1781 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001782 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001783 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001784 QualType LastT = T;
1785 switch (T->getTypeClass()) {
1786 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001787 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 case Type::TemplateSpecialization:
1789 T = cast<TemplateSpecializationType>(T)->desugar();
1790 break;
1791 case Type::TypeOfExpr:
1792 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1793 break;
1794 case Type::TypeOf:
1795 T = cast<TypeOfType>(T)->getUnderlyingType();
1796 break;
1797 case Type::Decltype:
1798 T = cast<DecltypeType>(T)->getUnderlyingType();
1799 break;
1800 case Type::UnaryTransform:
1801 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1802 break;
1803 case Type::Attributed:
1804 T = cast<AttributedType>(T)->getEquivalentType();
1805 break;
1806 case Type::Elaborated:
1807 T = cast<ElaboratedType>(T)->getNamedType();
1808 break;
1809 case Type::Paren:
1810 T = cast<ParenType>(T)->getInnerType();
1811 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001812 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001813 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001814 break;
1815 case Type::Auto:
1816 T = cast<AutoType>(T)->getDeducedType();
1817 break;
1818 }
1819
1820 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001821 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001822 } while (true);
1823}
1824
1825/// getType - Get the type from the cache or return null type if it doesn't exist.
1826llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1827
1828 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001829 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001830
1831 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001832 if (Ty->getTypeClass() == Type::ObjCInterface) {
1833 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1834 if (V)
1835 return llvm::DIType(cast<llvm::MDNode>(V));
1836 else return llvm::DIType();
1837 }
1838
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001839 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1840 TypeCache.find(Ty.getAsOpaquePtr());
1841 if (it != TypeCache.end()) {
1842 // Verify that the debug info still exists.
1843 if (llvm::Value *V = it->second)
1844 return llvm::DIType(cast<llvm::MDNode>(V));
1845 }
1846
1847 return llvm::DIType();
1848}
1849
1850/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1851/// doesn't exist.
1852llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1853
1854 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001855 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001856
1857 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001858 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001859 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1860 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001861 if (it != CompletedTypeCache.end())
1862 V = it->second;
1863 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001864 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001865 }
1866
Adrian Prantl4919de62013-03-06 22:03:30 +00001867 // Verify that any cached debug info still exists.
1868 if (V != 0)
1869 return llvm::DIType(cast<llvm::MDNode>(V));
1870
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001871 return llvm::DIType();
1872}
1873
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001874/// getCachedInterfaceTypeOrNull - Get the type from the interface
1875/// cache, unless it needs to regenerated. Otherwise return null.
1876llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1877 // Is there a cached interface that hasn't changed?
1878 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1879 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1880
1881 if (it1 != ObjCInterfaceCache.end())
1882 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1883 if (Checksum(Decl) == it1->second.second)
1884 // Return cached forward declaration.
1885 return it1->second.first;
1886
1887 return 0;
1888}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001889
1890/// getOrCreateType - Get the type from the cache or create a new
1891/// one if necessary.
1892llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1893 if (Ty.isNull())
1894 return llvm::DIType();
1895
1896 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001897 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001898
1899 llvm::DIType T = getCompletedTypeOrNull(Ty);
1900
1901 if (T.Verify())
1902 return T;
1903
1904 // Otherwise create the type.
1905 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001906 void* TyPtr = Ty.getAsOpaquePtr();
1907
1908 // And update the type cache.
1909 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001910
1911 llvm::DIType TC = getTypeOrNull(Ty);
1912 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001913 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1914 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1915 // Interface types may have elements added to them by a
1916 // subsequent implementation or extension, so we keep them in
1917 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001918 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001919 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1920 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1921 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1922 if (it != ObjCInterfaceCache.end())
1923 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1924 else
1925 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001926 Decl->getName(), TheCU, Unit,
1927 getLineNumber(Decl->getLocation()),
1928 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001929 // Store the forward declaration in the cache.
1930 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1931
1932 // Register the type for replacement in finalize().
1933 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1934 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001935 }
1936
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001937 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001938 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001939
1940 return Res;
1941}
1942
Adrian Prantl4919de62013-03-06 22:03:30 +00001943/// Currently the checksum merely consists of the number of ivars.
1944unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001945 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001946 unsigned IvarNo = 0;
1947 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1948 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1949 return IvarNo;
1950}
1951
1952ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1953 switch (Ty->getTypeClass()) {
1954 case Type::ObjCObjectPointer:
1955 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1956 case Type::ObjCInterface:
1957 return cast<ObjCInterfaceType>(Ty)->getDecl();
1958 default:
1959 return 0;
1960 }
1961}
1962
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001963/// CreateTypeNode - Create a new debug type node.
1964llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1965 // Handle qualifiers, which recursively handles what they refer to.
1966 if (Ty.hasLocalQualifiers())
1967 return CreateQualifiedType(Ty, Unit);
1968
1969 const char *Diag = 0;
1970
1971 // Work out details of type.
1972 switch (Ty->getTypeClass()) {
1973#define TYPE(Class, Base)
1974#define ABSTRACT_TYPE(Class, Base)
1975#define NON_CANONICAL_TYPE(Class, Base)
1976#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1977#include "clang/AST/TypeNodes.def"
1978 llvm_unreachable("Dependent types cannot show up in debug information");
1979
1980 case Type::ExtVector:
1981 case Type::Vector:
1982 return CreateType(cast<VectorType>(Ty), Unit);
1983 case Type::ObjCObjectPointer:
1984 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1985 case Type::ObjCObject:
1986 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1987 case Type::ObjCInterface:
1988 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1989 case Type::Builtin:
1990 return CreateType(cast<BuiltinType>(Ty));
1991 case Type::Complex:
1992 return CreateType(cast<ComplexType>(Ty));
1993 case Type::Pointer:
1994 return CreateType(cast<PointerType>(Ty), Unit);
1995 case Type::BlockPointer:
1996 return CreateType(cast<BlockPointerType>(Ty), Unit);
1997 case Type::Typedef:
1998 return CreateType(cast<TypedefType>(Ty), Unit);
1999 case Type::Record:
2000 return CreateType(cast<RecordType>(Ty));
2001 case Type::Enum:
2002 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2003 case Type::FunctionProto:
2004 case Type::FunctionNoProto:
2005 return CreateType(cast<FunctionType>(Ty), Unit);
2006 case Type::ConstantArray:
2007 case Type::VariableArray:
2008 case Type::IncompleteArray:
2009 return CreateType(cast<ArrayType>(Ty), Unit);
2010
2011 case Type::LValueReference:
2012 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2013 case Type::RValueReference:
2014 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2015
2016 case Type::MemberPointer:
2017 return CreateType(cast<MemberPointerType>(Ty), Unit);
2018
2019 case Type::Atomic:
2020 return CreateType(cast<AtomicType>(Ty), Unit);
2021
2022 case Type::Attributed:
2023 case Type::TemplateSpecialization:
2024 case Type::Elaborated:
2025 case Type::Paren:
2026 case Type::SubstTemplateTypeParm:
2027 case Type::TypeOfExpr:
2028 case Type::TypeOf:
2029 case Type::Decltype:
2030 case Type::UnaryTransform:
2031 case Type::Auto:
2032 llvm_unreachable("type should have been unwrapped!");
2033 }
2034
2035 assert(Diag && "Fall through without a diagnostic?");
2036 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2037 "debug information for %0 is not yet supported");
2038 CGM.getDiags().Report(DiagID)
2039 << Diag;
2040 return llvm::DIType();
2041}
2042
2043/// getOrCreateLimitedType - Get the type from the cache or create a new
2044/// limited type if necessary.
2045llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002046 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002047 if (Ty.isNull())
2048 return llvm::DIType();
2049
2050 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002051 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002052
2053 llvm::DIType T = getTypeOrNull(Ty);
2054
2055 // We may have cached a forward decl when we could have created
2056 // a non-forward decl. Go ahead and create a non-forward decl
2057 // now.
2058 if (T.Verify() && !T.isForwardDecl()) return T;
2059
2060 // Otherwise create the type.
2061 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2062
2063 if (T.Verify() && T.isForwardDecl())
2064 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2065 static_cast<llvm::Value*>(T)));
2066
2067 // And update the type cache.
2068 TypeCache[Ty.getAsOpaquePtr()] = Res;
2069 return Res;
2070}
2071
2072// TODO: Currently used for context chains when limiting debug info.
2073llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2074 RecordDecl *RD = Ty->getDecl();
2075
2076 // Get overall information about the record type for the debug info.
2077 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2078 unsigned Line = getLineNumber(RD->getLocation());
2079 StringRef RDName = getClassName(RD);
2080
2081 llvm::DIDescriptor RDContext;
2082 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2083 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2084 else
2085 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2086
2087 // If this is just a forward declaration, construct an appropriately
2088 // marked node and just return it.
2089 if (!RD->getDefinition())
2090 return createRecordFwdDecl(RD, RDContext);
2091
2092 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2093 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2094 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002095 llvm::DICompositeType RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002096
2097 if (RD->isUnion())
2098 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002099 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100 else if (RD->isClass()) {
2101 // FIXME: This could be a struct type giving a default visibility different
2102 // than C++ class type, but needs llvm metadata changes first.
2103 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002104 Size, Align, 0, 0, llvm::DIType(),
2105 llvm::DIArray(), llvm::DIType(),
2106 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002107 } else
2108 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002109 Size, Align, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002110
2111 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002112 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002113
2114 if (CXXDecl) {
2115 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002116 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002117 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2118 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2119 // Seek non virtual primary base root.
2120 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002121 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2122 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2123 if (PBT && !BRL.isPrimaryBaseVirtual())
2124 PBase = PBT;
2125 else
2126 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002127 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002128 ContainingType = llvm::DICompositeType(
2129 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2130 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131 ContainingType = RealDecl;
2132
David Blaikie2fcadbe2013-03-26 23:47:35 +00002133 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002134 }
2135 return llvm::DIType(RealDecl);
2136}
2137
2138/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2139/// declare composite types that haven't been processed yet.
2140llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2141
2142 // Work out details of type.
2143 switch (Ty->getTypeClass()) {
2144#define TYPE(Class, Base)
2145#define ABSTRACT_TYPE(Class, Base)
2146#define NON_CANONICAL_TYPE(Class, Base)
2147#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2148 #include "clang/AST/TypeNodes.def"
2149 llvm_unreachable("Dependent types cannot show up in debug information");
2150
2151 case Type::Record:
2152 return CreateLimitedType(cast<RecordType>(Ty));
2153 default:
2154 return CreateTypeNode(Ty, Unit);
2155 }
2156}
2157
2158/// CreateMemberType - Create new member and increase Offset by FType's size.
2159llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2160 StringRef Name,
2161 uint64_t *Offset) {
2162 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2163 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2164 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2165 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2166 FieldSize, FieldAlign,
2167 *Offset, 0, FieldTy);
2168 *Offset += FieldSize;
2169 return Ty;
2170}
2171
David Blaikie3923d6a2013-05-08 06:01:46 +00002172llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2173 if (const TypeDecl *RD = dyn_cast<TypeDecl>(D))
2174 return CreatePointeeType(QualType(RD->getTypeForDecl(), 0), llvm::DIFile());
2175 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2176 DeclCache.find(D->getCanonicalDecl());
2177 if (I == DeclCache.end())
2178 return llvm::DIDescriptor();
2179 llvm::Value *V = I->second;
2180 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2181}
2182
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002183/// getFunctionDeclaration - Return debug info descriptor to describe method
2184/// declaration for the given method definition.
2185llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2186 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2187 if (!FD) return llvm::DISubprogram();
2188
2189 // Setup context.
2190 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2191
2192 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2193 MI = SPCache.find(FD->getCanonicalDecl());
2194 if (MI != SPCache.end()) {
2195 llvm::Value *V = MI->second;
2196 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2197 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2198 return SP;
2199 }
2200
2201 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2202 E = FD->redecls_end(); I != E; ++I) {
2203 const FunctionDecl *NextFD = *I;
2204 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2205 MI = SPCache.find(NextFD->getCanonicalDecl());
2206 if (MI != SPCache.end()) {
2207 llvm::Value *V = MI->second;
2208 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2209 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2210 return SP;
2211 }
2212 }
2213 return llvm::DISubprogram();
2214}
2215
2216// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2217// implicit parameter "this".
2218llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2219 QualType FnType,
2220 llvm::DIFile F) {
2221
2222 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2223 return getOrCreateMethodType(Method, F);
2224 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2225 // Add "self" and "_cmd"
2226 SmallVector<llvm::Value *, 16> Elts;
2227
2228 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002229 QualType ResultTy = OMethod->hasRelatedResultType()
2230 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2231 : OMethod->getResultType();
2232 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002233 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002234 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2235 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2236 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002237 // "_cmd" pointer is always second argument.
2238 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2239 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2240 // Get rest of the arguments.
2241 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2242 PE = OMethod->param_end(); PI != PE; ++PI)
2243 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2244
2245 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2246 return DBuilder.createSubroutineType(F, EltTypeArray);
2247 }
2248 return getOrCreateType(FnType, F);
2249}
2250
2251/// EmitFunctionStart - Constructs the debug code for entering a function.
2252void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2253 llvm::Function *Fn,
2254 CGBuilderTy &Builder) {
2255
2256 StringRef Name;
2257 StringRef LinkageName;
2258
2259 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2260
2261 const Decl *D = GD.getDecl();
2262 // Function may lack declaration in source code if it is created by Clang
2263 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2264 bool HasDecl = (D != 0);
2265 // Use the location of the declaration.
2266 SourceLocation Loc;
2267 if (HasDecl)
2268 Loc = D->getLocation();
2269
2270 unsigned Flags = 0;
2271 llvm::DIFile Unit = getOrCreateFile(Loc);
2272 llvm::DIDescriptor FDContext(Unit);
2273 llvm::DIArray TParamsArray;
2274 if (!HasDecl) {
2275 // Use llvm function name.
2276 Name = Fn->getName();
2277 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2278 // If there is a DISubprogram for this function available then use it.
2279 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2280 FI = SPCache.find(FD->getCanonicalDecl());
2281 if (FI != SPCache.end()) {
2282 llvm::Value *V = FI->second;
2283 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2284 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2285 llvm::MDNode *SPN = SP;
2286 LexicalBlockStack.push_back(SPN);
2287 RegionMap[D] = llvm::WeakVH(SP);
2288 return;
2289 }
2290 }
2291 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002292 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002293 if (FD->hasPrototype()) {
2294 LinkageName = CGM.getMangledName(GD);
2295 Flags |= llvm::DIDescriptor::FlagPrototyped;
2296 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002297 // No need to replicate the linkage name if it isn't different from the
2298 // subprogram name, no need to have it at all unless coverage is enabled or
2299 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002300 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002301 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2302 !CGM.getCodeGenOpts().EmitGcovNotes &&
2303 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002304 LinkageName = StringRef();
2305
2306 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2307 if (const NamespaceDecl *NSDecl =
2308 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2309 FDContext = getOrCreateNameSpace(NSDecl);
2310 else if (const RecordDecl *RDecl =
2311 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2312 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2313
2314 // Collect template parameters.
2315 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2316 }
2317 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2318 Name = getObjCMethodName(OMD);
2319 Flags |= llvm::DIDescriptor::FlagPrototyped;
2320 } else {
2321 // Use llvm function name.
2322 Name = Fn->getName();
2323 Flags |= llvm::DIDescriptor::FlagPrototyped;
2324 }
2325 if (!Name.empty() && Name[0] == '\01')
2326 Name = Name.substr(1);
2327
2328 unsigned LineNo = getLineNumber(Loc);
2329 if (!HasDecl || D->isImplicit())
2330 Flags |= llvm::DIDescriptor::FlagArtificial;
2331
2332 llvm::DIType DIFnType;
2333 llvm::DISubprogram SPDecl;
2334 if (HasDecl &&
2335 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2336 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2337 SPDecl = getFunctionDeclaration(D);
2338 } else {
2339 // Create fake but valid subroutine type. Otherwise
2340 // llvm::DISubprogram::Verify() would return false, and
2341 // subprogram DIE will miss DW_AT_decl_file and
2342 // DW_AT_decl_line fields.
2343 SmallVector<llvm::Value*, 16> Elts;
2344 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2345 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2346 }
2347 llvm::DISubprogram SP;
2348 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2349 LineNo, DIFnType,
2350 Fn->hasInternalLinkage(), true/*definition*/,
2351 getLineNumber(CurLoc), Flags,
2352 CGM.getLangOpts().Optimize,
2353 Fn, TParamsArray, SPDecl);
David Blaikie3923d6a2013-05-08 06:01:46 +00002354 if (HasDecl)
2355 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002356
2357 // Push function on region stack.
2358 llvm::MDNode *SPN = SP;
2359 LexicalBlockStack.push_back(SPN);
2360 if (HasDecl)
2361 RegionMap[D] = llvm::WeakVH(SP);
2362}
2363
2364/// EmitLocation - Emit metadata to indicate a change in line/column
2365/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002366void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2367 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002368
2369 // Update our current location
2370 setLocation(Loc);
2371
2372 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2373
2374 // Don't bother if things are the same as last time.
2375 SourceManager &SM = CGM.getContext().getSourceManager();
2376 if (CurLoc == PrevLoc ||
2377 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2378 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002379 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2380 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2381 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002382 return;
2383
2384 // Update last state.
2385 PrevLoc = CurLoc;
2386
2387 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002388 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2389 (getLineNumber(CurLoc),
2390 getColumnNumber(CurLoc, ForceColumnInfo),
2391 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002392}
2393
2394/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2395/// the stack.
2396void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2397 llvm::DIDescriptor D =
2398 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2399 llvm::DIDescriptor() :
2400 llvm::DIDescriptor(LexicalBlockStack.back()),
2401 getOrCreateFile(CurLoc),
2402 getLineNumber(CurLoc),
2403 getColumnNumber(CurLoc));
2404 llvm::MDNode *DN = D;
2405 LexicalBlockStack.push_back(DN);
2406}
2407
2408/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2409/// region - beginning of a DW_TAG_lexical_block.
2410void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2411 // Set our current location.
2412 setLocation(Loc);
2413
2414 // Create a new lexical block and push it on the stack.
2415 CreateLexicalBlock(Loc);
2416
2417 // Emit a line table change for the current location inside the new scope.
2418 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2419 getColumnNumber(Loc),
2420 LexicalBlockStack.back()));
2421}
2422
2423/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2424/// region - end of a DW_TAG_lexical_block.
2425void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2426 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2427
2428 // Provide an entry in the line table for the end of the block.
2429 EmitLocation(Builder, Loc);
2430
2431 LexicalBlockStack.pop_back();
2432}
2433
2434/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2435void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2436 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2437 unsigned RCount = FnBeginRegionCount.back();
2438 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2439
2440 // Pop all regions for this function.
2441 while (LexicalBlockStack.size() != RCount)
2442 EmitLexicalBlockEnd(Builder, CurLoc);
2443 FnBeginRegionCount.pop_back();
2444}
2445
2446// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2447// See BuildByRefType.
2448llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2449 uint64_t *XOffset) {
2450
2451 SmallVector<llvm::Value *, 5> EltTys;
2452 QualType FType;
2453 uint64_t FieldSize, FieldOffset;
2454 unsigned FieldAlign;
2455
2456 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2457 QualType Type = VD->getType();
2458
2459 FieldOffset = 0;
2460 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2461 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2462 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2463 FType = CGM.getContext().IntTy;
2464 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2465 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2466
2467 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2468 if (HasCopyAndDispose) {
2469 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2470 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2471 &FieldOffset));
2472 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2473 &FieldOffset));
2474 }
2475 bool HasByrefExtendedLayout;
2476 Qualifiers::ObjCLifetime Lifetime;
2477 if (CGM.getContext().getByrefLifetime(Type,
2478 Lifetime, HasByrefExtendedLayout)
2479 && HasByrefExtendedLayout)
2480 EltTys.push_back(CreateMemberType(Unit, FType,
2481 "__byref_variable_layout",
2482 &FieldOffset));
2483
2484 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2485 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002486 CGM.getTarget().getPointerAlign(0))) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002487 CharUnits FieldOffsetInBytes
2488 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2489 CharUnits AlignedOffsetInBytes
2490 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2491 CharUnits NumPaddingBytes
2492 = AlignedOffsetInBytes - FieldOffsetInBytes;
2493
2494 if (NumPaddingBytes.isPositive()) {
2495 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2496 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2497 pad, ArrayType::Normal, 0);
2498 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2499 }
2500 }
2501
2502 FType = Type;
2503 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2504 FieldSize = CGM.getContext().getTypeSize(FType);
2505 FieldAlign = CGM.getContext().toBits(Align);
2506
2507 *XOffset = FieldOffset;
2508 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2509 0, FieldSize, FieldAlign,
2510 FieldOffset, 0, FieldTy);
2511 EltTys.push_back(FieldTy);
2512 FieldOffset += FieldSize;
2513
2514 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2515
2516 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2517
2518 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002519 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002520}
2521
2522/// EmitDeclare - Emit local variable declaration debug info.
2523void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2524 llvm::Value *Storage,
2525 unsigned ArgNo, CGBuilderTy &Builder) {
2526 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2527 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2528
2529 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2530 llvm::DIType Ty;
2531 uint64_t XOffset = 0;
2532 if (VD->hasAttr<BlocksAttr>())
2533 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2534 else
2535 Ty = getOrCreateType(VD->getType(), Unit);
2536
2537 // If there is no debug info for this type then do not emit debug info
2538 // for this variable.
2539 if (!Ty)
2540 return;
2541
2542 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2543 // If Storage is an aggregate returned as 'sret' then let debugger know
2544 // about this.
2545 if (Arg->hasStructRetAttr())
2546 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2547 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2548 // If an aggregate variable has non trivial destructor or non trivial copy
2549 // constructor than it is pass indirectly. Let debug info know about this
2550 // by using reference of the aggregate type as a argument type.
2551 if (Record->hasNonTrivialCopyConstructor() ||
2552 !Record->hasTrivialDestructor())
2553 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2554 }
2555 }
2556
2557 // Get location information.
2558 unsigned Line = getLineNumber(VD->getLocation());
2559 unsigned Column = getColumnNumber(VD->getLocation());
2560 unsigned Flags = 0;
2561 if (VD->isImplicit())
2562 Flags |= llvm::DIDescriptor::FlagArtificial;
2563 // If this is the first argument and it is implicit then
2564 // give it an object pointer flag.
2565 // FIXME: There has to be a better way to do this, but for static
2566 // functions there won't be an implicit param at arg1 and
2567 // otherwise it is 'self' or 'this'.
2568 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2569 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2570
2571 llvm::MDNode *Scope = LexicalBlockStack.back();
2572
2573 StringRef Name = VD->getName();
2574 if (!Name.empty()) {
2575 if (VD->hasAttr<BlocksAttr>()) {
2576 CharUnits offset = CharUnits::fromQuantity(32);
2577 SmallVector<llvm::Value *, 9> addr;
2578 llvm::Type *Int64Ty = CGM.Int64Ty;
2579 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2580 // offset of __forwarding field
2581 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002582 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002583 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2584 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2585 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2586 // offset of x field
2587 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2588 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2589
2590 // Create the descriptor for the variable.
2591 llvm::DIVariable D =
2592 DBuilder.createComplexVariable(Tag,
2593 llvm::DIDescriptor(Scope),
2594 VD->getName(), Unit, Line, Ty,
2595 addr, ArgNo);
2596
2597 // Insert an llvm.dbg.declare into the current block.
2598 llvm::Instruction *Call =
2599 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2600 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2601 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002602 } else if (isa<VariableArrayType>(VD->getType())) {
2603 // These are "complex" variables in that they need an op_deref.
2604 // Create the descriptor for the variable.
2605 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2606 llvm::DIBuilder::OpDeref);
2607 llvm::DIVariable D =
2608 DBuilder.createComplexVariable(Tag,
2609 llvm::DIDescriptor(Scope),
2610 Name, Unit, Line, Ty,
2611 Addr, ArgNo);
2612
2613 // Insert an llvm.dbg.declare into the current block.
2614 llvm::Instruction *Call =
2615 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2616 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2617 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002618 }
David Blaikie436653b2013-01-05 05:58:35 +00002619 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2620 // If VD is an anonymous union then Storage represents value for
2621 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002622 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002623 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002624 for (RecordDecl::field_iterator I = RD->field_begin(),
2625 E = RD->field_end();
2626 I != E; ++I) {
2627 FieldDecl *Field = *I;
2628 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2629 StringRef FieldName = Field->getName();
2630
2631 // Ignore unnamed fields. Do not ignore unnamed records.
2632 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2633 continue;
2634
2635 // Use VarDecl's Tag, Scope and Line number.
2636 llvm::DIVariable D =
2637 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2638 FieldName, Unit, Line, FieldTy,
2639 CGM.getLangOpts().Optimize, Flags,
2640 ArgNo);
2641
2642 // Insert an llvm.dbg.declare into the current block.
2643 llvm::Instruction *Call =
2644 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2645 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2646 }
David Blaikied8180cf2013-01-05 20:03:07 +00002647 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002648 }
2649 }
David Blaikie436653b2013-01-05 05:58:35 +00002650
2651 // Create the descriptor for the variable.
2652 llvm::DIVariable D =
2653 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2654 Name, Unit, Line, Ty,
2655 CGM.getLangOpts().Optimize, Flags, ArgNo);
2656
2657 // Insert an llvm.dbg.declare into the current block.
2658 llvm::Instruction *Call =
2659 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2660 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002661}
2662
2663void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2664 llvm::Value *Storage,
2665 CGBuilderTy &Builder) {
2666 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2667 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2668}
2669
Adrian Prantle86fcc42013-03-29 19:20:29 +00002670/// Look up the completed type for a self pointer in the TypeCache and
2671/// create a copy of it with the ObjectPointer and Artificial flags
2672/// set. If the type is not cached, a new one is created. This should
2673/// never happen though, since creating a type for the implicit self
2674/// argument implies that we already parsed the interface definition
2675/// and the ivar declarations in the implementation.
2676llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2677 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2678 if (CachedTy.Verify()) Ty = CachedTy;
2679 else DEBUG(llvm::dbgs() << "No cached type for self.");
2680 return DBuilder.createObjectPointerType(Ty);
2681}
2682
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002683void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2684 llvm::Value *Storage,
2685 CGBuilderTy &Builder,
2686 const CGBlockInfo &blockInfo) {
2687 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2688 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2689
2690 if (Builder.GetInsertBlock() == 0)
2691 return;
2692
2693 bool isByRef = VD->hasAttr<BlocksAttr>();
2694
2695 uint64_t XOffset = 0;
2696 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2697 llvm::DIType Ty;
2698 if (isByRef)
2699 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2700 else
2701 Ty = getOrCreateType(VD->getType(), Unit);
2702
2703 // Self is passed along as an implicit non-arg variable in a
2704 // block. Mark it as the object pointer.
2705 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002706 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002707
2708 // Get location information.
2709 unsigned Line = getLineNumber(VD->getLocation());
2710 unsigned Column = getColumnNumber(VD->getLocation());
2711
2712 const llvm::DataLayout &target = CGM.getDataLayout();
2713
2714 CharUnits offset = CharUnits::fromQuantity(
2715 target.getStructLayout(blockInfo.StructureType)
2716 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2717
2718 SmallVector<llvm::Value *, 9> addr;
2719 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002720 if (isa<llvm::AllocaInst>(Storage))
2721 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002722 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2723 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2724 if (isByRef) {
2725 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2726 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2727 // offset of __forwarding field
2728 offset = CGM.getContext()
2729 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2730 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2731 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2732 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2733 // offset of x field
2734 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2735 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2736 }
2737
2738 // Create the descriptor for the variable.
2739 llvm::DIVariable D =
2740 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2741 llvm::DIDescriptor(LexicalBlockStack.back()),
2742 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002743
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002744 // Insert an llvm.dbg.declare into the current block.
2745 llvm::Instruction *Call =
2746 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2747 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2748 LexicalBlockStack.back()));
2749}
2750
2751/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2752/// variable declaration.
2753void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2754 unsigned ArgNo,
2755 CGBuilderTy &Builder) {
2756 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2757 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2758}
2759
2760namespace {
2761 struct BlockLayoutChunk {
2762 uint64_t OffsetInBits;
2763 const BlockDecl::Capture *Capture;
2764 };
2765 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2766 return l.OffsetInBits < r.OffsetInBits;
2767 }
2768}
2769
2770void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002771 llvm::Value *Arg,
2772 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002773 CGBuilderTy &Builder) {
2774 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2775 ASTContext &C = CGM.getContext();
2776 const BlockDecl *blockDecl = block.getBlockDecl();
2777
2778 // Collect some general information about the block's location.
2779 SourceLocation loc = blockDecl->getCaretLocation();
2780 llvm::DIFile tunit = getOrCreateFile(loc);
2781 unsigned line = getLineNumber(loc);
2782 unsigned column = getColumnNumber(loc);
2783
2784 // Build the debug-info type for the block literal.
2785 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2786
2787 const llvm::StructLayout *blockLayout =
2788 CGM.getDataLayout().getStructLayout(block.StructureType);
2789
2790 SmallVector<llvm::Value*, 16> fields;
2791 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2792 blockLayout->getElementOffsetInBits(0),
2793 tunit, tunit));
2794 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2795 blockLayout->getElementOffsetInBits(1),
2796 tunit, tunit));
2797 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2798 blockLayout->getElementOffsetInBits(2),
2799 tunit, tunit));
2800 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2801 blockLayout->getElementOffsetInBits(3),
2802 tunit, tunit));
2803 fields.push_back(createFieldType("__descriptor",
2804 C.getPointerType(block.NeedsCopyDispose ?
2805 C.getBlockDescriptorExtendedType() :
2806 C.getBlockDescriptorType()),
2807 0, loc, AS_public,
2808 blockLayout->getElementOffsetInBits(4),
2809 tunit, tunit));
2810
2811 // We want to sort the captures by offset, not because DWARF
2812 // requires this, but because we're paranoid about debuggers.
2813 SmallVector<BlockLayoutChunk, 8> chunks;
2814
2815 // 'this' capture.
2816 if (blockDecl->capturesCXXThis()) {
2817 BlockLayoutChunk chunk;
2818 chunk.OffsetInBits =
2819 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2820 chunk.Capture = 0;
2821 chunks.push_back(chunk);
2822 }
2823
2824 // Variable captures.
2825 for (BlockDecl::capture_const_iterator
2826 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2827 i != e; ++i) {
2828 const BlockDecl::Capture &capture = *i;
2829 const VarDecl *variable = capture.getVariable();
2830 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2831
2832 // Ignore constant captures.
2833 if (captureInfo.isConstant())
2834 continue;
2835
2836 BlockLayoutChunk chunk;
2837 chunk.OffsetInBits =
2838 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2839 chunk.Capture = &capture;
2840 chunks.push_back(chunk);
2841 }
2842
2843 // Sort by offset.
2844 llvm::array_pod_sort(chunks.begin(), chunks.end());
2845
2846 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2847 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2848 uint64_t offsetInBits = i->OffsetInBits;
2849 const BlockDecl::Capture *capture = i->Capture;
2850
2851 // If we have a null capture, this must be the C++ 'this' capture.
2852 if (!capture) {
2853 const CXXMethodDecl *method =
2854 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2855 QualType type = method->getThisType(C);
2856
2857 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2858 offsetInBits, tunit, tunit));
2859 continue;
2860 }
2861
2862 const VarDecl *variable = capture->getVariable();
2863 StringRef name = variable->getName();
2864
2865 llvm::DIType fieldType;
2866 if (capture->isByRef()) {
2867 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2868
2869 // FIXME: this creates a second copy of this type!
2870 uint64_t xoffset;
2871 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2872 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2873 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2874 ptrInfo.first, ptrInfo.second,
2875 offsetInBits, 0, fieldType);
2876 } else {
2877 fieldType = createFieldType(name, variable->getType(), 0,
2878 loc, AS_public, offsetInBits, tunit, tunit);
2879 }
2880 fields.push_back(fieldType);
2881 }
2882
2883 SmallString<36> typeName;
2884 llvm::raw_svector_ostream(typeName)
2885 << "__block_literal_" << CGM.getUniqueBlockCount();
2886
2887 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2888
2889 llvm::DIType type =
2890 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2891 CGM.getContext().toBits(block.BlockSize),
2892 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002893 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002894 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2895
2896 // Get overall information about the block.
2897 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2898 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002899
2900 // Create the descriptor for the parameter.
2901 llvm::DIVariable debugVar =
2902 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2903 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002904 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002905 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002906 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2907
Adrian Prantlbea407c2013-03-14 21:52:59 +00002908 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002909 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002910 llvm::Instruction *DbgVal =
2911 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002912 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002913 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2914 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002915
Adrian Prantlbea407c2013-03-14 21:52:59 +00002916 // Insert an llvm.dbg.declare into the current block.
2917 llvm::Instruction *DbgDecl =
2918 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2919 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002920}
2921
Eric Christopher0395de32013-01-16 01:22:32 +00002922/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2923/// a static data member of a class, find its corresponding in-class
2924/// declaration.
2925llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2926 if (cast<VarDecl>(D)->isStaticDataMember()) {
2927 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2928 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2929 if (MI != StaticDataMemberCache.end())
2930 // Verify the info still exists.
2931 if (llvm::Value *V = MI->second)
2932 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2933 }
2934 return llvm::DIDerivedType();
2935}
2936
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002937/// EmitGlobalVariable - Emit information about a global variable.
2938void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2939 const VarDecl *D) {
2940 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2941 // Create global variable debug descriptor.
2942 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2943 unsigned LineNo = getLineNumber(D->getLocation());
2944
2945 setLocation(D->getLocation());
2946
2947 QualType T = D->getType();
2948 if (T->isIncompleteArrayType()) {
2949
2950 // CodeGen turns int[] into int[1] so we'll do the same here.
2951 llvm::APInt ConstVal(32, 1);
2952 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2953
2954 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2955 ArrayType::Normal, 0);
2956 }
2957 StringRef DeclName = D->getName();
2958 StringRef LinkageName;
2959 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2960 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2961 LinkageName = Var->getName();
2962 if (LinkageName == DeclName)
2963 LinkageName = StringRef();
2964 llvm::DIDescriptor DContext =
2965 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie3923d6a2013-05-08 06:01:46 +00002966 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002967 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00002968 Var->hasInternalLinkage(), Var,
2969 getStaticDataMemberDeclaration(D));
David Blaikie3923d6a2013-05-08 06:01:46 +00002970 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002971}
2972
2973/// EmitGlobalVariable - Emit information about an objective-c interface.
2974void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2975 ObjCInterfaceDecl *ID) {
2976 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2977 // Create global variable debug descriptor.
2978 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2979 unsigned LineNo = getLineNumber(ID->getLocation());
2980
2981 StringRef Name = ID->getName();
2982
2983 QualType T = CGM.getContext().getObjCInterfaceType(ID);
2984 if (T->isIncompleteArrayType()) {
2985
2986 // CodeGen turns int[] into int[1] so we'll do the same here.
2987 llvm::APInt ConstVal(32, 1);
2988 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2989
2990 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2991 ArrayType::Normal, 0);
2992 }
2993
2994 DBuilder.createGlobalVariable(Name, Unit, LineNo,
2995 getOrCreateType(T, Unit),
2996 Var->hasInternalLinkage(), Var);
2997}
2998
2999/// EmitGlobalVariable - Emit global variable's debug info.
3000void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3001 llvm::Constant *Init) {
3002 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
3003 // Create the descriptor for the variable.
3004 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3005 StringRef Name = VD->getName();
3006 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3007 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3008 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3009 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3010 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3011 }
3012 // Do not use DIGlobalVariable for enums.
3013 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3014 return;
David Blaikie3923d6a2013-05-08 06:01:46 +00003015 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003016 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003017 Ty, true, Init,
3018 getStaticDataMemberDeclaration(VD));
David Blaikie3923d6a2013-05-08 06:01:46 +00003019 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3020}
3021
3022llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3023 if (!LexicalBlockStack.empty())
3024 return llvm::DIScope(LexicalBlockStack.back());
3025 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003026}
3027
David Blaikie957dac52013-04-22 06:13:21 +00003028void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3029 DBuilder.createImportedModule(
David Blaikie3923d6a2013-05-08 06:01:46 +00003030 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3031 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003032 getLineNumber(UD.getLocation()));
3033}
3034
David Blaikie3923d6a2013-05-08 06:01:46 +00003035void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3036 assert(UD.shadow_size() &&
3037 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3038 // Emitting one decl is sufficient - debuggers can detect that this is an
3039 // overloaded name & provide lookup for all the overloads.
3040 const UsingShadowDecl &USD = **UD.shadow_begin();
3041 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3042 DBuilder.createImportedDeclaration(
3043 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3044 getLineNumber(USD.getLocation()));
3045}
3046
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003047/// getOrCreateNamesSpace - Return namespace descriptor for the given
3048/// namespace decl.
3049llvm::DINameSpace
3050CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3051 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3052 NameSpaceCache.find(NSDecl);
3053 if (I != NameSpaceCache.end())
3054 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3055
3056 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3057 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3058 llvm::DIDescriptor Context =
3059 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3060 llvm::DINameSpace NS =
3061 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3062 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3063 return NS;
3064}
3065
3066void CGDebugInfo::finalize() {
3067 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3068 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3069 llvm::DIType Ty, RepTy;
3070 // Verify that the debug info still exists.
3071 if (llvm::Value *V = VI->second)
3072 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3073
3074 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3075 TypeCache.find(VI->first);
3076 if (it != TypeCache.end()) {
3077 // Verify that the debug info still exists.
3078 if (llvm::Value *V = it->second)
3079 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3080 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003081
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003082 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003083 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003084 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003085
3086 // We keep our own list of retained types, because we need to look
3087 // up the final type in the type cache.
3088 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3089 RE = RetainedTypes.end(); RI != RE; ++RI)
3090 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3091
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003092 DBuilder.finalize();
3093}