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