blob: f6ad8f2cc592477b3f88bf60f5b5dfa7bf3a180f [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.
David Blaikief8aa1552013-05-13 06:57:50 +00001223 if (InstanceMember) {
David Blaikie9dfd2432013-05-10 21:53:14 +00001224 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1225 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikief8aa1552013-05-13 06:57:50 +00001226 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1227 V = CGM.GetAddrOfFunction(FD);
David Blaikie9dfd2432013-05-10 21:53:14 +00001228 // Member data pointers have special handling too to compute the fixed
1229 // offset within the object.
1230 if (isa<FieldDecl>(D)) {
1231 // These five lines (& possibly the above member function pointer
1232 // handling) might be able to be refactored to use similar code in
1233 // CodeGenModule::getMemberPointerConstant
1234 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1235 CharUnits chars =
1236 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1237 V = CGM.getCXXABI().EmitMemberDataPointer(
1238 cast<MemberPointerType>(T.getTypePtr()), chars);
1239 }
1240 llvm::DITemplateValueParameter TVP =
1241 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1242 TemplateParams.push_back(TVP);
1243 } break;
1244 case TemplateArgument::NullPtr: {
1245 QualType T = TA.getNullPtrType();
1246 llvm::DIType TTy = getOrCreateType(T, Unit);
1247 llvm::Value *V = 0;
1248 // Special case member data pointer null values since they're actually -1
1249 // instead of zero.
1250 if (const MemberPointerType *MPT =
1251 dyn_cast<MemberPointerType>(T.getTypePtr()))
1252 // But treat member function pointers as simple zero integers because
1253 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1254 // CodeGen grows handling for values of non-null member function
1255 // pointers then perhaps we could remove this special case and rely on
1256 // EmitNullMemberPointer for member function pointers.
1257 if (MPT->isMemberDataPointer())
1258 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1259 if (!V)
1260 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1261 llvm::DITemplateValueParameter TVP =
1262 DBuilder.createTemplateValueParameter(TheCU, ND->getName(), TTy, V);
1263 TemplateParams.push_back(TVP);
1264 } break;
1265 case TemplateArgument::Template:
1266 // We could support this with the GCC extension
1267 // DW_TAG_GNU_template_template_param
1268 break;
David Blaikie776a3642013-05-10 22:53:25 +00001269 case TemplateArgument::Pack:
1270 // And this with DW_TAG_GNU_template_parameter_pack
1271 break;
David Blaikiee8065122013-05-10 23:36:06 +00001272 // And the following should never occur:
David Blaikie9dfd2432013-05-10 21:53:14 +00001273 case TemplateArgument::Expression:
1274 case TemplateArgument::TemplateExpansion:
David Blaikie9dfd2432013-05-10 21:53:14 +00001275 case TemplateArgument::Null:
1276 llvm_unreachable(
1277 "These argument types shouldn't exist in concrete types");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001278 }
1279 }
1280 return DBuilder.getOrCreateArray(TemplateParams);
1281}
1282
1283/// CollectFunctionTemplateParams - A helper function to collect debug
1284/// info for function template parameters.
1285llvm::DIArray CGDebugInfo::
1286CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1287 if (FD->getTemplatedKind() ==
1288 FunctionDecl::TK_FunctionTemplateSpecialization) {
1289 const TemplateParameterList *TList =
1290 FD->getTemplateSpecializationInfo()->getTemplate()
1291 ->getTemplateParameters();
1292 return
1293 CollectTemplateParams(TList, *FD->getTemplateSpecializationArgs(), Unit);
1294 }
1295 return llvm::DIArray();
1296}
1297
1298/// CollectCXXTemplateParams - A helper function to collect debug info for
1299/// template parameters.
1300llvm::DIArray CGDebugInfo::
1301CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1302 llvm::DIFile Unit) {
1303 llvm::PointerUnion<ClassTemplateDecl *,
1304 ClassTemplatePartialSpecializationDecl *>
1305 PU = TSpecial->getSpecializedTemplateOrPartial();
1306
1307 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1308 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1309 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1310 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
1311 return CollectTemplateParams(TPList, TAList, Unit);
1312}
1313
1314/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1315llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1316 if (VTablePtrType.isValid())
1317 return VTablePtrType;
1318
1319 ASTContext &Context = CGM.getContext();
1320
1321 /* Function type */
1322 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1323 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1324 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1325 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1326 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1327 "__vtbl_ptr_type");
1328 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1329 return VTablePtrType;
1330}
1331
1332/// getVTableName - Get vtable name for the given Class.
1333StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1334 // Construct gdb compatible name name.
1335 std::string Name = "_vptr$" + RD->getNameAsString();
1336
1337 // Copy this name on the side and use its reference.
1338 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1339 memcpy(StrPtr, Name.data(), Name.length());
1340 return StringRef(StrPtr, Name.length());
1341}
1342
1343
1344/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1345/// debug info entry in EltTys vector.
1346void CGDebugInfo::
1347CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1348 SmallVectorImpl<llvm::Value *> &EltTys) {
1349 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1350
1351 // If there is a primary base then it will hold vtable info.
1352 if (RL.getPrimaryBase())
1353 return;
1354
1355 // If this class is not dynamic then there is not any vtable info to collect.
1356 if (!RD->isDynamicClass())
1357 return;
1358
1359 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1360 llvm::DIType VPTR
1361 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
1362 0, Size, 0, 0, llvm::DIDescriptor::FlagArtificial,
1363 getOrCreateVTablePtrType(Unit));
1364 EltTys.push_back(VPTR);
1365}
1366
1367/// getOrCreateRecordType - Emit record type's standalone debug info.
1368llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
1369 SourceLocation Loc) {
1370 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1371 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1372 return T;
1373}
1374
1375/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1376/// debug info.
1377llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001378 SourceLocation Loc) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001379 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
1380 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001381 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001382 return T;
1383}
1384
1385/// CreateType - get structure or union type.
1386llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
1387 RecordDecl *RD = Ty->getDecl();
1388
1389 // Get overall information about the record type for the debug info.
1390 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1391
1392 // Records and classes and unions can all be recursive. To handle them, we
1393 // first generate a debug descriptor for the struct as a forward declaration.
1394 // Then (if it is a definition) we go through and get debug info for all of
1395 // its members. Finally, we create a descriptor for the complete type (which
1396 // may refer to the forward decl if the struct is recursive) and replace all
1397 // uses of the forward declaration with the final definition.
1398
Eric Christopherf068c922013-04-02 22:59:11 +00001399 llvm::DICompositeType FwdDecl(
1400 getOrCreateLimitedType(QualType(Ty, 0), DefUnit));
1401 assert(FwdDecl.Verify() &&
1402 "The debug type of a RecordType should be a DICompositeType");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001403
1404 if (FwdDecl.isForwardDecl())
1405 return FwdDecl;
1406
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001407 // Push the struct on region stack.
Eric Christopherf068c922013-04-02 22:59:11 +00001408 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001409 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1410
Adrian Prantl4919de62013-03-06 22:03:30 +00001411 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001412 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1413
1414 // Convert all the elements.
1415 SmallVector<llvm::Value *, 16> EltTys;
1416
1417 // Note: The split of CXXDecl information here is intentional, the
1418 // gdb tests will depend on a certain ordering at printout. The debug
1419 // information offsets are still correct if we merge them all together
1420 // though.
1421 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1422 if (CXXDecl) {
1423 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1424 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1425 }
1426
Eric Christopher0395de32013-01-16 01:22:32 +00001427 // Collect data fields (including static variables and any initializers).
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001428 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
1429 llvm::DIArray TParamsArray;
1430 if (CXXDecl) {
1431 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1432 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
1433 if (const ClassTemplateSpecializationDecl *TSpecial
1434 = dyn_cast<ClassTemplateSpecializationDecl>(RD))
1435 TParamsArray = CollectCXXTemplateParams(TSpecial, DefUnit);
1436 }
1437
1438 LexicalBlockStack.pop_back();
1439 RegionMap.erase(Ty->getDecl());
1440
1441 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001442 FwdDecl.setTypeArray(Elements, TParamsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001443
Eric Christopherf068c922013-04-02 22:59:11 +00001444 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1445 return FwdDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001446}
1447
1448/// CreateType - get objective-c object type.
1449llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1450 llvm::DIFile Unit) {
1451 // Ignore protocols.
1452 return getOrCreateType(Ty->getBaseType(), Unit);
1453}
1454
1455/// CreateType - get objective-c interface type.
1456llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1457 llvm::DIFile Unit) {
1458 ObjCInterfaceDecl *ID = Ty->getDecl();
1459 if (!ID)
1460 return llvm::DIType();
1461
1462 // Get overall information about the record type for the debug info.
1463 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1464 unsigned Line = getLineNumber(ID->getLocation());
1465 unsigned RuntimeLang = TheCU.getLanguage();
1466
1467 // If this is just a forward declaration return a special forward-declaration
1468 // debug type since we won't be able to lay out the entire type.
1469 ObjCInterfaceDecl *Def = ID->getDefinition();
1470 if (!Def) {
1471 llvm::DIType FwdDecl =
1472 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001473 ID->getName(), TheCU, DefUnit, Line,
1474 RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001475 return FwdDecl;
1476 }
1477
1478 ID = Def;
1479
1480 // Bit size, align and offset of the type.
1481 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1482 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1483
1484 unsigned Flags = 0;
1485 if (ID->getImplementation())
1486 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1487
Eric Christopherf068c922013-04-02 22:59:11 +00001488 llvm::DICompositeType RealDecl =
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001489 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1490 Line, Size, Align, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00001491 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001492
1493 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1494 // will find it and we're emitting the complete type.
Adrian Prantl4919de62013-03-06 22:03:30 +00001495 QualType QualTy = QualType(Ty, 0);
1496 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001497 // Push the struct on region stack.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001498
Eric Christopherf068c922013-04-02 22:59:11 +00001499 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001500 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1501
1502 // Convert all the elements.
1503 SmallVector<llvm::Value *, 16> EltTys;
1504
1505 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1506 if (SClass) {
1507 llvm::DIType SClassTy =
1508 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1509 if (!SClassTy.isValid())
1510 return llvm::DIType();
1511
1512 llvm::DIType InhTag =
1513 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1514 EltTys.push_back(InhTag);
1515 }
1516
1517 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1518 E = ID->prop_end(); I != E; ++I) {
1519 const ObjCPropertyDecl *PD = *I;
1520 SourceLocation Loc = PD->getLocation();
1521 llvm::DIFile PUnit = getOrCreateFile(Loc);
1522 unsigned PLine = getLineNumber(Loc);
1523 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1524 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1525 llvm::MDNode *PropertyNode =
1526 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001527 PUnit, PLine,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001528 (Getter && Getter->isImplicit()) ? "" :
1529 getSelectorName(PD->getGetterName()),
1530 (Setter && Setter->isImplicit()) ? "" :
1531 getSelectorName(PD->getSetterName()),
1532 PD->getPropertyAttributes(),
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001533 getOrCreateType(PD->getType(), PUnit));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001534 EltTys.push_back(PropertyNode);
1535 }
1536
1537 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1538 unsigned FieldNo = 0;
1539 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1540 Field = Field->getNextIvar(), ++FieldNo) {
1541 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1542 if (!FieldTy.isValid())
1543 return llvm::DIType();
1544
1545 StringRef FieldName = Field->getName();
1546
1547 // Ignore unnamed fields.
1548 if (FieldName.empty())
1549 continue;
1550
1551 // Get the location for the field.
1552 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1553 unsigned FieldLine = getLineNumber(Field->getLocation());
1554 QualType FType = Field->getType();
1555 uint64_t FieldSize = 0;
1556 unsigned FieldAlign = 0;
1557
1558 if (!FType->isIncompleteArrayType()) {
1559
1560 // Bit size, align and offset of the type.
1561 FieldSize = Field->isBitField()
1562 ? Field->getBitWidthValue(CGM.getContext())
1563 : CGM.getContext().getTypeSize(FType);
1564 FieldAlign = CGM.getContext().getTypeAlign(FType);
1565 }
1566
1567 uint64_t FieldOffset;
1568 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1569 // We don't know the runtime offset of an ivar if we're using the
1570 // non-fragile ABI. For bitfields, use the bit offset into the first
1571 // byte of storage of the bitfield. For other fields, use zero.
1572 if (Field->isBitField()) {
1573 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1574 CGM, ID, Field);
1575 FieldOffset %= CGM.getContext().getCharWidth();
1576 } else {
1577 FieldOffset = 0;
1578 }
1579 } else {
1580 FieldOffset = RL.getFieldOffset(FieldNo);
1581 }
1582
1583 unsigned Flags = 0;
1584 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1585 Flags = llvm::DIDescriptor::FlagProtected;
1586 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1587 Flags = llvm::DIDescriptor::FlagPrivate;
1588
1589 llvm::MDNode *PropertyNode = NULL;
1590 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
1591 if (ObjCPropertyImplDecl *PImpD =
1592 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1593 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00001594 SourceLocation Loc = PD->getLocation();
1595 llvm::DIFile PUnit = getOrCreateFile(Loc);
1596 unsigned PLine = getLineNumber(Loc);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001597 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1598 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1599 PropertyNode =
1600 DBuilder.createObjCProperty(PD->getName(),
1601 PUnit, PLine,
1602 (Getter && Getter->isImplicit()) ? "" :
1603 getSelectorName(PD->getGetterName()),
1604 (Setter && Setter->isImplicit()) ? "" :
1605 getSelectorName(PD->getSetterName()),
1606 PD->getPropertyAttributes(),
1607 getOrCreateType(PD->getType(), PUnit));
1608 }
1609 }
1610 }
1611 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1612 FieldLine, FieldSize, FieldAlign,
1613 FieldOffset, Flags, FieldTy,
1614 PropertyNode);
1615 EltTys.push_back(FieldTy);
1616 }
1617
1618 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherf068c922013-04-02 22:59:11 +00001619 RealDecl.setTypeArray(Elements);
Adrian Prantl4919de62013-03-06 22:03:30 +00001620
1621 // If the implementation is not yet set, we do not want to mark it
1622 // as complete. An implementation may declare additional
1623 // private ivars that we would miss otherwise.
1624 if (ID->getImplementation() == 0)
1625 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001626
1627 LexicalBlockStack.pop_back();
Eric Christopherf068c922013-04-02 22:59:11 +00001628 return RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001629}
1630
1631llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1632 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1633 int64_t Count = Ty->getNumElements();
1634 if (Count == 0)
1635 // If number of elements are not known then this is an unbounded array.
1636 // Use Count == -1 to express such arrays.
1637 Count = -1;
1638
1639 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1640 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1641
1642 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1643 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1644
1645 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1646}
1647
1648llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1649 llvm::DIFile Unit) {
1650 uint64_t Size;
1651 uint64_t Align;
1652
1653 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1654 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1655 Size = 0;
1656 Align =
1657 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1658 } else if (Ty->isIncompleteArrayType()) {
1659 Size = 0;
1660 if (Ty->getElementType()->isIncompleteType())
1661 Align = 0;
1662 else
1663 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikie089db2e2013-05-09 20:48:12 +00001664 } else if (Ty->isIncompleteType()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001665 Size = 0;
1666 Align = 0;
1667 } else {
1668 // Size and align of the whole array, not the element type.
1669 Size = CGM.getContext().getTypeSize(Ty);
1670 Align = CGM.getContext().getTypeAlign(Ty);
1671 }
1672
1673 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1674 // interior arrays, do we care? Why aren't nested arrays represented the
1675 // obvious/recursive way?
1676 SmallVector<llvm::Value *, 8> Subscripts;
1677 QualType EltTy(Ty, 0);
1678 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1679 // If the number of elements is known, then count is that number. Otherwise,
1680 // it's -1. This allows us to represent a subrange with an array of 0
1681 // elements, like this:
1682 //
1683 // struct foo {
1684 // int x[0];
1685 // };
1686 int64_t Count = -1; // Count == -1 is an unbounded array.
1687 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1688 Count = CAT->getSize().getZExtValue();
1689
1690 // FIXME: Verify this is right for VLAs.
1691 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1692 EltTy = Ty->getElementType();
1693 }
1694
1695 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1696
1697 llvm::DIType DbgTy =
1698 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1699 SubscriptArray);
1700 return DbgTy;
1701}
1702
1703llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
1704 llvm::DIFile Unit) {
1705 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
1706 Ty, Ty->getPointeeType(), Unit);
1707}
1708
1709llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
1710 llvm::DIFile Unit) {
1711 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
1712 Ty, Ty->getPointeeType(), Unit);
1713}
1714
1715llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
1716 llvm::DIFile U) {
David Blaikiee8d75142013-01-19 19:20:56 +00001717 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1718 if (!Ty->getPointeeType()->isFunctionType())
1719 return DBuilder.createMemberPointerType(
1720 CreatePointeeType(Ty->getPointeeType(), U), ClassType);
1721 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1722 CGM.getContext().getPointerType(
1723 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1724 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1725 ClassType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001726}
1727
1728llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
1729 llvm::DIFile U) {
1730 // Ignore the atomic wrapping
1731 // FIXME: What is the correct representation?
1732 return getOrCreateType(Ty->getValueType(), U);
1733}
1734
1735/// CreateEnumType - get enumeration type.
1736llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1737 uint64_t Size = 0;
1738 uint64_t Align = 0;
1739 if (!ED->getTypeForDecl()->isIncompleteType()) {
1740 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1741 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1742 }
1743
1744 // If this is just a forward declaration, construct an appropriately
1745 // marked node and just return it.
1746 if (!ED->getDefinition()) {
1747 llvm::DIDescriptor EDContext;
1748 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1749 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1750 unsigned Line = getLineNumber(ED->getLocation());
1751 StringRef EDName = ED->getName();
1752 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1753 EDName, EDContext, DefUnit, Line, 0,
1754 Size, Align);
1755 }
1756
1757 // Create DIEnumerator elements for each enumerator.
1758 SmallVector<llvm::Value *, 16> Enumerators;
1759 ED = ED->getDefinition();
1760 for (EnumDecl::enumerator_iterator
1761 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1762 Enum != EnumEnd; ++Enum) {
1763 Enumerators.push_back(
1764 DBuilder.createEnumerator(Enum->getName(),
1765 Enum->getInitVal().getZExtValue()));
1766 }
1767
1768 // Return a CompositeType for the enum itself.
1769 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1770
1771 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1772 unsigned Line = getLineNumber(ED->getLocation());
1773 llvm::DIDescriptor EnumContext =
1774 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantl59d6a712013-04-19 19:56:39 +00001775 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001776 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
1777 llvm::DIType DbgTy =
1778 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1779 Size, Align, EltArray,
1780 ClassTy);
1781 return DbgTy;
1782}
1783
David Blaikie4b12be62013-01-21 04:37:12 +00001784static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1785 Qualifiers Quals;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001786 do {
David Blaikie4b12be62013-01-21 04:37:12 +00001787 Quals += T.getLocalQualifiers();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001788 QualType LastT = T;
1789 switch (T->getTypeClass()) {
1790 default:
David Blaikie4b12be62013-01-21 04:37:12 +00001791 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001792 case Type::TemplateSpecialization:
1793 T = cast<TemplateSpecializationType>(T)->desugar();
1794 break;
1795 case Type::TypeOfExpr:
1796 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1797 break;
1798 case Type::TypeOf:
1799 T = cast<TypeOfType>(T)->getUnderlyingType();
1800 break;
1801 case Type::Decltype:
1802 T = cast<DecltypeType>(T)->getUnderlyingType();
1803 break;
1804 case Type::UnaryTransform:
1805 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1806 break;
1807 case Type::Attributed:
1808 T = cast<AttributedType>(T)->getEquivalentType();
1809 break;
1810 case Type::Elaborated:
1811 T = cast<ElaboratedType>(T)->getNamedType();
1812 break;
1813 case Type::Paren:
1814 T = cast<ParenType>(T)->getInnerType();
1815 break;
David Blaikie4b12be62013-01-21 04:37:12 +00001816 case Type::SubstTemplateTypeParm:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001817 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001818 break;
1819 case Type::Auto:
1820 T = cast<AutoType>(T)->getDeducedType();
1821 break;
1822 }
1823
1824 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumid24c9ab2013-01-21 10:51:28 +00001825 (void)LastT;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001826 } while (true);
1827}
1828
1829/// getType - Get the type from the cache or return null type if it doesn't exist.
1830llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1831
1832 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001833 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001834
1835 // Check for existing entry.
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001836 if (Ty->getTypeClass() == Type::ObjCInterface) {
1837 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1838 if (V)
1839 return llvm::DIType(cast<llvm::MDNode>(V));
1840 else return llvm::DIType();
1841 }
1842
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001843 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1844 TypeCache.find(Ty.getAsOpaquePtr());
1845 if (it != TypeCache.end()) {
1846 // Verify that the debug info still exists.
1847 if (llvm::Value *V = it->second)
1848 return llvm::DIType(cast<llvm::MDNode>(V));
1849 }
1850
1851 return llvm::DIType();
1852}
1853
1854/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1855/// doesn't exist.
1856llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1857
1858 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001859 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001860
1861 // Check for existing entry.
Adrian Prantl4919de62013-03-06 22:03:30 +00001862 llvm::Value *V = 0;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001863 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1864 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantl4919de62013-03-06 22:03:30 +00001865 if (it != CompletedTypeCache.end())
1866 V = it->second;
1867 else {
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001868 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001869 }
1870
Adrian Prantl4919de62013-03-06 22:03:30 +00001871 // Verify that any cached debug info still exists.
1872 if (V != 0)
1873 return llvm::DIType(cast<llvm::MDNode>(V));
1874
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001875 return llvm::DIType();
1876}
1877
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001878/// getCachedInterfaceTypeOrNull - Get the type from the interface
1879/// cache, unless it needs to regenerated. Otherwise return null.
1880llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1881 // Is there a cached interface that hasn't changed?
1882 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1883 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1884
1885 if (it1 != ObjCInterfaceCache.end())
1886 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1887 if (Checksum(Decl) == it1->second.second)
1888 // Return cached forward declaration.
1889 return it1->second.first;
1890
1891 return 0;
1892}
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001893
1894/// getOrCreateType - Get the type from the cache or create a new
1895/// one if necessary.
1896llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
1897 if (Ty.isNull())
1898 return llvm::DIType();
1899
1900 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00001901 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001902
1903 llvm::DIType T = getCompletedTypeOrNull(Ty);
1904
1905 if (T.Verify())
1906 return T;
1907
1908 // Otherwise create the type.
1909 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001910 void* TyPtr = Ty.getAsOpaquePtr();
1911
1912 // And update the type cache.
1913 TypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001914
1915 llvm::DIType TC = getTypeOrNull(Ty);
1916 if (TC.Verify() && TC.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001917 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1918 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
1919 // Interface types may have elements added to them by a
1920 // subsequent implementation or extension, so we keep them in
1921 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlf06989b2013-05-08 23:37:22 +00001922 // the (possibly) incomplete interface type, we return a forward
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001923 // declaration that gets RAUW'd in CGDebugInfo::finalize().
1924 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1925 ::iterator it = ObjCInterfaceCache.find(TyPtr);
1926 if (it != ObjCInterfaceCache.end())
1927 TC = llvm::DIType(cast<llvm::MDNode>(it->second.first));
1928 else
1929 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001930 Decl->getName(), TheCU, Unit,
1931 getLineNumber(Decl->getLocation()),
1932 TheCU.getLanguage());
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001933 // Store the forward declaration in the cache.
1934 ObjCInterfaceCache[TyPtr] = std::make_pair(TC, Checksum(Decl));
1935
1936 // Register the type for replacement in finalize().
1937 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
1938 return TC;
Adrian Prantl4919de62013-03-06 22:03:30 +00001939 }
1940
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001941 if (!Res.isForwardDecl())
Adrian Prantlebbd7e02013-03-11 18:33:46 +00001942 CompletedTypeCache[TyPtr] = Res;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001943
1944 return Res;
1945}
1946
Adrian Prantl4919de62013-03-06 22:03:30 +00001947/// Currently the checksum merely consists of the number of ivars.
1948unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl
Adrian Prantl00df5ea2013-03-12 20:43:25 +00001949 *InterfaceDecl) {
Adrian Prantl4919de62013-03-06 22:03:30 +00001950 unsigned IvarNo = 0;
1951 for (const ObjCIvarDecl *Ivar = InterfaceDecl->all_declared_ivar_begin();
1952 Ivar != 0; Ivar = Ivar->getNextIvar()) ++IvarNo;
1953 return IvarNo;
1954}
1955
1956ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
1957 switch (Ty->getTypeClass()) {
1958 case Type::ObjCObjectPointer:
1959 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)->getPointeeType());
1960 case Type::ObjCInterface:
1961 return cast<ObjCInterfaceType>(Ty)->getDecl();
1962 default:
1963 return 0;
1964 }
1965}
1966
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001967/// CreateTypeNode - Create a new debug type node.
1968llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
1969 // Handle qualifiers, which recursively handles what they refer to.
1970 if (Ty.hasLocalQualifiers())
1971 return CreateQualifiedType(Ty, Unit);
1972
1973 const char *Diag = 0;
1974
1975 // Work out details of type.
1976 switch (Ty->getTypeClass()) {
1977#define TYPE(Class, Base)
1978#define ABSTRACT_TYPE(Class, Base)
1979#define NON_CANONICAL_TYPE(Class, Base)
1980#define DEPENDENT_TYPE(Class, Base) case Type::Class:
1981#include "clang/AST/TypeNodes.def"
1982 llvm_unreachable("Dependent types cannot show up in debug information");
1983
1984 case Type::ExtVector:
1985 case Type::Vector:
1986 return CreateType(cast<VectorType>(Ty), Unit);
1987 case Type::ObjCObjectPointer:
1988 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
1989 case Type::ObjCObject:
1990 return CreateType(cast<ObjCObjectType>(Ty), Unit);
1991 case Type::ObjCInterface:
1992 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
1993 case Type::Builtin:
1994 return CreateType(cast<BuiltinType>(Ty));
1995 case Type::Complex:
1996 return CreateType(cast<ComplexType>(Ty));
1997 case Type::Pointer:
1998 return CreateType(cast<PointerType>(Ty), Unit);
1999 case Type::BlockPointer:
2000 return CreateType(cast<BlockPointerType>(Ty), Unit);
2001 case Type::Typedef:
2002 return CreateType(cast<TypedefType>(Ty), Unit);
2003 case Type::Record:
2004 return CreateType(cast<RecordType>(Ty));
2005 case Type::Enum:
2006 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2007 case Type::FunctionProto:
2008 case Type::FunctionNoProto:
2009 return CreateType(cast<FunctionType>(Ty), Unit);
2010 case Type::ConstantArray:
2011 case Type::VariableArray:
2012 case Type::IncompleteArray:
2013 return CreateType(cast<ArrayType>(Ty), Unit);
2014
2015 case Type::LValueReference:
2016 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2017 case Type::RValueReference:
2018 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2019
2020 case Type::MemberPointer:
2021 return CreateType(cast<MemberPointerType>(Ty), Unit);
2022
2023 case Type::Atomic:
2024 return CreateType(cast<AtomicType>(Ty), Unit);
2025
2026 case Type::Attributed:
2027 case Type::TemplateSpecialization:
2028 case Type::Elaborated:
2029 case Type::Paren:
2030 case Type::SubstTemplateTypeParm:
2031 case Type::TypeOfExpr:
2032 case Type::TypeOf:
2033 case Type::Decltype:
2034 case Type::UnaryTransform:
2035 case Type::Auto:
2036 llvm_unreachable("type should have been unwrapped!");
2037 }
2038
2039 assert(Diag && "Fall through without a diagnostic?");
2040 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2041 "debug information for %0 is not yet supported");
2042 CGM.getDiags().Report(DiagID)
2043 << Diag;
2044 return llvm::DIType();
2045}
2046
2047/// getOrCreateLimitedType - Get the type from the cache or create a new
2048/// limited type if necessary.
2049llvm::DIType CGDebugInfo::getOrCreateLimitedType(QualType Ty,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002050 llvm::DIFile Unit) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002051 if (Ty.isNull())
2052 return llvm::DIType();
2053
2054 // Unwrap the type as needed for debug information.
David Blaikie4b12be62013-01-21 04:37:12 +00002055 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002056
2057 llvm::DIType T = getTypeOrNull(Ty);
2058
2059 // We may have cached a forward decl when we could have created
2060 // a non-forward decl. Go ahead and create a non-forward decl
2061 // now.
2062 if (T.Verify() && !T.isForwardDecl()) return T;
2063
2064 // Otherwise create the type.
2065 llvm::DIType Res = CreateLimitedTypeNode(Ty, Unit);
2066
2067 if (T.Verify() && T.isForwardDecl())
2068 ReplaceMap.push_back(std::make_pair(Ty.getAsOpaquePtr(),
2069 static_cast<llvm::Value*>(T)));
2070
2071 // And update the type cache.
2072 TypeCache[Ty.getAsOpaquePtr()] = Res;
2073 return Res;
2074}
2075
2076// TODO: Currently used for context chains when limiting debug info.
2077llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2078 RecordDecl *RD = Ty->getDecl();
2079
2080 // Get overall information about the record type for the debug info.
2081 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2082 unsigned Line = getLineNumber(RD->getLocation());
2083 StringRef RDName = getClassName(RD);
2084
2085 llvm::DIDescriptor RDContext;
2086 if (CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo)
2087 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2088 else
2089 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2090
2091 // If this is just a forward declaration, construct an appropriately
2092 // marked node and just return it.
2093 if (!RD->getDefinition())
2094 return createRecordFwdDecl(RD, RDContext);
2095
2096 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2097 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
2098 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002099 llvm::DICompositeType RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002100
2101 if (RD->isUnion())
2102 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002103 Size, Align, 0, llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002104 else if (RD->isClass()) {
2105 // FIXME: This could be a struct type giving a default visibility different
2106 // than C++ class type, but needs llvm metadata changes first.
2107 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002108 Size, Align, 0, 0, llvm::DIType(),
2109 llvm::DIArray(), llvm::DIType(),
2110 llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002111 } else
2112 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002113 Size, Align, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002114
2115 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie2fcadbe2013-03-26 23:47:35 +00002116 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002117
2118 if (CXXDecl) {
2119 // A class's primary base or the class itself contains the vtable.
David Blaikie2fcadbe2013-03-26 23:47:35 +00002120 llvm::DICompositeType ContainingType;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002121 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2122 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2123 // Seek non virtual primary base root.
2124 while (1) {
Eric Christopherbe5f1be2013-02-21 22:35:08 +00002125 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2126 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2127 if (PBT && !BRL.isPrimaryBaseVirtual())
2128 PBase = PBT;
2129 else
2130 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002131 }
David Blaikie2fcadbe2013-03-26 23:47:35 +00002132 ContainingType = llvm::DICompositeType(
2133 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2134 } else if (CXXDecl->isDynamicClass())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002135 ContainingType = RealDecl;
2136
David Blaikie2fcadbe2013-03-26 23:47:35 +00002137 RealDecl.setContainingType(ContainingType);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002138 }
2139 return llvm::DIType(RealDecl);
2140}
2141
2142/// CreateLimitedTypeNode - Create a new debug type node, but only forward
2143/// declare composite types that haven't been processed yet.
2144llvm::DIType CGDebugInfo::CreateLimitedTypeNode(QualType Ty,llvm::DIFile Unit) {
2145
2146 // Work out details of type.
2147 switch (Ty->getTypeClass()) {
2148#define TYPE(Class, Base)
2149#define ABSTRACT_TYPE(Class, Base)
2150#define NON_CANONICAL_TYPE(Class, Base)
2151#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2152 #include "clang/AST/TypeNodes.def"
2153 llvm_unreachable("Dependent types cannot show up in debug information");
2154
2155 case Type::Record:
2156 return CreateLimitedType(cast<RecordType>(Ty));
2157 default:
2158 return CreateTypeNode(Ty, Unit);
2159 }
2160}
2161
2162/// CreateMemberType - Create new member and increase Offset by FType's size.
2163llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2164 StringRef Name,
2165 uint64_t *Offset) {
2166 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2167 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2168 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2169 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2170 FieldSize, FieldAlign,
2171 *Offset, 0, FieldTy);
2172 *Offset += FieldSize;
2173 return Ty;
2174}
2175
David Blaikie3923d6a2013-05-08 06:01:46 +00002176llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
David Blaikie87360f22013-05-12 18:05:52 +00002177 // We only need a declaration (not a definition) of the type - so use whatever
2178 // we would otherwise do to get a type for a pointee. (forward declarations in
2179 // limited debug info, full definitions (if the type definition is available)
2180 // in unlimited debug info)
David Blaikie7be62a82013-05-14 00:34:20 +00002181 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2182 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
2183 return CreatePointeeType(CGM.getContext().getTypeDeclType(TD), DefUnit);
2184 }
David Blaikie87360f22013-05-12 18:05:52 +00002185 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2186 // This doesn't handle providing declarations (for functions or variables) for
2187 // entities without definitions in this TU, nor when the definition proceeds
2188 // the call to this function.
2189 // FIXME: This should be split out into more specific maps with support for
2190 // emitting forward declarations and merging definitions with declarations,
2191 // the same way as we do for types.
David Blaikie3923d6a2013-05-08 06:01:46 +00002192 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2193 DeclCache.find(D->getCanonicalDecl());
2194 if (I == DeclCache.end())
2195 return llvm::DIDescriptor();
2196 llvm::Value *V = I->second;
2197 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2198}
2199
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002200/// getFunctionDeclaration - Return debug info descriptor to describe method
2201/// declaration for the given method definition.
2202llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
2203 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2204 if (!FD) return llvm::DISubprogram();
2205
2206 // Setup context.
2207 getContextDescriptor(cast<Decl>(D->getDeclContext()));
2208
2209 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2210 MI = SPCache.find(FD->getCanonicalDecl());
2211 if (MI != SPCache.end()) {
2212 llvm::Value *V = MI->second;
2213 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2214 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2215 return SP;
2216 }
2217
2218 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2219 E = FD->redecls_end(); I != E; ++I) {
2220 const FunctionDecl *NextFD = *I;
2221 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2222 MI = SPCache.find(NextFD->getCanonicalDecl());
2223 if (MI != SPCache.end()) {
2224 llvm::Value *V = MI->second;
2225 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
2226 if (SP.isSubprogram() && !llvm::DISubprogram(SP).isDefinition())
2227 return SP;
2228 }
2229 }
2230 return llvm::DISubprogram();
2231}
2232
2233// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2234// implicit parameter "this".
2235llvm::DIType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2236 QualType FnType,
2237 llvm::DIFile F) {
2238
2239 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2240 return getOrCreateMethodType(Method, F);
2241 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2242 // Add "self" and "_cmd"
2243 SmallVector<llvm::Value *, 16> Elts;
2244
2245 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl566a9c32013-05-10 21:08:31 +00002246 QualType ResultTy = OMethod->hasRelatedResultType()
2247 ? QualType(OMethod->getClassInterface()->getTypeForDecl(), 0)
2248 : OMethod->getResultType();
2249 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002250 // "self" pointer is always first argument.
Adrian Prantle86fcc42013-03-29 19:20:29 +00002251 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2252 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2253 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002254 // "_cmd" pointer is always second argument.
2255 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2256 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2257 // Get rest of the arguments.
2258 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
2259 PE = OMethod->param_end(); PI != PE; ++PI)
2260 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2261
2262 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2263 return DBuilder.createSubroutineType(F, EltTypeArray);
2264 }
2265 return getOrCreateType(FnType, F);
2266}
2267
2268/// EmitFunctionStart - Constructs the debug code for entering a function.
2269void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2270 llvm::Function *Fn,
2271 CGBuilderTy &Builder) {
2272
2273 StringRef Name;
2274 StringRef LinkageName;
2275
2276 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2277
2278 const Decl *D = GD.getDecl();
2279 // Function may lack declaration in source code if it is created by Clang
2280 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2281 bool HasDecl = (D != 0);
2282 // Use the location of the declaration.
2283 SourceLocation Loc;
2284 if (HasDecl)
2285 Loc = D->getLocation();
2286
2287 unsigned Flags = 0;
2288 llvm::DIFile Unit = getOrCreateFile(Loc);
2289 llvm::DIDescriptor FDContext(Unit);
2290 llvm::DIArray TParamsArray;
2291 if (!HasDecl) {
2292 // Use llvm function name.
2293 Name = Fn->getName();
2294 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2295 // If there is a DISubprogram for this function available then use it.
2296 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2297 FI = SPCache.find(FD->getCanonicalDecl());
2298 if (FI != SPCache.end()) {
2299 llvm::Value *V = FI->second;
2300 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2301 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2302 llvm::MDNode *SPN = SP;
2303 LexicalBlockStack.push_back(SPN);
2304 RegionMap[D] = llvm::WeakVH(SP);
2305 return;
2306 }
2307 }
2308 Name = getFunctionName(FD);
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002309 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002310 if (FD->hasPrototype()) {
2311 LinkageName = CGM.getMangledName(GD);
2312 Flags |= llvm::DIDescriptor::FlagPrototyped;
2313 }
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002314 // No need to replicate the linkage name if it isn't different from the
2315 // subprogram name, no need to have it at all unless coverage is enabled or
2316 // debug is set to more than just line tables.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002317 if (LinkageName == Name ||
Nick Lewyckyf2b5e072013-03-20 01:38:16 +00002318 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2319 !CGM.getCodeGenOpts().EmitGcovNotes &&
2320 CGM.getCodeGenOpts().getDebugInfo() <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002321 LinkageName = StringRef();
2322
2323 if (CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2324 if (const NamespaceDecl *NSDecl =
2325 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2326 FDContext = getOrCreateNameSpace(NSDecl);
2327 else if (const RecordDecl *RDecl =
2328 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2329 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2330
2331 // Collect template parameters.
2332 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2333 }
2334 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2335 Name = getObjCMethodName(OMD);
2336 Flags |= llvm::DIDescriptor::FlagPrototyped;
2337 } else {
2338 // Use llvm function name.
2339 Name = Fn->getName();
2340 Flags |= llvm::DIDescriptor::FlagPrototyped;
2341 }
2342 if (!Name.empty() && Name[0] == '\01')
2343 Name = Name.substr(1);
2344
2345 unsigned LineNo = getLineNumber(Loc);
2346 if (!HasDecl || D->isImplicit())
2347 Flags |= llvm::DIDescriptor::FlagArtificial;
2348
2349 llvm::DIType DIFnType;
2350 llvm::DISubprogram SPDecl;
2351 if (HasDecl &&
2352 CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
2353 DIFnType = getOrCreateFunctionType(D, FnType, Unit);
2354 SPDecl = getFunctionDeclaration(D);
2355 } else {
2356 // Create fake but valid subroutine type. Otherwise
2357 // llvm::DISubprogram::Verify() would return false, and
2358 // subprogram DIE will miss DW_AT_decl_file and
2359 // DW_AT_decl_line fields.
2360 SmallVector<llvm::Value*, 16> Elts;
2361 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2362 DIFnType = DBuilder.createSubroutineType(Unit, EltTypeArray);
2363 }
2364 llvm::DISubprogram SP;
2365 SP = DBuilder.createFunction(FDContext, Name, LinkageName, Unit,
2366 LineNo, DIFnType,
2367 Fn->hasInternalLinkage(), true/*definition*/,
2368 getLineNumber(CurLoc), Flags,
2369 CGM.getLangOpts().Optimize,
2370 Fn, TParamsArray, SPDecl);
David Blaikie3923d6a2013-05-08 06:01:46 +00002371 if (HasDecl)
2372 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002373
2374 // Push function on region stack.
2375 llvm::MDNode *SPN = SP;
2376 LexicalBlockStack.push_back(SPN);
2377 if (HasDecl)
2378 RegionMap[D] = llvm::WeakVH(SP);
2379}
2380
2381/// EmitLocation - Emit metadata to indicate a change in line/column
2382/// information in the source file.
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002383void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2384 bool ForceColumnInfo) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002385
2386 // Update our current location
2387 setLocation(Loc);
2388
2389 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2390
2391 // Don't bother if things are the same as last time.
2392 SourceManager &SM = CGM.getContext().getSourceManager();
2393 if (CurLoc == PrevLoc ||
2394 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2395 // New Builder may not be in sync with CGDebugInfo.
David Blaikie0a0f93c2013-02-01 19:09:49 +00002396 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2397 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2398 LexicalBlockStack.back())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002399 return;
2400
2401 // Update last state.
2402 PrevLoc = CurLoc;
2403
2404 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantl00df5ea2013-03-12 20:43:25 +00002405 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2406 (getLineNumber(CurLoc),
2407 getColumnNumber(CurLoc, ForceColumnInfo),
2408 Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002409}
2410
2411/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2412/// the stack.
2413void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2414 llvm::DIDescriptor D =
2415 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2416 llvm::DIDescriptor() :
2417 llvm::DIDescriptor(LexicalBlockStack.back()),
2418 getOrCreateFile(CurLoc),
2419 getLineNumber(CurLoc),
2420 getColumnNumber(CurLoc));
2421 llvm::MDNode *DN = D;
2422 LexicalBlockStack.push_back(DN);
2423}
2424
2425/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2426/// region - beginning of a DW_TAG_lexical_block.
2427void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder, SourceLocation Loc) {
2428 // Set our current location.
2429 setLocation(Loc);
2430
2431 // Create a new lexical block and push it on the stack.
2432 CreateLexicalBlock(Loc);
2433
2434 // Emit a line table change for the current location inside the new scope.
2435 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2436 getColumnNumber(Loc),
2437 LexicalBlockStack.back()));
2438}
2439
2440/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2441/// region - end of a DW_TAG_lexical_block.
2442void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder, SourceLocation Loc) {
2443 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2444
2445 // Provide an entry in the line table for the end of the block.
2446 EmitLocation(Builder, Loc);
2447
2448 LexicalBlockStack.pop_back();
2449}
2450
2451/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2452void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2453 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2454 unsigned RCount = FnBeginRegionCount.back();
2455 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2456
2457 // Pop all regions for this function.
2458 while (LexicalBlockStack.size() != RCount)
2459 EmitLexicalBlockEnd(Builder, CurLoc);
2460 FnBeginRegionCount.pop_back();
2461}
2462
2463// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
2464// See BuildByRefType.
2465llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2466 uint64_t *XOffset) {
2467
2468 SmallVector<llvm::Value *, 5> EltTys;
2469 QualType FType;
2470 uint64_t FieldSize, FieldOffset;
2471 unsigned FieldAlign;
2472
2473 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2474 QualType Type = VD->getType();
2475
2476 FieldOffset = 0;
2477 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2478 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2479 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2480 FType = CGM.getContext().IntTy;
2481 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2482 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2483
2484 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2485 if (HasCopyAndDispose) {
2486 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2487 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2488 &FieldOffset));
2489 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2490 &FieldOffset));
2491 }
2492 bool HasByrefExtendedLayout;
2493 Qualifiers::ObjCLifetime Lifetime;
2494 if (CGM.getContext().getByrefLifetime(Type,
2495 Lifetime, HasByrefExtendedLayout)
2496 && HasByrefExtendedLayout)
2497 EltTys.push_back(CreateMemberType(Unit, FType,
2498 "__byref_variable_layout",
2499 &FieldOffset));
2500
2501 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2502 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002503 CGM.getTarget().getPointerAlign(0))) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002504 CharUnits FieldOffsetInBytes
2505 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2506 CharUnits AlignedOffsetInBytes
2507 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2508 CharUnits NumPaddingBytes
2509 = AlignedOffsetInBytes - FieldOffsetInBytes;
2510
2511 if (NumPaddingBytes.isPositive()) {
2512 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2513 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2514 pad, ArrayType::Normal, 0);
2515 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2516 }
2517 }
2518
2519 FType = Type;
2520 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2521 FieldSize = CGM.getContext().getTypeSize(FType);
2522 FieldAlign = CGM.getContext().toBits(Align);
2523
2524 *XOffset = FieldOffset;
2525 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2526 0, FieldSize, FieldAlign,
2527 FieldOffset, 0, FieldTy);
2528 EltTys.push_back(FieldTy);
2529 FieldOffset += FieldSize;
2530
2531 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
2532
2533 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
2534
2535 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikiec1d0af12013-02-25 01:07:08 +00002536 llvm::DIType(), Elements);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002537}
2538
2539/// EmitDeclare - Emit local variable declaration debug info.
2540void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
2541 llvm::Value *Storage,
2542 unsigned ArgNo, CGBuilderTy &Builder) {
2543 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2544 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2545
2546 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2547 llvm::DIType Ty;
2548 uint64_t XOffset = 0;
2549 if (VD->hasAttr<BlocksAttr>())
2550 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2551 else
2552 Ty = getOrCreateType(VD->getType(), Unit);
2553
2554 // If there is no debug info for this type then do not emit debug info
2555 // for this variable.
2556 if (!Ty)
2557 return;
2558
2559 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage)) {
2560 // If Storage is an aggregate returned as 'sret' then let debugger know
2561 // about this.
2562 if (Arg->hasStructRetAttr())
2563 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2564 else if (CXXRecordDecl *Record = VD->getType()->getAsCXXRecordDecl()) {
2565 // If an aggregate variable has non trivial destructor or non trivial copy
2566 // constructor than it is pass indirectly. Let debug info know about this
2567 // by using reference of the aggregate type as a argument type.
2568 if (Record->hasNonTrivialCopyConstructor() ||
2569 !Record->hasTrivialDestructor())
2570 Ty = DBuilder.createReferenceType(llvm::dwarf::DW_TAG_reference_type, Ty);
2571 }
2572 }
2573
2574 // Get location information.
2575 unsigned Line = getLineNumber(VD->getLocation());
2576 unsigned Column = getColumnNumber(VD->getLocation());
2577 unsigned Flags = 0;
2578 if (VD->isImplicit())
2579 Flags |= llvm::DIDescriptor::FlagArtificial;
2580 // If this is the first argument and it is implicit then
2581 // give it an object pointer flag.
2582 // FIXME: There has to be a better way to do this, but for static
2583 // functions there won't be an implicit param at arg1 and
2584 // otherwise it is 'self' or 'this'.
2585 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2586 Flags |= llvm::DIDescriptor::FlagObjectPointer;
2587
2588 llvm::MDNode *Scope = LexicalBlockStack.back();
2589
2590 StringRef Name = VD->getName();
2591 if (!Name.empty()) {
2592 if (VD->hasAttr<BlocksAttr>()) {
2593 CharUnits offset = CharUnits::fromQuantity(32);
2594 SmallVector<llvm::Value *, 9> addr;
2595 llvm::Type *Int64Ty = CGM.Int64Ty;
2596 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2597 // offset of __forwarding field
2598 offset = CGM.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00002599 CGM.getTarget().getPointerWidth(0));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002600 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2601 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2602 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2603 // offset of x field
2604 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2605 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2606
2607 // Create the descriptor for the variable.
2608 llvm::DIVariable D =
2609 DBuilder.createComplexVariable(Tag,
2610 llvm::DIDescriptor(Scope),
2611 VD->getName(), Unit, Line, Ty,
2612 addr, ArgNo);
2613
2614 // Insert an llvm.dbg.declare into the current block.
2615 llvm::Instruction *Call =
2616 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2617 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2618 return;
Adrian Prantl230ea412013-04-30 22:45:09 +00002619 } else if (isa<VariableArrayType>(VD->getType())) {
2620 // These are "complex" variables in that they need an op_deref.
2621 // Create the descriptor for the variable.
2622 llvm::Value *Addr = llvm::ConstantInt::get(CGM.Int64Ty,
2623 llvm::DIBuilder::OpDeref);
2624 llvm::DIVariable D =
2625 DBuilder.createComplexVariable(Tag,
2626 llvm::DIDescriptor(Scope),
2627 Name, Unit, Line, Ty,
2628 Addr, ArgNo);
2629
2630 // Insert an llvm.dbg.declare into the current block.
2631 llvm::Instruction *Call =
2632 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2633 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2634 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002635 }
David Blaikie436653b2013-01-05 05:58:35 +00002636 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2637 // If VD is an anonymous union then Storage represents value for
2638 // all union fields.
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002639 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikied8180cf2013-01-05 20:03:07 +00002640 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002641 for (RecordDecl::field_iterator I = RD->field_begin(),
2642 E = RD->field_end();
2643 I != E; ++I) {
2644 FieldDecl *Field = *I;
2645 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2646 StringRef FieldName = Field->getName();
2647
2648 // Ignore unnamed fields. Do not ignore unnamed records.
2649 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2650 continue;
2651
2652 // Use VarDecl's Tag, Scope and Line number.
2653 llvm::DIVariable D =
2654 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2655 FieldName, Unit, Line, FieldTy,
2656 CGM.getLangOpts().Optimize, Flags,
2657 ArgNo);
2658
2659 // Insert an llvm.dbg.declare into the current block.
2660 llvm::Instruction *Call =
2661 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2662 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2663 }
David Blaikied8180cf2013-01-05 20:03:07 +00002664 return;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002665 }
2666 }
David Blaikie436653b2013-01-05 05:58:35 +00002667
2668 // Create the descriptor for the variable.
2669 llvm::DIVariable D =
2670 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2671 Name, Unit, Line, Ty,
2672 CGM.getLangOpts().Optimize, Flags, ArgNo);
2673
2674 // Insert an llvm.dbg.declare into the current block.
2675 llvm::Instruction *Call =
2676 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2677 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002678}
2679
2680void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2681 llvm::Value *Storage,
2682 CGBuilderTy &Builder) {
2683 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2684 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2685}
2686
Adrian Prantle86fcc42013-03-29 19:20:29 +00002687/// Look up the completed type for a self pointer in the TypeCache and
2688/// create a copy of it with the ObjectPointer and Artificial flags
2689/// set. If the type is not cached, a new one is created. This should
2690/// never happen though, since creating a type for the implicit self
2691/// argument implies that we already parsed the interface definition
2692/// and the ivar declarations in the implementation.
2693llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy, llvm::DIType Ty) {
2694 llvm::DIType CachedTy = getTypeOrNull(QualTy);
2695 if (CachedTy.Verify()) Ty = CachedTy;
2696 else DEBUG(llvm::dbgs() << "No cached type for self.");
2697 return DBuilder.createObjectPointerType(Ty);
2698}
2699
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002700void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2701 llvm::Value *Storage,
2702 CGBuilderTy &Builder,
2703 const CGBlockInfo &blockInfo) {
2704 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2705 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2706
2707 if (Builder.GetInsertBlock() == 0)
2708 return;
2709
2710 bool isByRef = VD->hasAttr<BlocksAttr>();
2711
2712 uint64_t XOffset = 0;
2713 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2714 llvm::DIType Ty;
2715 if (isByRef)
2716 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
2717 else
2718 Ty = getOrCreateType(VD->getType(), Unit);
2719
2720 // Self is passed along as an implicit non-arg variable in a
2721 // block. Mark it as the object pointer.
2722 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantle86fcc42013-03-29 19:20:29 +00002723 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002724
2725 // Get location information.
2726 unsigned Line = getLineNumber(VD->getLocation());
2727 unsigned Column = getColumnNumber(VD->getLocation());
2728
2729 const llvm::DataLayout &target = CGM.getDataLayout();
2730
2731 CharUnits offset = CharUnits::fromQuantity(
2732 target.getStructLayout(blockInfo.StructureType)
2733 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2734
2735 SmallVector<llvm::Value *, 9> addr;
2736 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002737 if (isa<llvm::AllocaInst>(Storage))
2738 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002739 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2740 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2741 if (isByRef) {
2742 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2743 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2744 // offset of __forwarding field
2745 offset = CGM.getContext()
2746 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2747 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2748 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2749 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2750 // offset of x field
2751 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2752 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2753 }
2754
2755 // Create the descriptor for the variable.
2756 llvm::DIVariable D =
2757 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
2758 llvm::DIDescriptor(LexicalBlockStack.back()),
2759 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl9b97adf2013-03-29 19:20:35 +00002760
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002761 // Insert an llvm.dbg.declare into the current block.
2762 llvm::Instruction *Call =
2763 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2764 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2765 LexicalBlockStack.back()));
2766}
2767
2768/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2769/// variable declaration.
2770void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2771 unsigned ArgNo,
2772 CGBuilderTy &Builder) {
2773 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2774 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2775}
2776
2777namespace {
2778 struct BlockLayoutChunk {
2779 uint64_t OffsetInBits;
2780 const BlockDecl::Capture *Capture;
2781 };
2782 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2783 return l.OffsetInBits < r.OffsetInBits;
2784 }
2785}
2786
2787void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002788 llvm::Value *Arg,
2789 llvm::Value *LocalAddr,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002790 CGBuilderTy &Builder) {
2791 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2792 ASTContext &C = CGM.getContext();
2793 const BlockDecl *blockDecl = block.getBlockDecl();
2794
2795 // Collect some general information about the block's location.
2796 SourceLocation loc = blockDecl->getCaretLocation();
2797 llvm::DIFile tunit = getOrCreateFile(loc);
2798 unsigned line = getLineNumber(loc);
2799 unsigned column = getColumnNumber(loc);
2800
2801 // Build the debug-info type for the block literal.
2802 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2803
2804 const llvm::StructLayout *blockLayout =
2805 CGM.getDataLayout().getStructLayout(block.StructureType);
2806
2807 SmallVector<llvm::Value*, 16> fields;
2808 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2809 blockLayout->getElementOffsetInBits(0),
2810 tunit, tunit));
2811 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2812 blockLayout->getElementOffsetInBits(1),
2813 tunit, tunit));
2814 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2815 blockLayout->getElementOffsetInBits(2),
2816 tunit, tunit));
2817 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2818 blockLayout->getElementOffsetInBits(3),
2819 tunit, tunit));
2820 fields.push_back(createFieldType("__descriptor",
2821 C.getPointerType(block.NeedsCopyDispose ?
2822 C.getBlockDescriptorExtendedType() :
2823 C.getBlockDescriptorType()),
2824 0, loc, AS_public,
2825 blockLayout->getElementOffsetInBits(4),
2826 tunit, tunit));
2827
2828 // We want to sort the captures by offset, not because DWARF
2829 // requires this, but because we're paranoid about debuggers.
2830 SmallVector<BlockLayoutChunk, 8> chunks;
2831
2832 // 'this' capture.
2833 if (blockDecl->capturesCXXThis()) {
2834 BlockLayoutChunk chunk;
2835 chunk.OffsetInBits =
2836 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2837 chunk.Capture = 0;
2838 chunks.push_back(chunk);
2839 }
2840
2841 // Variable captures.
2842 for (BlockDecl::capture_const_iterator
2843 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2844 i != e; ++i) {
2845 const BlockDecl::Capture &capture = *i;
2846 const VarDecl *variable = capture.getVariable();
2847 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2848
2849 // Ignore constant captures.
2850 if (captureInfo.isConstant())
2851 continue;
2852
2853 BlockLayoutChunk chunk;
2854 chunk.OffsetInBits =
2855 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2856 chunk.Capture = &capture;
2857 chunks.push_back(chunk);
2858 }
2859
2860 // Sort by offset.
2861 llvm::array_pod_sort(chunks.begin(), chunks.end());
2862
2863 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2864 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2865 uint64_t offsetInBits = i->OffsetInBits;
2866 const BlockDecl::Capture *capture = i->Capture;
2867
2868 // If we have a null capture, this must be the C++ 'this' capture.
2869 if (!capture) {
2870 const CXXMethodDecl *method =
2871 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2872 QualType type = method->getThisType(C);
2873
2874 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2875 offsetInBits, tunit, tunit));
2876 continue;
2877 }
2878
2879 const VarDecl *variable = capture->getVariable();
2880 StringRef name = variable->getName();
2881
2882 llvm::DIType fieldType;
2883 if (capture->isByRef()) {
2884 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2885
2886 // FIXME: this creates a second copy of this type!
2887 uint64_t xoffset;
2888 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2889 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2890 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2891 ptrInfo.first, ptrInfo.second,
2892 offsetInBits, 0, fieldType);
2893 } else {
2894 fieldType = createFieldType(name, variable->getType(), 0,
2895 loc, AS_public, offsetInBits, tunit, tunit);
2896 }
2897 fields.push_back(fieldType);
2898 }
2899
2900 SmallString<36> typeName;
2901 llvm::raw_svector_ostream(typeName)
2902 << "__block_literal_" << CGM.getUniqueBlockCount();
2903
2904 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2905
2906 llvm::DIType type =
2907 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2908 CGM.getContext().toBits(block.BlockSize),
2909 CGM.getContext().toBits(block.BlockAlign),
David Blaikiec1d0af12013-02-25 01:07:08 +00002910 0, llvm::DIType(), fieldsArray);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002911 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2912
2913 // Get overall information about the block.
2914 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2915 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002916
2917 // Create the descriptor for the parameter.
2918 llvm::DIVariable debugVar =
2919 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
2920 llvm::DIDescriptor(scope),
Adrian Prantl836e7c92013-03-14 17:53:33 +00002921 Arg->getName(), tunit, line, type,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002922 CGM.getLangOpts().Optimize, flags,
Adrian Prantl836e7c92013-03-14 17:53:33 +00002923 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2924
Adrian Prantlbea407c2013-03-14 21:52:59 +00002925 if (LocalAddr) {
Adrian Prantl836e7c92013-03-14 17:53:33 +00002926 // Insert an llvm.dbg.value into the current block.
Adrian Prantlbea407c2013-03-14 21:52:59 +00002927 llvm::Instruction *DbgVal =
2928 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopherf068c922013-04-02 22:59:11 +00002929 Builder.GetInsertBlock());
Adrian Prantlbea407c2013-03-14 21:52:59 +00002930 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2931 }
Adrian Prantl836e7c92013-03-14 17:53:33 +00002932
Adrian Prantlbea407c2013-03-14 21:52:59 +00002933 // Insert an llvm.dbg.declare into the current block.
2934 llvm::Instruction *DbgDecl =
2935 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
2936 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002937}
2938
Eric Christopher0395de32013-01-16 01:22:32 +00002939/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
2940/// a static data member of a class, find its corresponding in-class
2941/// declaration.
2942llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
2943 if (cast<VarDecl>(D)->isStaticDataMember()) {
2944 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
2945 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
2946 if (MI != StaticDataMemberCache.end())
2947 // Verify the info still exists.
2948 if (llvm::Value *V = MI->second)
2949 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
2950 }
2951 return llvm::DIDerivedType();
2952}
2953
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002954/// EmitGlobalVariable - Emit information about a global variable.
2955void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2956 const VarDecl *D) {
2957 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2958 // Create global variable debug descriptor.
2959 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
2960 unsigned LineNo = getLineNumber(D->getLocation());
2961
2962 setLocation(D->getLocation());
2963
2964 QualType T = D->getType();
2965 if (T->isIncompleteArrayType()) {
2966
2967 // CodeGen turns int[] into int[1] so we'll do the same here.
2968 llvm::APInt ConstVal(32, 1);
2969 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
2970
2971 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
2972 ArrayType::Normal, 0);
2973 }
2974 StringRef DeclName = D->getName();
2975 StringRef LinkageName;
2976 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
2977 && !isa<ObjCMethodDecl>(D->getDeclContext()))
2978 LinkageName = Var->getName();
2979 if (LinkageName == DeclName)
2980 LinkageName = StringRef();
2981 llvm::DIDescriptor DContext =
2982 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie3923d6a2013-05-08 06:01:46 +00002983 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(DContext, DeclName, LinkageName,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002984 Unit, LineNo, getOrCreateType(T, Unit),
Eric Christopher0395de32013-01-16 01:22:32 +00002985 Var->hasInternalLinkage(), Var,
2986 getStaticDataMemberDeclaration(D));
David Blaikie3923d6a2013-05-08 06:01:46 +00002987 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002988}
2989
2990/// EmitGlobalVariable - Emit information about an objective-c interface.
2991void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
2992 ObjCInterfaceDecl *ID) {
2993 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
2994 // Create global variable debug descriptor.
2995 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
2996 unsigned LineNo = getLineNumber(ID->getLocation());
2997
2998 StringRef Name = ID->getName();
2999
3000 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3001 if (T->isIncompleteArrayType()) {
3002
3003 // CodeGen turns int[] into int[1] so we'll do the same here.
3004 llvm::APInt ConstVal(32, 1);
3005 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3006
3007 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3008 ArrayType::Normal, 0);
3009 }
3010
3011 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3012 getOrCreateType(T, Unit),
3013 Var->hasInternalLinkage(), Var);
3014}
3015
3016/// EmitGlobalVariable - Emit global variable's debug info.
3017void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3018 llvm::Constant *Init) {
3019 assert(CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo);
3020 // Create the descriptor for the variable.
3021 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3022 StringRef Name = VD->getName();
3023 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3024 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3025 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3026 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3027 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3028 }
3029 // Do not use DIGlobalVariable for enums.
3030 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3031 return;
David Blaikie3923d6a2013-05-08 06:01:46 +00003032 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(Unit, Name, Name, Unit,
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003033 getLineNumber(VD->getLocation()),
Eric Christopher0395de32013-01-16 01:22:32 +00003034 Ty, true, Init,
3035 getStaticDataMemberDeclaration(VD));
David Blaikie3923d6a2013-05-08 06:01:46 +00003036 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3037}
3038
3039llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3040 if (!LexicalBlockStack.empty())
3041 return llvm::DIScope(LexicalBlockStack.back());
3042 return getContextDescriptor(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003043}
3044
David Blaikie957dac52013-04-22 06:13:21 +00003045void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
3046 DBuilder.createImportedModule(
David Blaikie3923d6a2013-05-08 06:01:46 +00003047 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3048 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie957dac52013-04-22 06:13:21 +00003049 getLineNumber(UD.getLocation()));
3050}
3051
David Blaikie3923d6a2013-05-08 06:01:46 +00003052void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3053 assert(UD.shadow_size() &&
3054 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3055 // Emitting one decl is sufficient - debuggers can detect that this is an
3056 // overloaded name & provide lookup for all the overloads.
3057 const UsingShadowDecl &USD = **UD.shadow_begin();
3058 if (llvm::DIDescriptor Target = getDeclarationOrDefinition(USD.getUnderlyingDecl()))
3059 DBuilder.createImportedDeclaration(
3060 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3061 getLineNumber(USD.getLocation()));
3062}
3063
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003064/// getOrCreateNamesSpace - Return namespace descriptor for the given
3065/// namespace decl.
3066llvm::DINameSpace
3067CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
3068 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
3069 NameSpaceCache.find(NSDecl);
3070 if (I != NameSpaceCache.end())
3071 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
3072
3073 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3074 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
3075 llvm::DIDescriptor Context =
3076 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3077 llvm::DINameSpace NS =
3078 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3079 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3080 return NS;
3081}
3082
3083void CGDebugInfo::finalize() {
3084 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3085 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3086 llvm::DIType Ty, RepTy;
3087 // Verify that the debug info still exists.
3088 if (llvm::Value *V = VI->second)
3089 Ty = llvm::DIType(cast<llvm::MDNode>(V));
3090
3091 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3092 TypeCache.find(VI->first);
3093 if (it != TypeCache.end()) {
3094 // Verify that the debug info still exists.
3095 if (llvm::Value *V = it->second)
3096 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3097 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003098
Adrian Prantl9b97adf2013-03-29 19:20:35 +00003099 if (Ty.Verify() && Ty.isForwardDecl() && RepTy.Verify())
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003100 Ty.replaceAllUsesWith(RepTy);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003101 }
Adrian Prantlebbd7e02013-03-11 18:33:46 +00003102
3103 // We keep our own list of retained types, because we need to look
3104 // up the final type in the type cache.
3105 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3106 RE = RetainedTypes.end(); RI != RE; ++RI)
3107 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3108
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003109 DBuilder.finalize();
3110}