blob: 59ba47c334caceadb1174ae76ea846c1991a37a4 [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"
Adrian Prantl0630eb72013-12-18 21:48:18 +000040#include "llvm/Support/Path.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000041using namespace clang;
42using namespace clang::CodeGen;
43
44CGDebugInfo::CGDebugInfo(CodeGenModule &CGM)
Eric Christopher324bbbd2013-07-14 21:12:44 +000045 : CGM(CGM), DebugKind(CGM.getCodeGenOpts().getDebugInfo()),
46 DBuilder(CGM.getModule()) {
Guy Benyei11169dd2012-12-18 14:30:41 +000047 CreateCompileUnit();
48}
49
50CGDebugInfo::~CGDebugInfo() {
51 assert(LexicalBlockStack.empty() &&
52 "Region stack mismatch, stack not empty!");
53}
54
Adrian Prantl2e0637f2013-07-18 00:28:02 +000055
Adrian Prantld1b151e2014-01-17 00:15:10 +000056SaveAndRestoreLocation::SaveAndRestoreLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000057 : DI(CGF.getDebugInfo()), Builder(B) {
58 if (DI) {
59 SavedLoc = DI->getLocation();
60 DI->CurLoc = SourceLocation();
Adrian Prantl2e0637f2013-07-18 00:28:02 +000061 }
62}
63
Adrian Prantld1b151e2014-01-17 00:15:10 +000064SaveAndRestoreLocation::~SaveAndRestoreLocation() {
65 if (DI)
66 DI->EmitLocation(Builder, SavedLoc);
67}
68
69NoLocation::NoLocation(CodeGenFunction &CGF, CGBuilderTy &B)
70 : SaveAndRestoreLocation(CGF, B) {
71 if (DI)
72 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
73}
74
Adrian Prantl2e0637f2013-07-18 00:28:02 +000075NoLocation::~NoLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000076 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +000077 assert(Builder.getCurrentDebugLocation().isUnknown());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000078}
79
Adrian Prantlb75016d2013-07-18 01:36:04 +000080ArtificialLocation::ArtificialLocation(CodeGenFunction &CGF, CGBuilderTy &B)
Adrian Prantld1b151e2014-01-17 00:15:10 +000081 : SaveAndRestoreLocation(CGF, B) {
82 if (DI)
Adrian Prantl49a78562013-07-24 20:34:39 +000083 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Adrian Prantl49a78562013-07-24 20:34:39 +000084}
85
86void ArtificialLocation::Emit() {
87 if (DI) {
Adrian Prantl2e0637f2013-07-18 00:28:02 +000088 // Sync the Builder.
89 DI->EmitLocation(Builder, SavedLoc);
90 DI->CurLoc = SourceLocation();
91 // Construct a location that has a valid scope, but no line info.
Adrian Prantl49a78562013-07-24 20:34:39 +000092 assert(!DI->LexicalBlockStack.empty());
93 llvm::DIDescriptor Scope(DI->LexicalBlockStack.back());
Adrian Prantl2e0637f2013-07-18 00:28:02 +000094 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(0, 0, Scope));
95 }
96}
97
Adrian Prantlb75016d2013-07-18 01:36:04 +000098ArtificialLocation::~ArtificialLocation() {
Adrian Prantld1b151e2014-01-17 00:15:10 +000099 if (DI)
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000100 assert(Builder.getCurrentDebugLocation().getLine() == 0);
Adrian Prantl2e0637f2013-07-18 00:28:02 +0000101}
102
Guy Benyei11169dd2012-12-18 14:30:41 +0000103void CGDebugInfo::setLocation(SourceLocation Loc) {
104 // If the new location isn't valid return.
Adrian Prantlb1b3bfc2013-07-18 00:27:56 +0000105 if (Loc.isInvalid()) return;
Guy Benyei11169dd2012-12-18 14:30:41 +0000106
107 CurLoc = CGM.getContext().getSourceManager().getExpansionLoc(Loc);
108
109 // If we've changed files in the middle of a lexical scope go ahead
110 // and create a new lexical scope with file node if it's different
111 // from the one in the scope.
112 if (LexicalBlockStack.empty()) return;
113
114 SourceManager &SM = CGM.getContext().getSourceManager();
115 PresumedLoc PCLoc = SM.getPresumedLoc(CurLoc);
116 PresumedLoc PPLoc = SM.getPresumedLoc(PrevLoc);
117
118 if (PCLoc.isInvalid() || PPLoc.isInvalid() ||
119 !strcmp(PPLoc.getFilename(), PCLoc.getFilename()))
120 return;
121
122 llvm::MDNode *LB = LexicalBlockStack.back();
123 llvm::DIScope Scope = llvm::DIScope(LB);
124 if (Scope.isLexicalBlockFile()) {
125 llvm::DILexicalBlockFile LBF = llvm::DILexicalBlockFile(LB);
126 llvm::DIDescriptor D
127 = DBuilder.createLexicalBlockFile(LBF.getScope(),
128 getOrCreateFile(CurLoc));
129 llvm::MDNode *N = D;
130 LexicalBlockStack.pop_back();
131 LexicalBlockStack.push_back(N);
David Blaikie0a21d0d2013-01-26 22:16:26 +0000132 } else if (Scope.isLexicalBlock() || Scope.isSubprogram()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000133 llvm::DIDescriptor D
134 = DBuilder.createLexicalBlockFile(Scope, getOrCreateFile(CurLoc));
135 llvm::MDNode *N = D;
136 LexicalBlockStack.pop_back();
137 LexicalBlockStack.push_back(N);
138 }
139}
140
141/// getContextDescriptor - Get context info for the decl.
David Blaikiebfa52742013-04-19 06:56:38 +0000142llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000143 if (!Context)
144 return TheCU;
145
146 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator
147 I = RegionMap.find(Context);
148 if (I != RegionMap.end()) {
149 llvm::Value *V = I->second;
David Blaikiebfa52742013-04-19 06:56:38 +0000150 return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 }
152
153 // Check namespace.
154 if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
David Blaikiebfa52742013-04-19 06:56:38 +0000155 return getOrCreateNameSpace(NSDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +0000156
David Blaikiebfa52742013-04-19 06:56:38 +0000157 if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
158 if (!RDecl->isDependentType())
159 return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 getOrCreateMainFile());
Guy Benyei11169dd2012-12-18 14:30:41 +0000161 return TheCU;
162}
163
164/// getFunctionName - Get function name for the given FunctionDecl. If the
Benjamin Kramer60509af2013-09-09 14:48:42 +0000165/// name is constructed on demand (e.g. C++ destructor) then the name
Guy Benyei11169dd2012-12-18 14:30:41 +0000166/// is stored on the side.
167StringRef CGDebugInfo::getFunctionName(const FunctionDecl *FD) {
168 assert (FD && "Invalid FunctionDecl!");
169 IdentifierInfo *FII = FD->getIdentifier();
170 FunctionTemplateSpecializationInfo *Info
171 = FD->getTemplateSpecializationInfo();
172 if (!Info && FII)
173 return FII->getName();
174
175 // Otherwise construct human readable name for debug info.
Benjamin Kramer9170e912013-02-22 15:46:01 +0000176 SmallString<128> NS;
177 llvm::raw_svector_ostream OS(NS);
178 FD->printName(OS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000179
180 // Add any template specialization args.
181 if (Info) {
182 const TemplateArgumentList *TArgs = Info->TemplateArguments;
183 const TemplateArgument *Args = TArgs->data();
184 unsigned NumArgs = TArgs->size();
185 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000186 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
187 Policy);
Guy Benyei11169dd2012-12-18 14:30:41 +0000188 }
189
190 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000191 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000192}
193
194StringRef CGDebugInfo::getObjCMethodName(const ObjCMethodDecl *OMD) {
195 SmallString<256> MethodName;
196 llvm::raw_svector_ostream OS(MethodName);
197 OS << (OMD->isInstanceMethod() ? '-' : '+') << '[';
198 const DeclContext *DC = OMD->getDeclContext();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000199 if (const ObjCImplementationDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 dyn_cast<const ObjCImplementationDecl>(DC)) {
201 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000202 } else if (const ObjCInterfaceDecl *OID =
Guy Benyei11169dd2012-12-18 14:30:41 +0000203 dyn_cast<const ObjCInterfaceDecl>(DC)) {
204 OS << OID->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000205 } else if (const ObjCCategoryImplDecl *OCD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000206 dyn_cast<const ObjCCategoryImplDecl>(DC)){
207 OS << ((const NamedDecl *)OCD)->getIdentifier()->getNameStart() << '(' <<
208 OCD->getIdentifier()->getNameStart() << ')';
Adrian Prantlb39fc142013-05-17 23:58:45 +0000209 } else if (isa<ObjCProtocolDecl>(DC)) {
Adrian Prantl6e785ec2013-05-17 23:49:10 +0000210 // We can extract the type of the class from the self pointer.
211 if (ImplicitParamDecl* SelfDecl = OMD->getSelfDecl()) {
212 QualType ClassTy =
213 cast<ObjCObjectPointerType>(SelfDecl->getType())->getPointeeType();
214 ClassTy.print(OS, PrintingPolicy(LangOptions()));
215 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 }
217 OS << ' ' << OMD->getSelector().getAsString() << ']';
218
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000219 return internString(OS.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000220}
221
222/// getSelectorName - Return selector name. This is used for debugging
223/// info.
224StringRef CGDebugInfo::getSelectorName(Selector S) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000225 return internString(S.getAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +0000226}
227
228/// getClassName - Get class name including template argument list.
Eric Christopherb2a008c2013-05-16 00:45:12 +0000229StringRef
Guy Benyei11169dd2012-12-18 14:30:41 +0000230CGDebugInfo::getClassName(const RecordDecl *RD) {
231 const ClassTemplateSpecializationDecl *Spec
232 = dyn_cast<ClassTemplateSpecializationDecl>(RD);
233 if (!Spec)
234 return RD->getName();
235
236 const TemplateArgument *Args;
237 unsigned NumArgs;
238 if (TypeSourceInfo *TAW = Spec->getTypeAsWritten()) {
239 const TemplateSpecializationType *TST =
240 cast<TemplateSpecializationType>(TAW->getType());
241 Args = TST->getArgs();
242 NumArgs = TST->getNumArgs();
243 } else {
244 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
245 Args = TemplateArgs.data();
246 NumArgs = TemplateArgs.size();
247 }
248 StringRef Name = RD->getIdentifier()->getName();
249 PrintingPolicy Policy(CGM.getLangOpts());
Benjamin Kramer9170e912013-02-22 15:46:01 +0000250 SmallString<128> TemplateArgList;
251 {
252 llvm::raw_svector_ostream OS(TemplateArgList);
253 TemplateSpecializationType::PrintTemplateArgumentList(OS, Args, NumArgs,
254 Policy);
255 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000256
257 // Copy this name on the side and use its reference.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000258 return internString(Name, TemplateArgList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000259}
260
261/// getOrCreateFile - Get the file debug info descriptor for the input location.
262llvm::DIFile CGDebugInfo::getOrCreateFile(SourceLocation Loc) {
263 if (!Loc.isValid())
264 // If Location is not valid then use main input file.
265 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
266
267 SourceManager &SM = CGM.getContext().getSourceManager();
268 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
269
270 if (PLoc.isInvalid() || StringRef(PLoc.getFilename()).empty())
271 // If the location is not valid then use main input file.
272 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
273
274 // Cache the results.
275 const char *fname = PLoc.getFilename();
276 llvm::DenseMap<const char *, llvm::WeakVH>::iterator it =
277 DIFileCache.find(fname);
278
279 if (it != DIFileCache.end()) {
280 // Verify that the information still exists.
281 if (llvm::Value *V = it->second)
282 return llvm::DIFile(cast<llvm::MDNode>(V));
283 }
284
285 llvm::DIFile F = DBuilder.createFile(PLoc.getFilename(), getCurrentDirname());
286
287 DIFileCache[fname] = F;
288 return F;
289}
290
291/// getOrCreateMainFile - Get the file info for main compile unit.
292llvm::DIFile CGDebugInfo::getOrCreateMainFile() {
293 return DBuilder.createFile(TheCU.getFilename(), TheCU.getDirectory());
294}
295
296/// getLineNumber - Get line number for the location. If location is invalid
297/// then use current location.
298unsigned CGDebugInfo::getLineNumber(SourceLocation Loc) {
299 if (Loc.isInvalid() && CurLoc.isInvalid())
300 return 0;
301 SourceManager &SM = CGM.getContext().getSourceManager();
302 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
303 return PLoc.isValid()? PLoc.getLine() : 0;
304}
305
306/// getColumnNumber - Get column number for the location.
Adrian Prantlc7822422013-03-12 20:43:25 +0000307unsigned CGDebugInfo::getColumnNumber(SourceLocation Loc, bool Force) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 // We may not want column information at all.
Adrian Prantlc7822422013-03-12 20:43:25 +0000309 if (!Force && !CGM.getCodeGenOpts().DebugColumnInfo)
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 return 0;
311
312 // If the location is invalid then use the current column.
313 if (Loc.isInvalid() && CurLoc.isInvalid())
314 return 0;
315 SourceManager &SM = CGM.getContext().getSourceManager();
316 PresumedLoc PLoc = SM.getPresumedLoc(Loc.isValid() ? Loc : CurLoc);
317 return PLoc.isValid()? PLoc.getColumn() : 0;
318}
319
320StringRef CGDebugInfo::getCurrentDirname() {
321 if (!CGM.getCodeGenOpts().DebugCompilationDir.empty())
322 return CGM.getCodeGenOpts().DebugCompilationDir;
323
324 if (!CWDName.empty())
325 return CWDName;
326 SmallString<256> CWD;
327 llvm::sys::fs::current_path(CWD);
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000328 return CWDName = internString(CWD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000329}
330
331/// CreateCompileUnit - Create new compile unit.
332void CGDebugInfo::CreateCompileUnit() {
333
334 // Get absolute path name.
335 SourceManager &SM = CGM.getContext().getSourceManager();
336 std::string MainFileName = CGM.getCodeGenOpts().MainFileName;
337 if (MainFileName.empty())
338 MainFileName = "<unknown>";
339
340 // The main file name provided via the "-main-file-name" option contains just
341 // the file name itself with no path information. This file name may have had
342 // a relative path, so we look into the actual file entry for the main
343 // file to determine the real absolute path for the file.
344 std::string MainFileDir;
345 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
346 MainFileDir = MainFile->getDir()->getName();
Yaron Keren9fb7e902013-10-21 20:07:37 +0000347 if (MainFileDir != ".") {
348 llvm::SmallString<1024> MainFileDirSS(MainFileDir);
349 llvm::sys::path::append(MainFileDirSS, MainFileName);
350 MainFileName = MainFileDirSS.str();
351 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 }
353
354 // Save filename string.
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000355 StringRef Filename = internString(MainFileName);
Eric Christopherf1545832013-02-22 23:50:16 +0000356
357 // Save split dwarf file string.
358 std::string SplitDwarfFile = CGM.getCodeGenOpts().SplitDwarfFile;
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +0000359 StringRef SplitDwarfFilename = internString(SplitDwarfFile);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000360
Guy Benyei11169dd2012-12-18 14:30:41 +0000361 unsigned LangTag;
362 const LangOptions &LO = CGM.getLangOpts();
363 if (LO.CPlusPlus) {
364 if (LO.ObjC1)
365 LangTag = llvm::dwarf::DW_LANG_ObjC_plus_plus;
366 else
367 LangTag = llvm::dwarf::DW_LANG_C_plus_plus;
368 } else if (LO.ObjC1) {
369 LangTag = llvm::dwarf::DW_LANG_ObjC;
370 } else if (LO.C99) {
371 LangTag = llvm::dwarf::DW_LANG_C99;
372 } else {
373 LangTag = llvm::dwarf::DW_LANG_C89;
374 }
375
376 std::string Producer = getClangFullVersion();
377
378 // Figure out which version of the ObjC runtime we have.
379 unsigned RuntimeVers = 0;
380 if (LO.ObjC1)
381 RuntimeVers = LO.ObjCRuntime.isNonFragile() ? 2 : 1;
382
383 // Create new compile unit.
Guy Benyei11169dd2012-12-18 14:30:41 +0000384 // FIXME - Eliminate TheCU.
Eric Christopher978c8392013-07-19 00:51:58 +0000385 TheCU = DBuilder.createCompileUnit(LangTag, Filename, getCurrentDirname(),
386 Producer, LO.Optimize,
387 CGM.getCodeGenOpts().DwarfDebugFlags,
388 RuntimeVers, SplitDwarfFilename);
Guy Benyei11169dd2012-12-18 14:30:41 +0000389}
390
391/// CreateType - Get the Basic type from the cache or create a new
392/// one if necessary.
393llvm::DIType CGDebugInfo::CreateType(const BuiltinType *BT) {
394 unsigned Encoding = 0;
395 StringRef BTName;
396 switch (BT->getKind()) {
397#define BUILTIN_TYPE(Id, SingletonId)
398#define PLACEHOLDER_TYPE(Id, SingletonId) \
399 case BuiltinType::Id:
400#include "clang/AST/BuiltinTypes.def"
401 case BuiltinType::Dependent:
402 llvm_unreachable("Unexpected builtin type");
403 case BuiltinType::NullPtr:
Peter Collingbourne5c5e6172013-06-27 22:51:01 +0000404 return DBuilder.createNullPtrType();
Guy Benyei11169dd2012-12-18 14:30:41 +0000405 case BuiltinType::Void:
406 return llvm::DIType();
407 case BuiltinType::ObjCClass:
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000408 if (ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000409 return ClassTy;
410 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
411 "objc_class", TheCU,
412 getOrCreateMainFile(), 0);
413 return ClassTy;
414 case BuiltinType::ObjCId: {
415 // typedef struct objc_class *Class;
416 // typedef struct objc_object {
417 // Class isa;
418 // } *id;
419
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000420 if (ObjTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000421 return ObjTy;
422
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000423 if (!ClassTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000424 ClassTy = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
425 "objc_class", TheCU,
426 getOrCreateMainFile(), 0);
427
428 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000429
Guy Benyei11169dd2012-12-18 14:30:41 +0000430 llvm::DIType ISATy = DBuilder.createPointerType(ClassTy, Size);
431
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000432 ObjTy =
David Blaikie6d4fe152013-02-25 01:07:08 +0000433 DBuilder.createStructType(TheCU, "objc_object", getOrCreateMainFile(),
434 0, 0, 0, 0, llvm::DIType(), llvm::DIArray());
Guy Benyei11169dd2012-12-18 14:30:41 +0000435
Eric Christopher5c7ee8b2013-04-02 22:59:11 +0000436 ObjTy.setTypeArray(DBuilder.getOrCreateArray(&*DBuilder.createMemberType(
437 ObjTy, "isa", getOrCreateMainFile(), 0, Size, 0, 0, 0, ISATy)));
Guy Benyei11169dd2012-12-18 14:30:41 +0000438 return ObjTy;
439 }
440 case BuiltinType::ObjCSel: {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000441 if (SelTy)
Guy Benyei11169dd2012-12-18 14:30:41 +0000442 return SelTy;
443 SelTy =
444 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
445 "objc_selector", TheCU, getOrCreateMainFile(),
446 0);
447 return SelTy;
448 }
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000449
450 case BuiltinType::OCLImage1d:
451 return getOrCreateStructPtrType("opencl_image1d_t",
452 OCLImage1dDITy);
453 case BuiltinType::OCLImage1dArray:
Eric Christopherb2a008c2013-05-16 00:45:12 +0000454 return getOrCreateStructPtrType("opencl_image1d_array_t",
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000455 OCLImage1dArrayDITy);
456 case BuiltinType::OCLImage1dBuffer:
457 return getOrCreateStructPtrType("opencl_image1d_buffer_t",
458 OCLImage1dBufferDITy);
459 case BuiltinType::OCLImage2d:
460 return getOrCreateStructPtrType("opencl_image2d_t",
461 OCLImage2dDITy);
462 case BuiltinType::OCLImage2dArray:
463 return getOrCreateStructPtrType("opencl_image2d_array_t",
464 OCLImage2dArrayDITy);
465 case BuiltinType::OCLImage3d:
466 return getOrCreateStructPtrType("opencl_image3d_t",
467 OCLImage3dDITy);
Guy Benyei61054192013-02-07 10:55:47 +0000468 case BuiltinType::OCLSampler:
469 return DBuilder.createBasicType("opencl_sampler_t",
470 CGM.getContext().getTypeSize(BT),
471 CGM.getContext().getTypeAlign(BT),
472 llvm::dwarf::DW_ATE_unsigned);
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000473 case BuiltinType::OCLEvent:
474 return getOrCreateStructPtrType("opencl_event_t",
475 OCLEventDITy);
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000476
Guy Benyei11169dd2012-12-18 14:30:41 +0000477 case BuiltinType::UChar:
478 case BuiltinType::Char_U: Encoding = llvm::dwarf::DW_ATE_unsigned_char; break;
479 case BuiltinType::Char_S:
480 case BuiltinType::SChar: Encoding = llvm::dwarf::DW_ATE_signed_char; break;
481 case BuiltinType::Char16:
482 case BuiltinType::Char32: Encoding = llvm::dwarf::DW_ATE_UTF; break;
483 case BuiltinType::UShort:
484 case BuiltinType::UInt:
485 case BuiltinType::UInt128:
486 case BuiltinType::ULong:
487 case BuiltinType::WChar_U:
488 case BuiltinType::ULongLong: Encoding = llvm::dwarf::DW_ATE_unsigned; break;
489 case BuiltinType::Short:
490 case BuiltinType::Int:
491 case BuiltinType::Int128:
492 case BuiltinType::Long:
493 case BuiltinType::WChar_S:
494 case BuiltinType::LongLong: Encoding = llvm::dwarf::DW_ATE_signed; break;
495 case BuiltinType::Bool: Encoding = llvm::dwarf::DW_ATE_boolean; break;
496 case BuiltinType::Half:
497 case BuiltinType::Float:
498 case BuiltinType::LongDouble:
499 case BuiltinType::Double: Encoding = llvm::dwarf::DW_ATE_float; break;
500 }
501
502 switch (BT->getKind()) {
503 case BuiltinType::Long: BTName = "long int"; break;
504 case BuiltinType::LongLong: BTName = "long long int"; break;
505 case BuiltinType::ULong: BTName = "long unsigned int"; break;
506 case BuiltinType::ULongLong: BTName = "long long unsigned int"; break;
507 default:
508 BTName = BT->getName(CGM.getLangOpts());
509 break;
510 }
511 // Bit size, align and offset of the type.
512 uint64_t Size = CGM.getContext().getTypeSize(BT);
513 uint64_t Align = CGM.getContext().getTypeAlign(BT);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000514 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000515 DBuilder.createBasicType(BTName, Size, Align, Encoding);
516 return DbgTy;
517}
518
519llvm::DIType CGDebugInfo::CreateType(const ComplexType *Ty) {
520 // Bit size, align and offset of the type.
521 unsigned Encoding = llvm::dwarf::DW_ATE_complex_float;
522 if (Ty->isComplexIntegerType())
523 Encoding = llvm::dwarf::DW_ATE_lo_user;
524
525 uint64_t Size = CGM.getContext().getTypeSize(Ty);
526 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000527 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +0000528 DBuilder.createBasicType("complex", Size, Align, Encoding);
529
530 return DbgTy;
531}
532
533/// CreateCVRType - Get the qualified type from the cache or create
534/// a new one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +0000535llvm::DIType CGDebugInfo::CreateQualifiedType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000536 QualifierCollector Qc;
537 const Type *T = Qc.strip(Ty);
538
539 // Ignore these qualifiers for now.
540 Qc.removeObjCGCAttr();
541 Qc.removeAddressSpace();
542 Qc.removeObjCLifetime();
543
544 // We will create one Derived type for one qualifier and recurse to handle any
545 // additional ones.
546 unsigned Tag;
547 if (Qc.hasConst()) {
548 Tag = llvm::dwarf::DW_TAG_const_type;
549 Qc.removeConst();
550 } else if (Qc.hasVolatile()) {
551 Tag = llvm::dwarf::DW_TAG_volatile_type;
552 Qc.removeVolatile();
553 } else if (Qc.hasRestrict()) {
554 Tag = llvm::dwarf::DW_TAG_restrict_type;
555 Qc.removeRestrict();
556 } else {
557 assert(Qc.empty() && "Unknown type qualifier for debug info");
558 return getOrCreateType(QualType(T, 0), Unit);
559 }
560
David Blaikie99dab3b2013-09-04 22:03:57 +0000561 llvm::DIType FromTy = getOrCreateType(Qc.apply(CGM.getContext(), T), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +0000562
563 // No need to fill in the Name, Line, Size, Alignment, Offset in case of
564 // CVR derived types.
565 llvm::DIType DbgTy = DBuilder.createQualifiedType(Tag, FromTy);
Eric Christopherb2a008c2013-05-16 00:45:12 +0000566
Guy Benyei11169dd2012-12-18 14:30:41 +0000567 return DbgTy;
568}
569
570llvm::DIType CGDebugInfo::CreateType(const ObjCObjectPointerType *Ty,
571 llvm::DIFile Unit) {
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000572
573 // The frontend treats 'id' as a typedef to an ObjCObjectType,
574 // whereas 'id<protocol>' is treated as an ObjCPointerType. For the
575 // debug info, we want to emit 'id' in both cases.
576 if (Ty->isObjCQualifiedIdType())
577 return getOrCreateType(CGM.getContext().getObjCIdType(), Unit);
578
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 llvm::DIType DbgTy =
Eric Christopherb2a008c2013-05-16 00:45:12 +0000580 CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000581 Ty->getPointeeType(), Unit);
582 return DbgTy;
583}
584
585llvm::DIType CGDebugInfo::CreateType(const PointerType *Ty,
586 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +0000587 return CreatePointerLikeType(llvm::dwarf::DW_TAG_pointer_type, Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000588 Ty->getPointeeType(), Unit);
589}
590
Manman Rene0064d82013-08-29 23:19:58 +0000591/// In C++ mode, types have linkage, so we can rely on the ODR and
592/// on their mangled names, if they're external.
593static SmallString<256>
594getUniqueTagTypeName(const TagType *Ty, CodeGenModule &CGM,
595 llvm::DICompileUnit TheCU) {
596 SmallString<256> FullName;
597 // FIXME: ODR should apply to ObjC++ exactly the same wasy it does to C++.
598 // For now, only apply ODR with C++.
599 const TagDecl *TD = Ty->getDecl();
600 if (TheCU.getLanguage() != llvm::dwarf::DW_LANG_C_plus_plus ||
601 !TD->isExternallyVisible())
602 return FullName;
603 // Microsoft Mangler does not have support for mangleCXXRTTIName yet.
604 if (CGM.getTarget().getCXXABI().isMicrosoft())
605 return FullName;
606
607 // TODO: This is using the RTTI name. Is there a better way to get
608 // a unique string for a type?
609 llvm::raw_svector_ostream Out(FullName);
610 CGM.getCXXABI().getMangleContext().mangleCXXRTTIName(QualType(Ty, 0), Out);
611 Out.flush();
612 return FullName;
613}
614
Guy Benyei11169dd2012-12-18 14:30:41 +0000615// Creates a forward declaration for a RecordDecl in the given context.
David Blaikie8d5e1282013-08-20 21:03:29 +0000616llvm::DICompositeType
Manman Ren1b457022013-08-28 21:20:28 +0000617CGDebugInfo::getOrCreateRecordFwdDecl(const RecordType *Ty,
David Blaikie8d5e1282013-08-20 21:03:29 +0000618 llvm::DIDescriptor Ctx) {
Manman Ren1b457022013-08-28 21:20:28 +0000619 const RecordDecl *RD = Ty->getDecl();
David Blaikie4e7ef802013-08-15 20:17:25 +0000620 if (llvm::DIType T = getTypeOrNull(CGM.getContext().getRecordType(RD)))
David Blaikie8d5e1282013-08-20 21:03:29 +0000621 return llvm::DICompositeType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
623 unsigned Line = getLineNumber(RD->getLocation());
624 StringRef RDName = getClassName(RD);
625
626 unsigned Tag = 0;
627 if (RD->isStruct() || RD->isInterface())
628 Tag = llvm::dwarf::DW_TAG_structure_type;
629 else if (RD->isUnion())
630 Tag = llvm::dwarf::DW_TAG_union_type;
631 else {
632 assert(RD->isClass());
633 Tag = llvm::dwarf::DW_TAG_class_type;
634 }
635
636 // Create the type.
Manman Rene0064d82013-08-29 23:19:58 +0000637 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
638 return DBuilder.createForwardDecl(Tag, RDName, Ctx, DefUnit, Line, 0, 0, 0,
639 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +0000640}
641
Guy Benyei11169dd2012-12-18 14:30:41 +0000642llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +0000643 const Type *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +0000644 QualType PointeeTy,
645 llvm::DIFile Unit) {
646 if (Tag == llvm::dwarf::DW_TAG_reference_type ||
647 Tag == llvm::dwarf::DW_TAG_rvalue_reference_type)
David Blaikie99dab3b2013-09-04 22:03:57 +0000648 return DBuilder.createReferenceType(Tag, getOrCreateType(PointeeTy, Unit));
Fariborz Jahanian65f1fa12013-02-21 20:42:11 +0000649
Guy Benyei11169dd2012-12-18 14:30:41 +0000650 // Bit size, align and offset of the type.
651 // Size is always the size of a pointer. We can't use getTypeSize here
652 // because that does not return the correct value for references.
653 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000654 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
656
David Blaikie99dab3b2013-09-04 22:03:57 +0000657 return DBuilder.createPointerType(getOrCreateType(PointeeTy, Unit), Size,
658 Align);
Guy Benyei11169dd2012-12-18 14:30:41 +0000659}
660
Eric Christopher0fdcb312013-05-16 00:52:20 +0000661llvm::DIType CGDebugInfo::getOrCreateStructPtrType(StringRef Name,
662 llvm::DIType &Cache) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000663 if (Cache)
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000664 return Cache;
David Blaikiefefc7f72013-05-21 17:58:54 +0000665 Cache = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type, Name,
666 TheCU, getOrCreateMainFile(), 0);
667 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
668 Cache = DBuilder.createPointerType(Cache, Size);
669 return Cache;
Guy Benyeid8a08ea2012-12-18 14:38:23 +0000670}
671
Guy Benyei11169dd2012-12-18 14:30:41 +0000672llvm::DIType CGDebugInfo::CreateType(const BlockPointerType *Ty,
673 llvm::DIFile Unit) {
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000674 if (BlockLiteralGeneric)
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 return BlockLiteralGeneric;
676
677 SmallVector<llvm::Value *, 8> EltTys;
678 llvm::DIType FieldTy;
679 QualType FType;
680 uint64_t FieldSize, FieldOffset;
681 unsigned FieldAlign;
682 llvm::DIArray Elements;
683 llvm::DIType EltTy, DescTy;
684
685 FieldOffset = 0;
686 FType = CGM.getContext().UnsignedLongTy;
687 EltTys.push_back(CreateMemberType(Unit, FType, "reserved", &FieldOffset));
688 EltTys.push_back(CreateMemberType(Unit, FType, "Size", &FieldOffset));
689
690 Elements = DBuilder.getOrCreateArray(EltTys);
691 EltTys.clear();
692
693 unsigned Flags = llvm::DIDescriptor::FlagAppleBlock;
694 unsigned LineNo = getLineNumber(CurLoc);
695
696 EltTy = DBuilder.createStructType(Unit, "__block_descriptor",
697 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000698 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000699
700 // Bit size, align and offset of the type.
701 uint64_t Size = CGM.getContext().getTypeSize(Ty);
702
703 DescTy = DBuilder.createPointerType(EltTy, Size);
704
705 FieldOffset = 0;
706 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
707 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
708 FType = CGM.getContext().IntTy;
709 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
710 EltTys.push_back(CreateMemberType(Unit, FType, "__reserved", &FieldOffset));
711 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
712 EltTys.push_back(CreateMemberType(Unit, FType, "__FuncPtr", &FieldOffset));
713
714 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
715 FieldTy = DescTy;
716 FieldSize = CGM.getContext().getTypeSize(Ty);
717 FieldAlign = CGM.getContext().getTypeAlign(Ty);
718 FieldTy = DBuilder.createMemberType(Unit, "__descriptor", Unit,
719 LineNo, FieldSize, FieldAlign,
720 FieldOffset, 0, FieldTy);
721 EltTys.push_back(FieldTy);
722
723 FieldOffset += FieldSize;
724 Elements = DBuilder.getOrCreateArray(EltTys);
725
726 EltTy = DBuilder.createStructType(Unit, "__block_literal_generic",
727 Unit, LineNo, FieldOffset, 0,
David Blaikie6d4fe152013-02-25 01:07:08 +0000728 Flags, llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +0000729
Guy Benyei11169dd2012-12-18 14:30:41 +0000730 BlockLiteralGeneric = DBuilder.createPointerType(EltTy, Size);
731 return BlockLiteralGeneric;
732}
733
David Blaikie99dab3b2013-09-04 22:03:57 +0000734llvm::DIType CGDebugInfo::CreateType(const TypedefType *Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000735 // Typedefs are derived from some other type. If we have a typedef of a
736 // typedef, make sure to emit the whole chain.
David Blaikie99dab3b2013-09-04 22:03:57 +0000737 llvm::DIType Src = getOrCreateType(Ty->getDecl()->getUnderlyingType(), Unit);
Eric Christopherf8bc4d82013-07-18 00:52:50 +0000738 if (!Src)
Guy Benyei11169dd2012-12-18 14:30:41 +0000739 return llvm::DIType();
740 // We don't set size information, but do specify where the typedef was
741 // declared.
Adrian Prantl3eff2252014-01-21 18:42:27 +0000742 SourceLocation Loc = Ty->getDecl()->getLocation();
743 llvm::DIFile File = getOrCreateFile(Loc);
744 unsigned Line = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000746
Guy Benyei11169dd2012-12-18 14:30:41 +0000747 llvm::DIDescriptor TypedefContext =
748 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000749
Guy Benyei11169dd2012-12-18 14:30:41 +0000750 return
Adrian Prantl3eff2252014-01-21 18:42:27 +0000751 DBuilder.createTypedef(Src, TyDecl->getName(), File, Line, TypedefContext);
Guy Benyei11169dd2012-12-18 14:30:41 +0000752}
753
754llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
755 llvm::DIFile Unit) {
756 SmallVector<llvm::Value *, 16> EltTys;
757
758 // Add the result type at least.
Alp Toker314cc812014-01-25 16:55:45 +0000759 EltTys.push_back(getOrCreateType(Ty->getReturnType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000760
761 // Set up remainder of arguments if there is a prototype.
762 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
763 if (isa<FunctionNoProtoType>(Ty))
764 EltTys.push_back(DBuilder.createUnspecifiedParameter());
765 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000766 for (unsigned i = 0, e = FPT->getNumParams(); i != e; ++i)
767 EltTys.push_back(getOrCreateType(FPT->getParamType(i), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 }
769
770 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
771 return DBuilder.createSubroutineType(Unit, EltTypeArray);
772}
773
774
Guy Benyei11169dd2012-12-18 14:30:41 +0000775llvm::DIType CGDebugInfo::createFieldType(StringRef name,
776 QualType type,
777 uint64_t sizeInBitsOverride,
778 SourceLocation loc,
779 AccessSpecifier AS,
780 uint64_t offsetInBits,
781 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000782 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000783 llvm::DIType debugType = getOrCreateType(type, tunit);
784
785 // Get the location for the field.
786 llvm::DIFile file = getOrCreateFile(loc);
787 unsigned line = getLineNumber(loc);
788
789 uint64_t sizeInBits = 0;
790 unsigned alignInBits = 0;
791 if (!type->isIncompleteArrayType()) {
792 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
793
794 if (sizeInBitsOverride)
795 sizeInBits = sizeInBitsOverride;
796 }
797
798 unsigned flags = 0;
799 if (AS == clang::AS_private)
800 flags |= llvm::DIDescriptor::FlagPrivate;
801 else if (AS == clang::AS_protected)
802 flags |= llvm::DIDescriptor::FlagProtected;
803
804 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
805 alignInBits, offsetInBits, flags, debugType);
806}
807
Eric Christopher91a31902013-01-16 01:22:32 +0000808/// CollectRecordLambdaFields - Helper for CollectRecordFields.
809void CGDebugInfo::
810CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
811 SmallVectorImpl<llvm::Value *> &elements,
812 llvm::DIType RecordTy) {
813 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
814 // has the name and the location of the variable so we should iterate over
815 // both concurrently.
816 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
817 RecordDecl::field_iterator Field = CXXDecl->field_begin();
818 unsigned fieldno = 0;
819 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
820 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
821 const LambdaExpr::Capture C = *I;
822 if (C.capturesVariable()) {
823 VarDecl *V = C.getCapturedVar();
824 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
825 StringRef VName = V->getName();
826 uint64_t SizeInBitsOverride = 0;
827 if (Field->isBitField()) {
828 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
829 assert(SizeInBitsOverride && "found named 0-width bitfield");
830 }
831 llvm::DIType fieldType
832 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
833 C.getLocation(), Field->getAccess(),
834 layout.getFieldOffset(fieldno), VUnit, RecordTy);
835 elements.push_back(fieldType);
836 } else {
837 // TODO: Need to handle 'this' in some way by probably renaming the
838 // this of the lambda class and having a field member of 'this' or
839 // by using AT_object_pointer for the function and having that be
840 // used as 'this' for semantic references.
841 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
842 FieldDecl *f = *Field;
843 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
844 QualType type = f->getType();
845 llvm::DIType fieldType
846 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
847 layout.getFieldOffset(fieldno), VUnit, RecordTy);
848
849 elements.push_back(fieldType);
850 }
851 }
852}
853
David Blaikie6943dea2013-08-20 01:28:15 +0000854/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000855llvm::DIDerivedType
856CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
857 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000858 // Create the descriptor for the static variable, with or without
859 // constant initializers.
860 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
861 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
862
Eric Christopher91a31902013-01-16 01:22:32 +0000863 unsigned LineNumber = getLineNumber(Var->getLocation());
864 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000865 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000866 if (Var->getInit()) {
867 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000868 if (Value) {
869 if (Value->isInt())
870 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
871 if (Value->isFloat())
872 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
873 }
Eric Christopher91a31902013-01-16 01:22:32 +0000874 }
875
876 unsigned Flags = 0;
877 AccessSpecifier Access = Var->getAccess();
878 if (Access == clang::AS_private)
879 Flags |= llvm::DIDescriptor::FlagPrivate;
880 else if (Access == clang::AS_protected)
881 Flags |= llvm::DIDescriptor::FlagProtected;
882
David Blaikieae019462013-08-15 22:50:29 +0000883 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
884 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000885 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000886 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000887}
888
889/// CollectRecordNormalField - Helper for CollectRecordFields.
890void CGDebugInfo::
891CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
892 llvm::DIFile tunit,
893 SmallVectorImpl<llvm::Value *> &elements,
894 llvm::DIType RecordTy) {
895 StringRef name = field->getName();
896 QualType type = field->getType();
897
898 // Ignore unnamed fields unless they're anonymous structs/unions.
899 if (name.empty() && !type->isRecordType())
900 return;
901
902 uint64_t SizeInBitsOverride = 0;
903 if (field->isBitField()) {
904 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
905 assert(SizeInBitsOverride && "found named 0-width bitfield");
906 }
907
908 llvm::DIType fieldType
909 = createFieldType(name, type, SizeInBitsOverride,
910 field->getLocation(), field->getAccess(),
911 OffsetInBits, tunit, RecordTy);
912
913 elements.push_back(fieldType);
914}
915
Guy Benyei11169dd2012-12-18 14:30:41 +0000916/// CollectRecordFields - A helper function to collect debug info for
917/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000918void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
919 llvm::DIFile tunit,
920 SmallVectorImpl<llvm::Value *> &elements,
921 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000922 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
923
Eric Christopher91a31902013-01-16 01:22:32 +0000924 if (CXXDecl && CXXDecl->isLambda())
925 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
926 else {
927 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000928
Eric Christopher91a31902013-01-16 01:22:32 +0000929 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000930 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000931
Eric Christopher91a31902013-01-16 01:22:32 +0000932 // Static and non-static members should appear in the same order as
933 // the corresponding declarations in the source program.
934 for (RecordDecl::decl_iterator I = record->decls_begin(),
935 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000936 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
937 // Reuse the existing static member declaration if one exists
938 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
939 StaticDataMemberCache.find(V->getCanonicalDecl());
940 if (MI != StaticDataMemberCache.end()) {
941 assert(MI->second &&
942 "Static data member declaration should still exist");
943 elements.push_back(
944 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
945 } else
946 elements.push_back(CreateRecordStaticField(V, RecordTy));
947 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000948 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
949 tunit, elements, RecordTy);
950
951 // Bump field number for next field.
952 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000954 }
955}
956
957/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
958/// function type is not updated to include implicit "this" pointer. Use this
959/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000960llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000961CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
962 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000963 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000964 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000965 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000966 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
967 Func, Unit);
968}
David Blaikie2aaf0652013-01-07 22:24:59 +0000969
David Blaikie469f0792013-05-22 23:22:42 +0000970llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000971 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000973 llvm::DIArray Args = llvm::DICompositeType(
974 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000975 assert (Args.getNumElements() && "Invalid number of arguments!");
976
977 SmallVector<llvm::Value *, 16> Elts;
978
979 // First element is always return type. For 'void' functions it is NULL.
980 Elts.push_back(Args.getElement(0));
981
David Blaikie2aaf0652013-01-07 22:24:59 +0000982 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000983 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000984 if (isa<ClassTemplateSpecializationDecl>(RD)) {
985 // Create pointer type directly in this case.
986 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
987 QualType PointeeTy = ThisPtrTy->getPointeeType();
988 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000989 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000990 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
991 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000992 llvm::DIType ThisPtrType =
993 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000994 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
995 // TODO: This and the artificial type below are misleading, the
996 // types aren't artificial the argument is, but the current
997 // metadata doesn't represent that.
998 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
999 Elts.push_back(ThisPtrType);
1000 } else {
1001 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1002 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1003 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1004 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 }
1006
1007 // Copy rest of the arguments.
1008 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1009 Elts.push_back(Args.getElement(i));
1010
1011 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1012
Adrian Prantl0630eb72013-12-18 21:48:18 +00001013 unsigned Flags = 0;
1014 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1015 Flags |= llvm::DIDescriptor::FlagLValueReference;
1016 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1017 Flags |= llvm::DIDescriptor::FlagRValueReference;
1018
1019 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001020}
1021
Eric Christopherb2a008c2013-05-16 00:45:12 +00001022/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001023/// inside a function.
1024static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1025 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1026 return isFunctionLocalClass(NRD);
1027 if (isa<FunctionDecl>(RD->getDeclContext()))
1028 return true;
1029 return false;
1030}
1031
1032/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1033/// a single member function GlobalDecl.
1034llvm::DISubprogram
1035CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1036 llvm::DIFile Unit,
1037 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001038 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001040
Guy Benyei11169dd2012-12-18 14:30:41 +00001041 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001042 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001043
1044 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1045 // make sense to give a single ctor/dtor a linkage name.
1046 StringRef MethodLinkageName;
1047 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1048 MethodLinkageName = CGM.getMangledName(Method);
1049
1050 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001051 llvm::DIFile MethodDefUnit;
1052 unsigned MethodLine = 0;
1053 if (!Method->isImplicit()) {
1054 MethodDefUnit = getOrCreateFile(Method->getLocation());
1055 MethodLine = getLineNumber(Method->getLocation());
1056 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001057
1058 // Collect virtual method info.
1059 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001060 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001062
Guy Benyei11169dd2012-12-18 14:30:41 +00001063 if (Method->isVirtual()) {
1064 if (Method->isPure())
1065 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1066 else
1067 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001068
Guy Benyei11169dd2012-12-18 14:30:41 +00001069 // It doesn't make sense to give a virtual destructor a vtable index,
1070 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001071 // FIXME: Add proper support for debug info for virtual calls in
1072 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1073 // lookup if we have multiple or virtual inheritance.
1074 if (!isa<CXXDestructorDecl>(Method) &&
1075 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001076 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001077 ContainingType = RecordTy;
1078 }
1079
1080 unsigned Flags = 0;
1081 if (Method->isImplicit())
1082 Flags |= llvm::DIDescriptor::FlagArtificial;
1083 AccessSpecifier Access = Method->getAccess();
1084 if (Access == clang::AS_private)
1085 Flags |= llvm::DIDescriptor::FlagPrivate;
1086 else if (Access == clang::AS_protected)
1087 Flags |= llvm::DIDescriptor::FlagProtected;
1088 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1089 if (CXXC->isExplicit())
1090 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001091 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001092 dyn_cast<CXXConversionDecl>(Method)) {
1093 if (CXXC->isExplicit())
1094 Flags |= llvm::DIDescriptor::FlagExplicit;
1095 }
1096 if (Method->hasPrototype())
1097 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001098 if (Method->getRefQualifier() == RQ_LValue)
1099 Flags |= llvm::DIDescriptor::FlagLValueReference;
1100 if (Method->getRefQualifier() == RQ_RValue)
1101 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
1103 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1104 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001105 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001107 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 /* isDefinition=*/ false,
1109 Virtuality, VIndex, ContainingType,
1110 Flags, CGM.getLangOpts().Optimize, NULL,
1111 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001112
Guy Benyei11169dd2012-12-18 14:30:41 +00001113 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1114
1115 return SP;
1116}
1117
1118/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001119/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001120/// a Record.
1121void CGDebugInfo::
1122CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1123 SmallVectorImpl<llvm::Value *> &EltTys,
1124 llvm::DIType RecordTy) {
1125
1126 // Since we want more than just the individual member decls if we
1127 // have templated functions iterate over every declaration to gather
1128 // the functions.
1129 for(DeclContext::decl_iterator I = RD->decls_begin(),
1130 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001131 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001132 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001133 // It may be associated with the declaration of the type & should be
1134 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001135 //
1136 // This situation can arise in the vtable-based debug info reduction where
1137 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001138 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1139 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001140 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001141 // If the member is implicit, lazily create it when we see the
1142 // definition, not before. (an ODR-used implicit default ctor that's
1143 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001144 if (!Method->isImplicit())
1145 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1146 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001147 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001148 } else if (const FunctionTemplateDecl *FTD =
1149 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001150 // Add any template specializations that have already been seen. Like
1151 // implicit member functions, these may have been added to a declaration
1152 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001153 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1154 SE = FTD->spec_end();
1155 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001156 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1157 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1158 if (MI != SPCache.end())
1159 EltTys.push_back(MI->second);
1160 }
David Blaikie6943dea2013-08-20 01:28:15 +00001161 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001163}
Guy Benyei11169dd2012-12-18 14:30:41 +00001164
Guy Benyei11169dd2012-12-18 14:30:41 +00001165/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001166/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001167/// a Record.
1168void CGDebugInfo::
1169CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1170 SmallVectorImpl<llvm::Value *> &EltTys,
1171 llvm::DIType RecordTy) {
1172
1173 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1174 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1175 BE = RD->bases_end(); BI != BE; ++BI) {
1176 unsigned BFlags = 0;
1177 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001178
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 const CXXRecordDecl *Base =
1180 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001181
Guy Benyei11169dd2012-12-18 14:30:41 +00001182 if (BI->isVirtual()) {
1183 // virtual base offset offset is -ve. The code generator emits dwarf
1184 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001185 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001186 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001187 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1188 BFlags = llvm::DIDescriptor::FlagVirtual;
1189 } else
1190 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1191 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1192 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001193
Guy Benyei11169dd2012-12-18 14:30:41 +00001194 AccessSpecifier Access = BI->getAccessSpecifier();
1195 if (Access == clang::AS_private)
1196 BFlags |= llvm::DIDescriptor::FlagPrivate;
1197 else if (Access == clang::AS_protected)
1198 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001199
1200 llvm::DIType DTy =
1201 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 getOrCreateType(BI->getType(), Unit),
1203 BaseOffset, BFlags);
1204 EltTys.push_back(DTy);
1205 }
1206}
1207
1208/// CollectTemplateParams - A helper function to collect template parameters.
1209llvm::DIArray CGDebugInfo::
1210CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001211 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001213 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001214 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1215 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001216 StringRef Name;
1217 if (TPList)
1218 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001219 switch (TA.getKind()) {
1220 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001221 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1222 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001223 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001224 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001225 } break;
1226 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001227 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1228 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001229 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001230 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001231 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1232 TemplateParams.push_back(TVP);
1233 } break;
1234 case TemplateArgument::Declaration: {
1235 const ValueDecl *D = TA.getAsDecl();
1236 bool InstanceMember = D->isCXXInstanceMember();
1237 QualType T = InstanceMember
1238 ? CGM.getContext().getMemberPointerType(
1239 D->getType(), cast<RecordDecl>(D->getDeclContext())
1240 ->getTypeForDecl())
1241 : CGM.getContext().getPointerType(D->getType());
1242 llvm::DIType TTy = getOrCreateType(T, Unit);
1243 llvm::Value *V = 0;
1244 // Variable pointer template parameters have a value that is the address
1245 // of the variable.
1246 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1247 V = CGM.GetAddrOfGlobalVar(VD);
1248 // Member function pointers have special support for building them, though
1249 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001250 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001251 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1252 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001253 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1254 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001255 // Member data pointers have special handling too to compute the fixed
1256 // offset within the object.
1257 if (isa<FieldDecl>(D)) {
1258 // These five lines (& possibly the above member function pointer
1259 // handling) might be able to be refactored to use similar code in
1260 // CodeGenModule::getMemberPointerConstant
1261 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1262 CharUnits chars =
1263 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1264 V = CGM.getCXXABI().EmitMemberDataPointer(
1265 cast<MemberPointerType>(T.getTypePtr()), chars);
1266 }
1267 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001268 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1269 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001270 TemplateParams.push_back(TVP);
1271 } break;
1272 case TemplateArgument::NullPtr: {
1273 QualType T = TA.getNullPtrType();
1274 llvm::DIType TTy = getOrCreateType(T, Unit);
1275 llvm::Value *V = 0;
1276 // Special case member data pointer null values since they're actually -1
1277 // instead of zero.
1278 if (const MemberPointerType *MPT =
1279 dyn_cast<MemberPointerType>(T.getTypePtr()))
1280 // But treat member function pointers as simple zero integers because
1281 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1282 // CodeGen grows handling for values of non-null member function
1283 // pointers then perhaps we could remove this special case and rely on
1284 // EmitNullMemberPointer for member function pointers.
1285 if (MPT->isMemberDataPointer())
1286 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1287 if (!V)
1288 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1289 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001290 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001291 TemplateParams.push_back(TVP);
1292 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001293 case TemplateArgument::Template: {
1294 llvm::DITemplateValueParameter TVP =
1295 DBuilder.createTemplateTemplateParameter(
1296 TheCU, Name, llvm::DIType(),
1297 TA.getAsTemplate().getAsTemplateDecl()
1298 ->getQualifiedNameAsString());
1299 TemplateParams.push_back(TVP);
1300 } break;
1301 case TemplateArgument::Pack: {
1302 llvm::DITemplateValueParameter TVP =
1303 DBuilder.createTemplateParameterPack(
1304 TheCU, Name, llvm::DIType(),
1305 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1306 TemplateParams.push_back(TVP);
1307 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001308 case TemplateArgument::Expression: {
1309 const Expr *E = TA.getAsExpr();
1310 QualType T = E->getType();
1311 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1312 assert(V && "Expression in template argument isn't constant");
1313 llvm::DIType TTy = getOrCreateType(T, Unit);
1314 llvm::DITemplateValueParameter TVP =
1315 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1316 V->stripPointerCasts());
1317 TemplateParams.push_back(TVP);
1318 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001319 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001320 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001321 case TemplateArgument::Null:
1322 llvm_unreachable(
1323 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001324 }
1325 }
1326 return DBuilder.getOrCreateArray(TemplateParams);
1327}
1328
1329/// CollectFunctionTemplateParams - A helper function to collect debug
1330/// info for function template parameters.
1331llvm::DIArray CGDebugInfo::
1332CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1333 if (FD->getTemplatedKind() ==
1334 FunctionDecl::TK_FunctionTemplateSpecialization) {
1335 const TemplateParameterList *TList =
1336 FD->getTemplateSpecializationInfo()->getTemplate()
1337 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001338 return CollectTemplateParams(
1339 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001340 }
1341 return llvm::DIArray();
1342}
1343
1344/// CollectCXXTemplateParams - A helper function to collect debug info for
1345/// template parameters.
1346llvm::DIArray CGDebugInfo::
1347CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1348 llvm::DIFile Unit) {
1349 llvm::PointerUnion<ClassTemplateDecl *,
1350 ClassTemplatePartialSpecializationDecl *>
1351 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001352
Guy Benyei11169dd2012-12-18 14:30:41 +00001353 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1354 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1355 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1356 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001357 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001358}
1359
1360/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1361llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1362 if (VTablePtrType.isValid())
1363 return VTablePtrType;
1364
1365 ASTContext &Context = CGM.getContext();
1366
1367 /* Function type */
1368 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1369 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1370 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1371 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1372 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1373 "__vtbl_ptr_type");
1374 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1375 return VTablePtrType;
1376}
1377
1378/// getVTableName - Get vtable name for the given Class.
1379StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001380 // Copy the gdb compatible name on the side and use its reference.
1381 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001382}
1383
1384
1385/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1386/// debug info entry in EltTys vector.
1387void CGDebugInfo::
1388CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1389 SmallVectorImpl<llvm::Value *> &EltTys) {
1390 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1391
1392 // If there is a primary base then it will hold vtable info.
1393 if (RL.getPrimaryBase())
1394 return;
1395
1396 // If this class is not dynamic then there is not any vtable info to collect.
1397 if (!RD->isDynamicClass())
1398 return;
1399
1400 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1401 llvm::DIType VPTR
1402 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001403 0, Size, 0, 0,
1404 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001405 getOrCreateVTablePtrType(Unit));
1406 EltTys.push_back(VPTR);
1407}
1408
Eric Christopherb2a008c2013-05-16 00:45:12 +00001409/// getOrCreateRecordType - Emit record type's standalone debug info.
1410llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001412 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1414 return T;
1415}
1416
1417/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1418/// debug info.
1419llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001420 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001421 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001423 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001424 return T;
1425}
1426
David Blaikieb2e86eb2013-08-15 20:49:17 +00001427void CGDebugInfo::completeType(const RecordDecl *RD) {
1428 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1429 !CGM.getLangOpts().CPlusPlus)
1430 completeRequiredType(RD);
1431}
1432
1433void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001434 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1435 if (CXXDecl->isDynamicClass())
1436 return;
1437
David Blaikieb2e86eb2013-08-15 20:49:17 +00001438 QualType Ty = CGM.getContext().getRecordType(RD);
1439 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001440 if (T && T.isForwardDecl())
1441 completeClassData(RD);
1442}
1443
1444void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1445 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001446 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001447 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001448 void* TyPtr = Ty.getAsOpaquePtr();
1449 if (CompletedTypeCache.count(TyPtr))
1450 return;
1451 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1452 assert(!Res.isForwardDecl());
1453 CompletedTypeCache[TyPtr] = Res;
1454 TypeCache[TyPtr] = Res;
1455}
1456
Guy Benyei11169dd2012-12-18 14:30:41 +00001457/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001458llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001459 RecordDecl *RD = Ty->getDecl();
David Blaikie6943dea2013-08-20 01:28:15 +00001460 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie99dab3b2013-09-04 22:03:57 +00001461 // Always emit declarations for types that aren't required to be complete when
1462 // in limit-debug-info mode. If the type is later found to be required to be
1463 // complete this declaration will be upgraded to a definition by
1464 // `completeRequiredType`.
1465 // If the type is dynamic, only emit the definition in TUs that require class
1466 // data. This is handled by `completeClassData`.
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001467 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1468 // If we've already emitted the type, just use that, even if it's only a
1469 // declaration. The completeType, completeRequiredType, and completeClassData
1470 // callbacks will handle promoting the declaration to a definition.
1471 if (T ||
Adrian Prantld09906f2014-01-07 02:40:59 +00001472 // Under -fno-standalone-debug:
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001473 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
Adrian Prantla7634472014-01-07 01:19:08 +00001474 // Emit only a forward declaration unless the type is required.
1475 ((!RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1476 // If the class is dynamic, only emit a declaration. A definition will be
1477 // emitted whenever the vtable is emitted.
1478 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())))) {
David Blaikiee36464c2013-06-05 05:32:23 +00001479 llvm::DIDescriptor FDContext =
1480 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001481 if (!T)
1482 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1483 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001484 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001485
David Blaikieb2e86eb2013-08-15 20:49:17 +00001486 return CreateTypeDefinition(Ty);
1487}
1488
1489llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1490 RecordDecl *RD = Ty->getDecl();
1491
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 // Get overall information about the record type for the debug info.
1493 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1494
1495 // Records and classes and unions can all be recursive. To handle them, we
1496 // first generate a debug descriptor for the struct as a forward declaration.
1497 // Then (if it is a definition) we go through and get debug info for all of
1498 // its members. Finally, we create a descriptor for the complete type (which
1499 // may refer to the forward decl if the struct is recursive) and replace all
1500 // uses of the forward declaration with the final definition.
1501
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001502 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001503 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001504 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001505
1506 if (FwdDecl.isForwardDecl())
1507 return FwdDecl;
1508
David Blaikieadfbf992013-08-18 16:55:33 +00001509 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1510 CollectContainingType(CXXDecl, FwdDecl);
1511
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001513 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001514 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1515
Adrian Prantla03a85a2013-03-06 22:03:30 +00001516 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1518
1519 // Convert all the elements.
1520 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001521 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001522
1523 // Note: The split of CXXDecl information here is intentional, the
1524 // gdb tests will depend on a certain ordering at printout. The debug
1525 // information offsets are still correct if we merge them all together
1526 // though.
1527 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1528 if (CXXDecl) {
1529 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1530 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1531 }
1532
Eric Christopher91a31902013-01-16 01:22:32 +00001533 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001535 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001537
1538 LexicalBlockStack.pop_back();
1539 RegionMap.erase(Ty->getDecl());
1540
1541 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001542 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001544 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1545 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001546}
1547
1548/// CreateType - get objective-c object type.
1549llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1550 llvm::DIFile Unit) {
1551 // Ignore protocols.
1552 return getOrCreateType(Ty->getBaseType(), Unit);
1553}
1554
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001555
1556/// \return true if Getter has the default name for the property PD.
1557static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1558 const ObjCMethodDecl *Getter) {
1559 assert(PD);
1560 if (!Getter)
1561 return true;
1562
1563 assert(Getter->getDeclName().isObjCZeroArgSelector());
1564 return PD->getName() ==
1565 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1566}
1567
1568/// \return true if Setter has the default name for the property PD.
1569static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1570 const ObjCMethodDecl *Setter) {
1571 assert(PD);
1572 if (!Setter)
1573 return true;
1574
1575 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001576 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001577 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1578}
1579
Guy Benyei11169dd2012-12-18 14:30:41 +00001580/// CreateType - get objective-c interface type.
1581llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1582 llvm::DIFile Unit) {
1583 ObjCInterfaceDecl *ID = Ty->getDecl();
1584 if (!ID)
1585 return llvm::DIType();
1586
1587 // Get overall information about the record type for the debug info.
1588 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1589 unsigned Line = getLineNumber(ID->getLocation());
1590 unsigned RuntimeLang = TheCU.getLanguage();
1591
1592 // If this is just a forward declaration return a special forward-declaration
1593 // debug type since we won't be able to lay out the entire type.
1594 ObjCInterfaceDecl *Def = ID->getDefinition();
1595 if (!Def) {
1596 llvm::DIType FwdDecl =
1597 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001598 ID->getName(), TheCU, DefUnit, Line,
1599 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001600 return FwdDecl;
1601 }
1602
1603 ID = Def;
1604
1605 // Bit size, align and offset of the type.
1606 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1607 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1608
1609 unsigned Flags = 0;
1610 if (ID->getImplementation())
1611 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1612
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001613 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1615 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001616 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001617
1618 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1619 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001620 QualType QualTy = QualType(Ty, 0);
1621 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001622
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001623 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001624 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001625 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1626
1627 // Convert all the elements.
1628 SmallVector<llvm::Value *, 16> EltTys;
1629
1630 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1631 if (SClass) {
1632 llvm::DIType SClassTy =
1633 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1634 if (!SClassTy.isValid())
1635 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001636
Guy Benyei11169dd2012-12-18 14:30:41 +00001637 llvm::DIType InhTag =
1638 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1639 EltTys.push_back(InhTag);
1640 }
1641
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001642 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001643 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1644 E = ID->prop_end(); I != E; ++I) {
1645 const ObjCPropertyDecl *PD = *I;
1646 SourceLocation Loc = PD->getLocation();
1647 llvm::DIFile PUnit = getOrCreateFile(Loc);
1648 unsigned PLine = getLineNumber(Loc);
1649 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1650 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1651 llvm::MDNode *PropertyNode =
1652 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001653 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001654 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001656 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001657 getSelectorName(PD->getSetterName()),
1658 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001659 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001660 EltTys.push_back(PropertyNode);
1661 }
1662
1663 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1664 unsigned FieldNo = 0;
1665 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1666 Field = Field->getNextIvar(), ++FieldNo) {
1667 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1668 if (!FieldTy.isValid())
1669 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001670
Guy Benyei11169dd2012-12-18 14:30:41 +00001671 StringRef FieldName = Field->getName();
1672
1673 // Ignore unnamed fields.
1674 if (FieldName.empty())
1675 continue;
1676
1677 // Get the location for the field.
1678 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1679 unsigned FieldLine = getLineNumber(Field->getLocation());
1680 QualType FType = Field->getType();
1681 uint64_t FieldSize = 0;
1682 unsigned FieldAlign = 0;
1683
1684 if (!FType->isIncompleteArrayType()) {
1685
1686 // Bit size, align and offset of the type.
1687 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001688 ? Field->getBitWidthValue(CGM.getContext())
1689 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001690 FieldAlign = CGM.getContext().getTypeAlign(FType);
1691 }
1692
1693 uint64_t FieldOffset;
1694 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1695 // We don't know the runtime offset of an ivar if we're using the
1696 // non-fragile ABI. For bitfields, use the bit offset into the first
1697 // byte of storage of the bitfield. For other fields, use zero.
1698 if (Field->isBitField()) {
1699 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1700 CGM, ID, Field);
1701 FieldOffset %= CGM.getContext().getCharWidth();
1702 } else {
1703 FieldOffset = 0;
1704 }
1705 } else {
1706 FieldOffset = RL.getFieldOffset(FieldNo);
1707 }
1708
1709 unsigned Flags = 0;
1710 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1711 Flags = llvm::DIDescriptor::FlagProtected;
1712 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1713 Flags = llvm::DIDescriptor::FlagPrivate;
1714
1715 llvm::MDNode *PropertyNode = NULL;
1716 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001717 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1719 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001720 SourceLocation Loc = PD->getLocation();
1721 llvm::DIFile PUnit = getOrCreateFile(Loc);
1722 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1724 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1725 PropertyNode =
1726 DBuilder.createObjCProperty(PD->getName(),
1727 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001728 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001730 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001731 getSelectorName(PD->getSetterName()),
1732 PD->getPropertyAttributes(),
1733 getOrCreateType(PD->getType(), PUnit));
1734 }
1735 }
1736 }
1737 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1738 FieldLine, FieldSize, FieldAlign,
1739 FieldOffset, Flags, FieldTy,
1740 PropertyNode);
1741 EltTys.push_back(FieldTy);
1742 }
1743
1744 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001745 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001746
1747 // If the implementation is not yet set, we do not want to mark it
1748 // as complete. An implementation may declare additional
1749 // private ivars that we would miss otherwise.
1750 if (ID->getImplementation() == 0)
1751 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001752
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001754 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001755}
1756
1757llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1758 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1759 int64_t Count = Ty->getNumElements();
1760 if (Count == 0)
1761 // If number of elements are not known then this is an unbounded array.
1762 // Use Count == -1 to express such arrays.
1763 Count = -1;
1764
1765 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1766 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1767
1768 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1769 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1770
1771 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1772}
1773
1774llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1775 llvm::DIFile Unit) {
1776 uint64_t Size;
1777 uint64_t Align;
1778
1779 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1780 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1781 Size = 0;
1782 Align =
1783 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1784 } else if (Ty->isIncompleteArrayType()) {
1785 Size = 0;
1786 if (Ty->getElementType()->isIncompleteType())
1787 Align = 0;
1788 else
1789 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001790 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001791 Size = 0;
1792 Align = 0;
1793 } else {
1794 // Size and align of the whole array, not the element type.
1795 Size = CGM.getContext().getTypeSize(Ty);
1796 Align = CGM.getContext().getTypeAlign(Ty);
1797 }
1798
1799 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1800 // interior arrays, do we care? Why aren't nested arrays represented the
1801 // obvious/recursive way?
1802 SmallVector<llvm::Value *, 8> Subscripts;
1803 QualType EltTy(Ty, 0);
1804 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1805 // If the number of elements is known, then count is that number. Otherwise,
1806 // it's -1. This allows us to represent a subrange with an array of 0
1807 // elements, like this:
1808 //
1809 // struct foo {
1810 // int x[0];
1811 // };
1812 int64_t Count = -1; // Count == -1 is an unbounded array.
1813 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1814 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001815
Guy Benyei11169dd2012-12-18 14:30:41 +00001816 // FIXME: Verify this is right for VLAs.
1817 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1818 EltTy = Ty->getElementType();
1819 }
1820
1821 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1822
Eric Christopherb2a008c2013-05-16 00:45:12 +00001823 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001824 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1825 SubscriptArray);
1826 return DbgTy;
1827}
1828
Eric Christopherb2a008c2013-05-16 00:45:12 +00001829llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001831 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 Ty, Ty->getPointeeType(), Unit);
1833}
1834
Eric Christopherb2a008c2013-05-16 00:45:12 +00001835llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001836 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001837 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001838 Ty, Ty->getPointeeType(), Unit);
1839}
1840
Eric Christopherb2a008c2013-05-16 00:45:12 +00001841llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001842 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001843 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1844 if (!Ty->getPointeeType()->isFunctionType())
1845 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001846 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001847
1848 const FunctionProtoType *FPT =
1849 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001850 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001851 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1852 FPT->getTypeQuals())),
1853 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001854}
1855
Eric Christopherb2a008c2013-05-16 00:45:12 +00001856llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 llvm::DIFile U) {
1858 // Ignore the atomic wrapping
1859 // FIXME: What is the correct representation?
1860 return getOrCreateType(Ty->getValueType(), U);
1861}
1862
1863/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001864llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001865 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001866 uint64_t Size = 0;
1867 uint64_t Align = 0;
1868 if (!ED->getTypeForDecl()->isIncompleteType()) {
1869 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1870 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1871 }
1872
Manman Rene0064d82013-08-29 23:19:58 +00001873 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1874
Guy Benyei11169dd2012-12-18 14:30:41 +00001875 // If this is just a forward declaration, construct an appropriately
1876 // marked node and just return it.
1877 if (!ED->getDefinition()) {
1878 llvm::DIDescriptor EDContext;
1879 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1880 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1881 unsigned Line = getLineNumber(ED->getLocation());
1882 StringRef EDName = ED->getName();
1883 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1884 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001885 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001886 }
1887
1888 // Create DIEnumerator elements for each enumerator.
1889 SmallVector<llvm::Value *, 16> Enumerators;
1890 ED = ED->getDefinition();
1891 for (EnumDecl::enumerator_iterator
1892 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1893 Enum != EnumEnd; ++Enum) {
1894 Enumerators.push_back(
1895 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001896 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001897 }
1898
1899 // Return a CompositeType for the enum itself.
1900 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1901
1902 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1903 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001904 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001906 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001908 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001909 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1910 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001911 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001912 return DbgTy;
1913}
1914
David Blaikie05491062013-01-21 04:37:12 +00001915static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1916 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001917 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001918 Qualifiers InnerQuals = T.getLocalQualifiers();
1919 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1920 // that is already there.
1921 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1922 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001923 QualType LastT = T;
1924 switch (T->getTypeClass()) {
1925 default:
David Blaikie05491062013-01-21 04:37:12 +00001926 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001927 case Type::TemplateSpecialization:
1928 T = cast<TemplateSpecializationType>(T)->desugar();
1929 break;
1930 case Type::TypeOfExpr:
1931 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1932 break;
1933 case Type::TypeOf:
1934 T = cast<TypeOfType>(T)->getUnderlyingType();
1935 break;
1936 case Type::Decltype:
1937 T = cast<DecltypeType>(T)->getUnderlyingType();
1938 break;
1939 case Type::UnaryTransform:
1940 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1941 break;
1942 case Type::Attributed:
1943 T = cast<AttributedType>(T)->getEquivalentType();
1944 break;
1945 case Type::Elaborated:
1946 T = cast<ElaboratedType>(T)->getNamedType();
1947 break;
1948 case Type::Paren:
1949 T = cast<ParenType>(T)->getInnerType();
1950 break;
David Blaikie05491062013-01-21 04:37:12 +00001951 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001952 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001953 break;
1954 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001955 QualType DT = cast<AutoType>(T)->getDeducedType();
1956 if (DT.isNull())
1957 return T;
1958 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001959 break;
1960 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001961
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001963 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001964 } while (true);
1965}
1966
Eric Christopher0fdcb312013-05-16 00:52:20 +00001967/// getType - Get the type from the cache or return null type if it doesn't
1968/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001969llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1970
1971 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001972 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001973
Guy Benyei11169dd2012-12-18 14:30:41 +00001974 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001975 if (Ty->getTypeClass() == Type::ObjCInterface) {
1976 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1977 if (V)
1978 return llvm::DIType(cast<llvm::MDNode>(V));
1979 else return llvm::DIType();
1980 }
1981
Guy Benyei11169dd2012-12-18 14:30:41 +00001982 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1983 TypeCache.find(Ty.getAsOpaquePtr());
1984 if (it != TypeCache.end()) {
1985 // Verify that the debug info still exists.
1986 if (llvm::Value *V = it->second)
1987 return llvm::DIType(cast<llvm::MDNode>(V));
1988 }
1989
1990 return llvm::DIType();
1991}
1992
1993/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1994/// doesn't exist.
1995llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1996
1997 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001998 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001999
2000 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00002001 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002002 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2003 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002004 if (it != CompletedTypeCache.end())
2005 V = it->second;
2006 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002007 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002008 }
2009
Adrian Prantla03a85a2013-03-06 22:03:30 +00002010 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002011 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002012}
2013
Adrian Prantl73409ce2013-03-11 18:33:46 +00002014/// getCachedInterfaceTypeOrNull - Get the type from the interface
2015/// cache, unless it needs to regenerated. Otherwise return null.
2016llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2017 // Is there a cached interface that hasn't changed?
2018 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2019 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2020
2021 if (it1 != ObjCInterfaceCache.end())
2022 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2023 if (Checksum(Decl) == it1->second.second)
2024 // Return cached forward declaration.
2025 return it1->second.first;
2026
2027 return 0;
2028}
Guy Benyei11169dd2012-12-18 14:30:41 +00002029
2030/// getOrCreateType - Get the type from the cache or create a new
2031/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002032llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 if (Ty.isNull())
2034 return llvm::DIType();
2035
2036 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002037 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002038
David Blaikie99dab3b2013-09-04 22:03:57 +00002039 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002040 return T;
2041
2042 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002043 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002044 void* TyPtr = Ty.getAsOpaquePtr();
2045
2046 // And update the type cache.
2047 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002048
David Blaikie6a723442013-08-15 21:21:19 +00002049 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2050 // into the cache - but getTypeOrNull has a special case for cached interface
2051 // types. We should probably just pull that out as a special case for the
2052 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002053 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002054 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002055 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2056 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2057 // Interface types may have elements added to them by a
2058 // subsequent implementation or extension, so we keep them in
2059 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002060 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002061 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002062 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2063 if (V.first)
2064 return llvm::DIType(cast<llvm::MDNode>(V.first));
2065 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2066 Decl->getName(), TheCU, Unit,
2067 getLineNumber(Decl->getLocation()),
2068 TheCU.getLanguage());
2069 // Store the forward declaration in the cache.
2070 V.first = TC;
2071 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002072
David Blaikie8e5939b2013-05-21 18:29:40 +00002073 // Register the type for replacement in finalize().
2074 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2075
Adrian Prantl73409ce2013-03-11 18:33:46 +00002076 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002077 }
2078
Guy Benyei11169dd2012-12-18 14:30:41 +00002079 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002080 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002081
2082 return Res;
2083}
2084
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002085/// Currently the checksum of an interface includes the number of
2086/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002087unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002088 // The assumption is that the number of ivars can only increase
2089 // monotonically, so it is safe to just use their current number as
2090 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002091 unsigned Sum = 0;
2092 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2093 Ivar != 0; Ivar = Ivar->getNextIvar())
2094 ++Sum;
2095
2096 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002097}
2098
2099ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2100 switch (Ty->getTypeClass()) {
2101 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002102 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2103 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002104 case Type::ObjCInterface:
2105 return cast<ObjCInterfaceType>(Ty)->getDecl();
2106 default:
2107 return 0;
2108 }
2109}
2110
Guy Benyei11169dd2012-12-18 14:30:41 +00002111/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002112llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002113 // Handle qualifiers, which recursively handles what they refer to.
2114 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002115 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002116
2117 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002118
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 // Work out details of type.
2120 switch (Ty->getTypeClass()) {
2121#define TYPE(Class, Base)
2122#define ABSTRACT_TYPE(Class, Base)
2123#define NON_CANONICAL_TYPE(Class, Base)
2124#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2125#include "clang/AST/TypeNodes.def"
2126 llvm_unreachable("Dependent types cannot show up in debug information");
2127
2128 case Type::ExtVector:
2129 case Type::Vector:
2130 return CreateType(cast<VectorType>(Ty), Unit);
2131 case Type::ObjCObjectPointer:
2132 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2133 case Type::ObjCObject:
2134 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2135 case Type::ObjCInterface:
2136 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2137 case Type::Builtin:
2138 return CreateType(cast<BuiltinType>(Ty));
2139 case Type::Complex:
2140 return CreateType(cast<ComplexType>(Ty));
2141 case Type::Pointer:
2142 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002143 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002144 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002145 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002146 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002147 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002148 case Type::BlockPointer:
2149 return CreateType(cast<BlockPointerType>(Ty), Unit);
2150 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002151 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002153 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002155 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002156 case Type::FunctionProto:
2157 case Type::FunctionNoProto:
2158 return CreateType(cast<FunctionType>(Ty), Unit);
2159 case Type::ConstantArray:
2160 case Type::VariableArray:
2161 case Type::IncompleteArray:
2162 return CreateType(cast<ArrayType>(Ty), Unit);
2163
2164 case Type::LValueReference:
2165 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2166 case Type::RValueReference:
2167 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2168
2169 case Type::MemberPointer:
2170 return CreateType(cast<MemberPointerType>(Ty), Unit);
2171
2172 case Type::Atomic:
2173 return CreateType(cast<AtomicType>(Ty), Unit);
2174
2175 case Type::Attributed:
2176 case Type::TemplateSpecialization:
2177 case Type::Elaborated:
2178 case Type::Paren:
2179 case Type::SubstTemplateTypeParm:
2180 case Type::TypeOfExpr:
2181 case Type::TypeOf:
2182 case Type::Decltype:
2183 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002184 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002186 case Type::Auto:
2187 Diag = "auto";
2188 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002189 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002190
Guy Benyei11169dd2012-12-18 14:30:41 +00002191 assert(Diag && "Fall through without a diagnostic?");
2192 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2193 "debug information for %0 is not yet supported");
2194 CGM.getDiags().Report(DiagID)
2195 << Diag;
2196 return llvm::DIType();
2197}
2198
2199/// getOrCreateLimitedType - Get the type from the cache or create a new
2200/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002201llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002202 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002203 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
David Blaikie8d5e1282013-08-20 21:03:29 +00002205 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002206
2207 // We may have cached a forward decl when we could have created
2208 // a non-forward decl. Go ahead and create a non-forward decl
2209 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002210 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002211
2212 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002213 llvm::DICompositeType Res = CreateLimitedType(Ty);
2214
2215 // Propagate members from the declaration to the definition
2216 // CreateType(const RecordType*) will overwrite this with the members in the
2217 // correct order if the full type is needed.
2218 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002219
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002220 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002221 ReplaceMap.push_back(
2222 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002223
2224 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002225 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 return Res;
2227}
2228
2229// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002230llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002232
Guy Benyei11169dd2012-12-18 14:30:41 +00002233 // Get overall information about the record type for the debug info.
2234 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2235 unsigned Line = getLineNumber(RD->getLocation());
2236 StringRef RDName = getClassName(RD);
2237
Eric Christopher07429ff2013-10-15 21:22:34 +00002238 llvm::DIDescriptor RDContext =
2239 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002240
David Blaikied2785892013-08-18 17:36:19 +00002241 // If we ended up creating the type during the context chain construction,
2242 // just return that.
2243 // FIXME: this could be dealt with better if the type was recorded as
2244 // completed before we started this (see the CompletedTypeCache usage in
2245 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2246 // be pushed to before context creation, but after it was known to be
2247 // destined for completion (might still have an issue if this caller only
2248 // required a declaration but the context construction ended up creating a
2249 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002250 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2251 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002252 return T;
2253
Guy Benyei11169dd2012-12-18 14:30:41 +00002254 // If this is just a forward declaration, construct an appropriately
2255 // marked node and just return it.
2256 if (!RD->getDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002257 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002258
2259 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2260 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002261 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002262
Manman Rene0064d82013-08-29 23:19:58 +00002263 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2264
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 if (RD->isUnion())
2266 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002267 Size, Align, 0, llvm::DIArray(), 0,
2268 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002269 else if (RD->isClass()) {
2270 // FIXME: This could be a struct type giving a default visibility different
2271 // than C++ class type, but needs llvm metadata changes first.
2272 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002273 Size, Align, 0, 0, llvm::DIType(),
2274 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002275 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 } else
2277 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002278 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002279 llvm::DIArray(), 0, llvm::DIType(),
2280 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002281
2282 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002283 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002284
David Blaikieadfbf992013-08-18 16:55:33 +00002285 if (const ClassTemplateSpecializationDecl *TSpecial =
2286 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2287 RealDecl.setTypeArray(llvm::DIArray(),
2288 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002289 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002290}
2291
David Blaikieadfbf992013-08-18 16:55:33 +00002292void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2293 llvm::DICompositeType RealDecl) {
2294 // A class's primary base or the class itself contains the vtable.
2295 llvm::DICompositeType ContainingType;
2296 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2297 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002298 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002299 while (1) {
2300 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2301 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2302 if (PBT && !BRL.isPrimaryBaseVirtual())
2303 PBase = PBT;
2304 else
2305 break;
2306 }
2307 ContainingType = llvm::DICompositeType(
2308 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2309 getOrCreateFile(RD->getLocation())));
2310 } else if (RD->isDynamicClass())
2311 ContainingType = RealDecl;
2312
2313 RealDecl.setContainingType(ContainingType);
2314}
2315
Guy Benyei11169dd2012-12-18 14:30:41 +00002316/// CreateMemberType - Create new member and increase Offset by FType's size.
2317llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2318 StringRef Name,
2319 uint64_t *Offset) {
2320 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2321 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2322 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2323 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2324 FieldSize, FieldAlign,
2325 *Offset, 0, FieldTy);
2326 *Offset += FieldSize;
2327 return Ty;
2328}
2329
David Blaikiebd483762013-05-20 04:58:53 +00002330llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2331 // We only need a declaration (not a definition) of the type - so use whatever
2332 // we would otherwise do to get a type for a pointee. (forward declarations in
2333 // limited debug info, full definitions (if the type definition is available)
2334 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002335 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2336 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002337 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002338 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2339 // This doesn't handle providing declarations (for functions or variables) for
2340 // entities without definitions in this TU, nor when the definition proceeds
2341 // the call to this function.
2342 // FIXME: This should be split out into more specific maps with support for
2343 // emitting forward declarations and merging definitions with declarations,
2344 // the same way as we do for types.
2345 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2346 DeclCache.find(D->getCanonicalDecl());
2347 if (I == DeclCache.end())
2348 return llvm::DIDescriptor();
2349 llvm::Value *V = I->second;
2350 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2351}
2352
Guy Benyei11169dd2012-12-18 14:30:41 +00002353/// getFunctionDeclaration - Return debug info descriptor to describe method
2354/// declaration for the given method definition.
2355llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002356 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2357 return llvm::DISubprogram();
2358
Guy Benyei11169dd2012-12-18 14:30:41 +00002359 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2360 if (!FD) return llvm::DISubprogram();
2361
2362 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002363 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002364
2365 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2366 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002367 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002368 if (const CXXMethodDecl *MD =
2369 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002370 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002371 llvm::DISubprogram SP =
2372 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002373 return SP;
2374 }
2375 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 if (MI != SPCache.end()) {
2377 llvm::Value *V = MI->second;
2378 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002379 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002380 return SP;
2381 }
2382
2383 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2384 E = FD->redecls_end(); I != E; ++I) {
2385 const FunctionDecl *NextFD = *I;
2386 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2387 MI = SPCache.find(NextFD->getCanonicalDecl());
2388 if (MI != SPCache.end()) {
2389 llvm::Value *V = MI->second;
2390 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002391 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002392 return SP;
2393 }
2394 }
2395 return llvm::DISubprogram();
2396}
2397
2398// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2399// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002400llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2401 QualType FnType,
2402 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002403 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2404 // Create fake but valid subroutine type. Otherwise
2405 // llvm::DISubprogram::Verify() would return false, and
2406 // subprogram DIE will miss DW_AT_decl_file and
2407 // DW_AT_decl_line fields.
2408 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002409
2410 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2411 return getOrCreateMethodType(Method, F);
2412 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2413 // Add "self" and "_cmd"
2414 SmallVector<llvm::Value *, 16> Elts;
2415
2416 // First element is always return type. For 'void' functions it is NULL.
Alp Toker314cc812014-01-25 16:55:45 +00002417 QualType ResultTy = OMethod->getReturnType();
Adrian Prantl5f360102013-05-22 21:37:49 +00002418
2419 // Replace the instancetype keyword with the actual type.
2420 if (ResultTy == CGM.getContext().getObjCInstanceType())
2421 ResultTy = CGM.getContext().getPointerType(
2422 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2423
Adrian Prantl7bec9032013-05-10 21:08:31 +00002424 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002425 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002426 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2427 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2428 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 // "_cmd" pointer is always second argument.
2430 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2431 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2432 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002433 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002434 PE = OMethod->param_end(); PI != PE; ++PI)
2435 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2436
2437 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2438 return DBuilder.createSubroutineType(F, EltTypeArray);
2439 }
David Blaikie469f0792013-05-22 23:22:42 +00002440 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002441}
2442
2443/// EmitFunctionStart - Constructs the debug code for entering a function.
2444void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2445 llvm::Function *Fn,
2446 CGBuilderTy &Builder) {
2447
2448 StringRef Name;
2449 StringRef LinkageName;
2450
2451 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2452
2453 const Decl *D = GD.getDecl();
2454 // Function may lack declaration in source code if it is created by Clang
2455 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2456 bool HasDecl = (D != 0);
2457 // Use the location of the declaration.
2458 SourceLocation Loc;
2459 if (HasDecl)
2460 Loc = D->getLocation();
2461
2462 unsigned Flags = 0;
2463 llvm::DIFile Unit = getOrCreateFile(Loc);
2464 llvm::DIDescriptor FDContext(Unit);
2465 llvm::DIArray TParamsArray;
2466 if (!HasDecl) {
2467 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002468 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2470 // If there is a DISubprogram for this function available then use it.
2471 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2472 FI = SPCache.find(FD->getCanonicalDecl());
2473 if (FI != SPCache.end()) {
2474 llvm::Value *V = FI->second;
2475 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2476 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2477 llvm::MDNode *SPN = SP;
2478 LexicalBlockStack.push_back(SPN);
2479 RegionMap[D] = llvm::WeakVH(SP);
2480 return;
2481 }
2482 }
2483 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002484 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 if (FD->hasPrototype()) {
2486 LinkageName = CGM.getMangledName(GD);
2487 Flags |= llvm::DIDescriptor::FlagPrototyped;
2488 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002489 // No need to replicate the linkage name if it isn't different from the
2490 // subprogram name, no need to have it at all unless coverage is enabled or
2491 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002492 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002493 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2494 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002495 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002496 LinkageName = StringRef();
2497
Eric Christopher75e17682013-05-16 00:45:23 +00002498 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002500 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 FDContext = getOrCreateNameSpace(NSDecl);
2502 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002503 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2504 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002505
2506 // Collect template parameters.
2507 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2508 }
2509 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2510 Name = getObjCMethodName(OMD);
2511 Flags |= llvm::DIDescriptor::FlagPrototyped;
2512 } else {
2513 // Use llvm function name.
2514 Name = Fn->getName();
2515 Flags |= llvm::DIDescriptor::FlagPrototyped;
2516 }
2517 if (!Name.empty() && Name[0] == '\01')
2518 Name = Name.substr(1);
2519
2520 unsigned LineNo = getLineNumber(Loc);
2521 if (!HasDecl || D->isImplicit())
2522 Flags |= llvm::DIDescriptor::FlagArtificial;
2523
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002524 llvm::DISubprogram SP =
2525 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2526 getOrCreateFunctionType(D, FnType, Unit),
2527 Fn->hasInternalLinkage(), true /*definition*/,
2528 getLineNumber(CurLoc), Flags,
2529 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2530 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002531 if (HasDecl)
2532 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002533
2534 // Push function on region stack.
2535 llvm::MDNode *SPN = SP;
2536 LexicalBlockStack.push_back(SPN);
2537 if (HasDecl)
2538 RegionMap[D] = llvm::WeakVH(SP);
2539}
2540
2541/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002542/// information in the source file. If the location is invalid, the
2543/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002544void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002545 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002546 // Update our current location
2547 setLocation(Loc);
2548
2549 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2550
2551 // Don't bother if things are the same as last time.
2552 SourceManager &SM = CGM.getContext().getSourceManager();
2553 if (CurLoc == PrevLoc ||
2554 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2555 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002556 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2557 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2558 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002560
Guy Benyei11169dd2012-12-18 14:30:41 +00002561 // Update last state.
2562 PrevLoc = CurLoc;
2563
Adrian Prantle83b1302014-01-07 22:05:52 +00002564 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002565 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2566 (getLineNumber(CurLoc),
2567 getColumnNumber(CurLoc, ForceColumnInfo),
2568 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002569}
2570
2571/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2572/// the stack.
2573void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2574 llvm::DIDescriptor D =
2575 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2576 llvm::DIDescriptor() :
2577 llvm::DIDescriptor(LexicalBlockStack.back()),
2578 getOrCreateFile(CurLoc),
2579 getLineNumber(CurLoc),
2580 getColumnNumber(CurLoc));
2581 llvm::MDNode *DN = D;
2582 LexicalBlockStack.push_back(DN);
2583}
2584
2585/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2586/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002587void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2588 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002589 // Set our current location.
2590 setLocation(Loc);
2591
2592 // Create a new lexical block and push it on the stack.
2593 CreateLexicalBlock(Loc);
2594
2595 // Emit a line table change for the current location inside the new scope.
2596 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2597 getColumnNumber(Loc),
2598 LexicalBlockStack.back()));
2599}
2600
2601/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2602/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002603void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2604 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002605 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2606
2607 // Provide an entry in the line table for the end of the block.
2608 EmitLocation(Builder, Loc);
2609
2610 LexicalBlockStack.pop_back();
2611}
2612
2613/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2614void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2615 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2616 unsigned RCount = FnBeginRegionCount.back();
2617 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2618
2619 // Pop all regions for this function.
2620 while (LexicalBlockStack.size() != RCount)
2621 EmitLexicalBlockEnd(Builder, CurLoc);
2622 FnBeginRegionCount.pop_back();
2623}
2624
Eric Christopherb2a008c2013-05-16 00:45:12 +00002625// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002626// See BuildByRefType.
2627llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2628 uint64_t *XOffset) {
2629
2630 SmallVector<llvm::Value *, 5> EltTys;
2631 QualType FType;
2632 uint64_t FieldSize, FieldOffset;
2633 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002634
Guy Benyei11169dd2012-12-18 14:30:41 +00002635 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002636 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002637
2638 FieldOffset = 0;
2639 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2640 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2641 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2642 FType = CGM.getContext().IntTy;
2643 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2644 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2645
2646 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2647 if (HasCopyAndDispose) {
2648 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2649 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2650 &FieldOffset));
2651 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2652 &FieldOffset));
2653 }
2654 bool HasByrefExtendedLayout;
2655 Qualifiers::ObjCLifetime Lifetime;
2656 if (CGM.getContext().getByrefLifetime(Type,
2657 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002658 && HasByrefExtendedLayout) {
2659 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002660 EltTys.push_back(CreateMemberType(Unit, FType,
2661 "__byref_variable_layout",
2662 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002663 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002664
Guy Benyei11169dd2012-12-18 14:30:41 +00002665 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2666 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002667 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002668 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002669 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2670 CharUnits AlignedOffsetInBytes
2671 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2672 CharUnits NumPaddingBytes
2673 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002674
Guy Benyei11169dd2012-12-18 14:30:41 +00002675 if (NumPaddingBytes.isPositive()) {
2676 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2677 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2678 pad, ArrayType::Normal, 0);
2679 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2680 }
2681 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002682
Guy Benyei11169dd2012-12-18 14:30:41 +00002683 FType = Type;
2684 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2685 FieldSize = CGM.getContext().getTypeSize(FType);
2686 FieldAlign = CGM.getContext().toBits(Align);
2687
Eric Christopherb2a008c2013-05-16 00:45:12 +00002688 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2690 0, FieldSize, FieldAlign,
2691 FieldOffset, 0, FieldTy);
2692 EltTys.push_back(FieldTy);
2693 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002694
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002696
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002698
Guy Benyei11169dd2012-12-18 14:30:41 +00002699 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002700 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002701}
2702
2703/// EmitDeclare - Emit local variable declaration debug info.
2704void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002705 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002707 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002708 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2709
David Blaikie7fceebf2013-08-19 03:37:48 +00002710 bool Unwritten =
2711 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2712 cast<Decl>(VD->getDeclContext())->isImplicit());
2713 llvm::DIFile Unit;
2714 if (!Unwritten)
2715 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002716 llvm::DIType Ty;
2717 uint64_t XOffset = 0;
2718 if (VD->hasAttr<BlocksAttr>())
2719 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002720 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002721 Ty = getOrCreateType(VD->getType(), Unit);
2722
2723 // If there is no debug info for this type then do not emit debug info
2724 // for this variable.
2725 if (!Ty)
2726 return;
2727
Guy Benyei11169dd2012-12-18 14:30:41 +00002728 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002729 unsigned Line = 0;
2730 unsigned Column = 0;
2731 if (!Unwritten) {
2732 Line = getLineNumber(VD->getLocation());
2733 Column = getColumnNumber(VD->getLocation());
2734 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002735 unsigned Flags = 0;
2736 if (VD->isImplicit())
2737 Flags |= llvm::DIDescriptor::FlagArtificial;
2738 // If this is the first argument and it is implicit then
2739 // give it an object pointer flag.
2740 // FIXME: There has to be a better way to do this, but for static
2741 // functions there won't be an implicit param at arg1 and
2742 // otherwise it is 'self' or 'this'.
2743 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2744 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002745 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002746 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2747 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002748 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002749
2750 llvm::MDNode *Scope = LexicalBlockStack.back();
2751
2752 StringRef Name = VD->getName();
2753 if (!Name.empty()) {
2754 if (VD->hasAttr<BlocksAttr>()) {
2755 CharUnits offset = CharUnits::fromQuantity(32);
2756 SmallVector<llvm::Value *, 9> addr;
2757 llvm::Type *Int64Ty = CGM.Int64Ty;
2758 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2759 // offset of __forwarding field
2760 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002761 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2763 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2764 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2765 // offset of x field
2766 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2767 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2768
2769 // Create the descriptor for the variable.
2770 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002771 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002772 llvm::DIDescriptor(Scope),
2773 VD->getName(), Unit, Line, Ty,
2774 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002775
Guy Benyei11169dd2012-12-18 14:30:41 +00002776 // Insert an llvm.dbg.declare into the current block.
2777 llvm::Instruction *Call =
2778 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2779 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2780 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002781 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002782 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002783 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2784 // If VD is an anonymous union then Storage represents value for
2785 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002787 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002788 for (RecordDecl::field_iterator I = RD->field_begin(),
2789 E = RD->field_end();
2790 I != E; ++I) {
2791 FieldDecl *Field = *I;
2792 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2793 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002794
Guy Benyei11169dd2012-12-18 14:30:41 +00002795 // Ignore unnamed fields. Do not ignore unnamed records.
2796 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2797 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002798
Guy Benyei11169dd2012-12-18 14:30:41 +00002799 // Use VarDecl's Tag, Scope and Line number.
2800 llvm::DIVariable D =
2801 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002802 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002803 CGM.getLangOpts().Optimize, Flags,
2804 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002805
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 // Insert an llvm.dbg.declare into the current block.
2807 llvm::Instruction *Call =
2808 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2809 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2810 }
David Blaikie219c7d92013-01-05 20:03:07 +00002811 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 }
2813 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002814
2815 // Create the descriptor for the variable.
2816 llvm::DIVariable D =
2817 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2818 Name, Unit, Line, Ty,
2819 CGM.getLangOpts().Optimize, Flags, ArgNo);
2820
2821 // Insert an llvm.dbg.declare into the current block.
2822 llvm::Instruction *Call =
2823 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2824 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002825}
2826
2827void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2828 llvm::Value *Storage,
2829 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002830 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002831 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2832}
2833
Adrian Prantlde17db32013-03-29 19:20:29 +00002834/// Look up the completed type for a self pointer in the TypeCache and
2835/// create a copy of it with the ObjectPointer and Artificial flags
2836/// set. If the type is not cached, a new one is created. This should
2837/// never happen though, since creating a type for the implicit self
2838/// argument implies that we already parsed the interface definition
2839/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002840llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2841 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002842 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002843 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002844 else DEBUG(llvm::dbgs() << "No cached type for self.");
2845 return DBuilder.createObjectPointerType(Ty);
2846}
2847
Guy Benyei11169dd2012-12-18 14:30:41 +00002848void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2849 llvm::Value *Storage,
2850 CGBuilderTy &Builder,
2851 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002852 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002854
Guy Benyei11169dd2012-12-18 14:30:41 +00002855 if (Builder.GetInsertBlock() == 0)
2856 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002859
Guy Benyei11169dd2012-12-18 14:30:41 +00002860 uint64_t XOffset = 0;
2861 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2862 llvm::DIType Ty;
2863 if (isByRef)
2864 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002865 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002866 Ty = getOrCreateType(VD->getType(), Unit);
2867
2868 // Self is passed along as an implicit non-arg variable in a
2869 // block. Mark it as the object pointer.
2870 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002871 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002872
2873 // Get location information.
2874 unsigned Line = getLineNumber(VD->getLocation());
2875 unsigned Column = getColumnNumber(VD->getLocation());
2876
2877 const llvm::DataLayout &target = CGM.getDataLayout();
2878
2879 CharUnits offset = CharUnits::fromQuantity(
2880 target.getStructLayout(blockInfo.StructureType)
2881 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2882
2883 SmallVector<llvm::Value *, 9> addr;
2884 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002885 if (isa<llvm::AllocaInst>(Storage))
2886 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002887 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2888 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2889 if (isByRef) {
2890 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2891 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2892 // offset of __forwarding field
2893 offset = CGM.getContext()
2894 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2895 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2896 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2897 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2898 // offset of x field
2899 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2900 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2901 }
2902
2903 // Create the descriptor for the variable.
2904 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002905 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 llvm::DIDescriptor(LexicalBlockStack.back()),
2907 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002908
Guy Benyei11169dd2012-12-18 14:30:41 +00002909 // Insert an llvm.dbg.declare into the current block.
2910 llvm::Instruction *Call =
2911 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2912 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2913 LexicalBlockStack.back()));
2914}
2915
2916/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2917/// variable declaration.
2918void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2919 unsigned ArgNo,
2920 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002921 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002922 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2923}
2924
2925namespace {
2926 struct BlockLayoutChunk {
2927 uint64_t OffsetInBits;
2928 const BlockDecl::Capture *Capture;
2929 };
2930 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2931 return l.OffsetInBits < r.OffsetInBits;
2932 }
2933}
2934
2935void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002936 llvm::Value *Arg,
2937 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002939 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002940 ASTContext &C = CGM.getContext();
2941 const BlockDecl *blockDecl = block.getBlockDecl();
2942
2943 // Collect some general information about the block's location.
2944 SourceLocation loc = blockDecl->getCaretLocation();
2945 llvm::DIFile tunit = getOrCreateFile(loc);
2946 unsigned line = getLineNumber(loc);
2947 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002948
Guy Benyei11169dd2012-12-18 14:30:41 +00002949 // Build the debug-info type for the block literal.
2950 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2951
2952 const llvm::StructLayout *blockLayout =
2953 CGM.getDataLayout().getStructLayout(block.StructureType);
2954
2955 SmallVector<llvm::Value*, 16> fields;
2956 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2957 blockLayout->getElementOffsetInBits(0),
2958 tunit, tunit));
2959 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2960 blockLayout->getElementOffsetInBits(1),
2961 tunit, tunit));
2962 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2963 blockLayout->getElementOffsetInBits(2),
2964 tunit, tunit));
2965 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2966 blockLayout->getElementOffsetInBits(3),
2967 tunit, tunit));
2968 fields.push_back(createFieldType("__descriptor",
2969 C.getPointerType(block.NeedsCopyDispose ?
2970 C.getBlockDescriptorExtendedType() :
2971 C.getBlockDescriptorType()),
2972 0, loc, AS_public,
2973 blockLayout->getElementOffsetInBits(4),
2974 tunit, tunit));
2975
2976 // We want to sort the captures by offset, not because DWARF
2977 // requires this, but because we're paranoid about debuggers.
2978 SmallVector<BlockLayoutChunk, 8> chunks;
2979
2980 // 'this' capture.
2981 if (blockDecl->capturesCXXThis()) {
2982 BlockLayoutChunk chunk;
2983 chunk.OffsetInBits =
2984 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2985 chunk.Capture = 0;
2986 chunks.push_back(chunk);
2987 }
2988
2989 // Variable captures.
2990 for (BlockDecl::capture_const_iterator
2991 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2992 i != e; ++i) {
2993 const BlockDecl::Capture &capture = *i;
2994 const VarDecl *variable = capture.getVariable();
2995 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2996
2997 // Ignore constant captures.
2998 if (captureInfo.isConstant())
2999 continue;
3000
3001 BlockLayoutChunk chunk;
3002 chunk.OffsetInBits =
3003 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3004 chunk.Capture = &capture;
3005 chunks.push_back(chunk);
3006 }
3007
3008 // Sort by offset.
3009 llvm::array_pod_sort(chunks.begin(), chunks.end());
3010
3011 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3012 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3013 uint64_t offsetInBits = i->OffsetInBits;
3014 const BlockDecl::Capture *capture = i->Capture;
3015
3016 // If we have a null capture, this must be the C++ 'this' capture.
3017 if (!capture) {
3018 const CXXMethodDecl *method =
3019 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3020 QualType type = method->getThisType(C);
3021
3022 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3023 offsetInBits, tunit, tunit));
3024 continue;
3025 }
3026
3027 const VarDecl *variable = capture->getVariable();
3028 StringRef name = variable->getName();
3029
3030 llvm::DIType fieldType;
3031 if (capture->isByRef()) {
3032 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3033
3034 // FIXME: this creates a second copy of this type!
3035 uint64_t xoffset;
3036 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3037 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3038 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3039 ptrInfo.first, ptrInfo.second,
3040 offsetInBits, 0, fieldType);
3041 } else {
3042 fieldType = createFieldType(name, variable->getType(), 0,
3043 loc, AS_public, offsetInBits, tunit, tunit);
3044 }
3045 fields.push_back(fieldType);
3046 }
3047
3048 SmallString<36> typeName;
3049 llvm::raw_svector_ostream(typeName)
3050 << "__block_literal_" << CGM.getUniqueBlockCount();
3051
3052 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3053
3054 llvm::DIType type =
3055 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3056 CGM.getContext().toBits(block.BlockSize),
3057 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003058 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003059 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3060
3061 // Get overall information about the block.
3062 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3063 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003064
3065 // Create the descriptor for the parameter.
3066 llvm::DIVariable debugVar =
3067 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003068 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003069 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003070 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003071 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3072
Adrian Prantl616bef42013-03-14 21:52:59 +00003073 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003074 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003075 llvm::Instruction *DbgVal =
3076 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003077 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003078 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3079 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003080
Adrian Prantl616bef42013-03-14 21:52:59 +00003081 // Insert an llvm.dbg.declare into the current block.
3082 llvm::Instruction *DbgDecl =
3083 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3084 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003085}
3086
David Blaikie6943dea2013-08-20 01:28:15 +00003087/// If D is an out-of-class definition of a static data member of a class, find
3088/// its corresponding in-class declaration.
3089llvm::DIDerivedType
3090CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3091 if (!D->isStaticDataMember())
3092 return llvm::DIDerivedType();
3093 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3094 StaticDataMemberCache.find(D->getCanonicalDecl());
3095 if (MI != StaticDataMemberCache.end()) {
3096 assert(MI->second && "Static data member declaration should still exist");
3097 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003098 }
David Blaikiece763042013-08-20 21:49:21 +00003099
3100 // If the member wasn't found in the cache, lazily construct and add it to the
3101 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003102 llvm::DICompositeType Ctxt(
3103 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3104 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003105 return T;
3106}
3107
Guy Benyei11169dd2012-12-18 14:30:41 +00003108/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003109void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003111 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003112 // Create global variable debug descriptor.
3113 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3114 unsigned LineNo = getLineNumber(D->getLocation());
3115
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003116 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003117
3118 QualType T = D->getType();
3119 if (T->isIncompleteArrayType()) {
3120
3121 // CodeGen turns int[] into int[1] so we'll do the same here.
3122 llvm::APInt ConstVal(32, 1);
3123 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3124
3125 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3126 ArrayType::Normal, 0);
3127 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003128 StringRef DeclName = D->getName();
3129 StringRef LinkageName;
3130 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3131 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3132 LinkageName = Var->getName();
3133 if (LinkageName == DeclName)
3134 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003135 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003136 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003137 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3138 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003139 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003140 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003141 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003142}
3143
3144/// EmitGlobalVariable - Emit information about an objective-c interface.
3145void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3146 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003147 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003148 // Create global variable debug descriptor.
3149 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3150 unsigned LineNo = getLineNumber(ID->getLocation());
3151
3152 StringRef Name = ID->getName();
3153
3154 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3155 if (T->isIncompleteArrayType()) {
3156
3157 // CodeGen turns int[] into int[1] so we'll do the same here.
3158 llvm::APInt ConstVal(32, 1);
3159 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3160
3161 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3162 ArrayType::Normal, 0);
3163 }
3164
3165 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3166 getOrCreateType(T, Unit),
3167 Var->hasInternalLinkage(), Var);
3168}
3169
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003170/// EmitGlobalVariable - Emit global variable's debug info.
3171void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3172 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003173 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003174 // Create the descriptor for the variable.
3175 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3176 StringRef Name = VD->getName();
3177 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3178 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3179 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3180 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3181 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3182 }
3183 // Do not use DIGlobalVariable for enums.
3184 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3185 return;
3186 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3187 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3188 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3189 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003190}
3191
3192llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3193 if (!LexicalBlockStack.empty())
3194 return llvm::DIScope(LexicalBlockStack.back());
3195 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003196}
3197
David Blaikie9f88fe82013-04-22 06:13:21 +00003198void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003199 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3200 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003201 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003202 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3203 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003204 getLineNumber(UD.getLocation()));
3205}
3206
David Blaikiebd483762013-05-20 04:58:53 +00003207void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3208 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3209 return;
3210 assert(UD.shadow_size() &&
3211 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3212 // Emitting one decl is sufficient - debuggers can detect that this is an
3213 // overloaded name & provide lookup for all the overloads.
3214 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003215 if (llvm::DIDescriptor Target =
3216 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003217 DBuilder.createImportedDeclaration(
3218 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3219 getLineNumber(USD.getLocation()));
3220}
3221
David Blaikief121b932013-05-20 22:50:41 +00003222llvm::DIImportedEntity
3223CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3224 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3225 return llvm::DIImportedEntity(0);
3226 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3227 if (VH)
3228 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3229 llvm::DIImportedEntity R(0);
3230 if (const NamespaceAliasDecl *Underlying =
3231 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3232 // This could cache & dedup here rather than relying on metadata deduping.
3233 R = DBuilder.createImportedModule(
3234 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3235 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3236 NA.getName());
3237 else
3238 R = DBuilder.createImportedModule(
3239 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3240 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3241 getLineNumber(NA.getLocation()), NA.getName());
3242 VH = R;
3243 return R;
3244}
3245
Guy Benyei11169dd2012-12-18 14:30:41 +00003246/// getOrCreateNamesSpace - Return namespace descriptor for the given
3247/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003248llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003249CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003250 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003251 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003252 NameSpaceCache.find(NSDecl);
3253 if (I != NameSpaceCache.end())
3254 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003255
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3257 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003258 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003259 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3260 llvm::DINameSpace NS =
3261 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3262 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3263 return NS;
3264}
3265
3266void CGDebugInfo::finalize() {
3267 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3268 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3269 llvm::DIType Ty, RepTy;
3270 // Verify that the debug info still exists.
3271 if (llvm::Value *V = VI->second)
3272 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003273
Guy Benyei11169dd2012-12-18 14:30:41 +00003274 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3275 TypeCache.find(VI->first);
3276 if (it != TypeCache.end()) {
3277 // Verify that the debug info still exists.
3278 if (llvm::Value *V = it->second)
3279 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3280 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003281
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003282 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003284 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003285
3286 // We keep our own list of retained types, because we need to look
3287 // up the final type in the type cache.
3288 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3289 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003290 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003291
Guy Benyei11169dd2012-12-18 14:30:41 +00003292 DBuilder.finalize();
3293}