blob: e8f41bdf1f30d28e768e16aae0949db4672823ed [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- CGDebugInfo.cpp - Emit Debug Information for a Module ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the debug information generation while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGDebugInfo.h"
15#include "CGBlocks.h"
David Blaikie38079fd2013-05-10 21:53:14 +000016#include "CGCXXABI.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000017#include "CGObjCRuntime.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclFriend.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/Basic/FileManager.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/Version.h"
29#include "clang/Frontend/CodeGenOptions.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/DerivedTypes.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/Intrinsics.h"
37#include "llvm/IR/Module.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000038#include "llvm/Support/Dwarf.h"
39#include "llvm/Support/FileSystem.h"
40using namespace clang;
41using namespace clang::CodeGen;
42
43CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000044 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
45 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000046 CreateCompileUnit();
47}
48
49CGDebugInfo::~CGDebugInfo() {
50 assert(LexicalBlockStack.empty() &&
51 "Region stack mismatch, stack not empty!");
52}
53
Adrian Prantl2e0637f2013-07-18 00:28:02 +000054
55NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
56 : DI(CGF.getDebugInfo()), Builder(B) {
57 if (DI) {
58 SavedLoc = DI->getLocation();
59 DI->CurLoc = SourceLocation();
60 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
61 }
62}
63
64NoLocation::~NoLocation() {
65 if (DI) {
66 assert(Builder.getCurrentDebugLocation().isUnknown());
67 DI->CurLoc = SavedLoc;
68 }
69}
70
Adrian Prantlb75016d2013-07-18 01:36:04 +000071ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000072 : DI(CGF.getDebugInfo()), Builder(B) {
73 if (DI) {
74 SavedLoc = DI->getLocation();
Adrian Prantl49a78562013-07-24 20:34:39 +000075 DI->CurLoc = SourceLocation();
76 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
77 }
78}
79
80void ArtificialLocation::Emit() {
81 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000082 // Sync the Builder.
83 DI->EmitLocation(Builder, SavedLoc);
84 DI->CurLoc = SourceLocation();
85 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000086 assert(!DI->LexicalBlockStack.empty());
87 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000088 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
89 }
90}
91
Adrian Prantlb75016d2013-07-18 01:36:04 +000092ArtificialLocation::~ArtificialLocation() {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000093 if (DI) {
94 assert(Builder.getCurrentDebugLocation().getLine() == 0);
95 DI->CurLoc = SavedLoc;
96 }
97}
98
Guy Benyei11169dd2012-12-18 14:30:41 +000099void CGDebugInfo::setLocation(SourceLocation Loc) {
100 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000101 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102
103 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
104
105 // If we've changed files in the middle of a lexical scope go ahead
106 // and create a new lexical scope with file node if it's different
107 // from the one in the scope.
108 if (LexicalBlockStack.empty()) return;
109
110 SourceManager &SM = CGM.getContext().getSourceManager();
111 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
112 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
113
114 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
115 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
116 return;
117
118 llvm::MDNode *LB = LexicalBlockStack.back();
119 llvm::DIScope Scope = llvm::DIScope(LB);
120 if (Scope.isLexicalBlockFile()) {
121 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
122 llvm::DIDescriptor D
123 = DBuilder.createLexicalBlockFile(LBF.getScope(),
124 getOrCreateFile(CurLoc));
125 llvm::MDNode *N = D;
126 LexicalBlockStack.pop_back();
127 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000128 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DIDescriptor D
130 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
131 llvm::MDNode *N = D;
132 LexicalBlockStack.pop_back();
133 LexicalBlockStack.push_back(N);
134 }
135}
136
137/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000138llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000139 if (!Context)
140 return TheCU;
141
142 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
143 I = RegionMap.find(Context);
144 if (I != RegionMap.end()) {
145 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000146 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000147 }
148
149 // Check namespace.
150 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000151 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000152
David Blaikiebfa52742013-04-19 06:56:38 +0000153 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
154 if (!RDecl->isDependentType())
155 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000157 return TheCU;
158}
159
160/// getFunctionName - Get function name for the given FunctionDecl. If the
161/// name is constructred on demand (e.g. C++ destructor) then the name
162/// is stored on the side.
163StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
164 assert (FD && "Invalid FunctionDecl!");
165 IdentifierInfo *FII = FD->getIdentifier();
166 FunctionTemplateSpecializationInfo *Info
167 = FD->getTemplateSpecializationInfo();
168 if (!Info && FII)
169 return FII->getName();
170
171 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000172 SmallString<128> NS;
173 llvm::raw_svector_ostream OS(NS);
174 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000175
176 // Add any template specialization args.
177 if (Info) {
178 const TemplateArgumentList *TArgs = Info->TemplateArguments;
179 const TemplateArgument *Args = TArgs->data();
180 unsigned NumArgs = TArgs->size();
181 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000182 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
183 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000184 }
185
186 // Copy this name on the side and use its reference.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000187 OS.flush();
188 char *StrPtr = DebugInfoNames.Allocate<char>(NS.size());
189 memcpy(StrPtr, NS.data(), NS.size());
190 return StringRef(StrPtr, NS.size());
Guy Benyei11169dd2012-12-18 14:30:41 +0000191}
192
193StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
194 SmallString<256> MethodName;
195 llvm::raw_svector_ostream OS(MethodName);
196 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
197 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000198 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000199 dyn_cast<const ObjCImplementationDecl>(DC)) {
200 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000201 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000202 dyn_cast<const ObjCInterfaceDecl>(DC)) {
203 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000204 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 dyn_cast<const ObjCCategoryImplDecl>(DC)){
206 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
207 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000208 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000209 // We can extract the type of the class from the self pointer.
210 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
211 QualType ClassTy =
212 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
213 ClassTy.print(OS, PrintingPolicy(LangOptions()));
214 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000215 }
216 OS << ' ' << OMD->getSelector().getAsString() << ']';
217
218 char *StrPtr = DebugInfoNames.Allocate<char>(OS.tell());
219 memcpy(StrPtr, MethodName.begin(), OS.tell());
220 return StringRef(StrPtr, OS.tell());
221}
222
223/// getSelectorName - Return selector name. This is used for debugging
224/// info.
225StringRef CGDebugInfo::getSelectorName(Selector S) {
226 const std::string &SName = S.getAsString();
227 char *StrPtr = DebugInfoNames.Allocate<char>(SName.size());
228 memcpy(StrPtr, SName.data(), SName.size());
229 return StringRef(StrPtr, SName.size());
230}
231
232/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000233StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000234CGDebugInfo::getClassName(const RecordDecl *RD) {
235 const ClassTemplateSpecializationDecl *Spec
236 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
237 if (!Spec)
238 return RD->getName();
239
240 const TemplateArgument *Args;
241 unsigned NumArgs;
242 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
243 const TemplateSpecializationType *TST =
244 cast<TemplateSpecializationType>(TAW->getType());
245 Args = TST->getArgs();
246 NumArgs = TST->getNumArgs();
247 } else {
248 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
249 Args = TemplateArgs.data();
250 NumArgs = TemplateArgs.size();
251 }
252 StringRef Name = RD->getIdentifier()->getName();
253 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000254 SmallString<128> TemplateArgList;
255 {
256 llvm::raw_svector_ostream OS(TemplateArgList);
257 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
258 Policy);
259 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000260
261 // Copy this name on the side and use its reference.
262 size_t Length = Name.size() + TemplateArgList.size();
263 char *StrPtr = DebugInfoNames.Allocate<char>(Length);
264 memcpy(StrPtr, Name.data(), Name.size());
265 memcpy(StrPtr + Name.size(), TemplateArgList.data(), TemplateArgList.size());
266 return StringRef(StrPtr, Length);
267}
268
269/// getOrCreateFile - Get the file debug info descriptor for the input location.
270llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
271 if (!Loc.isValid())
272 // If Location is not valid then use main input file.
273 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
274
275 SourceManager &SM = CGM.getContext().getSourceManager();
276 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
277
278 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
279 // If the location is not valid then use main input file.
280 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
281
282 // Cache the results.
283 const char *fname = PLoc.getFilename();
284 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
285 DIFileCache.find(fname);
286
287 if (it != DIFileCache.end()) {
288 // Verify that the information still exists.
289 if (llvm::Value *V = it->second)
290 return llvm::DIFile(cast<llvm::MDNode>(V));
291 }
292
293 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
294
295 DIFileCache[fname] = F;
296 return F;
297}
298
299/// getOrCreateMainFile - Get the file info for main compile unit.
300llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
301 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
302}
303
304/// getLineNumber - Get line number for the location. If location is invalid
305/// then use current location.
306unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
307 if (Loc.isInvalid() && CurLoc.isInvalid())
308 return 0;
309 SourceManager &SM = CGM.getContext().getSourceManager();
310 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
311 return PLoc.isValid()? PLoc.getLine() : 0;
312}
313
314/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000315unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000316 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000317 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000318 return 0;
319
320 // If the location is invalid then use the current column.
321 if (Loc.isInvalid() && CurLoc.isInvalid())
322 return 0;
323 SourceManager &SM = CGM.getContext().getSourceManager();
324 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
325 return PLoc.isValid()? PLoc.getColumn() : 0;
326}
327
328StringRef CGDebugInfo::getCurrentDirname() {
329 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
330 return CGM.getCodeGenOpts().DebugCompilationDir;
331
332 if (!CWDName.empty())
333 return CWDName;
334 SmallString<256> CWD;
335 llvm::sys::fs::current_path(CWD);
336 char *CompDirnamePtr = DebugInfoNames.Allocate<char>(CWD.size());
337 memcpy(CompDirnamePtr, CWD.data(), CWD.size());
338 return CWDName = StringRef(CompDirnamePtr, CWD.size());
339}
340
341/// CreateCompileUnit - Create new compile unit.
342void CGDebugInfo::CreateCompileUnit() {
343
344 // Get absolute path name.
345 SourceManager &SM = CGM.getContext().getSourceManager();
346 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
347 if (MainFileName.empty())
348 MainFileName = "<unknown>";
349
350 // The main file name provided via the "-main-file-name" option contains just
351 // the file name itself with no path information. This file name may have had
352 // a relative path, so we look into the actual file entry for the main
353 // file to determine the real absolute path for the file.
354 std::string MainFileDir;
355 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
356 MainFileDir = MainFile->getDir()->getName();
357 if (MainFileDir != ".")
358 MainFileName = MainFileDir + "/" + MainFileName;
359 }
360
361 // Save filename string.
362 char *FilenamePtr = DebugInfoNames.Allocate<char>(MainFileName.length());
363 memcpy(FilenamePtr, MainFileName.c_str(), MainFileName.length());
364 StringRef Filename(FilenamePtr, MainFileName.length());
Eric Christopherf1545832013-02-22 23:50:16 +0000365
366 // Save split dwarf file string.
367 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
368 char *SplitDwarfPtr = DebugInfoNames.Allocate<char>(SplitDwarfFile.length());
369 memcpy(SplitDwarfPtr, SplitDwarfFile.c_str(), SplitDwarfFile.length());
370 StringRef SplitDwarfFilename(SplitDwarfPtr, SplitDwarfFile.length());
Eric Christopherb2a008c2013-05-16 00:45:12 +0000371
Guy Benyei11169dd2012-12-18 14:30:41 +0000372 unsigned LangTag;
373 const LangOptions &LO = CGM.getLangOpts();
374 if (LO.CPlusPlus) {
375 if (LO.ObjC1)
376 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
377 else
378 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
379 } else if (LO.ObjC1) {
380 LangTag = llvm::dwarf::DW_LANG_ObjC;
381 } else if (LO.C99) {
382 LangTag = llvm::dwarf::DW_LANG_C99;
383 } else {
384 LangTag = llvm::dwarf::DW_LANG_C89;
385 }
386
387 std::string Producer = getClangFullVersion();
388
389 // Figure out which version of the ObjC runtime we have.
390 unsigned RuntimeVers = 0;
391 if (LO.ObjC1)
392 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
393
394 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000395 // FIXME - Eliminate TheCU.
Eric Christopher978c8392013-07-19 00:51:58 +0000396 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
397 Producer, LO.Optimize,
398 CGM.getCodeGenOpts().DwarfDebugFlags,
399 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000400}
401
402/// CreateType - Get the Basic type from the cache or create a new
403/// one if necessary.
404llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
405 unsigned Encoding = 0;
406 StringRef BTName;
407 switch (BT->getKind()) {
408#define BUILTIN_TYPE(Id, SingletonId)
409#define PLACEHOLDER_TYPE(Id, SingletonId) \
410 case BuiltinType::Id:
411#include "clang/AST/BuiltinTypes.def"
412 case BuiltinType::Dependent:
413 llvm_unreachable("Unexpected builtin type");
414 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000415 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000416 case BuiltinType::Void:
417 return llvm::DIType();
418 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000419 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000420 return ClassTy;
421 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
422 "objc_class", TheCU,
423 getOrCreateMainFile(), 0);
424 return ClassTy;
425 case BuiltinType::ObjCId: {
426 // typedef struct objc_class *Class;
427 // typedef struct objc_object {
428 // Class isa;
429 // } *id;
430
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000431 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000432 return ObjTy;
433
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000434 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
436 "objc_class", TheCU,
437 getOrCreateMainFile(), 0);
438
439 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000440
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
442
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000443 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000444 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
445 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000446
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000447 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
448 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000449 return ObjTy;
450 }
451 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000452 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 return SelTy;
454 SelTy =
455 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
456 "objc_selector", TheCU, getOrCreateMainFile(),
457 0);
458 return SelTy;
459 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000460
461 case BuiltinType::OCLImage1d:
462 return getOrCreateStructPtrType("opencl_image1d_t",
463 OCLImage1dDITy);
464 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000465 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000466 OCLImage1dArrayDITy);
467 case BuiltinType::OCLImage1dBuffer:
468 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
469 OCLImage1dBufferDITy);
470 case BuiltinType::OCLImage2d:
471 return getOrCreateStructPtrType("opencl_image2d_t",
472 OCLImage2dDITy);
473 case BuiltinType::OCLImage2dArray:
474 return getOrCreateStructPtrType("opencl_image2d_array_t",
475 OCLImage2dArrayDITy);
476 case BuiltinType::OCLImage3d:
477 return getOrCreateStructPtrType("opencl_image3d_t",
478 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000479 case BuiltinType::OCLSampler:
480 return DBuilder.createBasicType("opencl_sampler_t",
481 CGM.getContext().getTypeSize(BT),
482 CGM.getContext().getTypeAlign(BT),
483 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000484 case BuiltinType::OCLEvent:
485 return getOrCreateStructPtrType("opencl_event_t",
486 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000487
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 case BuiltinType::UChar:
489 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
490 case BuiltinType::Char_S:
491 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
492 case BuiltinType::Char16:
493 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
494 case BuiltinType::UShort:
495 case BuiltinType::UInt:
496 case BuiltinType::UInt128:
497 case BuiltinType::ULong:
498 case BuiltinType::WChar_U:
499 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
500 case BuiltinType::Short:
501 case BuiltinType::Int:
502 case BuiltinType::Int128:
503 case BuiltinType::Long:
504 case BuiltinType::WChar_S:
505 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
506 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
507 case BuiltinType::Half:
508 case BuiltinType::Float:
509 case BuiltinType::LongDouble:
510 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
511 }
512
513 switch (BT->getKind()) {
514 case BuiltinType::Long: BTName = "long int"; break;
515 case BuiltinType::LongLong: BTName = "long long int"; break;
516 case BuiltinType::ULong: BTName = "long unsigned int"; break;
517 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
518 default:
519 BTName = BT->getName(CGM.getLangOpts());
520 break;
521 }
522 // Bit size, align and offset of the type.
523 uint64_t Size = CGM.getContext().getTypeSize(BT);
524 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000525 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000526 DBuilder.createBasicType(BTName, Size, Align, Encoding);
527 return DbgTy;
528}
529
530llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
531 // Bit size, align and offset of the type.
532 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
533 if (Ty->isComplexIntegerType())
534 Encoding = llvm::dwarf::DW_ATE_lo_user;
535
536 uint64_t Size = CGM.getContext().getTypeSize(Ty);
537 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000538 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000539 DBuilder.createBasicType("complex", Size, Align, Encoding);
540
541 return DbgTy;
542}
543
544/// CreateCVRType - Get the qualified type from the cache or create
545/// a new one if necessary.
Eric Christopher1ecc5632013-06-07 22:54:39 +0000546llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit,
547 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 QualifierCollector Qc;
549 const Type *T = Qc.strip(Ty);
550
551 // Ignore these qualifiers for now.
552 Qc.removeObjCGCAttr();
553 Qc.removeAddressSpace();
554 Qc.removeObjCLifetime();
555
556 // We will create one Derived type for one qualifier and recurse to handle any
557 // additional ones.
558 unsigned Tag;
559 if (Qc.hasConst()) {
560 Tag = llvm::dwarf::DW_TAG_const_type;
561 Qc.removeConst();
562 } else if (Qc.hasVolatile()) {
563 Tag = llvm::dwarf::DW_TAG_volatile_type;
564 Qc.removeVolatile();
565 } else if (Qc.hasRestrict()) {
566 Tag = llvm::dwarf::DW_TAG_restrict_type;
567 Qc.removeRestrict();
568 } else {
569 assert(Qc.empty() && "Unknown type qualifier for debug info");
570 return getOrCreateType(QualType(T, 0), Unit);
571 }
572
Eric Christopher1ecc5632013-06-07 22:54:39 +0000573 llvm::DIType FromTy =
574 getOrCreateType(Qc.apply(CGM.getContext(), T), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +0000575
576 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
577 // CVR derived types.
578 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000579
Guy Benyei11169dd2012-12-18 14:30:41 +0000580 return DbgTy;
581}
582
583llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
584 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000585
586 // The frontend treats 'id' as a typedef to an ObjCObjectType,
587 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
588 // debug info, we want to emit 'id' in both cases.
589 if (Ty->isObjCQualifiedIdType())
590 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
591
Guy Benyei11169dd2012-12-18 14:30:41 +0000592 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000593 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000594 Ty->getPointeeType(), Unit);
595 return DbgTy;
596}
597
598llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
599 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000600 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 Ty->getPointeeType(), Unit);
602}
603
604// Creates a forward declaration for a RecordDecl in the given context.
605llvm::DIType CGDebugInfo::createRecordFwdDecl(const RecordDecl *RD,
606 llvm::DIDescriptor Ctx) {
607 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
608 unsigned Line = getLineNumber(RD->getLocation());
609 StringRef RDName = getClassName(RD);
610
611 unsigned Tag = 0;
612 if (RD->isStruct() || RD->isInterface())
613 Tag = llvm::dwarf::DW_TAG_structure_type;
614 else if (RD->isUnion())
615 Tag = llvm::dwarf::DW_TAG_union_type;
616 else {
617 assert(RD->isClass());
618 Tag = llvm::dwarf::DW_TAG_class_type;
619 }
620
621 // Create the type.
622 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line);
623}
624
625// Walk up the context chain and create forward decls for record decls,
626// and normal descriptors for namespaces.
627llvm::DIDescriptor CGDebugInfo::createContextChain(const Decl *Context) {
628 if (!Context)
629 return TheCU;
630
631 // See if we already have the parent.
632 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
633 I = RegionMap.find(Context);
634 if (I != RegionMap.end()) {
635 llvm::Value *V = I->second;
636 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
637 }
Eric Christopherb2a008c2013-05-16 00:45:12 +0000638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 // Check namespace.
640 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
641 return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
642
643 if (const RecordDecl *RD = dyn_cast<RecordDecl>(Context)) {
644 if (!RD->isDependentType()) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +0000645 llvm::DIType Ty = getOrCreateLimitedType(
646 CGM.getContext().getRecordType(RD)->castAs<RecordType>(), getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 return llvm::DIDescriptor(Ty);
648 }
649 }
650 return TheCU;
651}
652
David Blaikie4583bea2013-05-24 21:33:22 +0000653/// getOrCreateTypeDeclaration - Create Pointee type. If Pointee is a record
Guy Benyei11169dd2012-12-18 14:30:41 +0000654/// then emit record's fwd if debug info size reduction is enabled.
David Blaikie4583bea2013-05-24 21:33:22 +0000655llvm::DIType CGDebugInfo::getOrCreateTypeDeclaration(QualType PointeeTy,
656 llvm::DIFile Unit) {
David Blaikiebd483762013-05-20 04:58:53 +0000657 if (DebugKind > CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000658 return getOrCreateType(PointeeTy, Unit);
David Blaikiee36464c2013-06-05 05:32:23 +0000659 return getOrCreateType(PointeeTy, Unit, true);
Guy Benyei11169dd2012-12-18 14:30:41 +0000660}
661
662llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000663 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000664 QualType PointeeTy,
665 llvm::DIFile Unit) {
666 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
667 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie4583bea2013-05-24 21:33:22 +0000668 return DBuilder.createReferenceType(
669 Tag, getOrCreateTypeDeclaration(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000670
Guy Benyei11169dd2012-12-18 14:30:41 +0000671 // Bit size, align and offset of the type.
672 // Size is always the size of a pointer. We can't use getTypeSize here
673 // because that does not return the correct value for references.
674 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000675 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000676 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
677
David Blaikie4583bea2013-05-24 21:33:22 +0000678 return DBuilder.createPointerType(getOrCreateTypeDeclaration(PointeeTy, Unit),
Guy Benyei11169dd2012-12-18 14:30:41 +0000679 Size, Align);
680}
681
Eric Christopher0fdcb312013-05-16 00:52:20 +0000682llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
683 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000684 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000685 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000686 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
687 TheCU, getOrCreateMainFile(), 0);
688 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
689 Cache = DBuilder.createPointerType(Cache, Size);
690 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000691}
692
Guy Benyei11169dd2012-12-18 14:30:41 +0000693llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
694 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000695 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000696 return BlockLiteralGeneric;
697
698 SmallVector<llvm::Value *, 8> EltTys;
699 llvm::DIType FieldTy;
700 QualType FType;
701 uint64_t FieldSize, FieldOffset;
702 unsigned FieldAlign;
703 llvm::DIArray Elements;
704 llvm::DIType EltTy, DescTy;
705
706 FieldOffset = 0;
707 FType = CGM.getContext().UnsignedLongTy;
708 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
709 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
710
711 Elements = DBuilder.getOrCreateArray(EltTys);
712 EltTys.clear();
713
714 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
715 unsigned LineNo = getLineNumber(CurLoc);
716
717 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
718 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000719 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000720
721 // Bit size, align and offset of the type.
722 uint64_t Size = CGM.getContext().getTypeSize(Ty);
723
724 DescTy = DBuilder.createPointerType(EltTy, Size);
725
726 FieldOffset = 0;
727 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
728 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
729 FType = CGM.getContext().IntTy;
730 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
731 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
732 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
733 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
734
735 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
736 FieldTy = DescTy;
737 FieldSize = CGM.getContext().getTypeSize(Ty);
738 FieldAlign = CGM.getContext().getTypeAlign(Ty);
739 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
740 LineNo, FieldSize, FieldAlign,
741 FieldOffset, 0, FieldTy);
742 EltTys.push_back(FieldTy);
743
744 FieldOffset += FieldSize;
745 Elements = DBuilder.getOrCreateArray(EltTys);
746
747 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
748 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000749 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000750
Guy Benyei11169dd2012-12-18 14:30:41 +0000751 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
752 return BlockLiteralGeneric;
753}
754
David Blaikiee36464c2013-06-05 05:32:23 +0000755llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit,
756 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000757 // Typedefs are derived from some other type. If we have a typedef of a
758 // typedef, make sure to emit the whole chain.
David Blaikie4583bea2013-05-24 21:33:22 +0000759 llvm::DIType Src =
David Blaikiee36464c2013-06-05 05:32:23 +0000760 getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit, Declaration);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000761 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000762 return llvm::DIType();
763 // We don't set size information, but do specify where the typedef was
764 // declared.
765 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
766 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000767
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 llvm::DIDescriptor TypedefContext =
769 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000770
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 return
772 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
773}
774
775llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
776 llvm::DIFile Unit) {
777 SmallVector<llvm::Value *, 16> EltTys;
778
779 // Add the result type at least.
780 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
781
782 // Set up remainder of arguments if there is a prototype.
783 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
784 if (isa<FunctionNoProtoType>(Ty))
785 EltTys.push_back(DBuilder.createUnspecifiedParameter());
786 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
787 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
788 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
789 }
790
791 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
792 return DBuilder.createSubroutineType(Unit, EltTypeArray);
793}
794
795
Guy Benyei11169dd2012-12-18 14:30:41 +0000796llvm::DIType CGDebugInfo::createFieldType(StringRef name,
797 QualType type,
798 uint64_t sizeInBitsOverride,
799 SourceLocation loc,
800 AccessSpecifier AS,
801 uint64_t offsetInBits,
802 llvm::DIFile tunit,
803 llvm::DIDescriptor scope) {
804 llvm::DIType debugType = getOrCreateType(type, tunit);
805
806 // Get the location for the field.
807 llvm::DIFile file = getOrCreateFile(loc);
808 unsigned line = getLineNumber(loc);
809
810 uint64_t sizeInBits = 0;
811 unsigned alignInBits = 0;
812 if (!type->isIncompleteArrayType()) {
813 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
814
815 if (sizeInBitsOverride)
816 sizeInBits = sizeInBitsOverride;
817 }
818
819 unsigned flags = 0;
820 if (AS == clang::AS_private)
821 flags |= llvm::DIDescriptor::FlagPrivate;
822 else if (AS == clang::AS_protected)
823 flags |= llvm::DIDescriptor::FlagProtected;
824
825 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
826 alignInBits, offsetInBits, flags, debugType);
827}
828
Eric Christopher91a31902013-01-16 01:22:32 +0000829/// CollectRecordLambdaFields - Helper for CollectRecordFields.
830void CGDebugInfo::
831CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
832 SmallVectorImpl<llvm::Value *> &elements,
833 llvm::DIType RecordTy) {
834 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
835 // has the name and the location of the variable so we should iterate over
836 // both concurrently.
837 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
838 RecordDecl::field_iterator Field = CXXDecl->field_begin();
839 unsigned fieldno = 0;
840 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
841 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
842 const LambdaExpr::Capture C = *I;
843 if (C.capturesVariable()) {
844 VarDecl *V = C.getCapturedVar();
845 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
846 StringRef VName = V->getName();
847 uint64_t SizeInBitsOverride = 0;
848 if (Field->isBitField()) {
849 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
850 assert(SizeInBitsOverride && "found named 0-width bitfield");
851 }
852 llvm::DIType fieldType
853 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
854 C.getLocation(), Field->getAccess(),
855 layout.getFieldOffset(fieldno), VUnit, RecordTy);
856 elements.push_back(fieldType);
857 } else {
858 // TODO: Need to handle 'this' in some way by probably renaming the
859 // this of the lambda class and having a field member of 'this' or
860 // by using AT_object_pointer for the function and having that be
861 // used as 'this' for semantic references.
862 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
863 FieldDecl *f = *Field;
864 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
865 QualType type = f->getType();
866 llvm::DIType fieldType
867 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
868 layout.getFieldOffset(fieldno), VUnit, RecordTy);
869
870 elements.push_back(fieldType);
871 }
872 }
873}
874
875/// CollectRecordStaticField - Helper for CollectRecordFields.
876void CGDebugInfo::
877CollectRecordStaticField(const VarDecl *Var,
878 SmallVectorImpl<llvm::Value *> &elements,
879 llvm::DIType RecordTy) {
880 // Create the descriptor for the static variable, with or without
881 // constant initializers.
882 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
883 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
884
885 // Do not describe enums as static members.
886 if (VTy.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
887 return;
888
889 unsigned LineNumber = getLineNumber(Var->getLocation());
890 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000891 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000892 if (Var->getInit()) {
893 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000894 if (Value) {
895 if (Value->isInt())
896 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
897 if (Value->isFloat())
898 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
899 }
Eric Christopher91a31902013-01-16 01:22:32 +0000900 }
901
902 unsigned Flags = 0;
903 AccessSpecifier Access = Var->getAccess();
904 if (Access == clang::AS_private)
905 Flags |= llvm::DIDescriptor::FlagPrivate;
906 else if (Access == clang::AS_protected)
907 Flags |= llvm::DIDescriptor::FlagProtected;
908
909 llvm::DIType GV = DBuilder.createStaticMemberType(RecordTy, VName, VUnit,
David Blaikied42917f2013-01-20 01:19:17 +0000910 LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000911 elements.push_back(GV);
912 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
913}
914
915/// CollectRecordNormalField - Helper for CollectRecordFields.
916void CGDebugInfo::
917CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
918 llvm::DIFile tunit,
919 SmallVectorImpl<llvm::Value *> &elements,
920 llvm::DIType RecordTy) {
921 StringRef name = field->getName();
922 QualType type = field->getType();
923
924 // Ignore unnamed fields unless they're anonymous structs/unions.
925 if (name.empty() && !type->isRecordType())
926 return;
927
928 uint64_t SizeInBitsOverride = 0;
929 if (field->isBitField()) {
930 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
931 assert(SizeInBitsOverride && "found named 0-width bitfield");
932 }
933
934 llvm::DIType fieldType
935 = createFieldType(name, type, SizeInBitsOverride,
936 field->getLocation(), field->getAccess(),
937 OffsetInBits, tunit, RecordTy);
938
939 elements.push_back(fieldType);
940}
941
Guy Benyei11169dd2012-12-18 14:30:41 +0000942/// CollectRecordFields - A helper function to collect debug info for
943/// record fields. This is used while creating debug info entry for a Record.
944void CGDebugInfo::
945CollectRecordFields(const RecordDecl *record, llvm::DIFile tunit,
946 SmallVectorImpl<llvm::Value *> &elements,
947 llvm::DIType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000948 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
949
Eric Christopher91a31902013-01-16 01:22:32 +0000950 if (CXXDecl && CXXDecl->isLambda())
951 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
952 else {
953 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000954
Eric Christopher91a31902013-01-16 01:22:32 +0000955 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000956 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000957
Eric Christopher91a31902013-01-16 01:22:32 +0000958 // Static and non-static members should appear in the same order as
959 // the corresponding declarations in the source program.
960 for (RecordDecl::decl_iterator I = record->decls_begin(),
961 E = record->decls_end(); I != E; ++I)
962 if (const VarDecl *V = dyn_cast<VarDecl>(*I))
963 CollectRecordStaticField(V, elements, RecordTy);
964 else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000965 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
966 tunit, elements, RecordTy);
967
968 // Bump field number for next field.
969 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 }
972}
973
974/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
975/// function type is not updated to include implicit "this" pointer. Use this
976/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000977llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000978CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
979 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000980 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000981 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000982 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000983 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
984 Func, Unit);
985}
David Blaikie2aaf0652013-01-07 22:24:59 +0000986
David Blaikie469f0792013-05-22 23:22:42 +0000987llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000988 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000989 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000990 llvm::DIArray Args = llvm::DICompositeType(
991 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000992 assert (Args.getNumElements() && "Invalid number of arguments!");
993
994 SmallVector<llvm::Value *, 16> Elts;
995
996 // First element is always return type. For 'void' functions it is NULL.
997 Elts.push_back(Args.getElement(0));
998
David Blaikie2aaf0652013-01-07 22:24:59 +0000999 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +00001000 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +00001001 if (isa<ClassTemplateSpecializationDecl>(RD)) {
1002 // Create pointer type directly in this case.
1003 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
1004 QualType PointeeTy = ThisPtrTy->getPointeeType();
1005 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +00001006 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +00001007 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
1008 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +00001009 llvm::DIType ThisPtrType =
1010 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +00001011 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1012 // TODO: This and the artificial type below are misleading, the
1013 // types aren't artificial the argument is, but the current
1014 // metadata doesn't represent that.
1015 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1016 Elts.push_back(ThisPtrType);
1017 } else {
1018 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1019 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1020 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1021 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001022 }
1023
1024 // Copy rest of the arguments.
1025 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1026 Elts.push_back(Args.getElement(i));
1027
1028 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1029
1030 return DBuilder.createSubroutineType(Unit, EltTypeArray);
1031}
1032
Eric Christopherb2a008c2013-05-16 00:45:12 +00001033/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001034/// inside a function.
1035static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1036 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1037 return isFunctionLocalClass(NRD);
1038 if (isa<FunctionDecl>(RD->getDeclContext()))
1039 return true;
1040 return false;
1041}
1042
1043/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1044/// a single member function GlobalDecl.
1045llvm::DISubprogram
1046CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1047 llvm::DIFile Unit,
1048 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001049 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001050 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001051
Guy Benyei11169dd2012-12-18 14:30:41 +00001052 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001053 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001054
1055 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1056 // make sense to give a single ctor/dtor a linkage name.
1057 StringRef MethodLinkageName;
1058 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1059 MethodLinkageName = CGM.getMangledName(Method);
1060
1061 // Get the location for the method.
1062 llvm::DIFile MethodDefUnit = getOrCreateFile(Method->getLocation());
1063 unsigned MethodLine = getLineNumber(Method->getLocation());
1064
1065 // Collect virtual method info.
1066 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001067 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001068 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001069
Guy Benyei11169dd2012-12-18 14:30:41 +00001070 if (Method->isVirtual()) {
1071 if (Method->isPure())
1072 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1073 else
1074 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001075
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 // It doesn't make sense to give a virtual destructor a vtable index,
1077 // since a single destructor has two entries in the vtable.
1078 if (!isa<CXXDestructorDecl>(Method))
1079 VIndex = CGM.getVTableContext().getMethodVTableIndex(Method);
1080 ContainingType = RecordTy;
1081 }
1082
1083 unsigned Flags = 0;
1084 if (Method->isImplicit())
1085 Flags |= llvm::DIDescriptor::FlagArtificial;
1086 AccessSpecifier Access = Method->getAccess();
1087 if (Access == clang::AS_private)
1088 Flags |= llvm::DIDescriptor::FlagPrivate;
1089 else if (Access == clang::AS_protected)
1090 Flags |= llvm::DIDescriptor::FlagProtected;
1091 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1092 if (CXXC->isExplicit())
1093 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001094 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001095 dyn_cast<CXXConversionDecl>(Method)) {
1096 if (CXXC->isExplicit())
1097 Flags |= llvm::DIDescriptor::FlagExplicit;
1098 }
1099 if (Method->hasPrototype())
1100 Flags |= llvm::DIDescriptor::FlagPrototyped;
1101
1102 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1103 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001104 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001106 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 /* isDefinition=*/ false,
1108 Virtuality, VIndex, ContainingType,
1109 Flags, CGM.getLangOpts().Optimize, NULL,
1110 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001111
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1113
1114 return SP;
1115}
1116
1117/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001118/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001119/// a Record.
1120void CGDebugInfo::
1121CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1122 SmallVectorImpl<llvm::Value *> &EltTys,
1123 llvm::DIType RecordTy) {
1124
1125 // Since we want more than just the individual member decls if we
1126 // have templated functions iterate over every declaration to gather
1127 // the functions.
1128 for(DeclContext::decl_iterator I = RD->decls_begin(),
1129 E = RD->decls_end(); I != E; ++I) {
1130 Decl *D = *I;
David Blaikiefd07c602013-08-09 17:20:05 +00001131 if (D->isImplicit())
Guy Benyei11169dd2012-12-18 14:30:41 +00001132 continue;
1133
1134 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1135 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00001136 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001137}
Guy Benyei11169dd2012-12-18 14:30:41 +00001138
1139/// CollectCXXFriends - A helper function to collect debug info for
1140/// C++ base classes. This is used while creating debug info entry for
1141/// a Record.
1142void CGDebugInfo::
1143CollectCXXFriends(const CXXRecordDecl *RD, llvm::DIFile Unit,
1144 SmallVectorImpl<llvm::Value *> &EltTys,
1145 llvm::DIType RecordTy) {
1146 for (CXXRecordDecl::friend_iterator BI = RD->friend_begin(),
1147 BE = RD->friend_end(); BI != BE; ++BI) {
1148 if ((*BI)->isUnsupportedFriend())
1149 continue;
1150 if (TypeSourceInfo *TInfo = (*BI)->getFriendType())
Eric Christopherb2a008c2013-05-16 00:45:12 +00001151 EltTys.push_back(DBuilder.createFriend(RecordTy,
1152 getOrCreateType(TInfo->getType(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 Unit)));
1154 }
1155}
1156
1157/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001158/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001159/// a Record.
1160void CGDebugInfo::
1161CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1162 SmallVectorImpl<llvm::Value *> &EltTys,
1163 llvm::DIType RecordTy) {
1164
1165 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1166 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1167 BE = RD->bases_end(); BI != BE; ++BI) {
1168 unsigned BFlags = 0;
1169 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001170
Guy Benyei11169dd2012-12-18 14:30:41 +00001171 const CXXRecordDecl *Base =
1172 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001173
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 if (BI->isVirtual()) {
1175 // virtual base offset offset is -ve. The code generator emits dwarf
1176 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001177 BaseOffset =
Guy Benyei11169dd2012-12-18 14:30:41 +00001178 0 - CGM.getVTableContext()
1179 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1180 BFlags = llvm::DIDescriptor::FlagVirtual;
1181 } else
1182 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1183 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1184 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001185
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 AccessSpecifier Access = BI->getAccessSpecifier();
1187 if (Access == clang::AS_private)
1188 BFlags |= llvm::DIDescriptor::FlagPrivate;
1189 else if (Access == clang::AS_protected)
1190 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001191
1192 llvm::DIType DTy =
1193 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 getOrCreateType(BI->getType(), Unit),
1195 BaseOffset, BFlags);
1196 EltTys.push_back(DTy);
1197 }
1198}
1199
1200/// CollectTemplateParams - A helper function to collect template parameters.
1201llvm::DIArray CGDebugInfo::
1202CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001203 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001205 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001206 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1207 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001208 StringRef Name;
1209 if (TPList)
1210 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001211 switch (TA.getKind()) {
1212 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1214 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001215 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001216 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001217 } break;
1218 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1220 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001221 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001222 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001223 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1224 TemplateParams.push_back(TVP);
1225 } break;
1226 case TemplateArgument::Declaration: {
1227 const ValueDecl *D = TA.getAsDecl();
1228 bool InstanceMember = D->isCXXInstanceMember();
1229 QualType T = InstanceMember
1230 ? CGM.getContext().getMemberPointerType(
1231 D->getType(), cast<RecordDecl>(D->getDeclContext())
1232 ->getTypeForDecl())
1233 : CGM.getContext().getPointerType(D->getType());
1234 llvm::DIType TTy = getOrCreateType(T, Unit);
1235 llvm::Value *V = 0;
1236 // Variable pointer template parameters have a value that is the address
1237 // of the variable.
1238 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1239 V = CGM.GetAddrOfGlobalVar(VD);
1240 // Member function pointers have special support for building them, though
1241 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001242 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001243 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1244 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001245 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1246 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001247 // Member data pointers have special handling too to compute the fixed
1248 // offset within the object.
1249 if (isa<FieldDecl>(D)) {
1250 // These five lines (& possibly the above member function pointer
1251 // handling) might be able to be refactored to use similar code in
1252 // CodeGenModule::getMemberPointerConstant
1253 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1254 CharUnits chars =
1255 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1256 V = CGM.getCXXABI().EmitMemberDataPointer(
1257 cast<MemberPointerType>(T.getTypePtr()), chars);
1258 }
1259 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001260 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001261 TemplateParams.push_back(TVP);
1262 } break;
1263 case TemplateArgument::NullPtr: {
1264 QualType T = TA.getNullPtrType();
1265 llvm::DIType TTy = getOrCreateType(T, Unit);
1266 llvm::Value *V = 0;
1267 // Special case member data pointer null values since they're actually -1
1268 // instead of zero.
1269 if (const MemberPointerType *MPT =
1270 dyn_cast<MemberPointerType>(T.getTypePtr()))
1271 // But treat member function pointers as simple zero integers because
1272 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1273 // CodeGen grows handling for values of non-null member function
1274 // pointers then perhaps we could remove this special case and rely on
1275 // EmitNullMemberPointer for member function pointers.
1276 if (MPT->isMemberDataPointer())
1277 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1278 if (!V)
1279 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1280 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001281 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001282 TemplateParams.push_back(TVP);
1283 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001284 case TemplateArgument::Template: {
1285 llvm::DITemplateValueParameter TVP =
1286 DBuilder.createTemplateTemplateParameter(
1287 TheCU, Name, llvm::DIType(),
1288 TA.getAsTemplate().getAsTemplateDecl()
1289 ->getQualifiedNameAsString());
1290 TemplateParams.push_back(TVP);
1291 } break;
1292 case TemplateArgument::Pack: {
1293 llvm::DITemplateValueParameter TVP =
1294 DBuilder.createTemplateParameterPack(
1295 TheCU, Name, llvm::DIType(),
1296 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1297 TemplateParams.push_back(TVP);
1298 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001299 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001300 case TemplateArgument::Expression:
1301 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001302 case TemplateArgument::Null:
1303 llvm_unreachable(
1304 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001305 }
1306 }
1307 return DBuilder.getOrCreateArray(TemplateParams);
1308}
1309
1310/// CollectFunctionTemplateParams - A helper function to collect debug
1311/// info for function template parameters.
1312llvm::DIArray CGDebugInfo::
1313CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1314 if (FD->getTemplatedKind() ==
1315 FunctionDecl::TK_FunctionTemplateSpecialization) {
1316 const TemplateParameterList *TList =
1317 FD->getTemplateSpecializationInfo()->getTemplate()
1318 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001319 return CollectTemplateParams(
1320 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 }
1322 return llvm::DIArray();
1323}
1324
1325/// CollectCXXTemplateParams - A helper function to collect debug info for
1326/// template parameters.
1327llvm::DIArray CGDebugInfo::
1328CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1329 llvm::DIFile Unit) {
1330 llvm::PointerUnion<ClassTemplateDecl *,
1331 ClassTemplatePartialSpecializationDecl *>
1332 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001333
Guy Benyei11169dd2012-12-18 14:30:41 +00001334 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1335 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1336 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1337 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001338 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001339}
1340
1341/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1342llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1343 if (VTablePtrType.isValid())
1344 return VTablePtrType;
1345
1346 ASTContext &Context = CGM.getContext();
1347
1348 /* Function type */
1349 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1350 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1351 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1352 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1353 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1354 "__vtbl_ptr_type");
1355 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1356 return VTablePtrType;
1357}
1358
1359/// getVTableName - Get vtable name for the given Class.
1360StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
1361 // Construct gdb compatible name name.
1362 std::string Name = "_vptr$" + RD->getNameAsString();
1363
1364 // Copy this name on the side and use its reference.
1365 char *StrPtr = DebugInfoNames.Allocate<char>(Name.length());
1366 memcpy(StrPtr, Name.data(), Name.length());
1367 return StringRef(StrPtr, Name.length());
1368}
1369
1370
1371/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1372/// debug info entry in EltTys vector.
1373void CGDebugInfo::
1374CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1375 SmallVectorImpl<llvm::Value *> &EltTys) {
1376 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1377
1378 // If there is a primary base then it will hold vtable info.
1379 if (RL.getPrimaryBase())
1380 return;
1381
1382 // If this class is not dynamic then there is not any vtable info to collect.
1383 if (!RD->isDynamicClass())
1384 return;
1385
1386 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1387 llvm::DIType VPTR
1388 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001389 0, Size, 0, 0,
1390 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 getOrCreateVTablePtrType(Unit));
1392 EltTys.push_back(VPTR);
1393}
1394
Eric Christopherb2a008c2013-05-16 00:45:12 +00001395/// getOrCreateRecordType - Emit record type's standalone debug info.
1396llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001398 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1400 return T;
1401}
1402
1403/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1404/// debug info.
1405llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001406 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001407 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001408 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001409 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 return T;
1411}
1412
1413/// CreateType - get structure or union type.
David Blaikiee36464c2013-06-05 05:32:23 +00001414llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty, bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 RecordDecl *RD = Ty->getDecl();
Adrian Prantl1f56b2a2013-06-18 23:32:21 +00001416 // Limited debug info should only remove struct definitions that can
1417 // safely be replaced by a forward declaration in the source code.
David Blaikie48ad6dc2013-07-13 21:08:14 +00001418 if (DebugKind <= CodeGenOptions::LimitedDebugInfo && Declaration &&
David Blaikie79af3842013-08-01 20:57:40 +00001419 !RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) {
Adrian Prantl1f56b2a2013-06-18 23:32:21 +00001420 // FIXME: This implementation is problematic; there are some test
1421 // cases where we violate the above principle, such as
1422 // test/CodeGen/debug-info-records.c .
David Blaikiee36464c2013-06-05 05:32:23 +00001423 llvm::DIDescriptor FDContext =
1424 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
1425 llvm::DIType RetTy = createRecordFwdDecl(RD, FDContext);
1426 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RetTy;
1427 return RetTy;
1428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001429
1430 // Get overall information about the record type for the debug info.
1431 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1432
1433 // Records and classes and unions can all be recursive. To handle them, we
1434 // first generate a debug descriptor for the struct as a forward declaration.
1435 // Then (if it is a definition) we go through and get debug info for all of
1436 // its members. Finally, we create a descriptor for the complete type (which
1437 // may refer to the forward decl if the struct is recursive) and replace all
1438 // uses of the forward declaration with the final definition.
1439
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001440 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001441 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001442 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001443
1444 if (FwdDecl.isForwardDecl())
1445 return FwdDecl;
1446
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001448 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1450
Adrian Prantla03a85a2013-03-06 22:03:30 +00001451 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001452 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1453
1454 // Convert all the elements.
1455 SmallVector<llvm::Value *, 16> EltTys;
1456
1457 // Note: The split of CXXDecl information here is intentional, the
1458 // gdb tests will depend on a certain ordering at printout. The debug
1459 // information offsets are still correct if we merge them all together
1460 // though.
1461 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1462 if (CXXDecl) {
1463 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1464 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1465 }
1466
Eric Christopher91a31902013-01-16 01:22:32 +00001467 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001468 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001469 if (CXXDecl) {
1470 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
1471 CollectCXXFriends(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 }
1473
1474 LexicalBlockStack.pop_back();
1475 RegionMap.erase(Ty->getDecl());
1476
1477 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001478 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001479
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001480 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1481 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001482}
1483
1484/// CreateType - get objective-c object type.
1485llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1486 llvm::DIFile Unit) {
1487 // Ignore protocols.
1488 return getOrCreateType(Ty->getBaseType(), Unit);
1489}
1490
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001491
1492/// \return true if Getter has the default name for the property PD.
1493static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1494 const ObjCMethodDecl *Getter) {
1495 assert(PD);
1496 if (!Getter)
1497 return true;
1498
1499 assert(Getter->getDeclName().isObjCZeroArgSelector());
1500 return PD->getName() ==
1501 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1502}
1503
1504/// \return true if Setter has the default name for the property PD.
1505static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1506 const ObjCMethodDecl *Setter) {
1507 assert(PD);
1508 if (!Setter)
1509 return true;
1510
1511 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001512 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001513 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1514}
1515
Guy Benyei11169dd2012-12-18 14:30:41 +00001516/// CreateType - get objective-c interface type.
1517llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1518 llvm::DIFile Unit) {
1519 ObjCInterfaceDecl *ID = Ty->getDecl();
1520 if (!ID)
1521 return llvm::DIType();
1522
1523 // Get overall information about the record type for the debug info.
1524 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1525 unsigned Line = getLineNumber(ID->getLocation());
1526 unsigned RuntimeLang = TheCU.getLanguage();
1527
1528 // If this is just a forward declaration return a special forward-declaration
1529 // debug type since we won't be able to lay out the entire type.
1530 ObjCInterfaceDecl *Def = ID->getDefinition();
1531 if (!Def) {
1532 llvm::DIType FwdDecl =
1533 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001534 ID->getName(), TheCU, DefUnit, Line,
1535 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 return FwdDecl;
1537 }
1538
1539 ID = Def;
1540
1541 // Bit size, align and offset of the type.
1542 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1543 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1544
1545 unsigned Flags = 0;
1546 if (ID->getImplementation())
1547 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1548
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001549 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1551 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001552 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001553
1554 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1555 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001556 QualType QualTy = QualType(Ty, 0);
1557 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001558
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001559 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001560 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1562
1563 // Convert all the elements.
1564 SmallVector<llvm::Value *, 16> EltTys;
1565
1566 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1567 if (SClass) {
1568 llvm::DIType SClassTy =
1569 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1570 if (!SClassTy.isValid())
1571 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001572
Guy Benyei11169dd2012-12-18 14:30:41 +00001573 llvm::DIType InhTag =
1574 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1575 EltTys.push_back(InhTag);
1576 }
1577
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001578 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001579 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1580 E = ID->prop_end(); I != E; ++I) {
1581 const ObjCPropertyDecl *PD = *I;
1582 SourceLocation Loc = PD->getLocation();
1583 llvm::DIFile PUnit = getOrCreateFile(Loc);
1584 unsigned PLine = getLineNumber(Loc);
1585 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1586 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1587 llvm::MDNode *PropertyNode =
1588 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001589 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001590 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001592 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001593 getSelectorName(PD->getSetterName()),
1594 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001595 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 EltTys.push_back(PropertyNode);
1597 }
1598
1599 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1600 unsigned FieldNo = 0;
1601 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1602 Field = Field->getNextIvar(), ++FieldNo) {
1603 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1604 if (!FieldTy.isValid())
1605 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001606
Guy Benyei11169dd2012-12-18 14:30:41 +00001607 StringRef FieldName = Field->getName();
1608
1609 // Ignore unnamed fields.
1610 if (FieldName.empty())
1611 continue;
1612
1613 // Get the location for the field.
1614 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1615 unsigned FieldLine = getLineNumber(Field->getLocation());
1616 QualType FType = Field->getType();
1617 uint64_t FieldSize = 0;
1618 unsigned FieldAlign = 0;
1619
1620 if (!FType->isIncompleteArrayType()) {
1621
1622 // Bit size, align and offset of the type.
1623 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001624 ? Field->getBitWidthValue(CGM.getContext())
1625 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001626 FieldAlign = CGM.getContext().getTypeAlign(FType);
1627 }
1628
1629 uint64_t FieldOffset;
1630 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1631 // We don't know the runtime offset of an ivar if we're using the
1632 // non-fragile ABI. For bitfields, use the bit offset into the first
1633 // byte of storage of the bitfield. For other fields, use zero.
1634 if (Field->isBitField()) {
1635 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1636 CGM, ID, Field);
1637 FieldOffset %= CGM.getContext().getCharWidth();
1638 } else {
1639 FieldOffset = 0;
1640 }
1641 } else {
1642 FieldOffset = RL.getFieldOffset(FieldNo);
1643 }
1644
1645 unsigned Flags = 0;
1646 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1647 Flags = llvm::DIDescriptor::FlagProtected;
1648 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1649 Flags = llvm::DIDescriptor::FlagPrivate;
1650
1651 llvm::MDNode *PropertyNode = NULL;
1652 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001653 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1655 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001656 SourceLocation Loc = PD->getLocation();
1657 llvm::DIFile PUnit = getOrCreateFile(Loc);
1658 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001659 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1660 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1661 PropertyNode =
1662 DBuilder.createObjCProperty(PD->getName(),
1663 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001664 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001665 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001666 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001667 getSelectorName(PD->getSetterName()),
1668 PD->getPropertyAttributes(),
1669 getOrCreateType(PD->getType(), PUnit));
1670 }
1671 }
1672 }
1673 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1674 FieldLine, FieldSize, FieldAlign,
1675 FieldOffset, Flags, FieldTy,
1676 PropertyNode);
1677 EltTys.push_back(FieldTy);
1678 }
1679
1680 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001681 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001682
1683 // If the implementation is not yet set, we do not want to mark it
1684 // as complete. An implementation may declare additional
1685 // private ivars that we would miss otherwise.
1686 if (ID->getImplementation() == 0)
1687 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001688
Guy Benyei11169dd2012-12-18 14:30:41 +00001689 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001690 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001691}
1692
1693llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1694 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1695 int64_t Count = Ty->getNumElements();
1696 if (Count == 0)
1697 // If number of elements are not known then this is an unbounded array.
1698 // Use Count == -1 to express such arrays.
1699 Count = -1;
1700
1701 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1702 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1703
1704 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1705 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1706
1707 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1708}
1709
1710llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1711 llvm::DIFile Unit) {
1712 uint64_t Size;
1713 uint64_t Align;
1714
1715 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1716 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1717 Size = 0;
1718 Align =
1719 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1720 } else if (Ty->isIncompleteArrayType()) {
1721 Size = 0;
1722 if (Ty->getElementType()->isIncompleteType())
1723 Align = 0;
1724 else
1725 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001726 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 Size = 0;
1728 Align = 0;
1729 } else {
1730 // Size and align of the whole array, not the element type.
1731 Size = CGM.getContext().getTypeSize(Ty);
1732 Align = CGM.getContext().getTypeAlign(Ty);
1733 }
1734
1735 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1736 // interior arrays, do we care? Why aren't nested arrays represented the
1737 // obvious/recursive way?
1738 SmallVector<llvm::Value *, 8> Subscripts;
1739 QualType EltTy(Ty, 0);
1740 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1741 // If the number of elements is known, then count is that number. Otherwise,
1742 // it's -1. This allows us to represent a subrange with an array of 0
1743 // elements, like this:
1744 //
1745 // struct foo {
1746 // int x[0];
1747 // };
1748 int64_t Count = -1; // Count == -1 is an unbounded array.
1749 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1750 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001751
Guy Benyei11169dd2012-12-18 14:30:41 +00001752 // FIXME: Verify this is right for VLAs.
1753 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1754 EltTy = Ty->getElementType();
1755 }
1756
1757 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1758
Eric Christopherb2a008c2013-05-16 00:45:12 +00001759 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001760 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1761 SubscriptArray);
1762 return DbgTy;
1763}
1764
Eric Christopherb2a008c2013-05-16 00:45:12 +00001765llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001766 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001767 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001768 Ty, Ty->getPointeeType(), Unit);
1769}
1770
Eric Christopherb2a008c2013-05-16 00:45:12 +00001771llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001772 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001773 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 Ty, Ty->getPointeeType(), Unit);
1775}
1776
Eric Christopherb2a008c2013-05-16 00:45:12 +00001777llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001778 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001779 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1780 if (!Ty->getPointeeType()->isFunctionType())
1781 return DBuilder.createMemberPointerType(
David Blaikie4583bea2013-05-24 21:33:22 +00001782 getOrCreateTypeDeclaration(Ty->getPointeeType(), U), ClassType);
David Blaikie2c705ca2013-01-19 19:20:56 +00001783 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
1784 CGM.getContext().getPointerType(
1785 QualType(Ty->getClass(), Ty->getPointeeType().getCVRQualifiers())),
1786 Ty->getPointeeType()->getAs<FunctionProtoType>(), U),
1787 ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001788}
1789
Eric Christopherb2a008c2013-05-16 00:45:12 +00001790llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 llvm::DIFile U) {
1792 // Ignore the atomic wrapping
1793 // FIXME: What is the correct representation?
1794 return getOrCreateType(Ty->getValueType(), U);
1795}
1796
1797/// CreateEnumType - get enumeration type.
1798llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
1799 uint64_t Size = 0;
1800 uint64_t Align = 0;
1801 if (!ED->getTypeForDecl()->isIncompleteType()) {
1802 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1803 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1804 }
1805
1806 // If this is just a forward declaration, construct an appropriately
1807 // marked node and just return it.
1808 if (!ED->getDefinition()) {
1809 llvm::DIDescriptor EDContext;
1810 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1811 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1812 unsigned Line = getLineNumber(ED->getLocation());
1813 StringRef EDName = ED->getName();
1814 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1815 EDName, EDContext, DefUnit, Line, 0,
1816 Size, Align);
1817 }
1818
1819 // Create DIEnumerator elements for each enumerator.
1820 SmallVector<llvm::Value *, 16> Enumerators;
1821 ED = ED->getDefinition();
1822 for (EnumDecl::enumerator_iterator
1823 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1824 Enum != EnumEnd; ++Enum) {
1825 Enumerators.push_back(
1826 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001827 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 }
1829
1830 // Return a CompositeType for the enum itself.
1831 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1832
1833 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1834 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001835 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001836 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001837 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001838 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001839 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1841 Size, Align, EltArray,
1842 ClassTy);
1843 return DbgTy;
1844}
1845
David Blaikie05491062013-01-21 04:37:12 +00001846static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1847 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001848 do {
David Blaikie05491062013-01-21 04:37:12 +00001849 Quals += T.getLocalQualifiers();
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 QualType LastT = T;
1851 switch (T->getTypeClass()) {
1852 default:
David Blaikie05491062013-01-21 04:37:12 +00001853 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001854 case Type::TemplateSpecialization:
1855 T = cast<TemplateSpecializationType>(T)->desugar();
1856 break;
1857 case Type::TypeOfExpr:
1858 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1859 break;
1860 case Type::TypeOf:
1861 T = cast<TypeOfType>(T)->getUnderlyingType();
1862 break;
1863 case Type::Decltype:
1864 T = cast<DecltypeType>(T)->getUnderlyingType();
1865 break;
1866 case Type::UnaryTransform:
1867 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1868 break;
1869 case Type::Attributed:
1870 T = cast<AttributedType>(T)->getEquivalentType();
1871 break;
1872 case Type::Elaborated:
1873 T = cast<ElaboratedType>(T)->getNamedType();
1874 break;
1875 case Type::Paren:
1876 T = cast<ParenType>(T)->getInnerType();
1877 break;
David Blaikie05491062013-01-21 04:37:12 +00001878 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001879 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001880 break;
1881 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001882 QualType DT = cast<AutoType>(T)->getDeducedType();
1883 if (DT.isNull())
1884 return T;
1885 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 break;
1887 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001888
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001890 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001891 } while (true);
1892}
1893
Eric Christopher0fdcb312013-05-16 00:52:20 +00001894/// getType - Get the type from the cache or return null type if it doesn't
1895/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001896llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1897
1898 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001899 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001900
Guy Benyei11169dd2012-12-18 14:30:41 +00001901 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001902 if (Ty->getTypeClass() == Type::ObjCInterface) {
1903 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1904 if (V)
1905 return llvm::DIType(cast<llvm::MDNode>(V));
1906 else return llvm::DIType();
1907 }
1908
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1910 TypeCache.find(Ty.getAsOpaquePtr());
1911 if (it != TypeCache.end()) {
1912 // Verify that the debug info still exists.
1913 if (llvm::Value *V = it->second)
1914 return llvm::DIType(cast<llvm::MDNode>(V));
1915 }
1916
1917 return llvm::DIType();
1918}
1919
1920/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1921/// doesn't exist.
1922llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1923
1924 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001925 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001926
1927 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001928 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001929 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1930 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00001931 if (it != CompletedTypeCache.end())
1932 V = it->second;
1933 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00001934 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001935 }
1936
Adrian Prantla03a85a2013-03-06 22:03:30 +00001937 // Verify that any cached debug info still exists.
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001938 if (V != 0)
1939 return llvm::DIType(cast<llvm::MDNode>(V));
Adrian Prantla03a85a2013-03-06 22:03:30 +00001940
Guy Benyei11169dd2012-12-18 14:30:41 +00001941 return llvm::DIType();
1942}
1943
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001944void CGDebugInfo::completeFwdDecl(const RecordDecl &RD) {
1945 // In limited debug info we only want to do this if the complete type was
1946 // required.
David Blaikie79af3842013-08-01 20:57:40 +00001947 if (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
1948 CGM.getLangOpts().CPlusPlus)
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001949 return;
1950
David Blaikief7bcb0c2013-06-21 00:59:44 +00001951 QualType QTy = CGM.getContext().getRecordType(&RD);
1952 llvm::DIType T = getTypeOrNull(QTy);
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001953
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001954 if (T && T.isForwardDecl())
David Blaikief7bcb0c2013-06-21 00:59:44 +00001955 getOrCreateType(QTy, getOrCreateFile(RD.getLocation()));
David Blaikieb8f2fbb2013-06-21 00:40:50 +00001956}
1957
Adrian Prantl73409ce2013-03-11 18:33:46 +00001958/// getCachedInterfaceTypeOrNull - Get the type from the interface
1959/// cache, unless it needs to regenerated. Otherwise return null.
1960llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
1961 // Is there a cached interface that hasn't changed?
1962 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
1963 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
1964
1965 if (it1 != ObjCInterfaceCache.end())
1966 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
1967 if (Checksum(Decl) == it1->second.second)
1968 // Return cached forward declaration.
1969 return it1->second.first;
1970
1971 return 0;
1972}
Guy Benyei11169dd2012-12-18 14:30:41 +00001973
1974/// getOrCreateType - Get the type from the cache or create a new
1975/// one if necessary.
Eric Christopher1ecc5632013-06-07 22:54:39 +00001976llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit,
1977 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001978 if (Ty.isNull())
1979 return llvm::DIType();
1980
1981 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001982 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001983
1984 llvm::DIType T = getCompletedTypeOrNull(Ty);
1985
Eric Christopherf8bc4d82013-07-18 00:52:50 +00001986 if (T) {
David Blaikie940ca4d2013-06-21 21:03:11 +00001987 // If we're looking for a definition, make sure we have definitions of any
1988 // underlying types.
1989 if (const TypedefType* TTy = dyn_cast<TypedefType>(Ty))
1990 getOrCreateType(TTy->getDecl()->getUnderlyingType(), Unit, Declaration);
1991 if (Ty.hasLocalQualifiers())
1992 getOrCreateType(QualType(Ty.getTypePtr(), 0), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00001993 return T;
David Blaikie940ca4d2013-06-21 21:03:11 +00001994 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001995
1996 // Otherwise create the type.
David Blaikiee36464c2013-06-05 05:32:23 +00001997 llvm::DIType Res = CreateTypeNode(Ty, Unit, Declaration);
Adrian Prantl73409ce2013-03-11 18:33:46 +00001998 void* TyPtr = Ty.getAsOpaquePtr();
1999
2000 // And update the type cache.
2001 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002
2003 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002004 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002005 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2006 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2007 // Interface types may have elements added to them by a
2008 // subsequent implementation or extension, so we keep them in
2009 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002010 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002011 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002012 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2013 if (V.first)
2014 return llvm::DIType(cast<llvm::MDNode>(V.first));
2015 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2016 Decl->getName(), TheCU, Unit,
2017 getLineNumber(Decl->getLocation()),
2018 TheCU.getLanguage());
2019 // Store the forward declaration in the cache.
2020 V.first = TC;
2021 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002022
David Blaikie8e5939b2013-05-21 18:29:40 +00002023 // Register the type for replacement in finalize().
2024 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2025
Adrian Prantl73409ce2013-03-11 18:33:46 +00002026 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002027 }
2028
Guy Benyei11169dd2012-12-18 14:30:41 +00002029 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002030 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002031
2032 return Res;
2033}
2034
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002035/// Currently the checksum of an interface includes the number of
2036/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002037unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002038 // The assumption is that the number of ivars can only increase
2039 // monotonically, so it is safe to just use their current number as
2040 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002041 unsigned Sum = 0;
2042 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2043 Ivar != 0; Ivar = Ivar->getNextIvar())
2044 ++Sum;
2045
2046 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002047}
2048
2049ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2050 switch (Ty->getTypeClass()) {
2051 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002052 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2053 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002054 case Type::ObjCInterface:
2055 return cast<ObjCInterfaceType>(Ty)->getDecl();
2056 default:
2057 return 0;
2058 }
2059}
2060
Guy Benyei11169dd2012-12-18 14:30:41 +00002061/// CreateTypeNode - Create a new debug type node.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002062llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit,
2063 bool Declaration) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002064 // Handle qualifiers, which recursively handles what they refer to.
2065 if (Ty.hasLocalQualifiers())
David Blaikiee36464c2013-06-05 05:32:23 +00002066 return CreateQualifiedType(Ty, Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002067
2068 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002069
Guy Benyei11169dd2012-12-18 14:30:41 +00002070 // Work out details of type.
2071 switch (Ty->getTypeClass()) {
2072#define TYPE(Class, Base)
2073#define ABSTRACT_TYPE(Class, Base)
2074#define NON_CANONICAL_TYPE(Class, Base)
2075#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2076#include "clang/AST/TypeNodes.def"
2077 llvm_unreachable("Dependent types cannot show up in debug information");
2078
2079 case Type::ExtVector:
2080 case Type::Vector:
2081 return CreateType(cast<VectorType>(Ty), Unit);
2082 case Type::ObjCObjectPointer:
2083 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2084 case Type::ObjCObject:
2085 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2086 case Type::ObjCInterface:
2087 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2088 case Type::Builtin:
2089 return CreateType(cast<BuiltinType>(Ty));
2090 case Type::Complex:
2091 return CreateType(cast<ComplexType>(Ty));
2092 case Type::Pointer:
2093 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner8a365022013-06-24 17:51:48 +00002094 case Type::Decayed:
2095 // Decayed types are just pointers in LLVM and DWARF.
2096 return CreateType(
2097 cast<PointerType>(cast<DecayedType>(Ty)->getDecayedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002098 case Type::BlockPointer:
2099 return CreateType(cast<BlockPointerType>(Ty), Unit);
2100 case Type::Typedef:
David Blaikiee36464c2013-06-05 05:32:23 +00002101 return CreateType(cast<TypedefType>(Ty), Unit, Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002102 case Type::Record:
David Blaikiee36464c2013-06-05 05:32:23 +00002103 return CreateType(cast<RecordType>(Ty), Declaration);
Guy Benyei11169dd2012-12-18 14:30:41 +00002104 case Type::Enum:
2105 return CreateEnumType(cast<EnumType>(Ty)->getDecl());
2106 case Type::FunctionProto:
2107 case Type::FunctionNoProto:
2108 return CreateType(cast<FunctionType>(Ty), Unit);
2109 case Type::ConstantArray:
2110 case Type::VariableArray:
2111 case Type::IncompleteArray:
2112 return CreateType(cast<ArrayType>(Ty), Unit);
2113
2114 case Type::LValueReference:
2115 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2116 case Type::RValueReference:
2117 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2118
2119 case Type::MemberPointer:
2120 return CreateType(cast<MemberPointerType>(Ty), Unit);
2121
2122 case Type::Atomic:
2123 return CreateType(cast<AtomicType>(Ty), Unit);
2124
2125 case Type::Attributed:
2126 case Type::TemplateSpecialization:
2127 case Type::Elaborated:
2128 case Type::Paren:
2129 case Type::SubstTemplateTypeParm:
2130 case Type::TypeOfExpr:
2131 case Type::TypeOf:
2132 case Type::Decltype:
2133 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002134 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002135 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002136 case Type::Auto:
2137 Diag = "auto";
2138 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002139 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002140
Guy Benyei11169dd2012-12-18 14:30:41 +00002141 assert(Diag && "Fall through without a diagnostic?");
2142 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2143 "debug information for %0 is not yet supported");
2144 CGM.getDiags().Report(DiagID)
2145 << Diag;
2146 return llvm::DIType();
2147}
2148
2149/// getOrCreateLimitedType - Get the type from the cache or create a new
2150/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002151llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002152 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002153 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002154
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002155 llvm::DIType T = getTypeOrNull(QTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002156
2157 // We may have cached a forward decl when we could have created
2158 // a non-forward decl. Go ahead and create a non-forward decl
2159 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002160 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002161
2162 // Otherwise create the type.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002163 llvm::DIType Res = CreateLimitedType(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002164
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002165 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002166 ReplaceMap.push_back(
2167 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002168
2169 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002170 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002171 return Res;
2172}
2173
2174// TODO: Currently used for context chains when limiting debug info.
2175llvm::DIType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
2176 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002177
Guy Benyei11169dd2012-12-18 14:30:41 +00002178 // Get overall information about the record type for the debug info.
2179 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2180 unsigned Line = getLineNumber(RD->getLocation());
2181 StringRef RDName = getClassName(RD);
2182
2183 llvm::DIDescriptor RDContext;
Eric Christopher75e17682013-05-16 00:45:23 +00002184 if (DebugKind == CodeGenOptions::LimitedDebugInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 RDContext = createContextChain(cast<Decl>(RD->getDeclContext()));
2186 else
2187 RDContext = getContextDescriptor(cast<Decl>(RD->getDeclContext()));
2188
2189 // If this is just a forward declaration, construct an appropriately
2190 // marked node and just return it.
2191 if (!RD->getDefinition())
2192 return createRecordFwdDecl(RD, RDContext);
2193
2194 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2195 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002196 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002197
Guy Benyei11169dd2012-12-18 14:30:41 +00002198 if (RD->isUnion())
2199 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002200 Size, Align, 0, llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002201 else if (RD->isClass()) {
2202 // FIXME: This could be a struct type giving a default visibility different
2203 // than C++ class type, but needs llvm metadata changes first.
2204 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002205 Size, Align, 0, 0, llvm::DIType(),
2206 llvm::DIArray(), llvm::DIType(),
2207 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002208 } else
2209 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002210 Size, Align, 0, llvm::DIType(),
2211 llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002212
2213 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002214 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002215
David Blaikie6f8f6002013-08-01 18:23:24 +00002216 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002217 // A class's primary base or the class itself contains the vtable.
David Blaikie49ae6a72013-03-26 23:47:35 +00002218 llvm::DICompositeType ContainingType;
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2220 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
2221 // Seek non virtual primary base root.
2222 while (1) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00002223 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2224 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2225 if (PBT && !BRL.isPrimaryBaseVirtual())
2226 PBase = PBT;
2227 else
2228 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 }
David Blaikie49ae6a72013-03-26 23:47:35 +00002230 ContainingType = llvm::DICompositeType(
2231 getOrCreateType(QualType(PBase->getTypeForDecl(), 0), DefUnit));
2232 } else if (CXXDecl->isDynamicClass())
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 ContainingType = RealDecl;
2234
David Blaikie49ae6a72013-03-26 23:47:35 +00002235 RealDecl.setContainingType(ContainingType);
David Blaikie4a5b8952013-08-01 20:31:40 +00002236 if (const ClassTemplateSpecializationDecl *TSpecial =
2237 dyn_cast<ClassTemplateSpecializationDecl>(CXXDecl))
2238 RealDecl.setTypeArray(llvm::DIArray(),
2239 CollectCXXTemplateParams(TSpecial, DefUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00002240 }
2241 return llvm::DIType(RealDecl);
2242}
2243
Guy Benyei11169dd2012-12-18 14:30:41 +00002244/// CreateMemberType - Create new member and increase Offset by FType's size.
2245llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2246 StringRef Name,
2247 uint64_t *Offset) {
2248 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2249 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2250 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2251 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2252 FieldSize, FieldAlign,
2253 *Offset, 0, FieldTy);
2254 *Offset += FieldSize;
2255 return Ty;
2256}
2257
David Blaikiebd483762013-05-20 04:58:53 +00002258llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2259 // We only need a declaration (not a definition) of the type - so use whatever
2260 // we would otherwise do to get a type for a pointee. (forward declarations in
2261 // limited debug info, full definitions (if the type definition is available)
2262 // in unlimited debug info)
2263 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
2264 llvm::DIFile DefUnit = getOrCreateFile(TD->getLocation());
David Blaikie4583bea2013-05-24 21:33:22 +00002265 return getOrCreateTypeDeclaration(CGM.getContext().getTypeDeclType(TD),
2266 DefUnit);
David Blaikiebd483762013-05-20 04:58:53 +00002267 }
2268 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2269 // This doesn't handle providing declarations (for functions or variables) for
2270 // entities without definitions in this TU, nor when the definition proceeds
2271 // the call to this function.
2272 // FIXME: This should be split out into more specific maps with support for
2273 // emitting forward declarations and merging definitions with declarations,
2274 // the same way as we do for types.
2275 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2276 DeclCache.find(D->getCanonicalDecl());
2277 if (I == DeclCache.end())
2278 return llvm::DIDescriptor();
2279 llvm::Value *V = I->second;
2280 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2281}
2282
Guy Benyei11169dd2012-12-18 14:30:41 +00002283/// getFunctionDeclaration - Return debug info descriptor to describe method
2284/// declaration for the given method definition.
2285llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002286 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2287 return llvm::DISubprogram();
2288
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2290 if (!FD) return llvm::DISubprogram();
2291
2292 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002293 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002294
2295 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2296 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002297 if (MI == SPCache.end()) {
2298 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2299 llvm::DICompositeType T(S);
2300 llvm::DISubprogram SP = CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
2301 T.addMember(SP);
2302 return SP;
2303 }
2304 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002305 if (MI != SPCache.end()) {
2306 llvm::Value *V = MI->second;
2307 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002308 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002309 return SP;
2310 }
2311
2312 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2313 E = FD->redecls_end(); I != E; ++I) {
2314 const FunctionDecl *NextFD = *I;
2315 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2316 MI = SPCache.find(NextFD->getCanonicalDecl());
2317 if (MI != SPCache.end()) {
2318 llvm::Value *V = MI->second;
2319 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002320 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002321 return SP;
2322 }
2323 }
2324 return llvm::DISubprogram();
2325}
2326
2327// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2328// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002329llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2330 QualType FnType,
2331 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002332 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2333 // Create fake but valid subroutine type. Otherwise
2334 // llvm::DISubprogram::Verify() would return false, and
2335 // subprogram DIE will miss DW_AT_decl_file and
2336 // DW_AT_decl_line fields.
2337 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002338
2339 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2340 return getOrCreateMethodType(Method, F);
2341 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2342 // Add "self" and "_cmd"
2343 SmallVector<llvm::Value *, 16> Elts;
2344
2345 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl5f360102013-05-22 21:37:49 +00002346 QualType ResultTy = OMethod->getResultType();
2347
2348 // Replace the instancetype keyword with the actual type.
2349 if (ResultTy == CGM.getContext().getObjCInstanceType())
2350 ResultTy = CGM.getContext().getPointerType(
2351 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2352
Adrian Prantl7bec9032013-05-10 21:08:31 +00002353 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002354 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002355 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2356 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2357 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002358 // "_cmd" pointer is always second argument.
2359 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2360 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2361 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002362 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002363 PE = OMethod->param_end(); PI != PE; ++PI)
2364 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2365
2366 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2367 return DBuilder.createSubroutineType(F, EltTypeArray);
2368 }
David Blaikie469f0792013-05-22 23:22:42 +00002369 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002370}
2371
2372/// EmitFunctionStart - Constructs the debug code for entering a function.
2373void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2374 llvm::Function *Fn,
2375 CGBuilderTy &Builder) {
2376
2377 StringRef Name;
2378 StringRef LinkageName;
2379
2380 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2381
2382 const Decl *D = GD.getDecl();
2383 // Function may lack declaration in source code if it is created by Clang
2384 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2385 bool HasDecl = (D != 0);
2386 // Use the location of the declaration.
2387 SourceLocation Loc;
2388 if (HasDecl)
2389 Loc = D->getLocation();
2390
2391 unsigned Flags = 0;
2392 llvm::DIFile Unit = getOrCreateFile(Loc);
2393 llvm::DIDescriptor FDContext(Unit);
2394 llvm::DIArray TParamsArray;
2395 if (!HasDecl) {
2396 // Use llvm function name.
2397 Name = Fn->getName();
2398 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2399 // If there is a DISubprogram for this function available then use it.
2400 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2401 FI = SPCache.find(FD->getCanonicalDecl());
2402 if (FI != SPCache.end()) {
2403 llvm::Value *V = FI->second;
2404 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2405 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2406 llvm::MDNode *SPN = SP;
2407 LexicalBlockStack.push_back(SPN);
2408 RegionMap[D] = llvm::WeakVH(SP);
2409 return;
2410 }
2411 }
2412 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002413 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002414 if (FD->hasPrototype()) {
2415 LinkageName = CGM.getMangledName(GD);
2416 Flags |= llvm::DIDescriptor::FlagPrototyped;
2417 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002418 // No need to replicate the linkage name if it isn't different from the
2419 // subprogram name, no need to have it at all unless coverage is enabled or
2420 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002421 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002422 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2423 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002424 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 LinkageName = StringRef();
2426
Eric Christopher75e17682013-05-16 00:45:23 +00002427 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002428 if (const NamespaceDecl *NSDecl =
2429 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
2430 FDContext = getOrCreateNameSpace(NSDecl);
2431 else if (const RecordDecl *RDecl =
2432 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2433 FDContext = getContextDescriptor(cast<Decl>(RDecl->getDeclContext()));
2434
2435 // Collect template parameters.
2436 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2437 }
2438 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2439 Name = getObjCMethodName(OMD);
2440 Flags |= llvm::DIDescriptor::FlagPrototyped;
2441 } else {
2442 // Use llvm function name.
2443 Name = Fn->getName();
2444 Flags |= llvm::DIDescriptor::FlagPrototyped;
2445 }
2446 if (!Name.empty() && Name[0] == '\01')
2447 Name = Name.substr(1);
2448
2449 unsigned LineNo = getLineNumber(Loc);
2450 if (!HasDecl || D->isImplicit())
2451 Flags |= llvm::DIDescriptor::FlagArtificial;
2452
David Blaikie18cfbc52013-06-22 00:09:36 +00002453 llvm::DISubprogram SP = DBuilder.createFunction(
2454 FDContext, Name, LinkageName, Unit, LineNo,
2455 getOrCreateFunctionType(D, FnType, Unit), Fn->hasInternalLinkage(),
2456 true /*definition*/, getLineNumber(CurLoc), Flags,
2457 CGM.getLangOpts().Optimize, Fn, TParamsArray, getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002458 if (HasDecl)
2459 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002460
2461 // Push function on region stack.
2462 llvm::MDNode *SPN = SP;
2463 LexicalBlockStack.push_back(SPN);
2464 if (HasDecl)
2465 RegionMap[D] = llvm::WeakVH(SP);
2466}
2467
2468/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002469/// information in the source file. If the location is invalid, the
2470/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002471void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
2472 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002473 // Update our current location
2474 setLocation(Loc);
2475
2476 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2477
2478 // Don't bother if things are the same as last time.
2479 SourceManager &SM = CGM.getContext().getSourceManager();
2480 if (CurLoc == PrevLoc ||
2481 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2482 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002483 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2484 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2485 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002487
Guy Benyei11169dd2012-12-18 14:30:41 +00002488 // Update last state.
2489 PrevLoc = CurLoc;
2490
2491 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002492 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2493 (getLineNumber(CurLoc),
2494 getColumnNumber(CurLoc, ForceColumnInfo),
2495 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002496}
2497
2498/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2499/// the stack.
2500void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2501 llvm::DIDescriptor D =
2502 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2503 llvm::DIDescriptor() :
2504 llvm::DIDescriptor(LexicalBlockStack.back()),
2505 getOrCreateFile(CurLoc),
2506 getLineNumber(CurLoc),
2507 getColumnNumber(CurLoc));
2508 llvm::MDNode *DN = D;
2509 LexicalBlockStack.push_back(DN);
2510}
2511
2512/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2513/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002514void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2515 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002516 // Set our current location.
2517 setLocation(Loc);
2518
2519 // Create a new lexical block and push it on the stack.
2520 CreateLexicalBlock(Loc);
2521
2522 // Emit a line table change for the current location inside the new scope.
2523 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2524 getColumnNumber(Loc),
2525 LexicalBlockStack.back()));
2526}
2527
2528/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2529/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002530void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2531 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002532 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2533
2534 // Provide an entry in the line table for the end of the block.
2535 EmitLocation(Builder, Loc);
2536
2537 LexicalBlockStack.pop_back();
2538}
2539
2540/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2541void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2542 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2543 unsigned RCount = FnBeginRegionCount.back();
2544 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2545
2546 // Pop all regions for this function.
2547 while (LexicalBlockStack.size() != RCount)
2548 EmitLexicalBlockEnd(Builder, CurLoc);
2549 FnBeginRegionCount.pop_back();
2550}
2551
Eric Christopherb2a008c2013-05-16 00:45:12 +00002552// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002553// See BuildByRefType.
2554llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2555 uint64_t *XOffset) {
2556
2557 SmallVector<llvm::Value *, 5> EltTys;
2558 QualType FType;
2559 uint64_t FieldSize, FieldOffset;
2560 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002561
Guy Benyei11169dd2012-12-18 14:30:41 +00002562 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002563 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002564
2565 FieldOffset = 0;
2566 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2567 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2568 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2569 FType = CGM.getContext().IntTy;
2570 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2571 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2572
2573 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2574 if (HasCopyAndDispose) {
2575 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2576 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2577 &FieldOffset));
2578 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2579 &FieldOffset));
2580 }
2581 bool HasByrefExtendedLayout;
2582 Qualifiers::ObjCLifetime Lifetime;
2583 if (CGM.getContext().getByrefLifetime(Type,
2584 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002585 && HasByrefExtendedLayout) {
2586 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 EltTys.push_back(CreateMemberType(Unit, FType,
2588 "__byref_variable_layout",
2589 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002590 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002591
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2593 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002594 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002595 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002596 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2597 CharUnits AlignedOffsetInBytes
2598 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2599 CharUnits NumPaddingBytes
2600 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002601
Guy Benyei11169dd2012-12-18 14:30:41 +00002602 if (NumPaddingBytes.isPositive()) {
2603 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2604 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2605 pad, ArrayType::Normal, 0);
2606 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2607 }
2608 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002609
Guy Benyei11169dd2012-12-18 14:30:41 +00002610 FType = Type;
2611 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2612 FieldSize = CGM.getContext().getTypeSize(FType);
2613 FieldAlign = CGM.getContext().toBits(Align);
2614
Eric Christopherb2a008c2013-05-16 00:45:12 +00002615 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2617 0, FieldSize, FieldAlign,
2618 FieldOffset, 0, FieldTy);
2619 EltTys.push_back(FieldTy);
2620 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002621
Guy Benyei11169dd2012-12-18 14:30:41 +00002622 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002623
Guy Benyei11169dd2012-12-18 14:30:41 +00002624 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002625
Guy Benyei11169dd2012-12-18 14:30:41 +00002626 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002627 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002628}
2629
2630/// EmitDeclare - Emit local variable declaration debug info.
2631void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002632 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002634 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2636
2637 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2638 llvm::DIType Ty;
2639 uint64_t XOffset = 0;
2640 if (VD->hasAttr<BlocksAttr>())
2641 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002642 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002643 Ty = getOrCreateType(VD->getType(), Unit);
2644
2645 // If there is no debug info for this type then do not emit debug info
2646 // for this variable.
2647 if (!Ty)
2648 return;
2649
Guy Benyei11169dd2012-12-18 14:30:41 +00002650 // Get location information.
2651 unsigned Line = getLineNumber(VD->getLocation());
2652 unsigned Column = getColumnNumber(VD->getLocation());
2653 unsigned Flags = 0;
2654 if (VD->isImplicit())
2655 Flags |= llvm::DIDescriptor::FlagArtificial;
2656 // If this is the first argument and it is implicit then
2657 // give it an object pointer flag.
2658 // FIXME: There has to be a better way to do this, but for static
2659 // functions there won't be an implicit param at arg1 and
2660 // otherwise it is 'self' or 'this'.
2661 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2662 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002663 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002664 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2665 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002666 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002667
2668 llvm::MDNode *Scope = LexicalBlockStack.back();
2669
2670 StringRef Name = VD->getName();
2671 if (!Name.empty()) {
2672 if (VD->hasAttr<BlocksAttr>()) {
2673 CharUnits offset = CharUnits::fromQuantity(32);
2674 SmallVector<llvm::Value *, 9> addr;
2675 llvm::Type *Int64Ty = CGM.Int64Ty;
2676 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2677 // offset of __forwarding field
2678 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002679 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002680 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2681 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2682 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2683 // offset of x field
2684 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2685 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2686
2687 // Create the descriptor for the variable.
2688 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002689 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 llvm::DIDescriptor(Scope),
2691 VD->getName(), Unit, Line, Ty,
2692 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002693
Guy Benyei11169dd2012-12-18 14:30:41 +00002694 // Insert an llvm.dbg.declare into the current block.
2695 llvm::Instruction *Call =
2696 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2697 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2698 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002700 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2701 // If VD is an anonymous union then Storage represents value for
2702 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002703 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002704 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002705 for (RecordDecl::field_iterator I = RD->field_begin(),
2706 E = RD->field_end();
2707 I != E; ++I) {
2708 FieldDecl *Field = *I;
2709 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2710 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002711
Guy Benyei11169dd2012-12-18 14:30:41 +00002712 // Ignore unnamed fields. Do not ignore unnamed records.
2713 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2714 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002715
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 // Use VarDecl's Tag, Scope and Line number.
2717 llvm::DIVariable D =
2718 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002719 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002720 CGM.getLangOpts().Optimize, Flags,
2721 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002722
Guy Benyei11169dd2012-12-18 14:30:41 +00002723 // Insert an llvm.dbg.declare into the current block.
2724 llvm::Instruction *Call =
2725 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2726 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2727 }
David Blaikie219c7d92013-01-05 20:03:07 +00002728 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002729 }
2730 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002731
2732 // Create the descriptor for the variable.
2733 llvm::DIVariable D =
2734 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2735 Name, Unit, Line, Ty,
2736 CGM.getLangOpts().Optimize, Flags, ArgNo);
2737
2738 // Insert an llvm.dbg.declare into the current block.
2739 llvm::Instruction *Call =
2740 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2741 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002742}
2743
2744void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2745 llvm::Value *Storage,
2746 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002747 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2749}
2750
Adrian Prantlde17db32013-03-29 19:20:29 +00002751/// Look up the completed type for a self pointer in the TypeCache and
2752/// create a copy of it with the ObjectPointer and Artificial flags
2753/// set. If the type is not cached, a new one is created. This should
2754/// never happen though, since creating a type for the implicit self
2755/// argument implies that we already parsed the interface definition
2756/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002757llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2758 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002759 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002760 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002761 else DEBUG(llvm::dbgs() << "No cached type for self.");
2762 return DBuilder.createObjectPointerType(Ty);
2763}
2764
Guy Benyei11169dd2012-12-18 14:30:41 +00002765void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2766 llvm::Value *Storage,
2767 CGBuilderTy &Builder,
2768 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002769 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002771
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 if (Builder.GetInsertBlock() == 0)
2773 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002774
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002776
Guy Benyei11169dd2012-12-18 14:30:41 +00002777 uint64_t XOffset = 0;
2778 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2779 llvm::DIType Ty;
2780 if (isByRef)
2781 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002782 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002783 Ty = getOrCreateType(VD->getType(), Unit);
2784
2785 // Self is passed along as an implicit non-arg variable in a
2786 // block. Mark it as the object pointer.
2787 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002788 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002789
2790 // Get location information.
2791 unsigned Line = getLineNumber(VD->getLocation());
2792 unsigned Column = getColumnNumber(VD->getLocation());
2793
2794 const llvm::DataLayout &target = CGM.getDataLayout();
2795
2796 CharUnits offset = CharUnits::fromQuantity(
2797 target.getStructLayout(blockInfo.StructureType)
2798 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2799
2800 SmallVector<llvm::Value *, 9> addr;
2801 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002802 if (isa<llvm::AllocaInst>(Storage))
2803 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2805 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2806 if (isByRef) {
2807 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2808 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2809 // offset of __forwarding field
2810 offset = CGM.getContext()
2811 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2812 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2813 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2814 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2815 // offset of x field
2816 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2817 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2818 }
2819
2820 // Create the descriptor for the variable.
2821 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002822 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002823 llvm::DIDescriptor(LexicalBlockStack.back()),
2824 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002825
Guy Benyei11169dd2012-12-18 14:30:41 +00002826 // Insert an llvm.dbg.declare into the current block.
2827 llvm::Instruction *Call =
2828 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2829 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2830 LexicalBlockStack.back()));
2831}
2832
2833/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2834/// variable declaration.
2835void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2836 unsigned ArgNo,
2837 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002838 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002839 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2840}
2841
2842namespace {
2843 struct BlockLayoutChunk {
2844 uint64_t OffsetInBits;
2845 const BlockDecl::Capture *Capture;
2846 };
2847 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2848 return l.OffsetInBits < r.OffsetInBits;
2849 }
2850}
2851
2852void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002853 llvm::Value *Arg,
2854 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002856 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002857 ASTContext &C = CGM.getContext();
2858 const BlockDecl *blockDecl = block.getBlockDecl();
2859
2860 // Collect some general information about the block's location.
2861 SourceLocation loc = blockDecl->getCaretLocation();
2862 llvm::DIFile tunit = getOrCreateFile(loc);
2863 unsigned line = getLineNumber(loc);
2864 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002865
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 // Build the debug-info type for the block literal.
2867 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2868
2869 const llvm::StructLayout *blockLayout =
2870 CGM.getDataLayout().getStructLayout(block.StructureType);
2871
2872 SmallVector<llvm::Value*, 16> fields;
2873 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2874 blockLayout->getElementOffsetInBits(0),
2875 tunit, tunit));
2876 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2877 blockLayout->getElementOffsetInBits(1),
2878 tunit, tunit));
2879 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2880 blockLayout->getElementOffsetInBits(2),
2881 tunit, tunit));
2882 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2883 blockLayout->getElementOffsetInBits(3),
2884 tunit, tunit));
2885 fields.push_back(createFieldType("__descriptor",
2886 C.getPointerType(block.NeedsCopyDispose ?
2887 C.getBlockDescriptorExtendedType() :
2888 C.getBlockDescriptorType()),
2889 0, loc, AS_public,
2890 blockLayout->getElementOffsetInBits(4),
2891 tunit, tunit));
2892
2893 // We want to sort the captures by offset, not because DWARF
2894 // requires this, but because we're paranoid about debuggers.
2895 SmallVector<BlockLayoutChunk, 8> chunks;
2896
2897 // 'this' capture.
2898 if (blockDecl->capturesCXXThis()) {
2899 BlockLayoutChunk chunk;
2900 chunk.OffsetInBits =
2901 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2902 chunk.Capture = 0;
2903 chunks.push_back(chunk);
2904 }
2905
2906 // Variable captures.
2907 for (BlockDecl::capture_const_iterator
2908 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2909 i != e; ++i) {
2910 const BlockDecl::Capture &capture = *i;
2911 const VarDecl *variable = capture.getVariable();
2912 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2913
2914 // Ignore constant captures.
2915 if (captureInfo.isConstant())
2916 continue;
2917
2918 BlockLayoutChunk chunk;
2919 chunk.OffsetInBits =
2920 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
2921 chunk.Capture = &capture;
2922 chunks.push_back(chunk);
2923 }
2924
2925 // Sort by offset.
2926 llvm::array_pod_sort(chunks.begin(), chunks.end());
2927
2928 for (SmallVectorImpl<BlockLayoutChunk>::iterator
2929 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
2930 uint64_t offsetInBits = i->OffsetInBits;
2931 const BlockDecl::Capture *capture = i->Capture;
2932
2933 // If we have a null capture, this must be the C++ 'this' capture.
2934 if (!capture) {
2935 const CXXMethodDecl *method =
2936 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
2937 QualType type = method->getThisType(C);
2938
2939 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
2940 offsetInBits, tunit, tunit));
2941 continue;
2942 }
2943
2944 const VarDecl *variable = capture->getVariable();
2945 StringRef name = variable->getName();
2946
2947 llvm::DIType fieldType;
2948 if (capture->isByRef()) {
2949 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
2950
2951 // FIXME: this creates a second copy of this type!
2952 uint64_t xoffset;
2953 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
2954 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
2955 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
2956 ptrInfo.first, ptrInfo.second,
2957 offsetInBits, 0, fieldType);
2958 } else {
2959 fieldType = createFieldType(name, variable->getType(), 0,
2960 loc, AS_public, offsetInBits, tunit, tunit);
2961 }
2962 fields.push_back(fieldType);
2963 }
2964
2965 SmallString<36> typeName;
2966 llvm::raw_svector_ostream(typeName)
2967 << "__block_literal_" << CGM.getUniqueBlockCount();
2968
2969 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
2970
2971 llvm::DIType type =
2972 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
2973 CGM.getContext().toBits(block.BlockSize),
2974 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00002975 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00002976 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
2977
2978 // Get overall information about the block.
2979 unsigned flags = llvm::DIDescriptor::FlagArtificial;
2980 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00002981
2982 // Create the descriptor for the parameter.
2983 llvm::DIVariable debugVar =
2984 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002985 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00002986 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002988 cast<llvm::Argument>(Arg)->getArgNo() + 1);
2989
Adrian Prantl616bef42013-03-14 21:52:59 +00002990 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00002991 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00002992 llvm::Instruction *DbgVal =
2993 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00002994 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00002995 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
2996 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00002997
Adrian Prantl616bef42013-03-14 21:52:59 +00002998 // Insert an llvm.dbg.declare into the current block.
2999 llvm::Instruction *DbgDecl =
3000 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3001 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003002}
3003
Eric Christopher91a31902013-01-16 01:22:32 +00003004/// getStaticDataMemberDeclaration - If D is an out-of-class definition of
3005/// a static data member of a class, find its corresponding in-class
3006/// declaration.
3007llvm::DIDerivedType CGDebugInfo::getStaticDataMemberDeclaration(const Decl *D) {
3008 if (cast<VarDecl>(D)->isStaticDataMember()) {
3009 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
3010 MI = StaticDataMemberCache.find(D->getCanonicalDecl());
3011 if (MI != StaticDataMemberCache.end())
3012 // Verify the info still exists.
3013 if (llvm::Value *V = MI->second)
3014 return llvm::DIDerivedType(cast<llvm::MDNode>(V));
3015 }
3016 return llvm::DIDerivedType();
3017}
3018
Guy Benyei11169dd2012-12-18 14:30:41 +00003019/// EmitGlobalVariable - Emit information about a global variable.
3020void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3021 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003022 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003023 // Create global variable debug descriptor.
3024 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3025 unsigned LineNo = getLineNumber(D->getLocation());
3026
3027 setLocation(D->getLocation());
3028
3029 QualType T = D->getType();
3030 if (T->isIncompleteArrayType()) {
3031
3032 // CodeGen turns int[] into int[1] so we'll do the same here.
3033 llvm::APInt ConstVal(32, 1);
3034 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3035
3036 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3037 ArrayType::Normal, 0);
3038 }
3039 StringRef DeclName = D->getName();
3040 StringRef LinkageName;
3041 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3042 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3043 LinkageName = Var->getName();
3044 if (LinkageName == DeclName)
3045 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003046 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003047 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
Eric Christopher1ecc5632013-06-07 22:54:39 +00003048 llvm::DIGlobalVariable GV =
3049 DBuilder.createStaticVariable(DContext, DeclName, LinkageName, Unit,
3050 LineNo, getOrCreateType(T, Unit),
3051 Var->hasInternalLinkage(), Var,
3052 getStaticDataMemberDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00003053 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003054}
3055
3056/// EmitGlobalVariable - Emit information about an objective-c interface.
3057void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3058 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003059 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003060 // Create global variable debug descriptor.
3061 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3062 unsigned LineNo = getLineNumber(ID->getLocation());
3063
3064 StringRef Name = ID->getName();
3065
3066 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3067 if (T->isIncompleteArrayType()) {
3068
3069 // CodeGen turns int[] into int[1] so we'll do the same here.
3070 llvm::APInt ConstVal(32, 1);
3071 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3072
3073 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3074 ArrayType::Normal, 0);
3075 }
3076
3077 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3078 getOrCreateType(T, Unit),
3079 Var->hasInternalLinkage(), Var);
3080}
3081
3082/// EmitGlobalVariable - Emit global variable's debug info.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003083void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
Guy Benyei11169dd2012-12-18 14:30:41 +00003084 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003085 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003086 // Create the descriptor for the variable.
3087 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3088 StringRef Name = VD->getName();
3089 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3090 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3091 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3092 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3093 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3094 }
3095 // Do not use DIGlobalVariable for enums.
3096 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3097 return;
Eric Christopher1ecc5632013-06-07 22:54:39 +00003098 llvm::DIGlobalVariable GV =
3099 DBuilder.createStaticVariable(Unit, Name, Name, Unit,
3100 getLineNumber(VD->getLocation()), Ty, true,
3101 Init, getStaticDataMemberDeclaration(VD));
David Blaikiebd483762013-05-20 04:58:53 +00003102 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
3103}
3104
3105llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3106 if (!LexicalBlockStack.empty())
3107 return llvm::DIScope(LexicalBlockStack.back());
3108 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003109}
3110
David Blaikie9f88fe82013-04-22 06:13:21 +00003111void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003112 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3113 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003114 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003115 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3116 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003117 getLineNumber(UD.getLocation()));
3118}
3119
David Blaikiebd483762013-05-20 04:58:53 +00003120void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3121 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3122 return;
3123 assert(UD.shadow_size() &&
3124 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3125 // Emitting one decl is sufficient - debuggers can detect that this is an
3126 // overloaded name & provide lookup for all the overloads.
3127 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003128 if (llvm::DIDescriptor Target =
3129 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003130 DBuilder.createImportedDeclaration(
3131 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3132 getLineNumber(USD.getLocation()));
3133}
3134
David Blaikief121b932013-05-20 22:50:41 +00003135llvm::DIImportedEntity
3136CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3137 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3138 return llvm::DIImportedEntity(0);
3139 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3140 if (VH)
3141 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3142 llvm::DIImportedEntity R(0);
3143 if (const NamespaceAliasDecl *Underlying =
3144 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3145 // This could cache & dedup here rather than relying on metadata deduping.
3146 R = DBuilder.createImportedModule(
3147 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3148 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3149 NA.getName());
3150 else
3151 R = DBuilder.createImportedModule(
3152 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3153 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3154 getLineNumber(NA.getLocation()), NA.getName());
3155 VH = R;
3156 return R;
3157}
3158
Guy Benyei11169dd2012-12-18 14:30:41 +00003159/// getOrCreateNamesSpace - Return namespace descriptor for the given
3160/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003161llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003162CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00003163 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003164 NameSpaceCache.find(NSDecl);
3165 if (I != NameSpaceCache.end())
3166 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003167
Guy Benyei11169dd2012-12-18 14:30:41 +00003168 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3169 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003170 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003171 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3172 llvm::DINameSpace NS =
3173 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3174 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3175 return NS;
3176}
3177
3178void CGDebugInfo::finalize() {
3179 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3180 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3181 llvm::DIType Ty, RepTy;
3182 // Verify that the debug info still exists.
3183 if (llvm::Value *V = VI->second)
3184 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003185
Guy Benyei11169dd2012-12-18 14:30:41 +00003186 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3187 TypeCache.find(VI->first);
3188 if (it != TypeCache.end()) {
3189 // Verify that the debug info still exists.
3190 if (llvm::Value *V = it->second)
3191 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3192 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003193
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003194 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003195 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003196 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003197
3198 // We keep our own list of retained types, because we need to look
3199 // up the final type in the type cache.
3200 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3201 RE = RetainedTypes.end(); RI != RE; ++RI)
3202 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
3203
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 DBuilder.finalize();
3205}