blob: 3edffa56566177c34bbc624ffbc4450d1c1ea9c4 [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.
742 unsigned Line = getLineNumber(Ty->getDecl()->getLocation());
743 const TypedefNameDecl *TyDecl = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +0000744
Guy Benyei11169dd2012-12-18 14:30:41 +0000745 llvm::DIDescriptor TypedefContext =
746 getContextDescriptor(cast<Decl>(Ty->getDecl()->getDeclContext()));
Eric Christopherb2a008c2013-05-16 00:45:12 +0000747
Guy Benyei11169dd2012-12-18 14:30:41 +0000748 return
749 DBuilder.createTypedef(Src, TyDecl->getName(), Unit, Line, TypedefContext);
750}
751
752llvm::DIType CGDebugInfo::CreateType(const FunctionType *Ty,
753 llvm::DIFile Unit) {
754 SmallVector<llvm::Value *, 16> EltTys;
755
756 // Add the result type at least.
David Blaikie99dab3b2013-09-04 22:03:57 +0000757 EltTys.push_back(getOrCreateType(Ty->getResultType(), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000758
759 // Set up remainder of arguments if there is a prototype.
760 // FIXME: IF NOT, HOW IS THIS REPRESENTED? llvm-gcc doesn't represent '...'!
761 if (isa<FunctionNoProtoType>(Ty))
762 EltTys.push_back(DBuilder.createUnspecifiedParameter());
763 else if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(Ty)) {
764 for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
David Blaikie99dab3b2013-09-04 22:03:57 +0000765 EltTys.push_back(getOrCreateType(FPT->getArgType(i), Unit));
Guy Benyei11169dd2012-12-18 14:30:41 +0000766 }
767
768 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(EltTys);
769 return DBuilder.createSubroutineType(Unit, EltTypeArray);
770}
771
772
Guy Benyei11169dd2012-12-18 14:30:41 +0000773llvm::DIType CGDebugInfo::createFieldType(StringRef name,
774 QualType type,
775 uint64_t sizeInBitsOverride,
776 SourceLocation loc,
777 AccessSpecifier AS,
778 uint64_t offsetInBits,
779 llvm::DIFile tunit,
Manman Ren2c826dc2013-09-08 03:45:05 +0000780 llvm::DIScope scope) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000781 llvm::DIType debugType = getOrCreateType(type, tunit);
782
783 // Get the location for the field.
784 llvm::DIFile file = getOrCreateFile(loc);
785 unsigned line = getLineNumber(loc);
786
787 uint64_t sizeInBits = 0;
788 unsigned alignInBits = 0;
789 if (!type->isIncompleteArrayType()) {
790 llvm::tie(sizeInBits, alignInBits) = CGM.getContext().getTypeInfo(type);
791
792 if (sizeInBitsOverride)
793 sizeInBits = sizeInBitsOverride;
794 }
795
796 unsigned flags = 0;
797 if (AS == clang::AS_private)
798 flags |= llvm::DIDescriptor::FlagPrivate;
799 else if (AS == clang::AS_protected)
800 flags |= llvm::DIDescriptor::FlagProtected;
801
802 return DBuilder.createMemberType(scope, name, file, line, sizeInBits,
803 alignInBits, offsetInBits, flags, debugType);
804}
805
Eric Christopher91a31902013-01-16 01:22:32 +0000806/// CollectRecordLambdaFields - Helper for CollectRecordFields.
807void CGDebugInfo::
808CollectRecordLambdaFields(const CXXRecordDecl *CXXDecl,
809 SmallVectorImpl<llvm::Value *> &elements,
810 llvm::DIType RecordTy) {
811 // For C++11 Lambdas a Field will be the same as a Capture, but the Capture
812 // has the name and the location of the variable so we should iterate over
813 // both concurrently.
814 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(CXXDecl);
815 RecordDecl::field_iterator Field = CXXDecl->field_begin();
816 unsigned fieldno = 0;
817 for (CXXRecordDecl::capture_const_iterator I = CXXDecl->captures_begin(),
818 E = CXXDecl->captures_end(); I != E; ++I, ++Field, ++fieldno) {
819 const LambdaExpr::Capture C = *I;
820 if (C.capturesVariable()) {
821 VarDecl *V = C.getCapturedVar();
822 llvm::DIFile VUnit = getOrCreateFile(C.getLocation());
823 StringRef VName = V->getName();
824 uint64_t SizeInBitsOverride = 0;
825 if (Field->isBitField()) {
826 SizeInBitsOverride = Field->getBitWidthValue(CGM.getContext());
827 assert(SizeInBitsOverride && "found named 0-width bitfield");
828 }
829 llvm::DIType fieldType
830 = createFieldType(VName, Field->getType(), SizeInBitsOverride,
831 C.getLocation(), Field->getAccess(),
832 layout.getFieldOffset(fieldno), VUnit, RecordTy);
833 elements.push_back(fieldType);
834 } else {
835 // TODO: Need to handle 'this' in some way by probably renaming the
836 // this of the lambda class and having a field member of 'this' or
837 // by using AT_object_pointer for the function and having that be
838 // used as 'this' for semantic references.
839 assert(C.capturesThis() && "Field that isn't captured and isn't this?");
840 FieldDecl *f = *Field;
841 llvm::DIFile VUnit = getOrCreateFile(f->getLocation());
842 QualType type = f->getType();
843 llvm::DIType fieldType
844 = createFieldType("this", type, 0, f->getLocation(), f->getAccess(),
845 layout.getFieldOffset(fieldno), VUnit, RecordTy);
846
847 elements.push_back(fieldType);
848 }
849 }
850}
851
David Blaikie6943dea2013-08-20 01:28:15 +0000852/// Helper for CollectRecordFields.
David Blaikieae019462013-08-15 22:50:29 +0000853llvm::DIDerivedType
854CGDebugInfo::CreateRecordStaticField(const VarDecl *Var,
855 llvm::DIType RecordTy) {
Eric Christopher91a31902013-01-16 01:22:32 +0000856 // Create the descriptor for the static variable, with or without
857 // constant initializers.
858 llvm::DIFile VUnit = getOrCreateFile(Var->getLocation());
859 llvm::DIType VTy = getOrCreateType(Var->getType(), VUnit);
860
Eric Christopher91a31902013-01-16 01:22:32 +0000861 unsigned LineNumber = getLineNumber(Var->getLocation());
862 StringRef VName = Var->getName();
David Blaikied42917f2013-01-20 01:19:17 +0000863 llvm::Constant *C = NULL;
Eric Christopher91a31902013-01-16 01:22:32 +0000864 if (Var->getInit()) {
865 const APValue *Value = Var->evaluateValue();
David Blaikied42917f2013-01-20 01:19:17 +0000866 if (Value) {
867 if (Value->isInt())
868 C = llvm::ConstantInt::get(CGM.getLLVMContext(), Value->getInt());
869 if (Value->isFloat())
870 C = llvm::ConstantFP::get(CGM.getLLVMContext(), Value->getFloat());
871 }
Eric Christopher91a31902013-01-16 01:22:32 +0000872 }
873
874 unsigned Flags = 0;
875 AccessSpecifier Access = Var->getAccess();
876 if (Access == clang::AS_private)
877 Flags |= llvm::DIDescriptor::FlagPrivate;
878 else if (Access == clang::AS_protected)
879 Flags |= llvm::DIDescriptor::FlagProtected;
880
David Blaikieae019462013-08-15 22:50:29 +0000881 llvm::DIDerivedType GV = DBuilder.createStaticMemberType(
882 RecordTy, VName, VUnit, LineNumber, VTy, Flags, C);
Eric Christopher91a31902013-01-16 01:22:32 +0000883 StaticDataMemberCache[Var->getCanonicalDecl()] = llvm::WeakVH(GV);
David Blaikieae019462013-08-15 22:50:29 +0000884 return GV;
Eric Christopher91a31902013-01-16 01:22:32 +0000885}
886
887/// CollectRecordNormalField - Helper for CollectRecordFields.
888void CGDebugInfo::
889CollectRecordNormalField(const FieldDecl *field, uint64_t OffsetInBits,
890 llvm::DIFile tunit,
891 SmallVectorImpl<llvm::Value *> &elements,
892 llvm::DIType RecordTy) {
893 StringRef name = field->getName();
894 QualType type = field->getType();
895
896 // Ignore unnamed fields unless they're anonymous structs/unions.
897 if (name.empty() && !type->isRecordType())
898 return;
899
900 uint64_t SizeInBitsOverride = 0;
901 if (field->isBitField()) {
902 SizeInBitsOverride = field->getBitWidthValue(CGM.getContext());
903 assert(SizeInBitsOverride && "found named 0-width bitfield");
904 }
905
906 llvm::DIType fieldType
907 = createFieldType(name, type, SizeInBitsOverride,
908 field->getLocation(), field->getAccess(),
909 OffsetInBits, tunit, RecordTy);
910
911 elements.push_back(fieldType);
912}
913
Guy Benyei11169dd2012-12-18 14:30:41 +0000914/// CollectRecordFields - A helper function to collect debug info for
915/// record fields. This is used while creating debug info entry for a Record.
David Blaikieab255bb2013-08-16 20:40:25 +0000916void CGDebugInfo::CollectRecordFields(const RecordDecl *record,
917 llvm::DIFile tunit,
918 SmallVectorImpl<llvm::Value *> &elements,
919 llvm::DICompositeType RecordTy) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000920 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(record);
921
Eric Christopher91a31902013-01-16 01:22:32 +0000922 if (CXXDecl && CXXDecl->isLambda())
923 CollectRecordLambdaFields(CXXDecl, elements, RecordTy);
924 else {
925 const ASTRecordLayout &layout = CGM.getContext().getASTRecordLayout(record);
Guy Benyei11169dd2012-12-18 14:30:41 +0000926
Eric Christopher91a31902013-01-16 01:22:32 +0000927 // Field number for non-static fields.
Eric Christopher0f7594372013-01-04 17:59:07 +0000928 unsigned fieldNo = 0;
Eric Christopher91a31902013-01-16 01:22:32 +0000929
Eric Christopher91a31902013-01-16 01:22:32 +0000930 // Static and non-static members should appear in the same order as
931 // the corresponding declarations in the source program.
932 for (RecordDecl::decl_iterator I = record->decls_begin(),
933 E = record->decls_end(); I != E; ++I)
David Blaikiece763042013-08-20 21:49:21 +0000934 if (const VarDecl *V = dyn_cast<VarDecl>(*I)) {
935 // Reuse the existing static member declaration if one exists
936 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
937 StaticDataMemberCache.find(V->getCanonicalDecl());
938 if (MI != StaticDataMemberCache.end()) {
939 assert(MI->second &&
940 "Static data member declaration should still exist");
941 elements.push_back(
942 llvm::DIDerivedType(cast<llvm::MDNode>(MI->second)));
943 } else
944 elements.push_back(CreateRecordStaticField(V, RecordTy));
945 } else if (FieldDecl *field = dyn_cast<FieldDecl>(*I)) {
Eric Christopher91a31902013-01-16 01:22:32 +0000946 CollectRecordNormalField(field, layout.getFieldOffset(fieldNo),
947 tunit, elements, RecordTy);
948
949 // Bump field number for next field.
950 ++fieldNo;
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000952 }
953}
954
955/// getOrCreateMethodType - CXXMethodDecl's type is a FunctionType. This
956/// function type is not updated to include implicit "this" pointer. Use this
957/// routine to get a method type which includes "this" pointer.
David Blaikie469f0792013-05-22 23:22:42 +0000958llvm::DICompositeType
Guy Benyei11169dd2012-12-18 14:30:41 +0000959CGDebugInfo::getOrCreateMethodType(const CXXMethodDecl *Method,
960 llvm::DIFile Unit) {
David Blaikie7eb06852013-01-07 23:06:35 +0000961 const FunctionProtoType *Func = Method->getType()->getAs<FunctionProtoType>();
David Blaikie2aaf0652013-01-07 22:24:59 +0000962 if (Method->isStatic())
David Blaikie469f0792013-05-22 23:22:42 +0000963 return llvm::DICompositeType(getOrCreateType(QualType(Func, 0), Unit));
David Blaikie7eb06852013-01-07 23:06:35 +0000964 return getOrCreateInstanceMethodType(Method->getThisType(CGM.getContext()),
965 Func, Unit);
966}
David Blaikie2aaf0652013-01-07 22:24:59 +0000967
David Blaikie469f0792013-05-22 23:22:42 +0000968llvm::DICompositeType CGDebugInfo::getOrCreateInstanceMethodType(
David Blaikie7eb06852013-01-07 23:06:35 +0000969 QualType ThisPtr, const FunctionProtoType *Func, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000970 // Add "this" pointer.
David Blaikie7eb06852013-01-07 23:06:35 +0000971 llvm::DIArray Args = llvm::DICompositeType(
972 getOrCreateType(QualType(Func, 0), Unit)).getTypeArray();
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 assert (Args.getNumElements() && "Invalid number of arguments!");
974
975 SmallVector<llvm::Value *, 16> Elts;
976
977 // First element is always return type. For 'void' functions it is NULL.
978 Elts.push_back(Args.getElement(0));
979
David Blaikie2aaf0652013-01-07 22:24:59 +0000980 // "this" pointer is always first argument.
David Blaikie7eb06852013-01-07 23:06:35 +0000981 const CXXRecordDecl *RD = ThisPtr->getPointeeCXXRecordDecl();
David Blaikie2aaf0652013-01-07 22:24:59 +0000982 if (isa<ClassTemplateSpecializationDecl>(RD)) {
983 // Create pointer type directly in this case.
984 const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
985 QualType PointeeTy = ThisPtrTy->getPointeeType();
986 unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
John McCallc8e01702013-04-16 22:48:15 +0000987 uint64_t Size = CGM.getTarget().getPointerWidth(AS);
David Blaikie2aaf0652013-01-07 22:24:59 +0000988 uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
989 llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
Eric Christopher0fdcb312013-05-16 00:52:20 +0000990 llvm::DIType ThisPtrType =
991 DBuilder.createPointerType(PointeeType, Size, Align);
David Blaikie2aaf0652013-01-07 22:24:59 +0000992 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
993 // TODO: This and the artificial type below are misleading, the
994 // types aren't artificial the argument is, but the current
995 // metadata doesn't represent that.
996 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
997 Elts.push_back(ThisPtrType);
998 } else {
999 llvm::DIType ThisPtrType = getOrCreateType(ThisPtr, Unit);
1000 TypeCache[ThisPtr.getAsOpaquePtr()] = ThisPtrType;
1001 ThisPtrType = DBuilder.createObjectPointerType(ThisPtrType);
1002 Elts.push_back(ThisPtrType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 }
1004
1005 // Copy rest of the arguments.
1006 for (unsigned i = 1, e = Args.getNumElements(); i != e; ++i)
1007 Elts.push_back(Args.getElement(i));
1008
1009 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
1010
Adrian Prantl0630eb72013-12-18 21:48:18 +00001011 unsigned Flags = 0;
1012 if (Func->getExtProtoInfo().RefQualifier == RQ_LValue)
1013 Flags |= llvm::DIDescriptor::FlagLValueReference;
1014 if (Func->getExtProtoInfo().RefQualifier == RQ_RValue)
1015 Flags |= llvm::DIDescriptor::FlagRValueReference;
1016
1017 return DBuilder.createSubroutineType(Unit, EltTypeArray, Flags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001018}
1019
Eric Christopherb2a008c2013-05-16 00:45:12 +00001020/// isFunctionLocalClass - Return true if CXXRecordDecl is defined
Guy Benyei11169dd2012-12-18 14:30:41 +00001021/// inside a function.
1022static bool isFunctionLocalClass(const CXXRecordDecl *RD) {
1023 if (const CXXRecordDecl *NRD = dyn_cast<CXXRecordDecl>(RD->getDeclContext()))
1024 return isFunctionLocalClass(NRD);
1025 if (isa<FunctionDecl>(RD->getDeclContext()))
1026 return true;
1027 return false;
1028}
1029
1030/// CreateCXXMemberFunction - A helper function to create a DISubprogram for
1031/// a single member function GlobalDecl.
1032llvm::DISubprogram
1033CGDebugInfo::CreateCXXMemberFunction(const CXXMethodDecl *Method,
1034 llvm::DIFile Unit,
1035 llvm::DIType RecordTy) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001036 bool IsCtorOrDtor =
Guy Benyei11169dd2012-12-18 14:30:41 +00001037 isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001038
Guy Benyei11169dd2012-12-18 14:30:41 +00001039 StringRef MethodName = getFunctionName(Method);
David Blaikie469f0792013-05-22 23:22:42 +00001040 llvm::DICompositeType MethodTy = getOrCreateMethodType(Method, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001041
1042 // Since a single ctor/dtor corresponds to multiple functions, it doesn't
1043 // make sense to give a single ctor/dtor a linkage name.
1044 StringRef MethodLinkageName;
1045 if (!IsCtorOrDtor && !isFunctionLocalClass(Method->getParent()))
1046 MethodLinkageName = CGM.getMangledName(Method);
1047
1048 // Get the location for the method.
David Blaikie7fceebf2013-08-19 03:37:48 +00001049 llvm::DIFile MethodDefUnit;
1050 unsigned MethodLine = 0;
1051 if (!Method->isImplicit()) {
1052 MethodDefUnit = getOrCreateFile(Method->getLocation());
1053 MethodLine = getLineNumber(Method->getLocation());
1054 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001055
1056 // Collect virtual method info.
1057 llvm::DIType ContainingType;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001058 unsigned Virtuality = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00001059 unsigned VIndex = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001060
Guy Benyei11169dd2012-12-18 14:30:41 +00001061 if (Method->isVirtual()) {
1062 if (Method->isPure())
1063 Virtuality = llvm::dwarf::DW_VIRTUALITY_pure_virtual;
1064 else
1065 Virtuality = llvm::dwarf::DW_VIRTUALITY_virtual;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 // It doesn't make sense to give a virtual destructor a vtable index,
1068 // since a single destructor has two entries in the vtable.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001069 // FIXME: Add proper support for debug info for virtual calls in
1070 // the Microsoft ABI, where we may use multiple vptrs to make a vftable
1071 // lookup if we have multiple or virtual inheritance.
1072 if (!isa<CXXDestructorDecl>(Method) &&
1073 !CGM.getTarget().getCXXABI().isMicrosoft())
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001074 VIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(Method);
Guy Benyei11169dd2012-12-18 14:30:41 +00001075 ContainingType = RecordTy;
1076 }
1077
1078 unsigned Flags = 0;
1079 if (Method->isImplicit())
1080 Flags |= llvm::DIDescriptor::FlagArtificial;
1081 AccessSpecifier Access = Method->getAccess();
1082 if (Access == clang::AS_private)
1083 Flags |= llvm::DIDescriptor::FlagPrivate;
1084 else if (Access == clang::AS_protected)
1085 Flags |= llvm::DIDescriptor::FlagProtected;
1086 if (const CXXConstructorDecl *CXXC = dyn_cast<CXXConstructorDecl>(Method)) {
1087 if (CXXC->isExplicit())
1088 Flags |= llvm::DIDescriptor::FlagExplicit;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001089 } else if (const CXXConversionDecl *CXXC =
Guy Benyei11169dd2012-12-18 14:30:41 +00001090 dyn_cast<CXXConversionDecl>(Method)) {
1091 if (CXXC->isExplicit())
1092 Flags |= llvm::DIDescriptor::FlagExplicit;
1093 }
1094 if (Method->hasPrototype())
1095 Flags |= llvm::DIDescriptor::FlagPrototyped;
Adrian Prantl0630eb72013-12-18 21:48:18 +00001096 if (Method->getRefQualifier() == RQ_LValue)
1097 Flags |= llvm::DIDescriptor::FlagLValueReference;
1098 if (Method->getRefQualifier() == RQ_RValue)
1099 Flags |= llvm::DIDescriptor::FlagRValueReference;
Guy Benyei11169dd2012-12-18 14:30:41 +00001100
1101 llvm::DIArray TParamsArray = CollectFunctionTemplateParams(Method, Unit);
1102 llvm::DISubprogram SP =
Eric Christopherb2a008c2013-05-16 00:45:12 +00001103 DBuilder.createMethod(RecordTy, MethodName, MethodLinkageName,
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 MethodDefUnit, MethodLine,
Eric Christopherb2a008c2013-05-16 00:45:12 +00001105 MethodTy, /*isLocalToUnit=*/false,
Guy Benyei11169dd2012-12-18 14:30:41 +00001106 /* isDefinition=*/ false,
1107 Virtuality, VIndex, ContainingType,
1108 Flags, CGM.getLangOpts().Optimize, NULL,
1109 TParamsArray);
Eric Christopherb2a008c2013-05-16 00:45:12 +00001110
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 SPCache[Method->getCanonicalDecl()] = llvm::WeakVH(SP);
1112
1113 return SP;
1114}
1115
1116/// CollectCXXMemberFunctions - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001117/// C++ member functions. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001118/// a Record.
1119void CGDebugInfo::
1120CollectCXXMemberFunctions(const CXXRecordDecl *RD, llvm::DIFile Unit,
1121 SmallVectorImpl<llvm::Value *> &EltTys,
1122 llvm::DIType RecordTy) {
1123
1124 // Since we want more than just the individual member decls if we
1125 // have templated functions iterate over every declaration to gather
1126 // the functions.
1127 for(DeclContext::decl_iterator I = RD->decls_begin(),
1128 E = RD->decls_end(); I != E; ++I) {
David Blaikiefae219a2013-08-28 17:27:13 +00001129 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
David Blaikiea6cc8212013-08-28 20:58:00 +00001130 // Reuse the existing member function declaration if it exists.
David Blaikie8c8e8e22013-08-28 20:24:55 +00001131 // It may be associated with the declaration of the type & should be
1132 // reused as we're building the definition.
David Blaikiea6cc8212013-08-28 20:58:00 +00001133 //
1134 // This situation can arise in the vtable-based debug info reduction where
1135 // implicit members are emitted in a non-vtable TU.
David Blaikie6943dea2013-08-20 01:28:15 +00001136 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1137 SPCache.find(Method->getCanonicalDecl());
David Blaikiefae219a2013-08-28 17:27:13 +00001138 if (MI == SPCache.end()) {
David Blaikie8c8e8e22013-08-28 20:24:55 +00001139 // If the member is implicit, lazily create it when we see the
1140 // definition, not before. (an ODR-used implicit default ctor that's
1141 // never actually code generated should not produce debug info)
David Blaikiefae219a2013-08-28 17:27:13 +00001142 if (!Method->isImplicit())
1143 EltTys.push_back(CreateCXXMemberFunction(Method, Unit, RecordTy));
1144 } else
David Blaikie6943dea2013-08-20 01:28:15 +00001145 EltTys.push_back(MI->second);
Eric Christopherf86c4052013-08-28 23:12:10 +00001146 } else if (const FunctionTemplateDecl *FTD =
1147 dyn_cast<FunctionTemplateDecl>(*I)) {
David Blaikief2053af2013-08-28 23:06:52 +00001148 // Add any template specializations that have already been seen. Like
1149 // implicit member functions, these may have been added to a declaration
1150 // in the case of vtable-based debug info reduction.
Eric Christopherf86c4052013-08-28 23:12:10 +00001151 for (FunctionTemplateDecl::spec_iterator SI = FTD->spec_begin(),
1152 SE = FTD->spec_end();
1153 SI != SE; ++SI) {
David Blaikief2053af2013-08-28 23:06:52 +00001154 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator MI =
1155 SPCache.find(cast<CXXMethodDecl>(*SI)->getCanonicalDecl());
1156 if (MI != SPCache.end())
1157 EltTys.push_back(MI->second);
1158 }
David Blaikie6943dea2013-08-20 01:28:15 +00001159 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001161}
Guy Benyei11169dd2012-12-18 14:30:41 +00001162
Guy Benyei11169dd2012-12-18 14:30:41 +00001163/// CollectCXXBases - A helper function to collect debug info for
Eric Christopherb2a008c2013-05-16 00:45:12 +00001164/// C++ base classes. This is used while creating debug info entry for
Guy Benyei11169dd2012-12-18 14:30:41 +00001165/// a Record.
1166void CGDebugInfo::
1167CollectCXXBases(const CXXRecordDecl *RD, llvm::DIFile Unit,
1168 SmallVectorImpl<llvm::Value *> &EltTys,
1169 llvm::DIType RecordTy) {
1170
1171 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1172 for (CXXRecordDecl::base_class_const_iterator BI = RD->bases_begin(),
1173 BE = RD->bases_end(); BI != BE; ++BI) {
1174 unsigned BFlags = 0;
1175 uint64_t BaseOffset;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001176
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 const CXXRecordDecl *Base =
1178 cast<CXXRecordDecl>(BI->getType()->getAs<RecordType>()->getDecl());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001179
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 if (BI->isVirtual()) {
1181 // virtual base offset offset is -ve. The code generator emits dwarf
1182 // expression where it expects +ve number.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001183 BaseOffset =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +00001184 0 - CGM.getItaniumVTableContext()
Guy Benyei11169dd2012-12-18 14:30:41 +00001185 .getVirtualBaseOffsetOffset(RD, Base).getQuantity();
1186 BFlags = llvm::DIDescriptor::FlagVirtual;
1187 } else
1188 BaseOffset = CGM.getContext().toBits(RL.getBaseClassOffset(Base));
1189 // FIXME: Inconsistent units for BaseOffset. It is in bytes when
1190 // BI->isVirtual() and bits when not.
Eric Christopherb2a008c2013-05-16 00:45:12 +00001191
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 AccessSpecifier Access = BI->getAccessSpecifier();
1193 if (Access == clang::AS_private)
1194 BFlags |= llvm::DIDescriptor::FlagPrivate;
1195 else if (Access == clang::AS_protected)
1196 BFlags |= llvm::DIDescriptor::FlagProtected;
Eric Christopherb2a008c2013-05-16 00:45:12 +00001197
1198 llvm::DIType DTy =
1199 DBuilder.createInheritance(RecordTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001200 getOrCreateType(BI->getType(), Unit),
1201 BaseOffset, BFlags);
1202 EltTys.push_back(DTy);
1203 }
1204}
1205
1206/// CollectTemplateParams - A helper function to collect template parameters.
1207llvm::DIArray CGDebugInfo::
1208CollectTemplateParams(const TemplateParameterList *TPList,
David Blaikie47c11502013-06-22 18:59:18 +00001209 ArrayRef<TemplateArgument> TAList,
Guy Benyei11169dd2012-12-18 14:30:41 +00001210 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001211 SmallVector<llvm::Value *, 16> TemplateParams;
Guy Benyei11169dd2012-12-18 14:30:41 +00001212 for (unsigned i = 0, e = TAList.size(); i != e; ++i) {
1213 const TemplateArgument &TA = TAList[i];
David Blaikie47c11502013-06-22 18:59:18 +00001214 StringRef Name;
1215 if (TPList)
1216 Name = TPList->getParam(i)->getName();
David Blaikie38079fd2013-05-10 21:53:14 +00001217 switch (TA.getKind()) {
1218 case TemplateArgument::Type: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001219 llvm::DIType TTy = getOrCreateType(TA.getAsType(), Unit);
1220 llvm::DITemplateTypeParameter TTP =
David Blaikie47c11502013-06-22 18:59:18 +00001221 DBuilder.createTemplateTypeParameter(TheCU, Name, TTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00001222 TemplateParams.push_back(TTP);
David Blaikie38079fd2013-05-10 21:53:14 +00001223 } break;
1224 case TemplateArgument::Integral: {
Guy Benyei11169dd2012-12-18 14:30:41 +00001225 llvm::DIType TTy = getOrCreateType(TA.getIntegralType(), Unit);
1226 llvm::DITemplateValueParameter TVP =
David Blaikie38079fd2013-05-10 21:53:14 +00001227 DBuilder.createTemplateValueParameter(
David Blaikie47c11502013-06-22 18:59:18 +00001228 TheCU, Name, TTy,
David Blaikie38079fd2013-05-10 21:53:14 +00001229 llvm::ConstantInt::get(CGM.getLLVMContext(), TA.getAsIntegral()));
1230 TemplateParams.push_back(TVP);
1231 } break;
1232 case TemplateArgument::Declaration: {
1233 const ValueDecl *D = TA.getAsDecl();
1234 bool InstanceMember = D->isCXXInstanceMember();
1235 QualType T = InstanceMember
1236 ? CGM.getContext().getMemberPointerType(
1237 D->getType(), cast<RecordDecl>(D->getDeclContext())
1238 ->getTypeForDecl())
1239 : CGM.getContext().getPointerType(D->getType());
1240 llvm::DIType TTy = getOrCreateType(T, Unit);
1241 llvm::Value *V = 0;
1242 // Variable pointer template parameters have a value that is the address
1243 // of the variable.
1244 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1245 V = CGM.GetAddrOfGlobalVar(VD);
1246 // Member function pointers have special support for building them, though
1247 // this is currently unsupported in LLVM CodeGen.
David Blaikied900f982013-05-13 06:57:50 +00001248 if (InstanceMember) {
David Blaikie38079fd2013-05-10 21:53:14 +00001249 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(D))
1250 V = CGM.getCXXABI().EmitMemberPointer(method);
David Blaikied900f982013-05-13 06:57:50 +00001251 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1252 V = CGM.GetAddrOfFunction(FD);
David Blaikie38079fd2013-05-10 21:53:14 +00001253 // Member data pointers have special handling too to compute the fixed
1254 // offset within the object.
1255 if (isa<FieldDecl>(D)) {
1256 // These five lines (& possibly the above member function pointer
1257 // handling) might be able to be refactored to use similar code in
1258 // CodeGenModule::getMemberPointerConstant
1259 uint64_t fieldOffset = CGM.getContext().getFieldOffset(D);
1260 CharUnits chars =
1261 CGM.getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1262 V = CGM.getCXXABI().EmitMemberDataPointer(
1263 cast<MemberPointerType>(T.getTypePtr()), chars);
1264 }
1265 llvm::DITemplateValueParameter TVP =
David Majnemera3644d62013-08-25 22:13:27 +00001266 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1267 V->stripPointerCasts());
David Blaikie38079fd2013-05-10 21:53:14 +00001268 TemplateParams.push_back(TVP);
1269 } break;
1270 case TemplateArgument::NullPtr: {
1271 QualType T = TA.getNullPtrType();
1272 llvm::DIType TTy = getOrCreateType(T, Unit);
1273 llvm::Value *V = 0;
1274 // Special case member data pointer null values since they're actually -1
1275 // instead of zero.
1276 if (const MemberPointerType *MPT =
1277 dyn_cast<MemberPointerType>(T.getTypePtr()))
1278 // But treat member function pointers as simple zero integers because
1279 // it's easier than having a special case in LLVM's CodeGen. If LLVM
1280 // CodeGen grows handling for values of non-null member function
1281 // pointers then perhaps we could remove this special case and rely on
1282 // EmitNullMemberPointer for member function pointers.
1283 if (MPT->isMemberDataPointer())
1284 V = CGM.getCXXABI().EmitNullMemberPointer(MPT);
1285 if (!V)
1286 V = llvm::ConstantInt::get(CGM.Int8Ty, 0);
1287 llvm::DITemplateValueParameter TVP =
David Blaikie47c11502013-06-22 18:59:18 +00001288 DBuilder.createTemplateValueParameter(TheCU, Name, TTy, V);
David Blaikie38079fd2013-05-10 21:53:14 +00001289 TemplateParams.push_back(TVP);
1290 } break;
David Blaikie47c11502013-06-22 18:59:18 +00001291 case TemplateArgument::Template: {
1292 llvm::DITemplateValueParameter TVP =
1293 DBuilder.createTemplateTemplateParameter(
1294 TheCU, Name, llvm::DIType(),
1295 TA.getAsTemplate().getAsTemplateDecl()
1296 ->getQualifiedNameAsString());
1297 TemplateParams.push_back(TVP);
1298 } break;
1299 case TemplateArgument::Pack: {
1300 llvm::DITemplateValueParameter TVP =
1301 DBuilder.createTemplateParameterPack(
1302 TheCU, Name, llvm::DIType(),
1303 CollectTemplateParams(NULL, TA.getPackAsArray(), Unit));
1304 TemplateParams.push_back(TVP);
1305 } break;
David Majnemer5559d472013-08-24 08:21:10 +00001306 case TemplateArgument::Expression: {
1307 const Expr *E = TA.getAsExpr();
1308 QualType T = E->getType();
1309 llvm::Value *V = CGM.EmitConstantExpr(E, T);
1310 assert(V && "Expression in template argument isn't constant");
1311 llvm::DIType TTy = getOrCreateType(T, Unit);
1312 llvm::DITemplateValueParameter TVP =
1313 DBuilder.createTemplateValueParameter(TheCU, Name, TTy,
1314 V->stripPointerCasts());
1315 TemplateParams.push_back(TVP);
1316 } break;
David Blaikie2b93c542013-05-10 23:36:06 +00001317 // And the following should never occur:
David Blaikie38079fd2013-05-10 21:53:14 +00001318 case TemplateArgument::TemplateExpansion:
David Blaikie38079fd2013-05-10 21:53:14 +00001319 case TemplateArgument::Null:
1320 llvm_unreachable(
1321 "These argument types shouldn't exist in concrete types");
Guy Benyei11169dd2012-12-18 14:30:41 +00001322 }
1323 }
1324 return DBuilder.getOrCreateArray(TemplateParams);
1325}
1326
1327/// CollectFunctionTemplateParams - A helper function to collect debug
1328/// info for function template parameters.
1329llvm::DIArray CGDebugInfo::
1330CollectFunctionTemplateParams(const FunctionDecl *FD, llvm::DIFile Unit) {
1331 if (FD->getTemplatedKind() ==
1332 FunctionDecl::TK_FunctionTemplateSpecialization) {
1333 const TemplateParameterList *TList =
1334 FD->getTemplateSpecializationInfo()->getTemplate()
1335 ->getTemplateParameters();
David Blaikie47c11502013-06-22 18:59:18 +00001336 return CollectTemplateParams(
1337 TList, FD->getTemplateSpecializationArgs()->asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001338 }
1339 return llvm::DIArray();
1340}
1341
1342/// CollectCXXTemplateParams - A helper function to collect debug info for
1343/// template parameters.
1344llvm::DIArray CGDebugInfo::
1345CollectCXXTemplateParams(const ClassTemplateSpecializationDecl *TSpecial,
1346 llvm::DIFile Unit) {
1347 llvm::PointerUnion<ClassTemplateDecl *,
1348 ClassTemplatePartialSpecializationDecl *>
1349 PU = TSpecial->getSpecializedTemplateOrPartial();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001350
Guy Benyei11169dd2012-12-18 14:30:41 +00001351 TemplateParameterList *TPList = PU.is<ClassTemplateDecl *>() ?
1352 PU.get<ClassTemplateDecl *>()->getTemplateParameters() :
1353 PU.get<ClassTemplatePartialSpecializationDecl *>()->getTemplateParameters();
1354 const TemplateArgumentList &TAList = TSpecial->getTemplateInstantiationArgs();
David Blaikie47c11502013-06-22 18:59:18 +00001355 return CollectTemplateParams(TPList, TAList.asArray(), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00001356}
1357
1358/// getOrCreateVTablePtrType - Return debug info descriptor for vtable.
1359llvm::DIType CGDebugInfo::getOrCreateVTablePtrType(llvm::DIFile Unit) {
1360 if (VTablePtrType.isValid())
1361 return VTablePtrType;
1362
1363 ASTContext &Context = CGM.getContext();
1364
1365 /* Function type */
1366 llvm::Value *STy = getOrCreateType(Context.IntTy, Unit);
1367 llvm::DIArray SElements = DBuilder.getOrCreateArray(STy);
1368 llvm::DIType SubTy = DBuilder.createSubroutineType(Unit, SElements);
1369 unsigned Size = Context.getTypeSize(Context.VoidPtrTy);
1370 llvm::DIType vtbl_ptr_type = DBuilder.createPointerType(SubTy, Size, 0,
1371 "__vtbl_ptr_type");
1372 VTablePtrType = DBuilder.createPointerType(vtbl_ptr_type, Size);
1373 return VTablePtrType;
1374}
1375
1376/// getVTableName - Get vtable name for the given Class.
1377StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
Benjamin Kramer1b18a5e2013-09-09 16:39:06 +00001378 // Copy the gdb compatible name on the side and use its reference.
1379 return internString("_vptr$", RD->getNameAsString());
Guy Benyei11169dd2012-12-18 14:30:41 +00001380}
1381
1382
1383/// CollectVTableInfo - If the C++ class has vtable info then insert appropriate
1384/// debug info entry in EltTys vector.
1385void CGDebugInfo::
1386CollectVTableInfo(const CXXRecordDecl *RD, llvm::DIFile Unit,
1387 SmallVectorImpl<llvm::Value *> &EltTys) {
1388 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
1389
1390 // If there is a primary base then it will hold vtable info.
1391 if (RL.getPrimaryBase())
1392 return;
1393
1394 // If this class is not dynamic then there is not any vtable info to collect.
1395 if (!RD->isDynamicClass())
1396 return;
1397
1398 unsigned Size = CGM.getContext().getTypeSize(CGM.getContext().VoidPtrTy);
1399 llvm::DIType VPTR
1400 = DBuilder.createMemberType(Unit, getVTableName(RD), Unit,
Eric Christopher0fdcb312013-05-16 00:52:20 +00001401 0, Size, 0, 0,
1402 llvm::DIDescriptor::FlagArtificial,
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 getOrCreateVTablePtrType(Unit));
1404 EltTys.push_back(VPTR);
1405}
1406
Eric Christopherb2a008c2013-05-16 00:45:12 +00001407/// getOrCreateRecordType - Emit record type's standalone debug info.
1408llvm::DIType CGDebugInfo::getOrCreateRecordType(QualType RTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001410 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 llvm::DIType T = getOrCreateType(RTy, getOrCreateFile(Loc));
1412 return T;
1413}
1414
1415/// getOrCreateInterfaceType - Emit an objective c interface type standalone
1416/// debug info.
1417llvm::DIType CGDebugInfo::getOrCreateInterfaceType(QualType D,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001418 SourceLocation Loc) {
Eric Christopher75e17682013-05-16 00:45:23 +00001419 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 llvm::DIType T = getOrCreateType(D, getOrCreateFile(Loc));
Adrian Prantl73409ce2013-03-11 18:33:46 +00001421 RetainedTypes.push_back(D.getAsOpaquePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001422 return T;
1423}
1424
David Blaikieb2e86eb2013-08-15 20:49:17 +00001425void CGDebugInfo::completeType(const RecordDecl *RD) {
1426 if (DebugKind > CodeGenOptions::LimitedDebugInfo ||
1427 !CGM.getLangOpts().CPlusPlus)
1428 completeRequiredType(RD);
1429}
1430
1431void CGDebugInfo::completeRequiredType(const RecordDecl *RD) {
David Blaikie6943dea2013-08-20 01:28:15 +00001432 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1433 if (CXXDecl->isDynamicClass())
1434 return;
1435
David Blaikieb2e86eb2013-08-15 20:49:17 +00001436 QualType Ty = CGM.getContext().getRecordType(RD);
1437 llvm::DIType T = getTypeOrNull(Ty);
David Blaikie6943dea2013-08-20 01:28:15 +00001438 if (T && T.isForwardDecl())
1439 completeClassData(RD);
1440}
1441
1442void CGDebugInfo::completeClassData(const RecordDecl *RD) {
1443 if (DebugKind <= CodeGenOptions::DebugLineTablesOnly)
Michael Gottesman349542b2013-08-19 18:46:16 +00001444 return;
David Blaikie6943dea2013-08-20 01:28:15 +00001445 QualType Ty = CGM.getContext().getRecordType(RD);
David Blaikieb2e86eb2013-08-15 20:49:17 +00001446 void* TyPtr = Ty.getAsOpaquePtr();
1447 if (CompletedTypeCache.count(TyPtr))
1448 return;
1449 llvm::DIType Res = CreateTypeDefinition(Ty->castAs<RecordType>());
1450 assert(!Res.isForwardDecl());
1451 CompletedTypeCache[TyPtr] = Res;
1452 TypeCache[TyPtr] = Res;
1453}
1454
Guy Benyei11169dd2012-12-18 14:30:41 +00001455/// CreateType - get structure or union type.
David Blaikie99dab3b2013-09-04 22:03:57 +00001456llvm::DIType CGDebugInfo::CreateType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001457 RecordDecl *RD = Ty->getDecl();
David Blaikie6943dea2013-08-20 01:28:15 +00001458 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
David Blaikie99dab3b2013-09-04 22:03:57 +00001459 // Always emit declarations for types that aren't required to be complete when
1460 // in limit-debug-info mode. If the type is later found to be required to be
1461 // complete this declaration will be upgraded to a definition by
1462 // `completeRequiredType`.
1463 // If the type is dynamic, only emit the definition in TUs that require class
1464 // data. This is handled by `completeClassData`.
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001465 llvm::DICompositeType T(getTypeOrNull(QualType(Ty, 0)));
1466 // If we've already emitted the type, just use that, even if it's only a
1467 // declaration. The completeType, completeRequiredType, and completeClassData
1468 // callbacks will handle promoting the declaration to a definition.
1469 if (T ||
Adrian Prantld09906f2014-01-07 02:40:59 +00001470 // Under -fno-standalone-debug:
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001471 (DebugKind <= CodeGenOptions::LimitedDebugInfo &&
Adrian Prantla7634472014-01-07 01:19:08 +00001472 // Emit only a forward declaration unless the type is required.
1473 ((!RD->isCompleteDefinitionRequired() && CGM.getLangOpts().CPlusPlus) ||
1474 // If the class is dynamic, only emit a declaration. A definition will be
1475 // emitted whenever the vtable is emitted.
1476 (CXXDecl && CXXDecl->hasDefinition() && CXXDecl->isDynamicClass())))) {
David Blaikiee36464c2013-06-05 05:32:23 +00001477 llvm::DIDescriptor FDContext =
1478 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
David Blaikie3b1cc9b2013-09-06 06:45:04 +00001479 if (!T)
1480 T = getOrCreateRecordFwdDecl(Ty, FDContext);
1481 return T;
David Blaikiee36464c2013-06-05 05:32:23 +00001482 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001483
David Blaikieb2e86eb2013-08-15 20:49:17 +00001484 return CreateTypeDefinition(Ty);
1485}
1486
1487llvm::DIType CGDebugInfo::CreateTypeDefinition(const RecordType *Ty) {
1488 RecordDecl *RD = Ty->getDecl();
1489
Guy Benyei11169dd2012-12-18 14:30:41 +00001490 // Get overall information about the record type for the debug info.
1491 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
1492
1493 // Records and classes and unions can all be recursive. To handle them, we
1494 // first generate a debug descriptor for the struct as a forward declaration.
1495 // Then (if it is a definition) we go through and get debug info for all of
1496 // its members. Finally, we create a descriptor for the complete type (which
1497 // may refer to the forward decl if the struct is recursive) and replace all
1498 // uses of the forward declaration with the final definition.
1499
David Blaikie4a2b5ef2013-08-12 22:24:20 +00001500 llvm::DICompositeType FwdDecl(getOrCreateLimitedType(Ty, DefUnit));
Manman Ren0d441f12013-07-02 19:01:53 +00001501 assert(FwdDecl.isCompositeType() &&
David Blaikie469f0792013-05-22 23:22:42 +00001502 "The debug type of a RecordType should be a llvm::DICompositeType");
Guy Benyei11169dd2012-12-18 14:30:41 +00001503
1504 if (FwdDecl.isForwardDecl())
1505 return FwdDecl;
1506
David Blaikieadfbf992013-08-18 16:55:33 +00001507 if (const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD))
1508 CollectContainingType(CXXDecl, FwdDecl);
1509
Guy Benyei11169dd2012-12-18 14:30:41 +00001510 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001511 LexicalBlockStack.push_back(&*FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1513
Adrian Prantla03a85a2013-03-06 22:03:30 +00001514 // Add this to the completed-type cache while we're completing it recursively.
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 CompletedTypeCache[QualType(Ty, 0).getAsOpaquePtr()] = FwdDecl;
1516
1517 // Convert all the elements.
1518 SmallVector<llvm::Value *, 16> EltTys;
David Blaikie6943dea2013-08-20 01:28:15 +00001519 // what about nested types?
Guy Benyei11169dd2012-12-18 14:30:41 +00001520
1521 // Note: The split of CXXDecl information here is intentional, the
1522 // gdb tests will depend on a certain ordering at printout. The debug
1523 // information offsets are still correct if we merge them all together
1524 // though.
1525 const CXXRecordDecl *CXXDecl = dyn_cast<CXXRecordDecl>(RD);
1526 if (CXXDecl) {
1527 CollectCXXBases(CXXDecl, DefUnit, EltTys, FwdDecl);
1528 CollectVTableInfo(CXXDecl, DefUnit, EltTys);
1529 }
1530
Eric Christopher91a31902013-01-16 01:22:32 +00001531 // Collect data fields (including static variables and any initializers).
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 CollectRecordFields(RD, DefUnit, EltTys, FwdDecl);
Eric Christopher2df080e2013-10-11 18:16:51 +00001533 if (CXXDecl)
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 CollectCXXMemberFunctions(CXXDecl, DefUnit, EltTys, FwdDecl);
Guy Benyei11169dd2012-12-18 14:30:41 +00001535
1536 LexicalBlockStack.pop_back();
1537 RegionMap.erase(Ty->getDecl());
1538
1539 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
David Blaikie4a5b8952013-08-01 20:31:40 +00001540 FwdDecl.setTypeArray(Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00001541
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001542 RegionMap[Ty->getDecl()] = llvm::WeakVH(FwdDecl);
1543 return FwdDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001544}
1545
1546/// CreateType - get objective-c object type.
1547llvm::DIType CGDebugInfo::CreateType(const ObjCObjectType *Ty,
1548 llvm::DIFile Unit) {
1549 // Ignore protocols.
1550 return getOrCreateType(Ty->getBaseType(), Unit);
1551}
1552
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001553
1554/// \return true if Getter has the default name for the property PD.
1555static bool hasDefaultGetterName(const ObjCPropertyDecl *PD,
1556 const ObjCMethodDecl *Getter) {
1557 assert(PD);
1558 if (!Getter)
1559 return true;
1560
1561 assert(Getter->getDeclName().isObjCZeroArgSelector());
1562 return PD->getName() ==
1563 Getter->getDeclName().getObjCSelector().getNameForSlot(0);
1564}
1565
1566/// \return true if Setter has the default name for the property PD.
1567static bool hasDefaultSetterName(const ObjCPropertyDecl *PD,
1568 const ObjCMethodDecl *Setter) {
1569 assert(PD);
1570 if (!Setter)
1571 return true;
1572
1573 assert(Setter->getDeclName().isObjCOneArgSelector());
Adrian Prantla4ce9062013-06-07 22:29:12 +00001574 return SelectorTable::constructSetterName(PD->getName()) ==
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001575 Setter->getDeclName().getObjCSelector().getNameForSlot(0);
1576}
1577
Guy Benyei11169dd2012-12-18 14:30:41 +00001578/// CreateType - get objective-c interface type.
1579llvm::DIType CGDebugInfo::CreateType(const ObjCInterfaceType *Ty,
1580 llvm::DIFile Unit) {
1581 ObjCInterfaceDecl *ID = Ty->getDecl();
1582 if (!ID)
1583 return llvm::DIType();
1584
1585 // Get overall information about the record type for the debug info.
1586 llvm::DIFile DefUnit = getOrCreateFile(ID->getLocation());
1587 unsigned Line = getLineNumber(ID->getLocation());
1588 unsigned RuntimeLang = TheCU.getLanguage();
1589
1590 // If this is just a forward declaration return a special forward-declaration
1591 // debug type since we won't be able to lay out the entire type.
1592 ObjCInterfaceDecl *Def = ID->getDefinition();
1593 if (!Def) {
1594 llvm::DIType FwdDecl =
1595 DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
Eric Christopherc0c5d462013-02-21 22:35:08 +00001596 ID->getName(), TheCU, DefUnit, Line,
1597 RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 return FwdDecl;
1599 }
1600
1601 ID = Def;
1602
1603 // Bit size, align and offset of the type.
1604 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1605 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1606
1607 unsigned Flags = 0;
1608 if (ID->getImplementation())
1609 Flags |= llvm::DIDescriptor::FlagObjcClassComplete;
1610
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001611 llvm::DICompositeType RealDecl =
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 DBuilder.createStructType(Unit, ID->getName(), DefUnit,
1613 Line, Size, Align, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00001614 llvm::DIType(), llvm::DIArray(), RuntimeLang);
Guy Benyei11169dd2012-12-18 14:30:41 +00001615
1616 // Otherwise, insert it into the CompletedTypeCache so that recursive uses
1617 // will find it and we're emitting the complete type.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001618 QualType QualTy = QualType(Ty, 0);
1619 CompletedTypeCache[QualTy.getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001620
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001621 // Push the struct on region stack.
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001622 LexicalBlockStack.push_back(static_cast<llvm::MDNode*>(RealDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
1624
1625 // Convert all the elements.
1626 SmallVector<llvm::Value *, 16> EltTys;
1627
1628 ObjCInterfaceDecl *SClass = ID->getSuperClass();
1629 if (SClass) {
1630 llvm::DIType SClassTy =
1631 getOrCreateType(CGM.getContext().getObjCInterfaceType(SClass), Unit);
1632 if (!SClassTy.isValid())
1633 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001634
Guy Benyei11169dd2012-12-18 14:30:41 +00001635 llvm::DIType InhTag =
1636 DBuilder.createInheritance(RealDecl, SClassTy, 0, 0);
1637 EltTys.push_back(InhTag);
1638 }
1639
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001640 // Create entries for all of the properties.
Guy Benyei11169dd2012-12-18 14:30:41 +00001641 for (ObjCContainerDecl::prop_iterator I = ID->prop_begin(),
1642 E = ID->prop_end(); I != E; ++I) {
1643 const ObjCPropertyDecl *PD = *I;
1644 SourceLocation Loc = PD->getLocation();
1645 llvm::DIFile PUnit = getOrCreateFile(Loc);
1646 unsigned PLine = getLineNumber(Loc);
1647 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1648 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1649 llvm::MDNode *PropertyNode =
1650 DBuilder.createObjCProperty(PD->getName(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001651 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001652 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001653 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001654 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001655 getSelectorName(PD->getSetterName()),
1656 PD->getPropertyAttributes(),
Eric Christopherc0c5d462013-02-21 22:35:08 +00001657 getOrCreateType(PD->getType(), PUnit));
Guy Benyei11169dd2012-12-18 14:30:41 +00001658 EltTys.push_back(PropertyNode);
1659 }
1660
1661 const ASTRecordLayout &RL = CGM.getContext().getASTObjCInterfaceLayout(ID);
1662 unsigned FieldNo = 0;
1663 for (ObjCIvarDecl *Field = ID->all_declared_ivar_begin(); Field;
1664 Field = Field->getNextIvar(), ++FieldNo) {
1665 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
1666 if (!FieldTy.isValid())
1667 return llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001668
Guy Benyei11169dd2012-12-18 14:30:41 +00001669 StringRef FieldName = Field->getName();
1670
1671 // Ignore unnamed fields.
1672 if (FieldName.empty())
1673 continue;
1674
1675 // Get the location for the field.
1676 llvm::DIFile FieldDefUnit = getOrCreateFile(Field->getLocation());
1677 unsigned FieldLine = getLineNumber(Field->getLocation());
1678 QualType FType = Field->getType();
1679 uint64_t FieldSize = 0;
1680 unsigned FieldAlign = 0;
1681
1682 if (!FType->isIncompleteArrayType()) {
1683
1684 // Bit size, align and offset of the type.
1685 FieldSize = Field->isBitField()
Eric Christopher35f1f9f2013-07-14 21:00:07 +00001686 ? Field->getBitWidthValue(CGM.getContext())
1687 : CGM.getContext().getTypeSize(FType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001688 FieldAlign = CGM.getContext().getTypeAlign(FType);
1689 }
1690
1691 uint64_t FieldOffset;
1692 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1693 // We don't know the runtime offset of an ivar if we're using the
1694 // non-fragile ABI. For bitfields, use the bit offset into the first
1695 // byte of storage of the bitfield. For other fields, use zero.
1696 if (Field->isBitField()) {
1697 FieldOffset = CGM.getObjCRuntime().ComputeBitfieldBitOffset(
1698 CGM, ID, Field);
1699 FieldOffset %= CGM.getContext().getCharWidth();
1700 } else {
1701 FieldOffset = 0;
1702 }
1703 } else {
1704 FieldOffset = RL.getFieldOffset(FieldNo);
1705 }
1706
1707 unsigned Flags = 0;
1708 if (Field->getAccessControl() == ObjCIvarDecl::Protected)
1709 Flags = llvm::DIDescriptor::FlagProtected;
1710 else if (Field->getAccessControl() == ObjCIvarDecl::Private)
1711 Flags = llvm::DIDescriptor::FlagPrivate;
1712
1713 llvm::MDNode *PropertyNode = NULL;
1714 if (ObjCImplementationDecl *ImpD = ID->getImplementation()) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001715 if (ObjCPropertyImplDecl *PImpD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 ImpD->FindPropertyImplIvarDecl(Field->getIdentifier())) {
1717 if (ObjCPropertyDecl *PD = PImpD->getPropertyDecl()) {
Eric Christopherc0c5d462013-02-21 22:35:08 +00001718 SourceLocation Loc = PD->getLocation();
1719 llvm::DIFile PUnit = getOrCreateFile(Loc);
1720 unsigned PLine = getLineNumber(Loc);
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 ObjCMethodDecl *Getter = PD->getGetterMethodDecl();
1722 ObjCMethodDecl *Setter = PD->getSetterMethodDecl();
1723 PropertyNode =
1724 DBuilder.createObjCProperty(PD->getName(),
1725 PUnit, PLine,
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001726 hasDefaultGetterName(PD, Getter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001727 getSelectorName(PD->getGetterName()),
Adrian Prantlb8fad1a2013-06-07 01:10:45 +00001728 hasDefaultSetterName(PD, Setter) ? "" :
Guy Benyei11169dd2012-12-18 14:30:41 +00001729 getSelectorName(PD->getSetterName()),
1730 PD->getPropertyAttributes(),
1731 getOrCreateType(PD->getType(), PUnit));
1732 }
1733 }
1734 }
1735 FieldTy = DBuilder.createObjCIVar(FieldName, FieldDefUnit,
1736 FieldLine, FieldSize, FieldAlign,
1737 FieldOffset, Flags, FieldTy,
1738 PropertyNode);
1739 EltTys.push_back(FieldTy);
1740 }
1741
1742 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001743 RealDecl.setTypeArray(Elements);
Adrian Prantla03a85a2013-03-06 22:03:30 +00001744
1745 // If the implementation is not yet set, we do not want to mark it
1746 // as complete. An implementation may declare additional
1747 // private ivars that we would miss otherwise.
1748 if (ID->getImplementation() == 0)
1749 CompletedTypeCache.erase(QualTy.getAsOpaquePtr());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001750
Guy Benyei11169dd2012-12-18 14:30:41 +00001751 LexicalBlockStack.pop_back();
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00001752 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00001753}
1754
1755llvm::DIType CGDebugInfo::CreateType(const VectorType *Ty, llvm::DIFile Unit) {
1756 llvm::DIType ElementTy = getOrCreateType(Ty->getElementType(), Unit);
1757 int64_t Count = Ty->getNumElements();
1758 if (Count == 0)
1759 // If number of elements are not known then this is an unbounded array.
1760 // Use Count == -1 to express such arrays.
1761 Count = -1;
1762
1763 llvm::Value *Subscript = DBuilder.getOrCreateSubrange(0, Count);
1764 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscript);
1765
1766 uint64_t Size = CGM.getContext().getTypeSize(Ty);
1767 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
1768
1769 return DBuilder.createVectorType(Size, Align, ElementTy, SubscriptArray);
1770}
1771
1772llvm::DIType CGDebugInfo::CreateType(const ArrayType *Ty,
1773 llvm::DIFile Unit) {
1774 uint64_t Size;
1775 uint64_t Align;
1776
1777 // FIXME: make getTypeAlign() aware of VLAs and incomplete array types
1778 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Ty)) {
1779 Size = 0;
1780 Align =
1781 CGM.getContext().getTypeAlign(CGM.getContext().getBaseElementType(VAT));
1782 } else if (Ty->isIncompleteArrayType()) {
1783 Size = 0;
1784 if (Ty->getElementType()->isIncompleteType())
1785 Align = 0;
1786 else
1787 Align = CGM.getContext().getTypeAlign(Ty->getElementType());
David Blaikief03b2e82013-05-09 20:48:12 +00001788 } else if (Ty->isIncompleteType()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001789 Size = 0;
1790 Align = 0;
1791 } else {
1792 // Size and align of the whole array, not the element type.
1793 Size = CGM.getContext().getTypeSize(Ty);
1794 Align = CGM.getContext().getTypeAlign(Ty);
1795 }
1796
1797 // Add the dimensions of the array. FIXME: This loses CV qualifiers from
1798 // interior arrays, do we care? Why aren't nested arrays represented the
1799 // obvious/recursive way?
1800 SmallVector<llvm::Value *, 8> Subscripts;
1801 QualType EltTy(Ty, 0);
1802 while ((Ty = dyn_cast<ArrayType>(EltTy))) {
1803 // If the number of elements is known, then count is that number. Otherwise,
1804 // it's -1. This allows us to represent a subrange with an array of 0
1805 // elements, like this:
1806 //
1807 // struct foo {
1808 // int x[0];
1809 // };
1810 int64_t Count = -1; // Count == -1 is an unbounded array.
1811 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Ty))
1812 Count = CAT->getSize().getZExtValue();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001813
Guy Benyei11169dd2012-12-18 14:30:41 +00001814 // FIXME: Verify this is right for VLAs.
1815 Subscripts.push_back(DBuilder.getOrCreateSubrange(0, Count));
1816 EltTy = Ty->getElementType();
1817 }
1818
1819 llvm::DIArray SubscriptArray = DBuilder.getOrCreateArray(Subscripts);
1820
Eric Christopherb2a008c2013-05-16 00:45:12 +00001821 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001822 DBuilder.createArrayType(Size, Align, getOrCreateType(EltTy, Unit),
1823 SubscriptArray);
1824 return DbgTy;
1825}
1826
Eric Christopherb2a008c2013-05-16 00:45:12 +00001827llvm::DIType CGDebugInfo::CreateType(const LValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001828 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001829 return CreatePointerLikeType(llvm::dwarf::DW_TAG_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 Ty, Ty->getPointeeType(), Unit);
1831}
1832
Eric Christopherb2a008c2013-05-16 00:45:12 +00001833llvm::DIType CGDebugInfo::CreateType(const RValueReferenceType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001834 llvm::DIFile Unit) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00001835 return CreatePointerLikeType(llvm::dwarf::DW_TAG_rvalue_reference_type,
Guy Benyei11169dd2012-12-18 14:30:41 +00001836 Ty, Ty->getPointeeType(), Unit);
1837}
1838
Eric Christopherb2a008c2013-05-16 00:45:12 +00001839llvm::DIType CGDebugInfo::CreateType(const MemberPointerType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 llvm::DIFile U) {
David Blaikie2c705ca2013-01-19 19:20:56 +00001841 llvm::DIType ClassType = getOrCreateType(QualType(Ty->getClass(), 0), U);
1842 if (!Ty->getPointeeType()->isFunctionType())
1843 return DBuilder.createMemberPointerType(
David Blaikie99dab3b2013-09-04 22:03:57 +00001844 getOrCreateType(Ty->getPointeeType(), U), ClassType);
Adrian Prantl0866acd2013-12-19 01:38:47 +00001845
1846 const FunctionProtoType *FPT =
1847 Ty->getPointeeType()->getAs<FunctionProtoType>();
David Blaikie2c705ca2013-01-19 19:20:56 +00001848 return DBuilder.createMemberPointerType(getOrCreateInstanceMethodType(
Adrian Prantl0866acd2013-12-19 01:38:47 +00001849 CGM.getContext().getPointerType(QualType(Ty->getClass(),
1850 FPT->getTypeQuals())),
1851 FPT, U), ClassType);
Guy Benyei11169dd2012-12-18 14:30:41 +00001852}
1853
Eric Christopherb2a008c2013-05-16 00:45:12 +00001854llvm::DIType CGDebugInfo::CreateType(const AtomicType *Ty,
Guy Benyei11169dd2012-12-18 14:30:41 +00001855 llvm::DIFile U) {
1856 // Ignore the atomic wrapping
1857 // FIXME: What is the correct representation?
1858 return getOrCreateType(Ty->getValueType(), U);
1859}
1860
1861/// CreateEnumType - get enumeration type.
Manman Ren501ecf92013-08-28 21:46:36 +00001862llvm::DIType CGDebugInfo::CreateEnumType(const EnumType *Ty) {
Manman Ren1b457022013-08-28 21:20:28 +00001863 const EnumDecl *ED = Ty->getDecl();
Guy Benyei11169dd2012-12-18 14:30:41 +00001864 uint64_t Size = 0;
1865 uint64_t Align = 0;
1866 if (!ED->getTypeForDecl()->isIncompleteType()) {
1867 Size = CGM.getContext().getTypeSize(ED->getTypeForDecl());
1868 Align = CGM.getContext().getTypeAlign(ED->getTypeForDecl());
1869 }
1870
Manman Rene0064d82013-08-29 23:19:58 +00001871 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
1872
Guy Benyei11169dd2012-12-18 14:30:41 +00001873 // If this is just a forward declaration, construct an appropriately
1874 // marked node and just return it.
1875 if (!ED->getDefinition()) {
1876 llvm::DIDescriptor EDContext;
1877 EDContext = getContextDescriptor(cast<Decl>(ED->getDeclContext()));
1878 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1879 unsigned Line = getLineNumber(ED->getLocation());
1880 StringRef EDName = ED->getName();
1881 return DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_enumeration_type,
1882 EDName, EDContext, DefUnit, Line, 0,
Manman Rene0064d82013-08-29 23:19:58 +00001883 Size, Align, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001884 }
1885
1886 // Create DIEnumerator elements for each enumerator.
1887 SmallVector<llvm::Value *, 16> Enumerators;
1888 ED = ED->getDefinition();
1889 for (EnumDecl::enumerator_iterator
1890 Enum = ED->enumerator_begin(), EnumEnd = ED->enumerator_end();
1891 Enum != EnumEnd; ++Enum) {
1892 Enumerators.push_back(
1893 DBuilder.createEnumerator(Enum->getName(),
David Blaikiece1ae382013-06-24 07:13:13 +00001894 Enum->getInitVal().getSExtValue()));
Guy Benyei11169dd2012-12-18 14:30:41 +00001895 }
1896
1897 // Return a CompositeType for the enum itself.
1898 llvm::DIArray EltArray = DBuilder.getOrCreateArray(Enumerators);
1899
1900 llvm::DIFile DefUnit = getOrCreateFile(ED->getLocation());
1901 unsigned Line = getLineNumber(ED->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001902 llvm::DIDescriptor EnumContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00001903 getContextDescriptor(cast<Decl>(ED->getDeclContext()));
Adrian Prantlc60dc712013-04-19 19:56:39 +00001904 llvm::DIType ClassTy = ED->isFixed() ?
Guy Benyei11169dd2012-12-18 14:30:41 +00001905 getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
Eric Christopherb2a008c2013-05-16 00:45:12 +00001906 llvm::DIType DbgTy =
Guy Benyei11169dd2012-12-18 14:30:41 +00001907 DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
1908 Size, Align, EltArray,
Manman Rene0064d82013-08-29 23:19:58 +00001909 ClassTy, FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00001910 return DbgTy;
1911}
1912
David Blaikie05491062013-01-21 04:37:12 +00001913static QualType UnwrapTypeForDebugInfo(QualType T, const ASTContext &C) {
1914 Qualifiers Quals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001915 do {
Adrian Prantl179af902013-09-26 21:35:50 +00001916 Qualifiers InnerQuals = T.getLocalQualifiers();
1917 // Qualifiers::operator+() doesn't like it if you add a Qualifier
1918 // that is already there.
1919 Quals += Qualifiers::removeCommonQualifiers(Quals, InnerQuals);
1920 Quals += InnerQuals;
Guy Benyei11169dd2012-12-18 14:30:41 +00001921 QualType LastT = T;
1922 switch (T->getTypeClass()) {
1923 default:
David Blaikie05491062013-01-21 04:37:12 +00001924 return C.getQualifiedType(T.getTypePtr(), Quals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001925 case Type::TemplateSpecialization:
1926 T = cast<TemplateSpecializationType>(T)->desugar();
1927 break;
1928 case Type::TypeOfExpr:
1929 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
1930 break;
1931 case Type::TypeOf:
1932 T = cast<TypeOfType>(T)->getUnderlyingType();
1933 break;
1934 case Type::Decltype:
1935 T = cast<DecltypeType>(T)->getUnderlyingType();
1936 break;
1937 case Type::UnaryTransform:
1938 T = cast<UnaryTransformType>(T)->getUnderlyingType();
1939 break;
1940 case Type::Attributed:
1941 T = cast<AttributedType>(T)->getEquivalentType();
1942 break;
1943 case Type::Elaborated:
1944 T = cast<ElaboratedType>(T)->getNamedType();
1945 break;
1946 case Type::Paren:
1947 T = cast<ParenType>(T)->getInnerType();
1948 break;
David Blaikie05491062013-01-21 04:37:12 +00001949 case Type::SubstTemplateTypeParm:
Guy Benyei11169dd2012-12-18 14:30:41 +00001950 T = cast<SubstTemplateTypeParmType>(T)->getReplacementType();
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 break;
1952 case Type::Auto:
David Blaikie22c460a02013-05-24 21:24:35 +00001953 QualType DT = cast<AutoType>(T)->getDeducedType();
1954 if (DT.isNull())
1955 return T;
1956 T = DT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001957 break;
1958 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00001959
Guy Benyei11169dd2012-12-18 14:30:41 +00001960 assert(T != LastT && "Type unwrapping failed to unwrap!");
NAKAMURA Takumi3e0a3632013-01-21 10:51:28 +00001961 (void)LastT;
Guy Benyei11169dd2012-12-18 14:30:41 +00001962 } while (true);
1963}
1964
Eric Christopher0fdcb312013-05-16 00:52:20 +00001965/// getType - Get the type from the cache or return null type if it doesn't
1966/// exist.
Guy Benyei11169dd2012-12-18 14:30:41 +00001967llvm::DIType CGDebugInfo::getTypeOrNull(QualType Ty) {
1968
1969 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001970 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Eric Christopherb2a008c2013-05-16 00:45:12 +00001971
Guy Benyei11169dd2012-12-18 14:30:41 +00001972 // Check for existing entry.
Adrian Prantl73409ce2013-03-11 18:33:46 +00001973 if (Ty->getTypeClass() == Type::ObjCInterface) {
1974 llvm::Value *V = getCachedInterfaceTypeOrNull(Ty);
1975 if (V)
1976 return llvm::DIType(cast<llvm::MDNode>(V));
1977 else return llvm::DIType();
1978 }
1979
Guy Benyei11169dd2012-12-18 14:30:41 +00001980 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
1981 TypeCache.find(Ty.getAsOpaquePtr());
1982 if (it != TypeCache.end()) {
1983 // Verify that the debug info still exists.
1984 if (llvm::Value *V = it->second)
1985 return llvm::DIType(cast<llvm::MDNode>(V));
1986 }
1987
1988 return llvm::DIType();
1989}
1990
1991/// getCompletedTypeOrNull - Get the type from the cache or return null if it
1992/// doesn't exist.
1993llvm::DIType CGDebugInfo::getCompletedTypeOrNull(QualType Ty) {
1994
1995 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00001996 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001997
1998 // Check for existing entry.
Adrian Prantla03a85a2013-03-06 22:03:30 +00001999 llvm::Value *V = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +00002000 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
2001 CompletedTypeCache.find(Ty.getAsOpaquePtr());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002002 if (it != CompletedTypeCache.end())
2003 V = it->second;
2004 else {
Adrian Prantl73409ce2013-03-11 18:33:46 +00002005 V = getCachedInterfaceTypeOrNull(Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002006 }
2007
Adrian Prantla03a85a2013-03-06 22:03:30 +00002008 // Verify that any cached debug info still exists.
David Blaikie80d28de2013-08-13 04:21:38 +00002009 return llvm::DIType(cast_or_null<llvm::MDNode>(V));
Guy Benyei11169dd2012-12-18 14:30:41 +00002010}
2011
Adrian Prantl73409ce2013-03-11 18:33:46 +00002012/// getCachedInterfaceTypeOrNull - Get the type from the interface
2013/// cache, unless it needs to regenerated. Otherwise return null.
2014llvm::Value *CGDebugInfo::getCachedInterfaceTypeOrNull(QualType Ty) {
2015 // Is there a cached interface that hasn't changed?
2016 llvm::DenseMap<void *, std::pair<llvm::WeakVH, unsigned > >
2017 ::iterator it1 = ObjCInterfaceCache.find(Ty.getAsOpaquePtr());
2018
2019 if (it1 != ObjCInterfaceCache.end())
2020 if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty))
2021 if (Checksum(Decl) == it1->second.second)
2022 // Return cached forward declaration.
2023 return it1->second.first;
2024
2025 return 0;
2026}
Guy Benyei11169dd2012-12-18 14:30:41 +00002027
2028/// getOrCreateType - Get the type from the cache or create a new
2029/// one if necessary.
David Blaikie99dab3b2013-09-04 22:03:57 +00002030llvm::DIType CGDebugInfo::getOrCreateType(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002031 if (Ty.isNull())
2032 return llvm::DIType();
2033
2034 // Unwrap the type as needed for debug information.
David Blaikie05491062013-01-21 04:37:12 +00002035 Ty = UnwrapTypeForDebugInfo(Ty, CGM.getContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002036
David Blaikie99dab3b2013-09-04 22:03:57 +00002037 if (llvm::DIType T = getCompletedTypeOrNull(Ty))
Guy Benyei11169dd2012-12-18 14:30:41 +00002038 return T;
2039
2040 // Otherwise create the type.
David Blaikie99dab3b2013-09-04 22:03:57 +00002041 llvm::DIType Res = CreateTypeNode(Ty, Unit);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002042 void* TyPtr = Ty.getAsOpaquePtr();
2043
2044 // And update the type cache.
2045 TypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002046
David Blaikie6a723442013-08-15 21:21:19 +00002047 // FIXME: this getTypeOrNull call seems silly when we just inserted the type
2048 // into the cache - but getTypeOrNull has a special case for cached interface
2049 // types. We should probably just pull that out as a special case for the
2050 // "else" block below & skip the otherwise needless lookup.
Guy Benyei11169dd2012-12-18 14:30:41 +00002051 llvm::DIType TC = getTypeOrNull(Ty);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002052 if (TC && TC.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002053 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2054 else if (ObjCInterfaceDecl* Decl = getObjCInterfaceDecl(Ty)) {
2055 // Interface types may have elements added to them by a
2056 // subsequent implementation or extension, so we keep them in
2057 // the ObjCInterfaceCache together with a checksum. Instead of
Adrian Prantlc20237d2013-05-08 23:37:22 +00002058 // the (possibly) incomplete interface type, we return a forward
Adrian Prantl73409ce2013-03-11 18:33:46 +00002059 // declaration that gets RAUW'd in CGDebugInfo::finalize().
David Blaikie8e5939b2013-05-21 18:29:40 +00002060 std::pair<llvm::WeakVH, unsigned> &V = ObjCInterfaceCache[TyPtr];
2061 if (V.first)
2062 return llvm::DIType(cast<llvm::MDNode>(V.first));
2063 TC = DBuilder.createForwardDecl(llvm::dwarf::DW_TAG_structure_type,
2064 Decl->getName(), TheCU, Unit,
2065 getLineNumber(Decl->getLocation()),
2066 TheCU.getLanguage());
2067 // Store the forward declaration in the cache.
2068 V.first = TC;
2069 V.second = Checksum(Decl);
Adrian Prantl73409ce2013-03-11 18:33:46 +00002070
David Blaikie8e5939b2013-05-21 18:29:40 +00002071 // Register the type for replacement in finalize().
2072 ReplaceMap.push_back(std::make_pair(TyPtr, static_cast<llvm::Value*>(TC)));
2073
Adrian Prantl73409ce2013-03-11 18:33:46 +00002074 return TC;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002075 }
2076
Guy Benyei11169dd2012-12-18 14:30:41 +00002077 if (!Res.isForwardDecl())
Adrian Prantl73409ce2013-03-11 18:33:46 +00002078 CompletedTypeCache[TyPtr] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002079
2080 return Res;
2081}
2082
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002083/// Currently the checksum of an interface includes the number of
2084/// ivars and property accessors.
Eric Christopher1ecc5632013-06-07 22:54:39 +00002085unsigned CGDebugInfo::Checksum(const ObjCInterfaceDecl *ID) {
Adrian Prantl817bbb32013-06-07 01:10:48 +00002086 // The assumption is that the number of ivars can only increase
2087 // monotonically, so it is safe to just use their current number as
2088 // a checksum.
Adrian Prantlc4de1ef2013-06-07 01:10:41 +00002089 unsigned Sum = 0;
2090 for (const ObjCIvarDecl *Ivar = ID->all_declared_ivar_begin();
2091 Ivar != 0; Ivar = Ivar->getNextIvar())
2092 ++Sum;
2093
2094 return Sum;
Adrian Prantla03a85a2013-03-06 22:03:30 +00002095}
2096
2097ObjCInterfaceDecl *CGDebugInfo::getObjCInterfaceDecl(QualType Ty) {
2098 switch (Ty->getTypeClass()) {
2099 case Type::ObjCObjectPointer:
Eric Christopher0fdcb312013-05-16 00:52:20 +00002100 return getObjCInterfaceDecl(cast<ObjCObjectPointerType>(Ty)
2101 ->getPointeeType());
Adrian Prantla03a85a2013-03-06 22:03:30 +00002102 case Type::ObjCInterface:
2103 return cast<ObjCInterfaceType>(Ty)->getDecl();
2104 default:
2105 return 0;
2106 }
2107}
2108
Guy Benyei11169dd2012-12-18 14:30:41 +00002109/// CreateTypeNode - Create a new debug type node.
David Blaikie99dab3b2013-09-04 22:03:57 +00002110llvm::DIType CGDebugInfo::CreateTypeNode(QualType Ty, llvm::DIFile Unit) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002111 // Handle qualifiers, which recursively handles what they refer to.
2112 if (Ty.hasLocalQualifiers())
David Blaikie99dab3b2013-09-04 22:03:57 +00002113 return CreateQualifiedType(Ty, Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002114
2115 const char *Diag = 0;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002116
Guy Benyei11169dd2012-12-18 14:30:41 +00002117 // Work out details of type.
2118 switch (Ty->getTypeClass()) {
2119#define TYPE(Class, Base)
2120#define ABSTRACT_TYPE(Class, Base)
2121#define NON_CANONICAL_TYPE(Class, Base)
2122#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2123#include "clang/AST/TypeNodes.def"
2124 llvm_unreachable("Dependent types cannot show up in debug information");
2125
2126 case Type::ExtVector:
2127 case Type::Vector:
2128 return CreateType(cast<VectorType>(Ty), Unit);
2129 case Type::ObjCObjectPointer:
2130 return CreateType(cast<ObjCObjectPointerType>(Ty), Unit);
2131 case Type::ObjCObject:
2132 return CreateType(cast<ObjCObjectType>(Ty), Unit);
2133 case Type::ObjCInterface:
2134 return CreateType(cast<ObjCInterfaceType>(Ty), Unit);
2135 case Type::Builtin:
2136 return CreateType(cast<BuiltinType>(Ty));
2137 case Type::Complex:
2138 return CreateType(cast<ComplexType>(Ty));
2139 case Type::Pointer:
2140 return CreateType(cast<PointerType>(Ty), Unit);
Reid Kleckner0503a872013-12-05 01:23:43 +00002141 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +00002142 case Type::Decayed:
Reid Kleckner0503a872013-12-05 01:23:43 +00002143 // Decayed and adjusted types use the adjusted type in LLVM and DWARF.
Reid Kleckner8a365022013-06-24 17:51:48 +00002144 return CreateType(
Reid Kleckner0503a872013-12-05 01:23:43 +00002145 cast<PointerType>(cast<AdjustedType>(Ty)->getAdjustedType()), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002146 case Type::BlockPointer:
2147 return CreateType(cast<BlockPointerType>(Ty), Unit);
2148 case Type::Typedef:
David Blaikie99dab3b2013-09-04 22:03:57 +00002149 return CreateType(cast<TypedefType>(Ty), Unit);
Guy Benyei11169dd2012-12-18 14:30:41 +00002150 case Type::Record:
David Blaikie99dab3b2013-09-04 22:03:57 +00002151 return CreateType(cast<RecordType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002152 case Type::Enum:
Manman Ren1b457022013-08-28 21:20:28 +00002153 return CreateEnumType(cast<EnumType>(Ty));
Guy Benyei11169dd2012-12-18 14:30:41 +00002154 case Type::FunctionProto:
2155 case Type::FunctionNoProto:
2156 return CreateType(cast<FunctionType>(Ty), Unit);
2157 case Type::ConstantArray:
2158 case Type::VariableArray:
2159 case Type::IncompleteArray:
2160 return CreateType(cast<ArrayType>(Ty), Unit);
2161
2162 case Type::LValueReference:
2163 return CreateType(cast<LValueReferenceType>(Ty), Unit);
2164 case Type::RValueReference:
2165 return CreateType(cast<RValueReferenceType>(Ty), Unit);
2166
2167 case Type::MemberPointer:
2168 return CreateType(cast<MemberPointerType>(Ty), Unit);
2169
2170 case Type::Atomic:
2171 return CreateType(cast<AtomicType>(Ty), Unit);
2172
2173 case Type::Attributed:
2174 case Type::TemplateSpecialization:
2175 case Type::Elaborated:
2176 case Type::Paren:
2177 case Type::SubstTemplateTypeParm:
2178 case Type::TypeOfExpr:
2179 case Type::TypeOf:
2180 case Type::Decltype:
2181 case Type::UnaryTransform:
David Blaikie66ed89d2013-07-13 21:08:08 +00002182 case Type::PackExpansion:
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 llvm_unreachable("type should have been unwrapped!");
David Blaikie22c460a02013-05-24 21:24:35 +00002184 case Type::Auto:
2185 Diag = "auto";
2186 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002188
Guy Benyei11169dd2012-12-18 14:30:41 +00002189 assert(Diag && "Fall through without a diagnostic?");
2190 unsigned DiagID = CGM.getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2191 "debug information for %0 is not yet supported");
2192 CGM.getDiags().Report(DiagID)
2193 << Diag;
2194 return llvm::DIType();
2195}
2196
2197/// getOrCreateLimitedType - Get the type from the cache or create a new
2198/// limited type if necessary.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002199llvm::DIType CGDebugInfo::getOrCreateLimitedType(const RecordType *Ty,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002200 llvm::DIFile Unit) {
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002201 QualType QTy(Ty, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00002202
David Blaikie8d5e1282013-08-20 21:03:29 +00002203 llvm::DICompositeType T(getTypeOrNull(QTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002204
2205 // We may have cached a forward decl when we could have created
2206 // a non-forward decl. Go ahead and create a non-forward decl
2207 // now.
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002208 if (T && !T.isForwardDecl()) return T;
Guy Benyei11169dd2012-12-18 14:30:41 +00002209
2210 // Otherwise create the type.
David Blaikie8d5e1282013-08-20 21:03:29 +00002211 llvm::DICompositeType Res = CreateLimitedType(Ty);
2212
2213 // Propagate members from the declaration to the definition
2214 // CreateType(const RecordType*) will overwrite this with the members in the
2215 // correct order if the full type is needed.
2216 Res.setTypeArray(T.getTypeArray());
Guy Benyei11169dd2012-12-18 14:30:41 +00002217
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002218 if (T && T.isForwardDecl())
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002219 ReplaceMap.push_back(
2220 std::make_pair(QTy.getAsOpaquePtr(), static_cast<llvm::Value *>(T)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002221
2222 // And update the type cache.
David Blaikie4a2b5ef2013-08-12 22:24:20 +00002223 TypeCache[QTy.getAsOpaquePtr()] = Res;
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 return Res;
2225}
2226
2227// TODO: Currently used for context chains when limiting debug info.
David Blaikie8d5e1282013-08-20 21:03:29 +00002228llvm::DICompositeType CGDebugInfo::CreateLimitedType(const RecordType *Ty) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 RecordDecl *RD = Ty->getDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002230
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 // Get overall information about the record type for the debug info.
2232 llvm::DIFile DefUnit = getOrCreateFile(RD->getLocation());
2233 unsigned Line = getLineNumber(RD->getLocation());
2234 StringRef RDName = getClassName(RD);
2235
Eric Christopher07429ff2013-10-15 21:22:34 +00002236 llvm::DIDescriptor RDContext =
2237 getContextDescriptor(cast<Decl>(RD->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002238
David Blaikied2785892013-08-18 17:36:19 +00002239 // If we ended up creating the type during the context chain construction,
2240 // just return that.
2241 // FIXME: this could be dealt with better if the type was recorded as
2242 // completed before we started this (see the CompletedTypeCache usage in
2243 // CGDebugInfo::CreateTypeDefinition(const RecordType*) - that would need to
2244 // be pushed to before context creation, but after it was known to be
2245 // destined for completion (might still have an issue if this caller only
2246 // required a declaration but the context construction ended up creating a
2247 // definition)
David Blaikie8d5e1282013-08-20 21:03:29 +00002248 llvm::DICompositeType T(getTypeOrNull(CGM.getContext().getRecordType(RD)));
2249 if (T && (!T.isForwardDecl() || !RD->getDefinition()))
David Blaikied2785892013-08-18 17:36:19 +00002250 return T;
2251
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 // If this is just a forward declaration, construct an appropriately
2253 // marked node and just return it.
2254 if (!RD->getDefinition())
Manman Ren1b457022013-08-28 21:20:28 +00002255 return getOrCreateRecordFwdDecl(Ty, RDContext);
Guy Benyei11169dd2012-12-18 14:30:41 +00002256
2257 uint64_t Size = CGM.getContext().getTypeSize(Ty);
2258 uint64_t Align = CGM.getContext().getTypeAlign(Ty);
David Blaikie49ae6a72013-03-26 23:47:35 +00002259 llvm::DICompositeType RealDecl;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002260
Manman Rene0064d82013-08-29 23:19:58 +00002261 SmallString<256> FullName = getUniqueTagTypeName(Ty, CGM, TheCU);
2262
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 if (RD->isUnion())
2264 RealDecl = DBuilder.createUnionType(RDContext, RDName, DefUnit, Line,
Manman Rene0064d82013-08-29 23:19:58 +00002265 Size, Align, 0, llvm::DIArray(), 0,
2266 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 else if (RD->isClass()) {
2268 // FIXME: This could be a struct type giving a default visibility different
2269 // than C++ class type, but needs llvm metadata changes first.
2270 RealDecl = DBuilder.createClassType(RDContext, RDName, DefUnit, Line,
Eric Christopherc0c5d462013-02-21 22:35:08 +00002271 Size, Align, 0, 0, llvm::DIType(),
2272 llvm::DIArray(), llvm::DIType(),
Manman Rene0064d82013-08-29 23:19:58 +00002273 llvm::DIArray(), FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002274 } else
2275 RealDecl = DBuilder.createStructType(RDContext, RDName, DefUnit, Line,
Eric Christopher0fdcb312013-05-16 00:52:20 +00002276 Size, Align, 0, llvm::DIType(),
David Blaikieba477362013-11-18 23:38:26 +00002277 llvm::DIArray(), 0, llvm::DIType(),
2278 FullName);
Guy Benyei11169dd2012-12-18 14:30:41 +00002279
2280 RegionMap[Ty->getDecl()] = llvm::WeakVH(RealDecl);
David Blaikie49ae6a72013-03-26 23:47:35 +00002281 TypeCache[QualType(Ty, 0).getAsOpaquePtr()] = RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002282
David Blaikieadfbf992013-08-18 16:55:33 +00002283 if (const ClassTemplateSpecializationDecl *TSpecial =
2284 dyn_cast<ClassTemplateSpecializationDecl>(RD))
2285 RealDecl.setTypeArray(llvm::DIArray(),
2286 CollectCXXTemplateParams(TSpecial, DefUnit));
David Blaikie952dac32013-08-15 22:42:12 +00002287 return RealDecl;
Guy Benyei11169dd2012-12-18 14:30:41 +00002288}
2289
David Blaikieadfbf992013-08-18 16:55:33 +00002290void CGDebugInfo::CollectContainingType(const CXXRecordDecl *RD,
2291 llvm::DICompositeType RealDecl) {
2292 // A class's primary base or the class itself contains the vtable.
2293 llvm::DICompositeType ContainingType;
2294 const ASTRecordLayout &RL = CGM.getContext().getASTRecordLayout(RD);
2295 if (const CXXRecordDecl *PBase = RL.getPrimaryBase()) {
Alp Tokerd4733632013-12-05 04:47:09 +00002296 // Seek non-virtual primary base root.
David Blaikieadfbf992013-08-18 16:55:33 +00002297 while (1) {
2298 const ASTRecordLayout &BRL = CGM.getContext().getASTRecordLayout(PBase);
2299 const CXXRecordDecl *PBT = BRL.getPrimaryBase();
2300 if (PBT && !BRL.isPrimaryBaseVirtual())
2301 PBase = PBT;
2302 else
2303 break;
2304 }
2305 ContainingType = llvm::DICompositeType(
2306 getOrCreateType(QualType(PBase->getTypeForDecl(), 0),
2307 getOrCreateFile(RD->getLocation())));
2308 } else if (RD->isDynamicClass())
2309 ContainingType = RealDecl;
2310
2311 RealDecl.setContainingType(ContainingType);
2312}
2313
Guy Benyei11169dd2012-12-18 14:30:41 +00002314/// CreateMemberType - Create new member and increase Offset by FType's size.
2315llvm::DIType CGDebugInfo::CreateMemberType(llvm::DIFile Unit, QualType FType,
2316 StringRef Name,
2317 uint64_t *Offset) {
2318 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2319 uint64_t FieldSize = CGM.getContext().getTypeSize(FType);
2320 unsigned FieldAlign = CGM.getContext().getTypeAlign(FType);
2321 llvm::DIType Ty = DBuilder.createMemberType(Unit, Name, Unit, 0,
2322 FieldSize, FieldAlign,
2323 *Offset, 0, FieldTy);
2324 *Offset += FieldSize;
2325 return Ty;
2326}
2327
David Blaikiebd483762013-05-20 04:58:53 +00002328llvm::DIDescriptor CGDebugInfo::getDeclarationOrDefinition(const Decl *D) {
2329 // We only need a declaration (not a definition) of the type - so use whatever
2330 // we would otherwise do to get a type for a pointee. (forward declarations in
2331 // limited debug info, full definitions (if the type definition is available)
2332 // in unlimited debug info)
David Blaikie6b7d060c2013-08-12 23:14:36 +00002333 if (const TypeDecl *TD = dyn_cast<TypeDecl>(D))
2334 return getOrCreateType(CGM.getContext().getTypeDeclType(TD),
David Blaikie99dab3b2013-09-04 22:03:57 +00002335 getOrCreateFile(TD->getLocation()));
David Blaikiebd483762013-05-20 04:58:53 +00002336 // Otherwise fall back to a fairly rudimentary cache of existing declarations.
2337 // This doesn't handle providing declarations (for functions or variables) for
2338 // entities without definitions in this TU, nor when the definition proceeds
2339 // the call to this function.
2340 // FIXME: This should be split out into more specific maps with support for
2341 // emitting forward declarations and merging definitions with declarations,
2342 // the same way as we do for types.
2343 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator I =
2344 DeclCache.find(D->getCanonicalDecl());
2345 if (I == DeclCache.end())
2346 return llvm::DIDescriptor();
2347 llvm::Value *V = I->second;
2348 return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
2349}
2350
Guy Benyei11169dd2012-12-18 14:30:41 +00002351/// getFunctionDeclaration - Return debug info descriptor to describe method
2352/// declaration for the given method definition.
2353llvm::DISubprogram CGDebugInfo::getFunctionDeclaration(const Decl *D) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002354 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2355 return llvm::DISubprogram();
2356
Guy Benyei11169dd2012-12-18 14:30:41 +00002357 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
2358 if (!FD) return llvm::DISubprogram();
2359
2360 // Setup context.
David Blaikiefd07c602013-08-09 17:20:05 +00002361 llvm::DIScope S = getContextDescriptor(cast<Decl>(D->getDeclContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002362
2363 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2364 MI = SPCache.find(FD->getCanonicalDecl());
David Blaikiefd07c602013-08-09 17:20:05 +00002365 if (MI == SPCache.end()) {
Eric Christopherf86c4052013-08-28 23:12:10 +00002366 if (const CXXMethodDecl *MD =
2367 dyn_cast<CXXMethodDecl>(FD->getCanonicalDecl())) {
David Blaikiefd07c602013-08-09 17:20:05 +00002368 llvm::DICompositeType T(S);
Eric Christopherf86c4052013-08-28 23:12:10 +00002369 llvm::DISubprogram SP =
2370 CreateCXXMemberFunction(MD, getOrCreateFile(MD->getLocation()), T);
David Blaikiefd07c602013-08-09 17:20:05 +00002371 return SP;
2372 }
2373 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 if (MI != SPCache.end()) {
2375 llvm::Value *V = MI->second;
2376 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002377 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 return SP;
2379 }
2380
2381 for (FunctionDecl::redecl_iterator I = FD->redecls_begin(),
2382 E = FD->redecls_end(); I != E; ++I) {
2383 const FunctionDecl *NextFD = *I;
2384 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2385 MI = SPCache.find(NextFD->getCanonicalDecl());
2386 if (MI != SPCache.end()) {
2387 llvm::Value *V = MI->second;
2388 llvm::DISubprogram SP(dyn_cast_or_null<llvm::MDNode>(V));
David Blaikie18cfbc52013-06-22 00:09:36 +00002389 if (SP.isSubprogram() && !SP.isDefinition())
Guy Benyei11169dd2012-12-18 14:30:41 +00002390 return SP;
2391 }
2392 }
2393 return llvm::DISubprogram();
2394}
2395
2396// getOrCreateFunctionType - Construct DIType. If it is a c++ method, include
2397// implicit parameter "this".
David Blaikie469f0792013-05-22 23:22:42 +00002398llvm::DICompositeType CGDebugInfo::getOrCreateFunctionType(const Decl *D,
2399 QualType FnType,
2400 llvm::DIFile F) {
David Blaikie18cfbc52013-06-22 00:09:36 +00002401 if (!D || DebugKind == CodeGenOptions::DebugLineTablesOnly)
2402 // Create fake but valid subroutine type. Otherwise
2403 // llvm::DISubprogram::Verify() would return false, and
2404 // subprogram DIE will miss DW_AT_decl_file and
2405 // DW_AT_decl_line fields.
2406 return DBuilder.createSubroutineType(F, DBuilder.getOrCreateArray(None));
Guy Benyei11169dd2012-12-18 14:30:41 +00002407
2408 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
2409 return getOrCreateMethodType(Method, F);
2410 if (const ObjCMethodDecl *OMethod = dyn_cast<ObjCMethodDecl>(D)) {
2411 // Add "self" and "_cmd"
2412 SmallVector<llvm::Value *, 16> Elts;
2413
2414 // First element is always return type. For 'void' functions it is NULL.
Adrian Prantl5f360102013-05-22 21:37:49 +00002415 QualType ResultTy = OMethod->getResultType();
2416
2417 // Replace the instancetype keyword with the actual type.
2418 if (ResultTy == CGM.getContext().getObjCInstanceType())
2419 ResultTy = CGM.getContext().getPointerType(
2420 QualType(OMethod->getClassInterface()->getTypeForDecl(), 0));
2421
Adrian Prantl7bec9032013-05-10 21:08:31 +00002422 Elts.push_back(getOrCreateType(ResultTy, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002423 // "self" pointer is always first argument.
Adrian Prantlde17db32013-03-29 19:20:29 +00002424 QualType SelfDeclTy = OMethod->getSelfDecl()->getType();
2425 llvm::DIType SelfTy = getOrCreateType(SelfDeclTy, F);
2426 Elts.push_back(CreateSelfType(SelfDeclTy, SelfTy));
Guy Benyei11169dd2012-12-18 14:30:41 +00002427 // "_cmd" pointer is always second argument.
2428 llvm::DIType CmdTy = getOrCreateType(OMethod->getCmdDecl()->getType(), F);
2429 Elts.push_back(DBuilder.createArtificialType(CmdTy));
2430 // Get rest of the arguments.
Eric Christopherb2a008c2013-05-16 00:45:12 +00002431 for (ObjCMethodDecl::param_const_iterator PI = OMethod->param_begin(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002432 PE = OMethod->param_end(); PI != PE; ++PI)
2433 Elts.push_back(getOrCreateType((*PI)->getType(), F));
2434
2435 llvm::DIArray EltTypeArray = DBuilder.getOrCreateArray(Elts);
2436 return DBuilder.createSubroutineType(F, EltTypeArray);
2437 }
David Blaikie469f0792013-05-22 23:22:42 +00002438 return llvm::DICompositeType(getOrCreateType(FnType, F));
Guy Benyei11169dd2012-12-18 14:30:41 +00002439}
2440
2441/// EmitFunctionStart - Constructs the debug code for entering a function.
2442void CGDebugInfo::EmitFunctionStart(GlobalDecl GD, QualType FnType,
2443 llvm::Function *Fn,
2444 CGBuilderTy &Builder) {
2445
2446 StringRef Name;
2447 StringRef LinkageName;
2448
2449 FnBeginRegionCount.push_back(LexicalBlockStack.size());
2450
2451 const Decl *D = GD.getDecl();
2452 // Function may lack declaration in source code if it is created by Clang
2453 // CodeGen (examples: _GLOBAL__I_a, __cxx_global_array_dtor, thunk).
2454 bool HasDecl = (D != 0);
2455 // Use the location of the declaration.
2456 SourceLocation Loc;
2457 if (HasDecl)
2458 Loc = D->getLocation();
2459
2460 unsigned Flags = 0;
2461 llvm::DIFile Unit = getOrCreateFile(Loc);
2462 llvm::DIDescriptor FDContext(Unit);
2463 llvm::DIArray TParamsArray;
2464 if (!HasDecl) {
2465 // Use llvm function name.
David Blaikieebe87e12013-08-27 23:57:18 +00002466 LinkageName = Fn->getName();
Guy Benyei11169dd2012-12-18 14:30:41 +00002467 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2468 // If there is a DISubprogram for this function available then use it.
2469 llvm::DenseMap<const FunctionDecl *, llvm::WeakVH>::iterator
2470 FI = SPCache.find(FD->getCanonicalDecl());
2471 if (FI != SPCache.end()) {
2472 llvm::Value *V = FI->second;
2473 llvm::DIDescriptor SP(dyn_cast_or_null<llvm::MDNode>(V));
2474 if (SP.isSubprogram() && llvm::DISubprogram(SP).isDefinition()) {
2475 llvm::MDNode *SPN = SP;
2476 LexicalBlockStack.push_back(SPN);
2477 RegionMap[D] = llvm::WeakVH(SP);
2478 return;
2479 }
2480 }
2481 Name = getFunctionName(FD);
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002482 // Use mangled name as linkage name for C/C++ functions.
Guy Benyei11169dd2012-12-18 14:30:41 +00002483 if (FD->hasPrototype()) {
2484 LinkageName = CGM.getMangledName(GD);
2485 Flags |= llvm::DIDescriptor::FlagPrototyped;
2486 }
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002487 // No need to replicate the linkage name if it isn't different from the
2488 // subprogram name, no need to have it at all unless coverage is enabled or
2489 // debug is set to more than just line tables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 if (LinkageName == Name ||
Nick Lewyckyc02bbb62013-03-20 01:38:16 +00002491 (!CGM.getCodeGenOpts().EmitGcovArcs &&
2492 !CGM.getCodeGenOpts().EmitGcovNotes &&
Eric Christopher75e17682013-05-16 00:45:23 +00002493 DebugKind <= CodeGenOptions::DebugLineTablesOnly))
Guy Benyei11169dd2012-12-18 14:30:41 +00002494 LinkageName = StringRef();
2495
Eric Christopher75e17682013-05-16 00:45:23 +00002496 if (DebugKind >= CodeGenOptions::LimitedDebugInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 if (const NamespaceDecl *NSDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002498 dyn_cast_or_null<NamespaceDecl>(FD->getDeclContext()))
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 FDContext = getOrCreateNameSpace(NSDecl);
2500 else if (const RecordDecl *RDecl =
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002501 dyn_cast_or_null<RecordDecl>(FD->getDeclContext()))
2502 FDContext = getContextDescriptor(cast<Decl>(RDecl));
Guy Benyei11169dd2012-12-18 14:30:41 +00002503
2504 // Collect template parameters.
2505 TParamsArray = CollectFunctionTemplateParams(FD, Unit);
2506 }
2507 } else if (const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D)) {
2508 Name = getObjCMethodName(OMD);
2509 Flags |= llvm::DIDescriptor::FlagPrototyped;
2510 } else {
2511 // Use llvm function name.
2512 Name = Fn->getName();
2513 Flags |= llvm::DIDescriptor::FlagPrototyped;
2514 }
2515 if (!Name.empty() && Name[0] == '\01')
2516 Name = Name.substr(1);
2517
2518 unsigned LineNo = getLineNumber(Loc);
2519 if (!HasDecl || D->isImplicit())
2520 Flags |= llvm::DIDescriptor::FlagArtificial;
2521
Eric Christopher9e6f5f92013-10-17 01:31:21 +00002522 llvm::DISubprogram SP =
2523 DBuilder.createFunction(FDContext, Name, LinkageName, Unit, LineNo,
2524 getOrCreateFunctionType(D, FnType, Unit),
2525 Fn->hasInternalLinkage(), true /*definition*/,
2526 getLineNumber(CurLoc), Flags,
2527 CGM.getLangOpts().Optimize, Fn, TParamsArray,
2528 getFunctionDeclaration(D));
David Blaikiebd483762013-05-20 04:58:53 +00002529 if (HasDecl)
2530 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(SP)));
Guy Benyei11169dd2012-12-18 14:30:41 +00002531
2532 // Push function on region stack.
2533 llvm::MDNode *SPN = SP;
2534 LexicalBlockStack.push_back(SPN);
2535 if (HasDecl)
2536 RegionMap[D] = llvm::WeakVH(SP);
2537}
2538
2539/// EmitLocation - Emit metadata to indicate a change in line/column
Adrian Prantl02c0caa2013-07-18 00:27:59 +00002540/// information in the source file. If the location is invalid, the
2541/// previous location will be reused.
Adrian Prantlc7822422013-03-12 20:43:25 +00002542void CGDebugInfo::EmitLocation(CGBuilderTy &Builder, SourceLocation Loc,
Adrian Prantle83b1302014-01-07 22:05:52 +00002543 bool ForceColumnInfo) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002544 // Update our current location
2545 setLocation(Loc);
2546
2547 if (CurLoc.isInvalid() || CurLoc.isMacroID()) return;
2548
2549 // Don't bother if things are the same as last time.
2550 SourceManager &SM = CGM.getContext().getSourceManager();
2551 if (CurLoc == PrevLoc ||
2552 SM.getExpansionLoc(CurLoc) == SM.getExpansionLoc(PrevLoc))
2553 // New Builder may not be in sync with CGDebugInfo.
David Blaikie357aafb2013-02-01 19:09:49 +00002554 if (!Builder.getCurrentDebugLocation().isUnknown() &&
2555 Builder.getCurrentDebugLocation().getScope(CGM.getLLVMContext()) ==
2556 LexicalBlockStack.back())
Guy Benyei11169dd2012-12-18 14:30:41 +00002557 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002558
Guy Benyei11169dd2012-12-18 14:30:41 +00002559 // Update last state.
2560 PrevLoc = CurLoc;
2561
Adrian Prantle83b1302014-01-07 22:05:52 +00002562 llvm::MDNode *Scope = LexicalBlockStack.back();
Adrian Prantlc7822422013-03-12 20:43:25 +00002563 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get
2564 (getLineNumber(CurLoc),
2565 getColumnNumber(CurLoc, ForceColumnInfo),
2566 Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002567}
2568
2569/// CreateLexicalBlock - Creates a new lexical block node and pushes it on
2570/// the stack.
2571void CGDebugInfo::CreateLexicalBlock(SourceLocation Loc) {
2572 llvm::DIDescriptor D =
2573 DBuilder.createLexicalBlock(LexicalBlockStack.empty() ?
2574 llvm::DIDescriptor() :
2575 llvm::DIDescriptor(LexicalBlockStack.back()),
2576 getOrCreateFile(CurLoc),
2577 getLineNumber(CurLoc),
2578 getColumnNumber(CurLoc));
2579 llvm::MDNode *DN = D;
2580 LexicalBlockStack.push_back(DN);
2581}
2582
2583/// EmitLexicalBlockStart - Constructs the debug code for entering a declarative
2584/// region - beginning of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002585void CGDebugInfo::EmitLexicalBlockStart(CGBuilderTy &Builder,
2586 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002587 // Set our current location.
2588 setLocation(Loc);
2589
2590 // Create a new lexical block and push it on the stack.
2591 CreateLexicalBlock(Loc);
2592
2593 // Emit a line table change for the current location inside the new scope.
2594 Builder.SetCurrentDebugLocation(llvm::DebugLoc::get(getLineNumber(Loc),
2595 getColumnNumber(Loc),
2596 LexicalBlockStack.back()));
2597}
2598
2599/// EmitLexicalBlockEnd - Constructs the debug code for exiting a declarative
2600/// region - end of a DW_TAG_lexical_block.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002601void CGDebugInfo::EmitLexicalBlockEnd(CGBuilderTy &Builder,
2602 SourceLocation Loc) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002603 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2604
2605 // Provide an entry in the line table for the end of the block.
2606 EmitLocation(Builder, Loc);
2607
2608 LexicalBlockStack.pop_back();
2609}
2610
2611/// EmitFunctionEnd - Constructs the debug code for exiting a function.
2612void CGDebugInfo::EmitFunctionEnd(CGBuilderTy &Builder) {
2613 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2614 unsigned RCount = FnBeginRegionCount.back();
2615 assert(RCount <= LexicalBlockStack.size() && "Region stack mismatch");
2616
2617 // Pop all regions for this function.
2618 while (LexicalBlockStack.size() != RCount)
2619 EmitLexicalBlockEnd(Builder, CurLoc);
2620 FnBeginRegionCount.pop_back();
2621}
2622
Eric Christopherb2a008c2013-05-16 00:45:12 +00002623// EmitTypeForVarWithBlocksAttr - Build up structure info for the byref.
Guy Benyei11169dd2012-12-18 14:30:41 +00002624// See BuildByRefType.
2625llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
2626 uint64_t *XOffset) {
2627
2628 SmallVector<llvm::Value *, 5> EltTys;
2629 QualType FType;
2630 uint64_t FieldSize, FieldOffset;
2631 unsigned FieldAlign;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002632
Guy Benyei11169dd2012-12-18 14:30:41 +00002633 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00002634 QualType Type = VD->getType();
Guy Benyei11169dd2012-12-18 14:30:41 +00002635
2636 FieldOffset = 0;
2637 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2638 EltTys.push_back(CreateMemberType(Unit, FType, "__isa", &FieldOffset));
2639 EltTys.push_back(CreateMemberType(Unit, FType, "__forwarding", &FieldOffset));
2640 FType = CGM.getContext().IntTy;
2641 EltTys.push_back(CreateMemberType(Unit, FType, "__flags", &FieldOffset));
2642 EltTys.push_back(CreateMemberType(Unit, FType, "__size", &FieldOffset));
2643
2644 bool HasCopyAndDispose = CGM.getContext().BlockRequiresCopying(Type, VD);
2645 if (HasCopyAndDispose) {
2646 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
2647 EltTys.push_back(CreateMemberType(Unit, FType, "__copy_helper",
2648 &FieldOffset));
2649 EltTys.push_back(CreateMemberType(Unit, FType, "__destroy_helper",
2650 &FieldOffset));
2651 }
2652 bool HasByrefExtendedLayout;
2653 Qualifiers::ObjCLifetime Lifetime;
2654 if (CGM.getContext().getByrefLifetime(Type,
2655 Lifetime, HasByrefExtendedLayout)
Adrian Prantlead2ba42013-07-23 00:12:14 +00002656 && HasByrefExtendedLayout) {
2657 FType = CGM.getContext().getPointerType(CGM.getContext().VoidTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00002658 EltTys.push_back(CreateMemberType(Unit, FType,
2659 "__byref_variable_layout",
2660 &FieldOffset));
Adrian Prantlead2ba42013-07-23 00:12:14 +00002661 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002662
Guy Benyei11169dd2012-12-18 14:30:41 +00002663 CharUnits Align = CGM.getContext().getDeclAlign(VD);
2664 if (Align > CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002665 CGM.getTarget().getPointerAlign(0))) {
Eric Christopherb2a008c2013-05-16 00:45:12 +00002666 CharUnits FieldOffsetInBytes
Guy Benyei11169dd2012-12-18 14:30:41 +00002667 = CGM.getContext().toCharUnitsFromBits(FieldOffset);
2668 CharUnits AlignedOffsetInBytes
2669 = FieldOffsetInBytes.RoundUpToAlignment(Align);
2670 CharUnits NumPaddingBytes
2671 = AlignedOffsetInBytes - FieldOffsetInBytes;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002672
Guy Benyei11169dd2012-12-18 14:30:41 +00002673 if (NumPaddingBytes.isPositive()) {
2674 llvm::APInt pad(32, NumPaddingBytes.getQuantity());
2675 FType = CGM.getContext().getConstantArrayType(CGM.getContext().CharTy,
2676 pad, ArrayType::Normal, 0);
2677 EltTys.push_back(CreateMemberType(Unit, FType, "", &FieldOffset));
2678 }
2679 }
Eric Christopherb2a008c2013-05-16 00:45:12 +00002680
Guy Benyei11169dd2012-12-18 14:30:41 +00002681 FType = Type;
2682 llvm::DIType FieldTy = CGDebugInfo::getOrCreateType(FType, Unit);
2683 FieldSize = CGM.getContext().getTypeSize(FType);
2684 FieldAlign = CGM.getContext().toBits(Align);
2685
Eric Christopherb2a008c2013-05-16 00:45:12 +00002686 *XOffset = FieldOffset;
Guy Benyei11169dd2012-12-18 14:30:41 +00002687 FieldTy = DBuilder.createMemberType(Unit, VD->getName(), Unit,
2688 0, FieldSize, FieldAlign,
2689 FieldOffset, 0, FieldTy);
2690 EltTys.push_back(FieldTy);
2691 FieldOffset += FieldSize;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002692
Guy Benyei11169dd2012-12-18 14:30:41 +00002693 llvm::DIArray Elements = DBuilder.getOrCreateArray(EltTys);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002694
Guy Benyei11169dd2012-12-18 14:30:41 +00002695 unsigned Flags = llvm::DIDescriptor::FlagBlockByrefStruct;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002696
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 return DBuilder.createStructType(Unit, "", Unit, 0, FieldOffset, 0, Flags,
David Blaikie6d4fe152013-02-25 01:07:08 +00002698 llvm::DIType(), Elements);
Guy Benyei11169dd2012-12-18 14:30:41 +00002699}
2700
2701/// EmitDeclare - Emit local variable declaration debug info.
2702void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
Eric Christopherb2a008c2013-05-16 00:45:12 +00002703 llvm::Value *Storage,
Guy Benyei11169dd2012-12-18 14:30:41 +00002704 unsigned ArgNo, CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002705 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002706 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
2707
David Blaikie7fceebf2013-08-19 03:37:48 +00002708 bool Unwritten =
2709 VD->isImplicit() || (isa<Decl>(VD->getDeclContext()) &&
2710 cast<Decl>(VD->getDeclContext())->isImplicit());
2711 llvm::DIFile Unit;
2712 if (!Unwritten)
2713 Unit = getOrCreateFile(VD->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00002714 llvm::DIType Ty;
2715 uint64_t XOffset = 0;
2716 if (VD->hasAttr<BlocksAttr>())
2717 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002718 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002719 Ty = getOrCreateType(VD->getType(), Unit);
2720
2721 // If there is no debug info for this type then do not emit debug info
2722 // for this variable.
2723 if (!Ty)
2724 return;
2725
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 // Get location information.
David Blaikie7fceebf2013-08-19 03:37:48 +00002727 unsigned Line = 0;
2728 unsigned Column = 0;
2729 if (!Unwritten) {
2730 Line = getLineNumber(VD->getLocation());
2731 Column = getColumnNumber(VD->getLocation());
2732 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002733 unsigned Flags = 0;
2734 if (VD->isImplicit())
2735 Flags |= llvm::DIDescriptor::FlagArtificial;
2736 // If this is the first argument and it is implicit then
2737 // give it an object pointer flag.
2738 // FIXME: There has to be a better way to do this, but for static
2739 // functions there won't be an implicit param at arg1 and
2740 // otherwise it is 'self' or 'this'.
2741 if (isa<ImplicitParamDecl>(VD) && ArgNo == 1)
2742 Flags |= llvm::DIDescriptor::FlagObjectPointer;
David Blaikieb9c667d2013-06-19 21:53:53 +00002743 if (llvm::Argument *Arg = dyn_cast<llvm::Argument>(Storage))
Eric Christopherffdeb1e2013-07-17 22:52:53 +00002744 if (Arg->getType()->isPointerTy() && !Arg->hasByValAttr() &&
2745 !VD->getType()->isPointerType())
David Blaikieb9c667d2013-06-19 21:53:53 +00002746 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
Guy Benyei11169dd2012-12-18 14:30:41 +00002747
2748 llvm::MDNode *Scope = LexicalBlockStack.back();
2749
2750 StringRef Name = VD->getName();
2751 if (!Name.empty()) {
2752 if (VD->hasAttr<BlocksAttr>()) {
2753 CharUnits offset = CharUnits::fromQuantity(32);
2754 SmallVector<llvm::Value *, 9> addr;
2755 llvm::Type *Int64Ty = CGM.Int64Ty;
2756 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2757 // offset of __forwarding field
2758 offset = CGM.getContext().toCharUnitsFromBits(
John McCallc8e01702013-04-16 22:48:15 +00002759 CGM.getTarget().getPointerWidth(0));
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2761 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2762 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2763 // offset of x field
2764 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2765 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2766
2767 // Create the descriptor for the variable.
2768 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002769 DBuilder.createComplexVariable(Tag,
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 llvm::DIDescriptor(Scope),
2771 VD->getName(), Unit, Line, Ty,
2772 addr, ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002773
Guy Benyei11169dd2012-12-18 14:30:41 +00002774 // Insert an llvm.dbg.declare into the current block.
2775 llvm::Instruction *Call =
2776 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2777 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2778 return;
Adrian Prantl7f2ef222013-09-18 22:18:17 +00002779 } else if (isa<VariableArrayType>(VD->getType()))
Adrian Prantl0315f382013-09-18 22:08:57 +00002780 Flags |= llvm::DIDescriptor::FlagIndirectVariable;
David Blaikiea76a7c92013-01-05 05:58:35 +00002781 } else if (const RecordType *RT = dyn_cast<RecordType>(VD->getType())) {
2782 // If VD is an anonymous union then Storage represents value for
2783 // all union fields.
Guy Benyei11169dd2012-12-18 14:30:41 +00002784 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
David Blaikie219c7d92013-01-05 20:03:07 +00002785 if (RD->isUnion() && RD->isAnonymousStructOrUnion()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002786 for (RecordDecl::field_iterator I = RD->field_begin(),
2787 E = RD->field_end();
2788 I != E; ++I) {
2789 FieldDecl *Field = *I;
2790 llvm::DIType FieldTy = getOrCreateType(Field->getType(), Unit);
2791 StringRef FieldName = Field->getName();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002792
Guy Benyei11169dd2012-12-18 14:30:41 +00002793 // Ignore unnamed fields. Do not ignore unnamed records.
2794 if (FieldName.empty() && !isa<RecordType>(Field->getType()))
2795 continue;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002796
Guy Benyei11169dd2012-12-18 14:30:41 +00002797 // Use VarDecl's Tag, Scope and Line number.
2798 llvm::DIVariable D =
2799 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
Eric Christopherb2a008c2013-05-16 00:45:12 +00002800 FieldName, Unit, Line, FieldTy,
Guy Benyei11169dd2012-12-18 14:30:41 +00002801 CGM.getLangOpts().Optimize, Flags,
2802 ArgNo);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002803
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 // Insert an llvm.dbg.declare into the current block.
2805 llvm::Instruction *Call =
2806 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2807 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
2808 }
David Blaikie219c7d92013-01-05 20:03:07 +00002809 return;
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 }
2811 }
David Blaikiea76a7c92013-01-05 05:58:35 +00002812
2813 // Create the descriptor for the variable.
2814 llvm::DIVariable D =
2815 DBuilder.createLocalVariable(Tag, llvm::DIDescriptor(Scope),
2816 Name, Unit, Line, Ty,
2817 CGM.getLangOpts().Optimize, Flags, ArgNo);
2818
2819 // Insert an llvm.dbg.declare into the current block.
2820 llvm::Instruction *Call =
2821 DBuilder.insertDeclare(Storage, D, Builder.GetInsertBlock());
2822 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column, Scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00002823}
2824
2825void CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl *VD,
2826 llvm::Value *Storage,
2827 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002828 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002829 EmitDeclare(VD, llvm::dwarf::DW_TAG_auto_variable, Storage, 0, Builder);
2830}
2831
Adrian Prantlde17db32013-03-29 19:20:29 +00002832/// Look up the completed type for a self pointer in the TypeCache and
2833/// create a copy of it with the ObjectPointer and Artificial flags
2834/// set. If the type is not cached, a new one is created. This should
2835/// never happen though, since creating a type for the implicit self
2836/// argument implies that we already parsed the interface definition
2837/// and the ivar declarations in the implementation.
Eric Christopher0fdcb312013-05-16 00:52:20 +00002838llvm::DIType CGDebugInfo::CreateSelfType(const QualType &QualTy,
2839 llvm::DIType Ty) {
Adrian Prantlde17db32013-03-29 19:20:29 +00002840 llvm::DIType CachedTy = getTypeOrNull(QualTy);
Eric Christopherf8bc4d82013-07-18 00:52:50 +00002841 if (CachedTy) Ty = CachedTy;
Adrian Prantlde17db32013-03-29 19:20:29 +00002842 else DEBUG(llvm::dbgs() << "No cached type for self.");
2843 return DBuilder.createObjectPointerType(Ty);
2844}
2845
Guy Benyei11169dd2012-12-18 14:30:41 +00002846void CGDebugInfo::EmitDeclareOfBlockDeclRefVariable(const VarDecl *VD,
2847 llvm::Value *Storage,
2848 CGBuilderTy &Builder,
2849 const CGBlockInfo &blockInfo) {
Eric Christopher75e17682013-05-16 00:45:23 +00002850 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002851 assert(!LexicalBlockStack.empty() && "Region stack mismatch, stack empty!");
Eric Christopherb2a008c2013-05-16 00:45:12 +00002852
Guy Benyei11169dd2012-12-18 14:30:41 +00002853 if (Builder.GetInsertBlock() == 0)
2854 return;
Eric Christopherb2a008c2013-05-16 00:45:12 +00002855
Guy Benyei11169dd2012-12-18 14:30:41 +00002856 bool isByRef = VD->hasAttr<BlocksAttr>();
Eric Christopherb2a008c2013-05-16 00:45:12 +00002857
Guy Benyei11169dd2012-12-18 14:30:41 +00002858 uint64_t XOffset = 0;
2859 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
2860 llvm::DIType Ty;
2861 if (isByRef)
2862 Ty = EmitTypeForVarWithBlocksAttr(VD, &XOffset);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002863 else
Guy Benyei11169dd2012-12-18 14:30:41 +00002864 Ty = getOrCreateType(VD->getType(), Unit);
2865
2866 // Self is passed along as an implicit non-arg variable in a
2867 // block. Mark it as the object pointer.
2868 if (isa<ImplicitParamDecl>(VD) && VD->getName() == "self")
Adrian Prantlde17db32013-03-29 19:20:29 +00002869 Ty = CreateSelfType(VD->getType(), Ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002870
2871 // Get location information.
2872 unsigned Line = getLineNumber(VD->getLocation());
2873 unsigned Column = getColumnNumber(VD->getLocation());
2874
2875 const llvm::DataLayout &target = CGM.getDataLayout();
2876
2877 CharUnits offset = CharUnits::fromQuantity(
2878 target.getStructLayout(blockInfo.StructureType)
2879 ->getElementOffset(blockInfo.getCapture(VD).getIndex()));
2880
2881 SmallVector<llvm::Value *, 9> addr;
2882 llvm::Type *Int64Ty = CGM.Int64Ty;
Adrian Prantl0f6df002013-03-29 19:20:35 +00002883 if (isa<llvm::AllocaInst>(Storage))
2884 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
Guy Benyei11169dd2012-12-18 14:30:41 +00002885 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2886 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2887 if (isByRef) {
2888 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2889 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2890 // offset of __forwarding field
2891 offset = CGM.getContext()
2892 .toCharUnitsFromBits(target.getPointerSizeInBits(0));
2893 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2894 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
2895 addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
2896 // offset of x field
2897 offset = CGM.getContext().toCharUnitsFromBits(XOffset);
2898 addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
2899 }
2900
2901 // Create the descriptor for the variable.
2902 llvm::DIVariable D =
Eric Christopherb2a008c2013-05-16 00:45:12 +00002903 DBuilder.createComplexVariable(llvm::dwarf::DW_TAG_auto_variable,
Guy Benyei11169dd2012-12-18 14:30:41 +00002904 llvm::DIDescriptor(LexicalBlockStack.back()),
2905 VD->getName(), Unit, Line, Ty, addr);
Adrian Prantl0f6df002013-03-29 19:20:35 +00002906
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 // Insert an llvm.dbg.declare into the current block.
2908 llvm::Instruction *Call =
2909 DBuilder.insertDeclare(Storage, D, Builder.GetInsertPoint());
2910 Call->setDebugLoc(llvm::DebugLoc::get(Line, Column,
2911 LexicalBlockStack.back()));
2912}
2913
2914/// EmitDeclareOfArgVariable - Emit call to llvm.dbg.declare for an argument
2915/// variable declaration.
2916void CGDebugInfo::EmitDeclareOfArgVariable(const VarDecl *VD, llvm::Value *AI,
2917 unsigned ArgNo,
2918 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002919 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002920 EmitDeclare(VD, llvm::dwarf::DW_TAG_arg_variable, AI, ArgNo, Builder);
2921}
2922
2923namespace {
2924 struct BlockLayoutChunk {
2925 uint64_t OffsetInBits;
2926 const BlockDecl::Capture *Capture;
2927 };
2928 bool operator<(const BlockLayoutChunk &l, const BlockLayoutChunk &r) {
2929 return l.OffsetInBits < r.OffsetInBits;
2930 }
2931}
2932
2933void CGDebugInfo::EmitDeclareOfBlockLiteralArgVariable(const CGBlockInfo &block,
Adrian Prantl51936dd2013-03-14 17:53:33 +00002934 llvm::Value *Arg,
2935 llvm::Value *LocalAddr,
Guy Benyei11169dd2012-12-18 14:30:41 +00002936 CGBuilderTy &Builder) {
Eric Christopher75e17682013-05-16 00:45:23 +00002937 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 ASTContext &C = CGM.getContext();
2939 const BlockDecl *blockDecl = block.getBlockDecl();
2940
2941 // Collect some general information about the block's location.
2942 SourceLocation loc = blockDecl->getCaretLocation();
2943 llvm::DIFile tunit = getOrCreateFile(loc);
2944 unsigned line = getLineNumber(loc);
2945 unsigned column = getColumnNumber(loc);
Eric Christopherb2a008c2013-05-16 00:45:12 +00002946
Guy Benyei11169dd2012-12-18 14:30:41 +00002947 // Build the debug-info type for the block literal.
2948 getContextDescriptor(cast<Decl>(blockDecl->getDeclContext()));
2949
2950 const llvm::StructLayout *blockLayout =
2951 CGM.getDataLayout().getStructLayout(block.StructureType);
2952
2953 SmallVector<llvm::Value*, 16> fields;
2954 fields.push_back(createFieldType("__isa", C.VoidPtrTy, 0, loc, AS_public,
2955 blockLayout->getElementOffsetInBits(0),
2956 tunit, tunit));
2957 fields.push_back(createFieldType("__flags", C.IntTy, 0, loc, AS_public,
2958 blockLayout->getElementOffsetInBits(1),
2959 tunit, tunit));
2960 fields.push_back(createFieldType("__reserved", C.IntTy, 0, loc, AS_public,
2961 blockLayout->getElementOffsetInBits(2),
2962 tunit, tunit));
2963 fields.push_back(createFieldType("__FuncPtr", C.VoidPtrTy, 0, loc, AS_public,
2964 blockLayout->getElementOffsetInBits(3),
2965 tunit, tunit));
2966 fields.push_back(createFieldType("__descriptor",
2967 C.getPointerType(block.NeedsCopyDispose ?
2968 C.getBlockDescriptorExtendedType() :
2969 C.getBlockDescriptorType()),
2970 0, loc, AS_public,
2971 blockLayout->getElementOffsetInBits(4),
2972 tunit, tunit));
2973
2974 // We want to sort the captures by offset, not because DWARF
2975 // requires this, but because we're paranoid about debuggers.
2976 SmallVector<BlockLayoutChunk, 8> chunks;
2977
2978 // 'this' capture.
2979 if (blockDecl->capturesCXXThis()) {
2980 BlockLayoutChunk chunk;
2981 chunk.OffsetInBits =
2982 blockLayout->getElementOffsetInBits(block.CXXThisIndex);
2983 chunk.Capture = 0;
2984 chunks.push_back(chunk);
2985 }
2986
2987 // Variable captures.
2988 for (BlockDecl::capture_const_iterator
2989 i = blockDecl->capture_begin(), e = blockDecl->capture_end();
2990 i != e; ++i) {
2991 const BlockDecl::Capture &capture = *i;
2992 const VarDecl *variable = capture.getVariable();
2993 const CGBlockInfo::Capture &captureInfo = block.getCapture(variable);
2994
2995 // Ignore constant captures.
2996 if (captureInfo.isConstant())
2997 continue;
2998
2999 BlockLayoutChunk chunk;
3000 chunk.OffsetInBits =
3001 blockLayout->getElementOffsetInBits(captureInfo.getIndex());
3002 chunk.Capture = &capture;
3003 chunks.push_back(chunk);
3004 }
3005
3006 // Sort by offset.
3007 llvm::array_pod_sort(chunks.begin(), chunks.end());
3008
3009 for (SmallVectorImpl<BlockLayoutChunk>::iterator
3010 i = chunks.begin(), e = chunks.end(); i != e; ++i) {
3011 uint64_t offsetInBits = i->OffsetInBits;
3012 const BlockDecl::Capture *capture = i->Capture;
3013
3014 // If we have a null capture, this must be the C++ 'this' capture.
3015 if (!capture) {
3016 const CXXMethodDecl *method =
3017 cast<CXXMethodDecl>(blockDecl->getNonClosureContext());
3018 QualType type = method->getThisType(C);
3019
3020 fields.push_back(createFieldType("this", type, 0, loc, AS_public,
3021 offsetInBits, tunit, tunit));
3022 continue;
3023 }
3024
3025 const VarDecl *variable = capture->getVariable();
3026 StringRef name = variable->getName();
3027
3028 llvm::DIType fieldType;
3029 if (capture->isByRef()) {
3030 std::pair<uint64_t,unsigned> ptrInfo = C.getTypeInfo(C.VoidPtrTy);
3031
3032 // FIXME: this creates a second copy of this type!
3033 uint64_t xoffset;
3034 fieldType = EmitTypeForVarWithBlocksAttr(variable, &xoffset);
3035 fieldType = DBuilder.createPointerType(fieldType, ptrInfo.first);
3036 fieldType = DBuilder.createMemberType(tunit, name, tunit, line,
3037 ptrInfo.first, ptrInfo.second,
3038 offsetInBits, 0, fieldType);
3039 } else {
3040 fieldType = createFieldType(name, variable->getType(), 0,
3041 loc, AS_public, offsetInBits, tunit, tunit);
3042 }
3043 fields.push_back(fieldType);
3044 }
3045
3046 SmallString<36> typeName;
3047 llvm::raw_svector_ostream(typeName)
3048 << "__block_literal_" << CGM.getUniqueBlockCount();
3049
3050 llvm::DIArray fieldsArray = DBuilder.getOrCreateArray(fields);
3051
3052 llvm::DIType type =
3053 DBuilder.createStructType(tunit, typeName.str(), tunit, line,
3054 CGM.getContext().toBits(block.BlockSize),
3055 CGM.getContext().toBits(block.BlockAlign),
David Blaikie6d4fe152013-02-25 01:07:08 +00003056 0, llvm::DIType(), fieldsArray);
Guy Benyei11169dd2012-12-18 14:30:41 +00003057 type = DBuilder.createPointerType(type, CGM.PointerWidthInBits);
3058
3059 // Get overall information about the block.
3060 unsigned flags = llvm::DIDescriptor::FlagArtificial;
3061 llvm::MDNode *scope = LexicalBlockStack.back();
Guy Benyei11169dd2012-12-18 14:30:41 +00003062
3063 // Create the descriptor for the parameter.
3064 llvm::DIVariable debugVar =
3065 DBuilder.createLocalVariable(llvm::dwarf::DW_TAG_arg_variable,
Eric Christopherb2a008c2013-05-16 00:45:12 +00003066 llvm::DIDescriptor(scope),
Adrian Prantl51936dd2013-03-14 17:53:33 +00003067 Arg->getName(), tunit, line, type,
Guy Benyei11169dd2012-12-18 14:30:41 +00003068 CGM.getLangOpts().Optimize, flags,
Adrian Prantl51936dd2013-03-14 17:53:33 +00003069 cast<llvm::Argument>(Arg)->getArgNo() + 1);
3070
Adrian Prantl616bef42013-03-14 21:52:59 +00003071 if (LocalAddr) {
Adrian Prantl51936dd2013-03-14 17:53:33 +00003072 // Insert an llvm.dbg.value into the current block.
Adrian Prantl616bef42013-03-14 21:52:59 +00003073 llvm::Instruction *DbgVal =
3074 DBuilder.insertDbgValueIntrinsic(LocalAddr, 0, debugVar,
Eric Christopher5c7ee8b2013-04-02 22:59:11 +00003075 Builder.GetInsertBlock());
Adrian Prantl616bef42013-03-14 21:52:59 +00003076 DbgVal->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
3077 }
Adrian Prantl51936dd2013-03-14 17:53:33 +00003078
Adrian Prantl616bef42013-03-14 21:52:59 +00003079 // Insert an llvm.dbg.declare into the current block.
3080 llvm::Instruction *DbgDecl =
3081 DBuilder.insertDeclare(Arg, debugVar, Builder.GetInsertBlock());
3082 DbgDecl->setDebugLoc(llvm::DebugLoc::get(line, column, scope));
Guy Benyei11169dd2012-12-18 14:30:41 +00003083}
3084
David Blaikie6943dea2013-08-20 01:28:15 +00003085/// If D is an out-of-class definition of a static data member of a class, find
3086/// its corresponding in-class declaration.
3087llvm::DIDerivedType
3088CGDebugInfo::getOrCreateStaticDataMemberDeclarationOrNull(const VarDecl *D) {
3089 if (!D->isStaticDataMember())
3090 return llvm::DIDerivedType();
3091 llvm::DenseMap<const Decl *, llvm::WeakVH>::iterator MI =
3092 StaticDataMemberCache.find(D->getCanonicalDecl());
3093 if (MI != StaticDataMemberCache.end()) {
3094 assert(MI->second && "Static data member declaration should still exist");
3095 return llvm::DIDerivedType(cast<llvm::MDNode>(MI->second));
Evgeniy Stepanov37b3f732013-08-16 10:35:31 +00003096 }
David Blaikiece763042013-08-20 21:49:21 +00003097
3098 // If the member wasn't found in the cache, lazily construct and add it to the
3099 // type (used when a limited form of the type is emitted).
David Blaikie6943dea2013-08-20 01:28:15 +00003100 llvm::DICompositeType Ctxt(
3101 getContextDescriptor(cast<Decl>(D->getDeclContext())));
3102 llvm::DIDerivedType T = CreateRecordStaticField(D, Ctxt);
David Blaikie6943dea2013-08-20 01:28:15 +00003103 return T;
3104}
3105
Guy Benyei11169dd2012-12-18 14:30:41 +00003106/// EmitGlobalVariable - Emit information about a global variable.
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003107void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 const VarDecl *D) {
Eric Christopher75e17682013-05-16 00:45:23 +00003109 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003110 // Create global variable debug descriptor.
3111 llvm::DIFile Unit = getOrCreateFile(D->getLocation());
3112 unsigned LineNo = getLineNumber(D->getLocation());
3113
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003114 setLocation(D->getLocation());
Guy Benyei11169dd2012-12-18 14:30:41 +00003115
3116 QualType T = D->getType();
3117 if (T->isIncompleteArrayType()) {
3118
3119 // CodeGen turns int[] into int[1] so we'll do the same here.
3120 llvm::APInt ConstVal(32, 1);
3121 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3122
3123 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3124 ArrayType::Normal, 0);
3125 }
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003126 StringRef DeclName = D->getName();
3127 StringRef LinkageName;
3128 if (D->getDeclContext() && !isa<FunctionDecl>(D->getDeclContext())
3129 && !isa<ObjCMethodDecl>(D->getDeclContext()))
3130 LinkageName = Var->getName();
3131 if (LinkageName == DeclName)
3132 LinkageName = StringRef();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003133 llvm::DIDescriptor DContext =
Guy Benyei11169dd2012-12-18 14:30:41 +00003134 getContextDescriptor(dyn_cast<Decl>(D->getDeclContext()));
David Blaikie6943dea2013-08-20 01:28:15 +00003135 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3136 DContext, DeclName, LinkageName, Unit, LineNo, getOrCreateType(T, Unit),
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003137 Var->hasInternalLinkage(), Var,
David Blaikie6943dea2013-08-20 01:28:15 +00003138 getOrCreateStaticDataMemberDeclarationOrNull(D));
David Blaikiebd483762013-05-20 04:58:53 +00003139 DeclCache.insert(std::make_pair(D->getCanonicalDecl(), llvm::WeakVH(GV)));
Guy Benyei11169dd2012-12-18 14:30:41 +00003140}
3141
3142/// EmitGlobalVariable - Emit information about an objective-c interface.
3143void CGDebugInfo::EmitGlobalVariable(llvm::GlobalVariable *Var,
3144 ObjCInterfaceDecl *ID) {
Eric Christopher75e17682013-05-16 00:45:23 +00003145 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Guy Benyei11169dd2012-12-18 14:30:41 +00003146 // Create global variable debug descriptor.
3147 llvm::DIFile Unit = getOrCreateFile(ID->getLocation());
3148 unsigned LineNo = getLineNumber(ID->getLocation());
3149
3150 StringRef Name = ID->getName();
3151
3152 QualType T = CGM.getContext().getObjCInterfaceType(ID);
3153 if (T->isIncompleteArrayType()) {
3154
3155 // CodeGen turns int[] into int[1] so we'll do the same here.
3156 llvm::APInt ConstVal(32, 1);
3157 QualType ET = CGM.getContext().getAsArrayType(T)->getElementType();
3158
3159 T = CGM.getContext().getConstantArrayType(ET, ConstVal,
3160 ArrayType::Normal, 0);
3161 }
3162
3163 DBuilder.createGlobalVariable(Name, Unit, LineNo,
3164 getOrCreateType(T, Unit),
3165 Var->hasInternalLinkage(), Var);
3166}
3167
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003168/// EmitGlobalVariable - Emit global variable's debug info.
3169void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
3170 llvm::Constant *Init) {
Eric Christopher75e17682013-05-16 00:45:23 +00003171 assert(DebugKind >= CodeGenOptions::LimitedDebugInfo);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00003172 // Create the descriptor for the variable.
3173 llvm::DIFile Unit = getOrCreateFile(VD->getLocation());
3174 StringRef Name = VD->getName();
3175 llvm::DIType Ty = getOrCreateType(VD->getType(), Unit);
3176 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(VD)) {
3177 const EnumDecl *ED = cast<EnumDecl>(ECD->getDeclContext());
3178 assert(isa<EnumType>(ED->getTypeForDecl()) && "Enum without EnumType?");
3179 Ty = getOrCreateType(QualType(ED->getTypeForDecl(), 0), Unit);
3180 }
3181 // Do not use DIGlobalVariable for enums.
3182 if (Ty.getTag() == llvm::dwarf::DW_TAG_enumeration_type)
3183 return;
3184 llvm::DIGlobalVariable GV = DBuilder.createStaticVariable(
3185 Unit, Name, Name, Unit, getLineNumber(VD->getLocation()), Ty, true, Init,
3186 getOrCreateStaticDataMemberDeclarationOrNull(cast<VarDecl>(VD)));
3187 DeclCache.insert(std::make_pair(VD->getCanonicalDecl(), llvm::WeakVH(GV)));
David Blaikiebd483762013-05-20 04:58:53 +00003188}
3189
3190llvm::DIScope CGDebugInfo::getCurrentContextDescriptor(const Decl *D) {
3191 if (!LexicalBlockStack.empty())
3192 return llvm::DIScope(LexicalBlockStack.back());
3193 return getContextDescriptor(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003194}
3195
David Blaikie9f88fe82013-04-22 06:13:21 +00003196void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
David Blaikiebd483762013-05-20 04:58:53 +00003197 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3198 return;
David Blaikie9f88fe82013-04-22 06:13:21 +00003199 DBuilder.createImportedModule(
David Blaikiebd483762013-05-20 04:58:53 +00003200 getCurrentContextDescriptor(cast<Decl>(UD.getDeclContext())),
3201 getOrCreateNameSpace(UD.getNominatedNamespace()),
David Blaikie9f88fe82013-04-22 06:13:21 +00003202 getLineNumber(UD.getLocation()));
3203}
3204
David Blaikiebd483762013-05-20 04:58:53 +00003205void CGDebugInfo::EmitUsingDecl(const UsingDecl &UD) {
3206 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3207 return;
3208 assert(UD.shadow_size() &&
3209 "We shouldn't be codegening an invalid UsingDecl containing no decls");
3210 // Emitting one decl is sufficient - debuggers can detect that this is an
3211 // overloaded name & provide lookup for all the overloads.
3212 const UsingShadowDecl &USD = **UD.shadow_begin();
Eric Christopher1ecc5632013-06-07 22:54:39 +00003213 if (llvm::DIDescriptor Target =
3214 getDeclarationOrDefinition(USD.getUnderlyingDecl()))
David Blaikiebd483762013-05-20 04:58:53 +00003215 DBuilder.createImportedDeclaration(
3216 getCurrentContextDescriptor(cast<Decl>(USD.getDeclContext())), Target,
3217 getLineNumber(USD.getLocation()));
3218}
3219
David Blaikief121b932013-05-20 22:50:41 +00003220llvm::DIImportedEntity
3221CGDebugInfo::EmitNamespaceAlias(const NamespaceAliasDecl &NA) {
3222 if (CGM.getCodeGenOpts().getDebugInfo() < CodeGenOptions::LimitedDebugInfo)
3223 return llvm::DIImportedEntity(0);
3224 llvm::WeakVH &VH = NamespaceAliasCache[&NA];
3225 if (VH)
3226 return llvm::DIImportedEntity(cast<llvm::MDNode>(VH));
3227 llvm::DIImportedEntity R(0);
3228 if (const NamespaceAliasDecl *Underlying =
3229 dyn_cast<NamespaceAliasDecl>(NA.getAliasedNamespace()))
3230 // This could cache & dedup here rather than relying on metadata deduping.
3231 R = DBuilder.createImportedModule(
3232 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3233 EmitNamespaceAlias(*Underlying), getLineNumber(NA.getLocation()),
3234 NA.getName());
3235 else
3236 R = DBuilder.createImportedModule(
3237 getCurrentContextDescriptor(cast<Decl>(NA.getDeclContext())),
3238 getOrCreateNameSpace(cast<NamespaceDecl>(NA.getAliasedNamespace())),
3239 getLineNumber(NA.getLocation()), NA.getName());
3240 VH = R;
3241 return R;
3242}
3243
Guy Benyei11169dd2012-12-18 14:30:41 +00003244/// getOrCreateNamesSpace - Return namespace descriptor for the given
3245/// namespace decl.
Eric Christopherb2a008c2013-05-16 00:45:12 +00003246llvm::DINameSpace
Guy Benyei11169dd2012-12-18 14:30:41 +00003247CGDebugInfo::getOrCreateNameSpace(const NamespaceDecl *NSDecl) {
David Blaikie9fdedec2013-08-16 22:52:07 +00003248 NSDecl = NSDecl->getCanonicalDecl();
Eric Christopherb2a008c2013-05-16 00:45:12 +00003249 llvm::DenseMap<const NamespaceDecl *, llvm::WeakVH>::iterator I =
Guy Benyei11169dd2012-12-18 14:30:41 +00003250 NameSpaceCache.find(NSDecl);
3251 if (I != NameSpaceCache.end())
3252 return llvm::DINameSpace(cast<llvm::MDNode>(I->second));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003253
Guy Benyei11169dd2012-12-18 14:30:41 +00003254 unsigned LineNo = getLineNumber(NSDecl->getLocation());
3255 llvm::DIFile FileD = getOrCreateFile(NSDecl->getLocation());
Eric Christopherb2a008c2013-05-16 00:45:12 +00003256 llvm::DIDescriptor Context =
Guy Benyei11169dd2012-12-18 14:30:41 +00003257 getContextDescriptor(dyn_cast<Decl>(NSDecl->getDeclContext()));
3258 llvm::DINameSpace NS =
3259 DBuilder.createNameSpace(Context, NSDecl->getName(), FileD, LineNo);
3260 NameSpaceCache[NSDecl] = llvm::WeakVH(NS);
3261 return NS;
3262}
3263
3264void CGDebugInfo::finalize() {
3265 for (std::vector<std::pair<void *, llvm::WeakVH> >::const_iterator VI
3266 = ReplaceMap.begin(), VE = ReplaceMap.end(); VI != VE; ++VI) {
3267 llvm::DIType Ty, RepTy;
3268 // Verify that the debug info still exists.
3269 if (llvm::Value *V = VI->second)
3270 Ty = llvm::DIType(cast<llvm::MDNode>(V));
Eric Christopherb2a008c2013-05-16 00:45:12 +00003271
Guy Benyei11169dd2012-12-18 14:30:41 +00003272 llvm::DenseMap<void *, llvm::WeakVH>::iterator it =
3273 TypeCache.find(VI->first);
3274 if (it != TypeCache.end()) {
3275 // Verify that the debug info still exists.
3276 if (llvm::Value *V = it->second)
3277 RepTy = llvm::DIType(cast<llvm::MDNode>(V));
3278 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003279
Eric Christopherf8bc4d82013-07-18 00:52:50 +00003280 if (Ty && Ty.isForwardDecl() && RepTy)
Guy Benyei11169dd2012-12-18 14:30:41 +00003281 Ty.replaceAllUsesWith(RepTy);
Guy Benyei11169dd2012-12-18 14:30:41 +00003282 }
Adrian Prantl73409ce2013-03-11 18:33:46 +00003283
3284 // We keep our own list of retained types, because we need to look
3285 // up the final type in the type cache.
3286 for (std::vector<void *>::const_iterator RI = RetainedTypes.begin(),
3287 RE = RetainedTypes.end(); RI != RE; ++RI)
Manman Renf801f802013-08-29 20:48:48 +00003288 DBuilder.retainType(llvm::DIType(cast<llvm::MDNode>(TypeCache[*RI])));
Adrian Prantl73409ce2013-03-11 18:33:46 +00003289
Guy Benyei11169dd2012-12-18 14:30:41 +00003290 DBuilder.finalize();
3291}